Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(onshape): upload released drawings + CAD models to Carbon (#1092)
Leo Stock9700f3017c72
diff --git a/.ai/playbooks/onshape-asset-sync.md b/.ai/playbooks/onshape-asset-sync.mdnew file mode 100644index 0000000000..67597970ed--- /dev/null+++ b/.ai/playbooks/onshape-asset-sync.md@@ -0,0 +1,72 @@+# Onshape Asset Sync++Last tested: 2026-07-03+Routes:+- `/x/settings/integrations/onshape` (settings UI: toggle + backfill action)+- `POST /api/integrations/onshape/backfill` (admin trigger, gated)+- `POST /api/webhook/onshape/:companyId` (inbound receiver, public)++## Prerequisites++- Dev stack up. **Use `crbn up --no-portless`** (plain localhost) — the portless+ `.dev` URLs did not resolve for the node server / curl / automation browser on+ this machine (root-owned `~/.portless` → no routes registered). localhost mode+ sidesteps it entirely. ERP at `http://localhost:3000`, API at `:54321`.+- Onshape is NOT connected on a fresh seed (`ONSHAPE_CLIENT_ID` unset, no+ `companyIntegration` row). The toggle/backfill only render when an ACTIVE+ `companyIntegration` row exists, so inject a fixture (fake OAuth creds):++```sql+-- companyId: get with: select id from company limit 1;+insert into "companyIntegration" (id,"companyId",active,metadata,"updatedAt","updatedBy")+values ('onshape','<companyId>',true,+ '{"baseUrl":"https://cad.onshape.com","credentials":{"type":"oauth","accessToken":"FIXTURE_FAKE_TOKEN","refreshToken":"FIXTURE_FAKE_REFRESH","expiresAt":"2030-01-01T00:00:00.000Z"},"assetSyncEnabled":false}'::json,+ now(),'<userId>')+on conflict (id,"companyId") do update set active=excluded.active, metadata=excluded.metadata, "updatedAt"=now();+```++The metadata MUST match the onshape `integration.jsonschema` (requires+`baseUrl` + `credentials{type,accessToken,refreshToken,expiresAt}`) or the+`sync_verify_integration` trigger rejects the row when `active=true`.++## Steps++### 1. Login — `http://localhost:3000/login`, fill "Email Address" = `[email protected]`, click "Sign in with Email". The button enables only after a valid email; redirects to `/x`.++### 2. Settings — navigate `/x/settings/integrations/onshape`. Expect a "Sync released assets" **switch** (off) and a "Backfill released assets" action with a **"Run"** button.++### 3. Toggle persistence — flip the switch on, click **"Update"** (the save button; NOT a click-to-submit on the switch). Redirects to `/x/settings/integrations`. Verify the DB merge preserved credentials:++```sql+select jsonb_pretty(metadata::jsonb) from "companyIntegration" where id='onshape';+-- expect: assetSyncEnabled=true AND baseUrl + credentials still present+```++### 4. Backfill gating — POST the endpoint from the authenticated session:+- `assetSyncEnabled=true` → `200 {"success":true,"message":"Onshape asset backfill started"}`+- `assetSyncEnabled=false` → `400 "...asset sync is disabled..."`++### 5. Webhook (public, curl over localhost) — `POST /api/webhook/onshape/<companyId>`:+- active row + `{"event":"onshape.workflow.transition",...}` → `200 {"success":true}`+- missing `event` → `400` zod error+- unknown companyId → `400 "Integration not configured"`++## Cleanup++```sql+delete from "companyIntegration" where id='onshape'+ and metadata->'credentials'->>'accessToken'='FIXTURE_FAKE_TOKEN';+```++## Selector Notes+- Save button reads **"Update"** (not "Save").+- The switch is `[switch] "Sync released assets"`; action button is `[button] "Run"`.++## Common Failures+- All `.dev` URLs return HTTP 000 / `chrome-error://` → portless routes not+ registered (root-owned `~/.portless`). Use `--no-portless` or+ `sudo chown -R $USER ~/.portless` + restart proxy & `crbn up`.+- Webhook / settings loader "Integration query failed" → node server can't reach+ `SUPABASE_URL` (again portless `.dev` unresolved). localhost mode fixes it.+- Row insert "metadata does not match jsonschema" → metadata missing+ `baseUrl`/`credentials` required by the onshape schema.diff --git a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsxindex c61dc50861..838b08a2f7 100644--- a/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx+++ b/apps/erp/app/modules/settings/ui/Integrations/IntegrationForm.tsx@@ -96,6 +96,21 @@ function IntegrationActionButton({);}+// Wraps an action gated by a boolean setting (`enabledWhenSetting`), reading the+// LIVE form value so it appears/disappears as the toggle changes — not only after+// save. Renders nothing when the setting is off.+function GatedIntegrationActionButton({+ action,+ isDisabled+}: {+ action: IntegrationAction;+ isDisabled: boolean;+}) {+ const [value] = useControlField<boolean>(action.enabledWhenSetting as string);+ if (value !== true) return null;+ return <IntegrationActionButton action={action} isDisabled={isDisabled} />;+}+/*** Helper to normalize option to consistent format*/@@ -573,6 +588,9 @@ export function IntegrationForm({);}, [integration, metadata]);+ const integrationActions =+ (integration as { actions?: IntegrationAction[] })?.actions ?? [];+if (!integrationId) {throw new Error("Integration ID is required");}@@ -666,27 +684,33 @@ export function IntegrationForm({/>))}- {installed &&- // @ts-expect-error TS2339 - TODO: fix type- integration.actions &&- // @ts-expect-error TS2339 - TODO: fix type- integration.actions.length > 0 && (- <div className="flex w-full flex-col gap-3 border-t border-border pt-4">- <div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">- <Trans>Actions</Trans>- </div>- <VStack spacing={2} className="w-full">- {/* @ts-expect-error TS7006 */}- {integration.actions.map((action) => (+ {installed && integrationActions.length > 0 && (+ // `has-[button]` collapses the whole section (header included)+ // when every gated action is hidden, so the toggle live-controls+ // visibility without leaving an empty "Actions" header.+ <div className="hidden has-[button]:flex w-full flex-col gap-3 border-t border-border pt-4">+ <div className="text-[0.6875rem] font-semibold uppercase tracking-wider text-foreground/70">+ <Trans>Actions</Trans>+ </div>+ <VStack spacing={2} className="w-full">+ {integrationActions.map((action) =>+ action.enabledWhenSetting ? (+ <GatedIntegrationActionButton+ key={action.id}+ action={action}+ isDisabled={isDisabled}+ />+ ) : (<IntegrationActionButtonkey={action.id}action={action}isDisabled={isDisabled}/>- ))}- </VStack>- </div>- )}+ )+ )}+ </VStack>+ </div>+ )}</VStack></ScrollArea><div className="mt-2">diff --git a/apps/erp/app/routes/api+/integrations.onshape.backfill.ts b/apps/erp/app/routes/api+/integrations.onshape.backfill.tsnew file mode 100644index 0000000000..05e9618222--- /dev/null+++ b/apps/erp/app/routes/api+/integrations.onshape.backfill.ts@@ -0,0 +1,51 @@+import { requirePermissions } from "@carbon/auth/auth.server";+import { trigger } from "@carbon/jobs";+import type { ActionFunctionArgs } from "react-router";+import { data } from "react-router";++export const config = {+ runtime: "nodejs"+};++// POST: kick off the Onshape released-asset backfill for the current company.+// Admin-only. Gated on the SAME configurable flag the job checks+// (companyIntegration.metadata.assetSyncEnabled) so it can't be run unless the+// company has turned Onshape asset sync on.+export async function action({ request }: ActionFunctionArgs) {+ const { client, companyId, userId } = await requirePermissions(request, {+ update: "settings"+ });++ const integration = await client+ .from("companyIntegration")+ .select("active, metadata")+ .eq("companyId", companyId)+ .eq("id", "onshape")+ .single();++ if (integration.error || !integration.data?.active) {+ return data(+ { error: "Onshape integration not found or inactive" },+ { status: 400 }+ );+ }++ const metadata = (integration.data.metadata ?? {}) as Record<string, unknown>;+ if (metadata.assetSyncEnabled !== true) {+ return data(+ {+ error:+ "Onshape asset sync is disabled — enable it on the Onshape integration before running a backfill"+ },+ { status: 400 }+ );+ }++ try {+ await trigger("onshape-backfill", { companyId, userId });+ return data({ success: true, message: "Onshape asset backfill started" });+ } catch (error) {+ console.error("Failed to start Onshape backfill:", error);+ return data({ error: "Failed to start Onshape backfill" }, { status: 500 });+ }+}diff --git a/apps/erp/app/routes/api+/integrations.onshape.install.ts b/apps/erp/app/routes/api+/integrations.onshape.install.tsindex 9e4a022022..441f3c2471 100644--- a/apps/erp/app/routes/api+/integrations.onshape.install.ts+++ b/apps/erp/app/routes/api+/integrations.onshape.install.ts@@ -16,7 +16,9 @@ export async function loader({ request }: LoaderFunctionArgs) {client_id: ONSHAPE_CLIENT_ID,redirect_uri: ONSHAPE_OAUTH_REDIRECT_URL,response_type: "code",- scope: "OAuth2Read",+ // Read for models/revisions/documents; Write to create translation (STEP/PDF+ // export) jobs and manage the release webhook subscription.+ scope: "OAuth2Read OAuth2Write",state});diff --git a/apps/erp/app/routes/api+/integrations.onshape.oauth.ts b/apps/erp/app/routes/api+/integrations.onshape.oauth.tsindex 60f3836d39..b5ae44d029 100644--- a/apps/erp/app/routes/api+/integrations.onshape.oauth.ts+++ b/apps/erp/app/routes/api+/integrations.onshape.oauth.ts@@ -94,6 +94,13 @@ export async function loader({ request }: LoaderFunctionArgs) {refreshToken: tokenData.refresh_token,expiresAt: new Date(Date.now() + 3600 * 1000).toISOString()},+ // The scope actually granted by this authorization. Onshape returns it on+ // the token response; fall back to what we requested (install.ts always+ // asks for read+write). Used to tell an already-connected user they must+ // reconnect before enabling asset sync — a token minted before write was+ // requested is read-only, and a refresh can't widen it. Legacy installs+ // predate this field (no `scope`), which reads as read-only → prompt.+ scope: tokenData.scope ?? "OAuth2Read OAuth2Write",baseUrl: "https://cad.onshape.com"},updatedBy: userId,@@ -101,6 +108,10 @@ export async function loader({ request }: LoaderFunctionArgs) {});if (createdIntegration?.data?.metadata) {+ // The release webhook is registered when the user enables asset sync (see+ // the integration settings save + ensureOnshapeReleaseWebhook), not on+ // connect — asset sync is off by default, so there's nothing to subscribe+ // to yet at this point.const requestUrl = new URL(request.url);if (!VERCEL_URL || VERCEL_URL.includes("localhost")) {diff --git a/apps/erp/app/routes/api+/webhook.onshape.$companyId.ts b/apps/erp/app/routes/api+/webhook.onshape.$companyId.tsnew file mode 100644index 0000000000..45b93446bc--- /dev/null+++ b/apps/erp/app/routes/api+/webhook.onshape.$companyId.ts@@ -0,0 +1,194 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { trigger } from "@carbon/jobs";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";+import { data } from "react-router";+import { z } from "zod";+import { getIntegration } from "../../modules/settings";++// Inbound receiver for Onshape lifecycle webhooks (mirrors+// webhook.jira.$companyId.ts / webhook.linear.$companyId.ts).+//+// Onshape ──POST──▶ /api/webhook/onshape/:companyId+// │ resolve companyId + active onshape integration+// │ validate minimal envelope, log the event+// ▼+// onshape.revision.created ──▶ trigger("onshape-revision-sync")+// everything else ──▶ ack 200 (logged, no dispatch)+//+// AUTH: like the jira/linear receivers, no signature verification — the endpoint+// relies on the callback URL + the active-integration check. A forged event can't+// inject content: the sync job re-resolves the released revision against the+// Onshape API, so at worst it triggers a sync of a genuinely released revision.++// Minimal envelope — only fields confirmed against Onshape's webhook docs. Kept+// permissive (passthrough) on purpose so real events aren't rejected if Onshape+// adds fields; unhandled events are logged rather than errored.+const onshapeWebhookEnvelope = z+ .object({+ event: z.string(),+ messageId: z.string().optional(),+ webhookId: z.string().optional(),+ documentId: z.string().optional(),+ workspaceId: z.string().optional(),+ elementId: z.string().optional(),+ versionId: z.string().optional(),+ translationId: z.string().optional(),+ // onshape.revision.created carries the released element identity directly.+ partNumber: z.string().optional(),+ elementType: z.number().optional(), // 0 = part studio, 1 = assembly, 2 = drawing+ revisionId: z.string().optional()+ })+ .passthrough();++export async function loader({ params }: LoaderFunctionArgs) {+ // Onshape (and manual health checks) may GET this endpoint to validate it.+ const { companyId } = params;+ if (!companyId) {+ return data({ success: false }, { status: 400 });+ }++ return { success: true };+}++export async function action({ request, params }: ActionFunctionArgs) {+ const { companyId } = params;++ if (!companyId) {+ return data({ success: false }, { status: 400 });+ }++ const serviceRole = getCarbonServiceRole();+ const integration = await getIntegration(serviceRole, "onshape", companyId);++ if (integration.error) {+ console.error(+ "Onshape webhook: integration query failed",+ integration.error+ );+ return data(+ { success: false, error: "Integration query failed" },+ { status: 400 }+ );+ }++ if (!integration.data) {+ return data(+ { success: false, error: "Integration not configured" },+ { status: 400 }+ );+ }++ if (!integration.data.active) {+ return data(+ { success: false, error: "Integration not active" },+ { status: 400 }+ );+ }++ // Defense-in-depth: only process events while asset sync is enabled. If a+ // deregister failed when the toggle was turned off, the subscription can+ // linger — drop (ack 200 so Onshape doesn't retry) rather than dispatch.+ const integrationMetadata = (integration.data.metadata ?? {}) as Record<+ string,+ unknown+ >;+ if (integrationMetadata.assetSyncEnabled !== true) {+ console.log("Onshape webhook: asset sync disabled; ignoring event", {+ companyId+ });+ return { success: true };+ }++ let body: unknown;+ try {+ body = await request.json();+ } catch (parseError) {+ console.error("Onshape webhook: body is not valid JSON", parseError);+ return data(+ { success: false, error: "Invalid JSON body" },+ { status: 400 }+ );+ }++ const parsed = onshapeWebhookEnvelope.safeParse(body);++ if (!parsed.success) {+ return data(+ { success: false, error: parsed.error.format() },+ { status: 400 }+ );+ }++ const {+ event,+ messageId,+ documentId,+ elementId,+ versionId,+ partNumber,+ elementType,+ revisionId+ } = parsed.data;++ console.log("Onshape webhook received", {+ companyId,+ event,+ messageId,+ partNumber,+ documentId,+ versionId,+ elementId,+ elementType+ });++ switch (event) {+ case "onshape.revision.created": {+ // Go-forward trigger: a part/assembly was released. This event carries the+ // released element's identity directly (documentId/versionId/elementId/+ // elementType/partNumber), so we dispatch the sync job to attach its CAD+ // model to the matching Carbon item. Idempotency is on messageId (see the+ // onshape-revision-sync function). The acting user is the integration+ // installer (the webhook itself is unauthenticated).+ const installerUserId = integration.data.updatedBy;+ if (+ !installerUserId ||+ !messageId ||+ !partNumber ||+ !documentId ||+ !versionId ||+ !elementId ||+ typeof elementType !== "number"+ ) {+ console.warn(+ "Onshape webhook: revision.created missing required fields; skipping dispatch",+ { companyId, messageId, partNumber }+ );+ break;+ }+ await trigger("onshape-revision-sync", {+ companyId,+ userId: installerUserId,+ messageId,+ partNumber,+ documentId,+ versionId,+ elementId,+ elementType,+ revisionId+ });+ break;+ }+ case "onshape.workflow.transition":+ // The release-workflow wrapper — thin (only a release-package objectId + the+ // transition name). We act on the per-element onshape.revision.created events+ // that follow a release instead, so there is nothing to dispatch here.+ break;+ default:+ // System events (webhook.register / ping) and anything we don't handle:+ // ack so Onshape doesn't retry-storm; the log above captures them.+ break;+ }++ // Always ack a well-formed, authorized event so Onshape does not retry.+ return { success: true };+}diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsxindex 55989b8adc..45ed51e943 100644--- a/apps/erp/app/routes/file+/model+/public.$.tsx+++ b/apps/erp/app/routes/file+/model+/public.$.tsx@@ -46,7 +46,11 @@ export async function loader({ params }: LoaderFunctionArgs) {!supportedModelTypes.includes(fileType)))throw new Error(`File type ${fileType} not supported`);- const contentType = supportedFileTypes[fileType];+ // Model extensions (step, glb, …) aren't in supportedFileTypes — without a+ // fallback they'd be served with "Content-Type: undefined".+ const contentType =+ supportedFileTypes[fileType] ??+ (fileType === "glb" ? "model/gltf-binary" : "application/octet-stream");async function downloadFile() {const result = await client.storage.from("private").download(`${path}`);diff --git a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx b/apps/erp/app/routes/x+/settings+/integrations.$id.tsxindex b53b1bfafc..de9d037309 100644--- a/apps/erp/app/routes/x+/settings+/integrations.$id.tsx+++ b/apps/erp/app/routes/x+/settings+/integrations.$id.tsx@@ -8,7 +8,11 @@ import {ProviderID,type XeroProvider} from "@carbon/ee/accounting";-import { getIntegrationServerHooks } from "@carbon/ee/hooks.server";+import {+ ensureOnshapeReleaseWebhook,+ getIntegrationServerHooks,+ onshapeConnectionHasWriteScope+} from "@carbon/ee/hooks.server";import { isIntegrationWhitelisted } from "@carbon/ee/plan";import { requirePlan } from "@carbon/ee/plan.server";import { validationError, validator } from "@carbon/form";@@ -265,6 +269,19 @@ export async function action({ request, params }: ActionFunctionArgs) {// Build metadata, transforming owner settings into syncConfig structureconst metadata = buildIntegrationMetadata(existingMetadata, d);+ // Onshape asset sync needs the OAuth2Write scope (export jobs + webhook). A+ // connection authorized read-only can't run it, and a refresh can't widen the+ // scope — only a reconnect can. If a read-only user is turning the feature ON,+ // don't persist an on-but-non-functional toggle: force it back off here and+ // tell them to reconnect first (below). Leaving it off imposes nothing.+ const onshapeActivatingWithoutWrite =+ integrationId === "onshape" &&+ (metadata as Record<string, unknown>).assetSyncEnabled === true &&+ !onshapeConnectionHasWriteScope(existingMetadata);+ if (onshapeActivatingWithoutWrite) {+ (metadata as Record<string, unknown>).assetSyncEnabled = false;+ }+const wasInstalled = existing.data?.active === true;const update = await upsertCompanyIntegration(client, {@@ -315,6 +332,52 @@ export async function action({ request, params }: ActionFunctionArgs) {}}+ // Onshape: keep the release-webhook subscription in lockstep with the+ // asset-sync toggle. Registering here (not just on connect) also covers+ // already-connected installs when they enable the feature — but connections+ // authorized before the OAuth2Write scope was requested hold Read-only tokens+ // and need a reconnect, so surface a registration failure instead of flashing+ // success while the sync silently never fires. The settings themselves are+ // already saved either way.+ if (integrationId === "onshape") {+ // Read-only connection trying to turn asset sync on: we already forced the+ // toggle back off above, so just tell them exactly what to do. Explicit and+ // scope-accurate — not inferred from a downstream webhook failure.+ if (onshapeActivatingWithoutWrite) {+ await invalidateIntegrationHealthCache(integrationId, companyId);+ throw redirect(+ path.to.integrations,+ await flash(+ request,+ error(+ "onshape connection is read-only",+ "Onshape is connected with read-only access. Reconnect Onshape to grant write access, then enable asset sync."+ )+ )+ );+ }++ const assetSyncEnabled =+ (metadata as Record<string, unknown>).assetSyncEnabled === true;+ const webhookResult = await ensureOnshapeReleaseWebhook(+ companyId,+ assetSyncEnabled+ );+ if (assetSyncEnabled && !webhookResult.ok) {+ await invalidateIntegrationHealthCache(integrationId, companyId);+ throw redirect(+ path.to.integrations,+ await flash(+ request,+ error(+ webhookResult.error,+ "Saved Onshape settings, but couldn't register the release webhook. Reconnect Onshape to grant write access, then save again."+ )+ )+ );+ }+ }+await invalidateIntegrationHealthCache(integrationId, companyId);throw redirect(diff --git a/apps/erp/vite.config.ts b/apps/erp/vite.config.tsindex 69de408b64..6d37d0e20b 100644--- a/apps/erp/vite.config.ts+++ b/apps/erp/vite.config.ts@@ -46,7 +46,13 @@ export default defineConfig(({ isSsrBuild, mode }) => {server: {port: 3000,strictPort: true,- allowedHosts: [".ngrok-free.app", ".ngrok-free.dev", ".dev", ".localhost"],+ allowedHosts: [+ ".ngrok-free.app",+ ".ngrok-free.dev",+ ".trycloudflare.com",+ ".dev",+ ".localhost",+ ],},plugins: [tailwindcss(),diff --git a/packages/database/supabase/migrations/20260703165330_onshape-asset-sync-jsonschema.sql b/packages/database/supabase/migrations/20260703165330_onshape-asset-sync-jsonschema.sqlnew file mode 100644index 0000000000..76db1cfc04--- /dev/null+++ b/packages/database/supabase/migrations/20260703165330_onshape-asset-sync-jsonschema.sql@@ -0,0 +1,43 @@+-- Declare assetSyncEnabled in the onshape integration jsonschema. The+-- verify_integration() trigger validates companyIntegration.metadata against+-- this schema; the toggle currently passes only because additionalProperties+-- defaults to true. Declaring it makes the setting survive a future+-- additionalProperties: false tightening.+UPDATE "integration"+SET "jsonschema" = '{+ "type": "object",+ "properties": {+ "baseUrl": {+ "type": "string"+ },+ "credentials": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string"+ },+ "accessToken": {+ "type": "string"+ },+ "refreshToken": {+ "type": "string"+ },+ "expiresAt": {+ "type": "string"+ }+ },+ "required": ["type", "accessToken", "refreshToken", "expiresAt"]+ },+ "assetSyncEnabled": {+ "type": "boolean"+ },+ "onshapeCompanyId": {+ "type": "string"+ },+ "scope": {+ "type": "string"+ }+ },+ "required": ["baseUrl", "credentials"]+}'::json+WHERE "id" = 'onshape';diff --git a/packages/ee/package.json b/packages/ee/package.jsonindex fd109684d7..743b244ec4 100644--- a/packages/ee/package.json+++ b/packages/ee/package.json@@ -36,6 +36,7 @@"@ai-sdk/openai": "catalog:","@carbon/auth": "workspace:*","@carbon/database": "workspace:*",+ "@carbon/env": "workspace:*","@carbon/kv": "workspace:*","@carbon/lib": "workspace:*","@carbon/logger": "workspace:*",diff --git a/packages/ee/src/hooks.server.ts b/packages/ee/src/hooks.server.tsindex cf35dd56c7..d0b9fae815 100644--- a/packages/ee/src/hooks.server.ts+++ b/packages/ee/src/hooks.server.ts@@ -1,7 +1,17 @@import { emailHealthcheck } from "./email/hooks.server";import { jiraHealthcheck } from "./jira/hooks.server";import { linearHealthcheck } from "./linear/hooks.server";+import { onshapeOnUninstall } from "./onshape/hooks.server";import type { IntegrationServerHooks } from "./types";++// Onshape keeps its release webhook subscription in lockstep with the asset-sync+// toggle; the integration settings save calls this. onshapeConnectionHasWriteScope+// lets the save tell a read-only connection to reconnect before enabling sync.+export {+ ensureOnshapeReleaseWebhook,+ onshapeConnectionHasWriteScope+} from "./onshape/hooks.server";+import {xeroHealthcheck,xeroOnInstall,@@ -26,6 +36,9 @@ const serverHooks: Record<string, IntegrationServerHooks> = {linear: {onHealthcheck: linearHealthcheck},+ onshape: {+ onUninstall: onshapeOnUninstall+ },xero: {onHealthcheck: xeroHealthcheck,onInstall: xeroOnInstall,diff --git a/packages/ee/src/onshape/config.tsx b/packages/ee/src/onshape/config.tsxindex 73416481b2..9ec9533aab 100644--- a/packages/ee/src/onshape/config.tsx+++ b/packages/ee/src/onshape/config.tsx@@ -13,8 +13,41 @@ export const Onshape = defineIntegration({"Onshape is a browser-based CAD/PLM software for modern engineering teams. This integration will sync data from Onshape to Carbon.",shortDescription: "Sync data from Onshape to Carbon.",images: [],- settings: [],- schema: z.object({}),+ settings: [+ {+ name: "assetSyncEnabled",+ label: "Sync released assets",+ description:+ "Automatically pull released Onshape drawings and CAD models onto matching Carbon items (matched by part number). Off by default.",+ type: "switch",+ required: false,+ value: false+ }+ ],+ schema: z.object({+ // SwitchField posts a literal "true"/"false" string; preprocess explicitly so+ // unchecking sticks (z.coerce.boolean would treat "false" as truthy).+ assetSyncEnabled: z+ .preprocess((value) => {+ if (typeof value === "boolean") return value;+ if (value === "true") return true;+ if (value === "false") return false;+ return value;+ }, z.boolean())+ .default(false)+ }),+ actions: [+ {+ id: "backfill",+ label: "Backfill released assets",+ description:+ "Pull released Onshape assets onto all matching Carbon items now (link-only). Requires asset sync enabled.",+ endpoint: "/api/integrations/onshape/backfill",+ // Only shown once asset sync is enabled (the backfill route is gated on it+ // too, so hide the button rather than show one that errors).+ enabledWhenSetting: "assetSyncEnabled"+ }+ ],onClientInstall: async () => {const response = await fetch("/api/integrations/onshape/install").then((res) => res.json()diff --git a/packages/ee/src/onshape/hooks.server.ts b/packages/ee/src/onshape/hooks.server.tsnew file mode 100644index 0000000000..f689f61045--- /dev/null+++ b/packages/ee/src/onshape/hooks.server.ts@@ -0,0 +1,194 @@+import { getAppUrl } from "@carbon/auth";+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { getOnshapeClient } from "./lib/client";++// The release webhook's callback path for a company. We match/deregister by this+// PATH (not the full URL) so a host change — localhost, a tunnel, or the prod+// domain — still resolves this company's webhook(s).+function callbackPath(companyId: string): string {+ return `/api/webhook/onshape/${companyId}`;+}++// Build an Onshape client for background webhook management. Reads the installer+// (updatedBy) for token refresh/audit; falls back to "system".+async function onshapeClientForCompany(companyId: string) {+ const client = getCarbonServiceRole();+ const integration = await client+ .from("companyIntegration")+ .select("updatedBy")+ .eq("id", "onshape")+ .eq("companyId", companyId)+ .maybeSingle();+ const userId = integration.data?.updatedBy ?? "system";+ return getOnshapeClient(client, companyId, userId);+}++// Resolve the Onshape company id to register the webhook under. Prefer the id+// stored on the integration (written here at first resolve) so every path — this+// webhook registration and the sync/backfill jobs (resolveOnshapeCompanyId in+// @carbon/jobs) — targets the SAME Onshape tenant. Fall back to the first company+// the token can see, persisting it for consistency. Returns null if none.+async function resolveAndStoreOnshapeCompanyId(+ companyId: string,+ client: Awaited<ReturnType<typeof getOnshapeClient>>["client"]+): Promise<string | null> {+ const carbon = getCarbonServiceRole();+ const integration = await carbon+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "onshape")+ .eq("companyId", companyId)+ .maybeSingle();+ const metadata = (integration.data?.metadata ?? {}) as Record<+ string,+ unknown+ >;+ const stored = metadata.onshapeCompanyId;+ if (typeof stored === "string" && stored.length > 0) return stored;++ const companies = (await client?.getCompanies()) ?? [];+ const resolved = companies[0]?.id;+ if (!resolved) return null;++ const update = await carbon+ .from("companyIntegration")+ .update({ metadata: { ...metadata, onshapeCompanyId: resolved } })+ .eq("id", "onshape")+ .eq("companyId", companyId);+ if (update.error) {+ // Non-fatal: we can still register with the resolved id; the jobs just fall+ // back to their own getCompanies() resolve if the store didn't stick.+ console.error(+ "onshape: failed to persist resolved Onshape company id",+ update.error+ );+ }+ return resolved;+}++// Onshape's write scope — needed to create translation (export) jobs and manage+// the release webhook. A connection authorized before this scope was requested+// holds a read-only token, and a refresh can't widen it (the refresh grant sends+// no scope), so the only remedy is a reconnect.+const ONSHAPE_WRITE_SCOPE = "OAuth2Write";++// Does the stored connection have write access? Read from the scope captured at+// the OAuth callback. Legacy installs predate that field (no `scope`) — treat+// them as read-only so we prompt for a reconnect rather than silently failing.+export function onshapeConnectionHasWriteScope(+ metadata: Record<string, unknown> | null | undefined+): boolean {+ const scope = metadata?.scope;+ if (typeof scope !== "string") return false;+ return scope.split(/\s+/).includes(ONSHAPE_WRITE_SCOPE);+}++export type OnshapeWebhookResult = { ok: true } | { ok: false; error: string };++function webhookFailure(error: unknown): OnshapeWebhookResult {+ return {+ ok: false,+ error: error instanceof Error ? error.message : String(error)+ };+}++// Register the go-forward release webhook (onshape.revision.created). Idempotent:+// no-op if a subscription for this company's callback already exists. Never+// throws — failures are logged and returned so the caller can surface them (the+// common causes: a callback that isn't publicly reachable, or an OAuth token+// granted before OAuth2Write was requested, which can't manage webhooks until+// the user reconnects Onshape).+export async function registerOnshapeWebhook(+ companyId: string+): Promise<OnshapeWebhookResult> {+ const onshape = await onshapeClientForCompany(companyId);+ if (onshape.error || !onshape.client) {+ console.error(+ "onshape: could not build client; skipping webhook registration",+ onshape.error+ );+ return { ok: false, error: onshape.error ?? "no client" };+ }+ const path = callbackPath(companyId);+ try {+ const existing = await onshape.client.getWebhooks();+ const alreadyRegistered = (existing.items ?? []).some(+ (webhook) => typeof webhook.url === "string" && webhook.url.includes(path)+ );+ if (alreadyRegistered) return { ok: true };++ const onshapeCompanyId = await resolveAndStoreOnshapeCompanyId(+ companyId,+ onshape.client+ );+ if (!onshapeCompanyId) {+ console.error(+ "onshape: could not resolve Onshape company id; skipping webhook registration"+ );+ return { ok: false, error: "could not resolve Onshape company id" };+ }+ await onshape.client.createWebhook({+ url: `${getAppUrl()}${path}`,+ events: ["onshape.revision.created"],+ companyId: onshapeCompanyId+ });+ console.log(`onshape: registered release webhook for company ${companyId}`);+ return { ok: true };+ } catch (error) {+ console.error("onshape: webhook registration failed", error);+ return webhookFailure(error);+ }+}++// Delete Carbon's release webhook(s) for this company. Idempotent; never throws.+export async function deregisterOnshapeWebhooks(+ companyId: string+): Promise<OnshapeWebhookResult> {+ const onshape = await onshapeClientForCompany(companyId);+ if (onshape.error || !onshape.client) {+ console.error(+ "onshape: could not build client; skipping webhook cleanup",+ onshape.error+ );+ return { ok: false, error: onshape.error ?? "no client" };+ }+ const path = callbackPath(companyId);+ try {+ const webhooks = await onshape.client.getWebhooks();+ const ours = (webhooks.items ?? []).filter(+ (webhook) => typeof webhook.url === "string" && webhook.url.includes(path)+ );+ for (const webhook of ours) {+ await onshape.client.deleteWebhook(webhook.id);+ }+ console.log(+ `onshape: deregistered ${ours.length} webhook(s) for company ${companyId}`+ );+ return { ok: true };+ } catch (error) {+ console.error("onshape: webhook deregistration failed", error);+ return webhookFailure(error);+ }+}++// Keep the subscription in lockstep with the asset-sync toggle: it should exist+// iff asset sync is enabled. Called from the integration settings save — the+// universal hook point, since asset sync is off by default and every company+// (new or already-connected) must enable it there. NOTE: connections authorized+// before the OAuth2Write scope was requested hold Read-only tokens and will fail+// here until the user reconnects Onshape — the settings save surfaces that+// failure rather than swallowing it.+export async function ensureOnshapeReleaseWebhook(+ companyId: string,+ assetSyncEnabled: boolean+): Promise<OnshapeWebhookResult> {+ if (assetSyncEnabled) {+ return registerOnshapeWebhook(companyId);+ }+ return deregisterOnshapeWebhooks(companyId);+}++// Disconnect: remove the subscription so it doesn't keep firing at a dead callback.+export async function onshapeOnUninstall(companyId: string): Promise<void> {+ await deregisterOnshapeWebhooks(companyId);+}diff --git a/packages/ee/src/onshape/lib/client.ts b/packages/ee/src/onshape/lib/client.tsindex 1243ff56d9..692a1bf88f 100644--- a/packages/ee/src/onshape/lib/client.ts+++ b/packages/ee/src/onshape/lib/client.ts@@ -1,5 +1,9 @@-import { ONSHAPE_CLIENT_ID, ONSHAPE_CLIENT_SECRET } from "@carbon/auth";+// From @carbon/env directly (not the @carbon/auth root barrel, which pulls in+// React UI code with top-level await and breaks non-bundler tooling — scripts,+// test runners — that imports this client).+import type { Database } from "@carbon/database";+import { ONSHAPE_CLIENT_ID, ONSHAPE_CLIENT_SECRET } from "@carbon/env";import { getLogger } from "@carbon/logger";import type { SupabaseClient } from "@supabase/supabase-js";import axios from "axios";@@ -22,6 +26,81 @@ export interface OnshapePart {metadata: Record<string, string>;}+export interface OnshapeCompany {+ id: string;+ name?: string;+ [key: string]: unknown;+}++// The only export formats Carbon ingests: GLTF for models (compressed to a+// viewer-renderable GLB before attaching) and PDF for drawings. Onshape's API+// supports more (STEP, PARASOLID, IGES, ...) but they are deliberately not+// accepted here — real assemblies export to multi-GB STEP files, and Onshape+// stays the CAD system of record.+export type OnshapeModelTranslationFormat = "GLTF";+export type OnshapeDrawingTranslationFormat = "PDF";++// Tessellation presets Onshape accepts for mesh exports (mirrors the UI's+// resolution picker). Mesh translations fail without one.+export type OnshapeMeshResolution = "coarse" | "medium" | "fine";++// Async translation job (GLTF / PDF export). requestState transitions+// ACTIVE -> DONE | FAILED. When storeInDocument=false the result is fetched via+// resultExternalDataIds; when true, via resultElementIds (a blob element).+export interface OnshapeTranslation {+ id: string;+ requestState?: "ACTIVE" | "DONE" | "FAILED" | string;+ resultExternalDataIds?: string[] | null;+ resultElementIds?: string[] | null;+ resultDocumentId?: string | null; // download external data FROM this document+ failureReason?: string | null;+ [key: string]: unknown;+}++// A released revision (company revisions API). elementType is NUMERIC:+// 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 {+ partNumber: string;+ revision: string;+ elementType: number;+ documentId: string;+ versionId: string;+ elementId: string;+ partId?: string | null;+ mimeType?: string;+ name?: string;+ releaseId?: string;+ releaseName?: string;+ isObsolete?: boolean;+ [key: string]: unknown;+}++// Typed API error so callers can detect rate limiting (status 429) and honor+// Retry-After instead of hammering the quota.+export class OnshapeApiError extends Error {+ status?: number;+ retryAfterSeconds?: number;++ constructor(message: string, status?: number, retryAfterSeconds?: number) {+ super(message);+ this.name = "OnshapeApiError";+ this.status = status;+ this.retryAfterSeconds = retryAfterSeconds;+ }+}++// Thrown when a translation result exceeds the caller's size cap — large+// assemblies export far beyond what Carbon's storage accepts or its browser+// viewer can render — so callers skip the asset (permanently: retrying can't+// shrink it) instead of failing the sync.+export class OnshapeAssetTooLargeError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "OnshapeAssetTooLargeError";+ }+}+export class OnshapeClient {private baseUrl: string;private accessToken: string;@@ -33,7 +112,10 @@ export class OnshapeClient {this.axiosInstance = axios.create({baseURL: this.baseUrl,- headers: this.getAuthHeaders()+ headers: this.getAuthHeaders(),+ // Bound every request so a slow/unresponsive Onshape can't hang callers+ // indefinitely (e.g. webhook reconcile during the settings-save request).+ timeout: 60_000});}@@ -58,17 +140,31 @@ export class OnshapeClient {});return response.data;} catch (error) {- if (axios.isAxiosError(error)) {- throw new Error(- `Onshape API error (${error.response?.status}): ${- typeof error.response?.data === "string"- ? error.response.data- : JSON.stringify(error.response?.data)- }`- );+ throw this.toApiError(error);+ }+ }++ private toApiError(error: unknown): Error {+ if (axios.isAxiosError(error)) {+ const status = error.response?.status;+ // No response => network error / timeout / DNS / ECONNREFUSED. Keep axios's+ // own message (e.g. "timeout of 60000ms exceeded") instead of the useless+ // "Onshape API error (undefined): undefined".+ if (status === undefined) {+ return new OnshapeApiError(`Onshape request failed: ${error.message}`);}- throw error;+ const parsedRetryAfter = Number(error.response?.headers?.["retry-after"]);+ return new OnshapeApiError(+ `Onshape API error (${status}): ${+ typeof error.response?.data === "string"+ ? error.response.data+ : JSON.stringify(error.response?.data)+ }`,+ status,+ Number.isFinite(parsedRetryAfter) ? parsedRetryAfter : undefined+ );}+ return error instanceof Error ? error : new Error(String(error));}async getDocuments(limit: number = 20, offset: number = 0): Promise<any> {@@ -78,6 +174,57 @@ export class OnshapeClient {);}+ // The authenticated principal's Onshape companies — used to resolve the company+ // id for the revisions API. Returns { items: [...] } in practice, but handled+ // defensively (array | { items }). If a token ever spans multiple companies,+ // resolve/choose explicitly rather than trusting [0].+ async getCompanies(): Promise<OnshapeCompany[]> {+ const response = await this.request<+ OnshapeCompany[] | { items?: OnshapeCompany[] }+ >("GET", "/api/v10/companies");+ return Array.isArray(response) ? response : (response.items ?? []);+ }++ // Register a webhook subscription so Onshape POSTs lifecycle events to Carbon.+ // Used to subscribe to onshape.revision.created (go-forward asset sync) on+ // connect. Requires a publicly reachable callback URL and an OAuth app that+ // permits webhook management. The API also REQUIRES `options` and a scope+ // (`companyId` or `documentId`) — omitting either is a 400 ("options field is+ // required" / "company id or document id required").+ async createWebhook(params: {+ url: string;+ events: string[];+ companyId: string; // Onshape company id — scopes the subscription+ collapseEvents?: boolean;+ }): Promise<{ id: string } & Record<string, unknown>> {+ return this.request<{ id: string } & Record<string, unknown>>(+ "POST",+ "/api/v10/webhooks",+ {+ url: params.url,+ events: params.events,+ companyId: params.companyId,+ options: { collapseEvents: params.collapseEvents ?? false }+ }+ );+ }++ // List the webhook subscriptions visible to the authenticated principal. Used+ // on disconnect to find (and delete) the ones Carbon registered.+ async getWebhooks(): Promise<{+ items?: Array<{ id: string; url: string } & Record<string, unknown>>;+ }> {+ return this.request<{+ items?: Array<{ id: string; url: string } & Record<string, unknown>>;+ }>("GET", "/api/v10/webhooks");+ }++ // Delete a webhook subscription (called on disconnect so a dead callback isn't+ // left registered).+ async deleteWebhook(webhookId: string): Promise<void> {+ await this.request<unknown>("DELETE", `/api/v10/webhooks/${webhookId}`);+ }+async getVersions(documentId: string,limit: number = 20,@@ -110,6 +257,305 @@ export class OnshapeClient {);}+ // Released revisions for a part number (company-scoped). elementType is NUMERIC+ // (0 Part Studio / 1 Assembly / 2 Drawing). Each item carries the released+ // documentId/versionId/elementId/revision.+ async getRevisions(+ onshapeCompanyId: string,+ partNumber: string,+ elementType: number+ ): Promise<{ items: OnshapeRevision[] } & Record<string, unknown>> {+ return this.request<{ items: OnshapeRevision[] } & Record<string, unknown>>(+ "GET",+ `/api/v10/revisions/companies/${onshapeCompanyId}/partnumber/${encodeURIComponent(+ partNumber+ )}?elementType=${elementType}`+ );+ }++ // All released revisions for a company, paginated. No elementType filter+ // needed — returns every type (0/1/2). Optional `after` (ISO+ // date) returns only revisions released after it, enabling cheap incremental sync.+ // Far fewer calls than per-part-number lookups for a backfill/reconcile.+ async getCompanyRevisions(+ onshapeCompanyId: string,+ options: { limit?: number; offset?: number; after?: string } = {}+ ): Promise<+ { items: OnshapeRevision[]; next?: string | null } & Record<string, unknown>+ > {+ const params = new URLSearchParams({ limit: String(options.limit ?? 50) });+ if (options.offset != null) {+ params.set("offset", String(options.offset));+ }+ if (options.after) {+ params.set("after", options.after);+ }+ return this.request<+ { items: OnshapeRevision[]; next?: string | null } & Record<+ string,+ unknown+ >+ >(+ "GET",+ `/api/v10/revisions/companies/${onshapeCompanyId}?${params.toString()}`+ );+ }++ // Follow Onshape's own pagination cursor (the `next` URL from+ // getCompanyRevisions). Onshape caps `offset` at 100 and its `next` advances by+ // `after=<date>&offset=1`, so following the cursor — NOT incrementing offset — is+ // the only way to page a company's full revision history. `next` is an absolute+ // cad.onshape.com URL; axios uses it as-is (same host, so the auth header applies).+ async getCompanyRevisionsPage(+ nextUrl: string+ ): Promise<+ { items: OnshapeRevision[]; next?: string | null } & Record<string, unknown>+ > {+ return this.request<+ { items: OnshapeRevision[]; next?: string | null } & Record<+ string,+ unknown+ >+ >("GET", nextUrl);+ }++ // --- Release-asset export ---------------------------------------------------+ // Onshape's api/v10 translation API. Version-scoped (/v/) to match+ // getBillOfMaterials — released assets live at a version. The async flow:+ // create translation -> poll getTranslation until requestState DONE ->+ // download the result.+ //+ // Behavior confirmed against live translations of a Part Studio and a+ // released Assembly at a version (a revision's canExport:false is a UI flag,+ // not an API gate — export succeeds):+ // - POST returns { id, requestState: "ACTIVE" };+ // - getTranslation polls requestState ACTIVE -> DONE;+ // - with storeInDocument=false the DONE result is at resultExternalDataIds[],+ // downloaded from resultDocumentId via downloadExternalData(). Completions+ // are typically seconds, so poll-with-backoff is sufficient (no+ // translation.complete webhook needed).+ // Untested paths (low risk):+ // - single-part export via `partIds` (whole-Part-Studio export is confirmed);+ // - drawing (PDF) translation — same pattern, but not yet exercised against+ // a live DRAWING element.++ // Parts inside a Part Studio: bridges geometry addressing (part `id` = partId)+ // and business identity (`partNumber`, the Onshape<->Carbon join key).+ async getParts(+ documentId: string,+ versionId: string,+ elementId: string+ ): Promise<OnshapePart[]> {+ return this.request<OnshapePart[]>(+ "GET",+ `/api/v10/parts/d/${documentId}/v/${versionId}/e/${elementId}`+ );+ }++ async createPartStudioTranslation(+ documentId: string,+ versionId: string,+ elementId: string,+ options: {+ formatName?: OnshapeModelTranslationFormat;+ storeInDocument?: boolean;+ configuration?: string;+ resolution?: OnshapeMeshResolution;+ // FLAGGED: single-part export support unverified. Omit to export the whole+ // Part Studio; the reliable documented path is a whole-Part-Studio translation.+ partIds?: string;+ } = {}+ ): Promise<OnshapeTranslation> {+ return this.request<OnshapeTranslation>(+ "POST",+ `/api/v10/partstudios/d/${documentId}/v/${versionId}/e/${elementId}/translations`,+ {+ formatName: options.formatName ?? "GLTF",+ storeInDocument: options.storeInDocument ?? false,+ // Mesh exports (GLTF) REQUIRE tessellation detail — without it Onshape+ // fails the translation with "Invalid GLTF detail parameters were+ // specified" (verified live). "medium" mirrors the Onshape UI default.+ resolution: options.resolution ?? "medium",+ ...(options.configuration+ ? { configuration: options.configuration }+ : {}),+ ...(options.partIds ? { partIds: options.partIds } : {})+ }+ );+ }++ async createAssemblyTranslation(+ documentId: string,+ versionId: string,+ elementId: string,+ options: {+ formatName?: OnshapeModelTranslationFormat;+ storeInDocument?: boolean;+ configuration?: string;+ resolution?: OnshapeMeshResolution;+ } = {}+ ): Promise<OnshapeTranslation> {+ return this.request<OnshapeTranslation>(+ "POST",+ `/api/v10/assemblies/d/${documentId}/v/${versionId}/e/${elementId}/translations`,+ {+ formatName: options.formatName ?? "GLTF",+ storeInDocument: options.storeInDocument ?? false,+ // Same requirement as the Part Studio path — see comment there.+ resolution: options.resolution ?? "medium",+ ...(options.configuration+ ? { configuration: options.configuration }+ : {})+ }+ );+ }++ async createDrawingTranslation(+ documentId: string,+ versionId: string,+ elementId: string,+ options: {+ formatName?: OnshapeDrawingTranslationFormat;+ storeInDocument?: boolean;+ } = {}+ ): Promise<OnshapeTranslation> {+ return this.request<OnshapeTranslation>(+ "POST",+ `/api/v10/drawings/d/${documentId}/v/${versionId}/e/${elementId}/translations`,+ {+ formatName: options.formatName ?? "PDF",+ storeInDocument: options.storeInDocument ?? false+ }+ );+ }++ async getTranslation(translationId: string): Promise<OnshapeTranslation> {+ return this.request<OnshapeTranslation>(+ "GET",+ `/api/v10/translations/${translationId}`+ );+ }++ // Binary download for storeInDocument=false results (GLTF/PDF bytes). Uses the+ // axios instance directly with arraybuffer — the shared `request` helper is+ // JSON-oriented and would corrupt binary. `maxBytes` bounds the download via+ // axios maxContentLength: when Onshape sends Content-Length the request+ // aborts before the body transfers; otherwise it aborts as soon as the cap+ // is crossed — either way a multi-GB assembly export never gets buffered.+ async downloadExternalData(+ documentId: string,+ foreignId: string,+ options: { maxBytes?: number } = {}+ ): Promise<ArrayBuffer> {+ try {+ const response = await this.axiosInstance.request<ArrayBuffer>({+ method: "GET",+ url: `/api/v10/documents/d/${documentId}/externaldata/${foreignId}`,+ responseType: "arraybuffer",+ ...(options.maxBytes ? { maxContentLength: options.maxBytes } : {})+ });+ return response.data;+ } catch (error) {+ if (+ options.maxBytes &&+ error instanceof Error &&+ /maxContentLength/i.test(error.message)+ ) {+ throw new OnshapeAssetTooLargeError(+ `Onshape external data ${foreignId} exceeds the ${Math.round(+ options.maxBytes / (1024 * 1024)+ )}MB limit`+ );+ }+ throw this.toApiError(error);+ }+ }++ // Onshape-rendered element thumbnail at a version (shaded view PNG). Lets the+ // sync set an item thumbnail with one small API call instead of screenshotting+ // the viewer against the full decoded mesh (the model-thumbnail pipeline).+ // `size` is a WxH string from Onshape's fixed set (e.g. "300x300").+ async getElementThumbnail(+ documentId: string,+ versionId: string,+ elementId: string,+ size: string = "300x300"+ ): Promise<ArrayBuffer> {+ try {+ const response = await this.axiosInstance.request<ArrayBuffer>({+ method: "GET",+ url: `/api/v10/thumbnails/d/${documentId}/v/${versionId}/e/${elementId}/s/${size}`,+ responseType: "arraybuffer",+ headers: { Accept: "image/png" }+ });+ return response.data;+ } catch (error) {+ throw this.toApiError(error);+ }+ }++ // Stream external data to a file on disk — for results too large to buffer+ // in memory (e.g. a multi-GB GLTF export destined for compression, not+ // attachment). Aborts with OnshapeAssetTooLargeError as soon as the+ // Content-Length header (or the byte count, when the header is absent)+ // crosses `maxBytes`. Returns the number of bytes written.+ async downloadExternalDataToFile(+ documentId: string,+ foreignId: string,+ destinationPath: string,+ options: { maxBytes: number }+ ): Promise<number> {+ const { createWriteStream } = await import("node:fs");+ const { pipeline } = await import("node:stream/promises");+ const { Transform } = await import("node:stream");++ let response: {+ headers: Record<string, unknown>;+ data: NodeJS.ReadableStream;+ };+ try {+ response = await this.axiosInstance.request({+ method: "GET",+ url: `/api/v10/documents/d/${documentId}/externaldata/${foreignId}`,+ responseType: "stream"+ });+ } catch (error) {+ throw this.toApiError(error);+ }++ const tooLarge = () =>+ new OnshapeAssetTooLargeError(+ `Onshape external data ${foreignId} exceeds the ${Math.round(+ options.maxBytes / (1024 * 1024)+ )}MB limit`+ );++ const contentLength = Number(response.headers["content-length"]);+ if (Number.isFinite(contentLength) && contentLength > options.maxBytes) {+ (response.data as unknown as { destroy: () => void }).destroy();+ throw tooLarge();+ }++ let bytesWritten = 0;+ const byteCounter = new Transform({+ transform(chunk: Buffer, _encoding, callback) {+ bytesWritten += chunk.byteLength;+ if (bytesWritten > options.maxBytes) {+ callback(tooLarge());+ return;+ }+ callback(null, chunk);+ }+ });++ await pipeline(+ response.data,+ byteCounter,+ createWriteStream(destinationPath)+ );+ return bytesWritten;+ }+static async refreshAccessToken(refreshToken: string): Promise<{access_token: string;refresh_token: string;diff --git a/packages/ee/src/onshape/lib/element.type.ts b/packages/ee/src/onshape/lib/element.type.tsindex 69c2459aad..1dfb8ffec5 100644--- a/packages/ee/src/onshape/lib/element.type.ts+++ b/packages/ee/src/onshape/lib/element.type.ts@@ -9,5 +9,6 @@ export interface OnshapeElement extends OnshapeDocument {export enum OnshapeElementType {ASSEMBLY = "ASSEMBLY",- PART_STUDIO = "PARTSTUDIO"+ PART_STUDIO = "PARTSTUDIO",+ DRAWING = "DRAWING"}diff --git a/packages/ee/src/types.ts b/packages/ee/src/types.tsindex 96fc46fc01..e0ff66af55 100644--- a/packages/ee/src/types.ts+++ b/packages/ee/src/types.ts@@ -5,6 +5,11 @@ export type IntegrationAction = {label: string;description: string;endpoint: string;+ /**+ * Name of a boolean setting that must be enabled for this action to be shown.+ * Omit to always show the action on an installed integration.+ */+ enabledWhenSetting?: string;};/**diff --git a/packages/env/src/index.ts b/packages/env/src/index.tsindex abaf61b851..e9853c8a4d 100644--- a/packages/env/src/index.ts+++ b/packages/env/src/index.ts@@ -238,6 +238,15 @@ export const ONSHAPE_CLIENT_SECRET = getEnv("ONSHAPE_CLIENT_SECRET", {export const ONSHAPE_OAUTH_REDIRECT_URL = getEnv("ONSHAPE_OAUTH_REDIRECT_URL", {isRequired: false});+// Path to the native gltfpack binary (github.com/zeux/meshoptimizer), used to+// compress oversized Onshape GLTF exports into viewer-ready GLBs. Optional:+// when unset (and gltfpack isn't on PATH), oversized models are skipped+// instead of compressed. The npm gltfpack is WASM with a 4GB memory ceiling+// and cannot process large CAD exports — this must point to a native build.+export const GLTFPACK_PATH = getEnv("GLTFPACK_PATH", {+ isRequired: false,+ isSecret: false+});export const QUICKBOOKS_CLIENT_ID = getEnv("QUICKBOOKS_CLIENT_ID", {isRequired: falsediff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 2f9f8311c4..f4f1d8f8af 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -1,6 +1,6 @@# @carbon/jobs-Background job system built on Inngest. Handles event system processing (webhooks, sync, search, audit, embeddings), integrations (Jira, Linear, Xero, Slack), notifications, scheduled tasks, and async workflows.+Background job system built on Inngest. Handles event system processing (webhooks, sync, search, audit, embeddings), integrations (Jira, Linear, Xero, Slack, Onshape), notifications, scheduled tasks, and async workflows.## Alwaysdiff --git a/packages/jobs/src/inngest/functions/integrations/index.ts b/packages/jobs/src/inngest/functions/integrations/index.tsindex 59f0e36df0..1da35552ab 100644--- a/packages/jobs/src/inngest/functions/integrations/index.ts+++ b/packages/jobs/src/inngest/functions/integrations/index.ts@@ -1,6 +1,8 @@export { accountingBackfillFunction } from "./accounting-backfill";export { jiraSyncFunction, syncIssueFromJiraSchema } from "./jira";export { linearSyncFunction, syncIssueFromLinearSchema } from "./linear";+export { onshapeBackfillFunction } from "./onshape-backfill";+export { onshapeRevisionSyncFunction } from "./onshape-revision-sync";export { paperlessPartsFunction } from "./paperless-parts";export {slackDocumentAssignmentUpdateFunction,diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts b/packages/jobs/src/inngest/functions/integrations/onshape-attach.tsnew file mode 100644index 0000000000..486955208d--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/onshape-attach.ts@@ -0,0 +1,422 @@+import { openAsBlob } from "node:fs";+import type { Database } from "@carbon/database";+import type { SupabaseClient } from "@supabase/supabase-js";+import { nanoid } from "nanoid";+import { resolveModelSourceBucket } from "../tasks/assembler-client";++// Carbon-side attachment of Onshape released assets to an item. Lives in+// @carbon/jobs (not @carbon/ee): it needs the service-role client + document+// writes, and the release-sync/backfill Inngest functions (its callers) live here.+//+// The caller (release-sync job) is responsible for:+// - resolving `itemId` by matching the Onshape part number + revision against+// item.readableIdWithRevision (LINK-ONLY: skip if no match, do NOT create);+// - downloading the GLTF/PDF from Onshape (OnshapeClient export methods);+// - sending the "carbon/model-optimize" event for the returned modelUploadId+// (the assembler turns the raw export into the viewer GLB) and the+// "carbon/model-thumbnail" fallback (both via step.sendEvent).++type CarbonClient = SupabaseClient<Database>;+type DocumentSourceType = Database["public"]["Enums"]["documentSourceType"];++export interface OnshapeAssetFile {+ fileName: string;+ bytes: Uint8Array;+}++// Raw model export on disk. Streamed into storage via openAsBlob — a+// whole-vehicle GLTF export reaches 1.7GB and must never be buffered in memory.+export interface OnshapeModelFile {+ fileName: string;+ localPath: string;+ size: number;+}++export interface AttachOnshapeAssetsInput {+ companyId: string;+ createdBy: string; // userId for audit (the Onshape integration installer)+ itemId: string; // resolved Carbon item (caller guarantees it exists)+ sourceDocument: DocumentSourceType; // e.g. "Part"+ model?: OnshapeModelFile; // raw GLTF -> item's modelUpload (optimized by the assembler)+ documents?: OnshapeAssetFile[]; // drawing PDFs -> item documents+}++export interface AttachOnshapeAssetsResult {+ modelUploadId: string | null;+ documentIds: string[];+ preservedPriorModelAsDocument: boolean;+}++const BUCKET = "private";+// Raw model sources live in temp-staging (same as manual CadModel uploads); the+// model-optimize job reads from there and later zstd-compacts the raw in place.+const STAGING_BUCKET = "temp-staging";++function modelContentType(extension: string): string {+ return extension === "glb" ? "model/gltf-binary" : "model/gltf+json";+}++function fileExtension(fileName: string): string {+ const lastDot = fileName.lastIndexOf(".");+ return lastDot >= 0 ? fileName.slice(lastDot + 1).toLowerCase() : "";+}++// Mirrors ~/utils/string stripSpecialCharacters (app-only, not importable here):+// keep only characters valid for storage (S3) keys.+function stripSpecialCharacters(inputString: string): string {+ return inputString.replace(/[^a-zA-Z0-9/!_\-.*'() &$@=;:+,?]/g, "");+}++// document.type is a required `documentType` enum (NOT generated). Our synced+// assets are drawing PDFs or CAD models; map explicitly since the filename->enum+// helper (shared.service.ts) is app-only and not importable here.+function documentTypeForFile(+ fileName: string+): Database["public"]["Enums"]["documentType"] {+ return fileExtension(fileName) === "pdf" ? "PDF" : "Other";+}++// "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.+async function upsertSyncedDocument(+ carbon: CarbonClient,+ row: {+ path: string;+ name: string;+ size: number;+ sourceDocument: DocumentSourceType;+ sourceDocumentId: string;+ companyId: string;+ userId: string;+ groups: string[];+ }+): Promise<string> {+ const existing = await carbon+ .from("document")+ .select("id")+ .eq("companyId", row.companyId)+ .eq("path", row.path)+ .limit(1)+ .maybeSingle();+ if (existing.error) {+ throw new Error(+ `upsertSyncedDocument: lookup failed (${row.path}): ${existing.error.message}`+ );+ }++ if (existing.data?.id) {+ const updated = await carbon+ .from("document")+ .update({+ name: row.name,+ size: row.size,+ type: documentTypeForFile(row.name),+ updatedBy: row.userId,+ updatedAt: new Date().toISOString()+ })+ .eq("id", existing.data.id)+ .eq("companyId", row.companyId);+ if (updated.error) {+ throw new Error(+ `upsertSyncedDocument: update failed (${row.path}): ${updated.error.message}`+ );+ }+ return existing.data.id;+ }++ const inserted = await carbon+ .from("document")+ .insert({+ path: row.path,+ name: row.name,+ size: row.size,+ type: documentTypeForFile(row.name),+ sourceDocument: row.sourceDocument,+ sourceDocumentId: row.sourceDocumentId,+ companyId: row.companyId,+ createdBy: row.userId,+ readGroups: row.groups,+ writeGroups: row.groups+ })+ .select("id")+ .single();+ if (inserted.error) {+ throw new Error(+ `upsertSyncedDocument: insert failed (${row.path}): ${inserted.error.message}`+ );+ }+ return inserted.data.id;+}++// Store an Onshape-rendered thumbnail for a modelUpload, matching the+// model-thumbnail pipeline's path convention+// ({companyId}/thumbnails/{modelId}/{modelId}.png) so both producers are+// interchangeable to consumers of modelUpload.thumbnailPath.+export async function attachModelThumbnail(+ carbon: CarbonClient,+ input: { companyId: string; modelUploadId: string; pngBytes: Uint8Array }+): Promise<void> {+ const thumbnailPath = `${input.companyId}/thumbnails/${input.modelUploadId}/${input.modelUploadId}.png`;+ const uploaded = await carbon.storage+ .from(BUCKET)+ .upload(thumbnailPath, input.pngBytes, {+ upsert: true,+ contentType: "image/png"+ });+ if (uploaded.error) {+ throw new Error(+ `attachModelThumbnail: upload failed (${thumbnailPath}): ${uploaded.error.message}`+ );+ }+ const updated = await carbon+ .from("modelUpload")+ .update({ thumbnailPath })+ .eq("id", input.modelUploadId)+ .eq("companyId", input.companyId);+ if (updated.error) {+ throw new Error(+ `attachModelThumbnail: modelUpload update failed: ${updated.error.message}`+ );+ }+}++export async function attachOnshapeAssetsToItem(+ carbon: CarbonClient,+ input: AttachOnshapeAssetsInput+): Promise<AttachOnshapeAssetsResult> {+ const { companyId, createdBy, itemId, sourceDocument } = input;++ // Company root group -> company-wide document visibility (every employee reaches+ // it via groups_for_user). Note: no Carbon doc is company-visible via [userId];+ // synced release assets are intentionally broader than manual uploads.+ const company = await carbon+ .from("company")+ .select("companyGroupId")+ .eq("id", companyId)+ .single();+ if (company.error || !company.data?.companyGroupId) {+ throw new Error(+ `attachOnshapeAssetsToItem: could not resolve companyGroupId for company ${companyId}`+ );+ }+ const companyGroups = [company.data.companyGroupId];++ const documentIds: string[] = [];+ let modelUploadId: string | null = null;+ let preservedPriorModelAsDocument = false;++ // --- Primary model -> modelUpload + item.modelUploadId --------------------+ // The raw export lands in temp-staging exactly like a manual CadModel upload+ // (path stem == modelUpload.id — the artifacts route derives the id from the+ // filename); the caller then fires "carbon/model-optimize" so the assembler+ // produces the viewer GLB.+ 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.+ const currentItem = await carbon+ .from("item")+ .select("modelUploadId")+ .eq("id", itemId)+ .eq("companyId", companyId)+ .single();+ if (currentItem.error) {+ // Abort rather than treat "lookup failed" as "no prior model" — that+ // would repoint the item without preserving what it currently has.+ throw new Error(+ `attachOnshapeAssetsToItem: item lookup failed for ${itemId}: ${currentItem.error.message}`+ );+ }+ 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+ : 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 (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+ .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}`+ );+ }++ // 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) {+ const preservedName = stripSpecialCharacters(+ priorModel.name ?? `prior-model-${priorModel.id}`+ );+ const preservedPath = `${companyId}/parts/${itemId}/${preservedName}`;+ // Raw sources live in temp-staging since the assembler pipeline;+ // pre-pipeline rows live in private. Copy into private either way so+ // the preserved file sits with the item's documents.+ const priorBucket = await resolveModelSourceBucket(+ carbon,+ priorModel.modelPath+ );+ const copied = await carbon.storage+ .from(priorBucket)+ .copy(priorModel.modelPath, preservedPath, {+ destinationBucket: BUCKET+ });+ if (copied.error && !/already exists/i.test(copied.error.message)) {+ console.error(+ `attachOnshapeAssetsToItem: failed to copy prior model ${priorModel.id} for preservation`,+ copied.error+ );+ } else {+ try {+ const preservedId = await upsertSyncedDocument(carbon, {+ path: preservedPath,+ name: priorModel.name ?? preservedName,+ size: priorModel.size ?? 0,+ sourceDocument,+ sourceDocumentId: itemId,+ companyId,+ userId: createdBy,+ groups: companyGroups+ });+ documentIds.push(preservedId);+ preservedPriorModelAsDocument = true;+ } catch (preserveError) {+ console.error(+ `attachOnshapeAssetsToItem: failed to preserve prior model ${priorModel.id} as a document`,+ preserveError+ );+ }+ }+ }++ const itemLink = await carbon+ .from("item")+ .update({ modelUploadId: modelId })+ .eq("id", itemId)+ .eq("companyId", companyId);+ if (itemLink.error) {+ throw new Error(+ `attachOnshapeAssetsToItem: item model link failed: ${itemLink.error.message}`+ );+ }+ modelUploadId = modelId;+ }+ }++ // --- Documents (drawing PDFs + overflow STEP) -> company-visible rows ------+ for (const document of input.documents ?? []) {+ const safeName = stripSpecialCharacters(document.fileName);+ const documentPath = `${companyId}/parts/${itemId}/${safeName}`;++ const documentUpload = await carbon.storage+ .from(BUCKET)+ .upload(documentPath, document.bytes, { upsert: true });+ if (documentUpload.error) {+ throw new Error(+ `attachOnshapeAssetsToItem: document upload failed (${document.fileName}): ${documentUpload.error.message}`+ );+ }++ const documentId = await upsertSyncedDocument(carbon, {+ path: documentPath,+ name: document.fileName,+ size: document.bytes.byteLength,+ sourceDocument,+ sourceDocumentId: itemId,+ companyId,+ userId: createdBy,+ groups: companyGroups+ });+ documentIds.push(documentId);+ }++ return { modelUploadId, documentIds, preservedPriorModelAsDocument };+}diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts b/packages/jobs/src/inngest/functions/integrations/onshape-backfill.tsnew file mode 100644index 0000000000..9f555c23c0--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/onshape-backfill.ts@@ -0,0 +1,577 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import type { Database } from "@carbon/database";+import {+ getOnshapeClient,+ OnshapeApiError,+ OnshapeAssetTooLargeError+} from "@carbon/ee/onshape";+import type { SupabaseClient } from "@supabase/supabase-js";+import { RetryAfterError } from "inngest";+import { z } from "zod";+import { inngest } from "../../client";+import {+ escapeLikePattern,+ releaseKey,+ sharedNumberSuffix+} from "./onshape-matching";+import {+ syncOnshapeDrawingAssetsToItem,+ syncOnshapeElementAssetsToItem+} from "./onshape-sync-element";++// Backfill / reconcile: pull released Onshape assets onto existing Carbon items.+// Onshape-DRIVEN and LINK-ONLY, and call-light: enumerate the company's released+// revisions from the list endpoint (a few paginated calls), match each to a+// Carbon item LOCALLY by part number (one DB query per page), and only spend+// export calls on matches. Never creates items.+//+// Two modes, same code:+// - Full backfill: omit `after` — pages through all released revisions.+// - Incremental reconcile: pass `after` (ISO date of the last sync) — the list+// endpoint returns only revisions released since, so this is the cheap safety+// net for anything a go-forward webhook missed (no full re-scan).+//+// Step granularity: each page is matched in one fast memoized step (list + DB+// join, no exports), then every matched export+attach runs as its OWN memoized+// step. Inngest executes each step as a separate HTTP call into the app, so a+// single step must stay well under request-timeout territory — one export+// (seconds) is safe where a whole page of exports (potentially many minutes)+// is not. On retry, completed steps replay from cache and work resumes at the+// first unfinished item. onshapeCompanyId auto-resolves via getCompanies when+// omitted.++type CarbonClient = SupabaseClient<Database>;++export interface OnshapeBackfillInput {+ companyId: string; // Carbon company+ userId: string; // Onshape integration installer (auth + audit)+ onshapeCompanyId?: string; // resolved via getCompanies if omitted+ after?: string; // ISO date — only revisions released after this (incremental)+ pageLimit?: number; // revisions per page (default 50)+}++// One matched export+attach, produced by the page-match step and executed as+// its own Inngest step.+export interface OnshapeBackfillWorkItem {+ kind: "model" | "drawing";+ label: string; // for logs, e.g. "model PRT-002033 rev A"+ itemId: string; // resolved Carbon item+ documentId: string;+ versionId: string;+ elementId: string;+ modelElementKind?: "partstudio" | "assembly"; // kind === "model" only+ assetBaseName?: string;+}++export interface OnshapeBackfillPageResult {+ revisionsScanned: number;+ skippedNoItem: number; // released in Onshape but no matching Carbon item (link-only)+ skippedAlreadySynced: number; // item already has this asset — skipped to save API calls+ skippedNonModel: number; // unknown element type (not part studio / assembly / drawing)+ workItems: OnshapeBackfillWorkItem[]; // matched exports for the per-item sync steps+ hasMore: boolean;+ nextCursor: string | null; // Onshape `next` cursor URL for the following page+}++const RATE_LIMIT_DEFAULT_WAIT_SECONDS = 60;+// Clamp Onshape's Retry-After so a bad/huge value can't schedule an absurd wait.+const RATE_LIMIT_MAX_WAIT_SECONDS = 300;+const MAX_CONSECUTIVE_FAILURES = 5;++// On a 429, surface it to Inngest as a RetryAfterError rather than blocking the+// step with an in-process sleep. Inngest SUSPENDS the function — releasing its+// compute window and the per-company concurrency slot — and reschedules it after+// the delay; the memoized steps mean it resumes at the first unfinished item, and+// every export/attach is idempotent so a re-run is safe. The wait honors Onshape's+// Retry-After (default 60s), clamped to a sane maximum. Anything else rethrows.+export async function withRateLimitRetry<T>(+ operation: () => Promise<T>,+ label: string+): Promise<T> {+ try {+ return await operation();+ } catch (error) {+ if (error instanceof OnshapeApiError && error.status === 429) {+ const waitSeconds = Math.min(+ error.retryAfterSeconds ?? RATE_LIMIT_DEFAULT_WAIT_SECONDS,+ RATE_LIMIT_MAX_WAIT_SECONDS+ );+ throw new RetryAfterError(+ `onshape: rate limited on ${label}; retrying after ${waitSeconds}s`,+ waitSeconds * 1000,+ { cause: error }+ );+ }+ throw error;+ }+}++// Shared gate for the Onshape asset-sync jobs: run only when the integration is+// active AND asset sync is enabled. One definition so the backfill and go-forward+// gates can't silently drift apart.+export async function isOnshapeAssetSyncEnabled(+ carbon: CarbonClient,+ companyId: string+): Promise<boolean> {+ const integration = await carbon+ .from("companyIntegration")+ .select("active, metadata")+ .eq("id", "onshape")+ .eq("companyId", companyId)+ .maybeSingle();+ const metadata = (integration.data?.metadata ?? {}) as Record<+ string,+ unknown+ >;+ return (+ Boolean(integration.data?.active) && metadata.assetSyncEnabled === true+ );+}++export async function resolveOnshapeCompanyId(+ carbon: CarbonClient,+ input: Pick<OnshapeBackfillInput, "companyId" | "userId">+): Promise<string> {+ // Prefer the company id captured at connect (explicit + stable) over guessing+ // getCompanies()[0], which is ambiguous for multi-company Onshape accounts.+ const stored = await carbon+ .from("companyIntegration")+ .select("metadata")+ .eq("id", "onshape")+ .eq("companyId", input.companyId)+ .maybeSingle();+ const storedCompanyId = (+ stored.data?.metadata as Record<string, unknown> | undefined+ )?.onshapeCompanyId;+ if (typeof storedCompanyId === "string" && storedCompanyId) {+ return storedCompanyId;+ }++ const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);+ if (onshape.error || !onshape.client) {+ throw new Error(+ `resolveOnshapeCompanyId: getOnshapeClient failed: ${+ onshape.error ?? "no client"+ }`+ );+ }+ const companies = await onshape.client.getCompanies();+ const onshapeCompanyId = companies[0]?.id;+ if (!onshapeCompanyId) {+ throw new Error(+ "resolveOnshapeCompanyId: could not resolve an Onshape company id — pass onshapeCompanyId explicitly"+ );+ }+ return onshapeCompanyId;+}++// Does this item already have a drawing PDF attached? Lets the backfill skip+// re-exporting a drawing it already has (Onshape API quota is limited).+async function itemHasPdfDocument(+ carbon: CarbonClient,+ companyId: string,+ itemId: string+): Promise<boolean> {+ const docs = await carbon+ .from("document")+ .select("id")+ .eq("companyId", companyId)+ .eq("type", "PDF")+ .like("path", `${escapeLikePattern(`${companyId}/parts/${itemId}/`)}%`)+ .limit(1);+ return (docs.data?.length ?? 0) > 0;+}++// One page of the backfill: fetch a page of released revisions and match them to+// Carbon items locally (no exports here — those run as per-item steps). Exported+// so the Inngest function can run each page match as its own memoized step.+export async function matchOnshapeBackfillPage(+ carbon: CarbonClient,+ input: OnshapeBackfillInput & { onshapeCompanyId: string },+ cursor: string | null+): Promise<OnshapeBackfillPageResult> {+ const pageLimit = input.pageLimit ?? 50;++ const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);+ if (onshape.error || !onshape.client) {+ throw new Error(+ `matchOnshapeBackfillPage: getOnshapeClient failed: ${+ onshape.error ?? "no client"+ }`+ );+ }+ const client = onshape.client;++ // Follow Onshape's own `next` cursor rather than incrementing offset — Onshape+ // caps `offset` at 100, and its `next` advances via `after=<date>&offset=1`. The+ // first page (cursor === null) starts from the given `after`; each subsequent+ // page is fetched from the previous page's `next` URL.+ const page = await withRateLimitRetry(+ () =>+ cursor+ ? client.getCompanyRevisionsPage(cursor)+ : client.getCompanyRevisions(input.onshapeCompanyId, {+ limit: pageLimit,+ after: input.after+ }),+ cursor ? "revisions next page" : "revisions first page"+ );+ const pageItems = page.items ?? [];+ // Onshape's `next` presence is authoritative for whether more pages exist (a+ // full page can be entirely obsolete revisions and still have more behind it).+ const nextCursor = page.next ?? null;+ const hasMore = Boolean(nextCursor);+ const revisions = pageItems.filter((revision) => !revision.isObsolete);++ const result: OnshapeBackfillPageResult = {+ revisionsScanned: 0,+ skippedNoItem: 0,+ skippedAlreadySynced: 0,+ skippedNonModel: 0,+ workItems: [],+ hasMore,+ nextCursor+ };+ if (revisions.length === 0) {+ return result;+ }++ // Match this page's MODEL revisions (part studios/assemblies) to Carbon items+ // in one query (local join). modelUploadId lets us skip already-synced models+ // without an Onshape call. Drawings are matched separately by shared number.+ const modelKeys = Array.from(+ new Set(+ revisions+ .filter(+ (revision) => revision.elementType === 0 || revision.elementType === 1+ )+ .map((revision) => releaseKey(revision.partNumber, revision.revision))+ )+ );+ const itemByKey = new Map<+ string,+ { id: string; modelUploadId: string | null }+ >();+ if (modelKeys.length > 0) {+ const carbonItems = await carbon+ .from("item")+ .select("id, readableIdWithRevision, modelUploadId")+ .eq("companyId", input.companyId)+ .in("readableIdWithRevision", modelKeys);+ if (carbonItems.error) {+ throw new Error(+ `matchOnshapeBackfillPage: item match query failed: ${carbonItems.error.message}`+ );+ }+ for (const item of carbonItems.data ?? []) {+ if (item.readableIdWithRevision) {+ itemByKey.set(item.readableIdWithRevision, {+ id: item.id,+ modelUploadId: item.modelUploadId+ });+ }+ }+ }++ for (const revision of revisions) {+ result.revisionsScanned++;++ // DRAWING (elementType 2): released as its own DRW-xxxx element. Attach its+ // PDF to the model item sharing its number (PRT/ASM); never create a DRW item.+ if (revision.elementType === 2) {+ const suffix = sharedNumberSuffix(revision.partNumber);+ if (suffix.length < 2) {+ result.skippedNoItem++;+ continue;+ }+ const candidates = await carbon+ .from("item")+ .select("id, readableIdWithRevision")+ .eq("companyId", input.companyId)+ .eq("revision", revision.revision)+ .ilike("readableId", `%${escapeLikePattern(suffix)}`);+ if (candidates.error) {+ throw new Error(+ `matchOnshapeBackfillPage: drawing item match query failed: ${candidates.error.message}`+ );+ }+ const items = candidates.data ?? [];+ // Exactly-one match only; 0 or >1 (ambiguous) is not safe to attach.+ const target = items.length === 1 ? items[0] : undefined;+ if (!target) {+ result.skippedNoItem++;+ continue;+ }+ // Already has a drawing PDF => skip the export (save an Onshape call).+ if (await itemHasPdfDocument(carbon, input.companyId, target.id)) {+ result.skippedAlreadySynced++;+ continue;+ }+ result.workItems.push({+ kind: "drawing",+ label: `drawing ${revision.partNumber} rev ${revision.revision}`,+ itemId: target.id,+ documentId: revision.documentId,+ versionId: revision.versionId,+ elementId: revision.elementId,+ assetBaseName: target.readableIdWithRevision ?? undefined+ });+ continue;+ }++ // MODEL (elementType 0 = part studio, 1 = assembly). Anything else is an+ // element type we don't export.+ if (revision.elementType !== 0 && revision.elementType !== 1) {+ result.skippedNonModel++;+ continue;+ }+ const match = itemByKey.get(+ releaseKey(revision.partNumber, revision.revision)+ );+ if (!match) {+ result.skippedNoItem++;+ continue;+ }+ // Already has a model => skip the export (save an Onshape call).+ if (match.modelUploadId) {+ result.skippedAlreadySynced++;+ continue;+ }+ result.workItems.push({+ kind: "model",+ label: `model ${revision.partNumber} rev ${revision.revision}`,+ itemId: match.id,+ documentId: revision.documentId,+ versionId: revision.versionId,+ elementId: revision.elementId,+ modelElementKind: revision.elementType === 1 ? "assembly" : "partstudio",+ assetBaseName: releaseKey(revision.partNumber, revision.revision)+ });+ }++ return result;+}++// One matched export+attach — the body of a per-item Inngest step. An export+// that exceeds Carbon's upload limits returns `skippedTooLarge` instead of+// throwing: the skip is permanent (a retry can't shrink the asset), so it must+// not fail the step and burn retries/quota.+export async function syncOnshapeBackfillWorkItem(+ carbon: CarbonClient,+ input: Pick<OnshapeBackfillInput, "companyId" | "userId">,+ workItem: OnshapeBackfillWorkItem+): Promise<{+ modelUploadId: string | null;+ thumbnailAttached?: boolean; // Onshape-rendered thumbnail stored — no fallback event needed+ skippedTooLarge?: boolean;+}> {+ try {+ if (workItem.kind === "drawing") {+ const attached = await withRateLimitRetry(+ () =>+ syncOnshapeDrawingAssetsToItem(carbon, {+ companyId: input.companyId,+ userId: input.userId,+ itemId: workItem.itemId,+ sourceDocument: "Part",+ documentId: workItem.documentId,+ versionId: workItem.versionId,+ drawingElementId: workItem.elementId,+ assetBaseName: workItem.assetBaseName+ }),+ workItem.label+ );+ return { modelUploadId: attached.modelUploadId };+ }++ const attached = await withRateLimitRetry(+ () =>+ syncOnshapeElementAssetsToItem(carbon, {+ companyId: input.companyId,+ userId: input.userId,+ itemId: workItem.itemId,+ sourceDocument: "Part", // v1: released items are parts/assemblies+ documentId: workItem.documentId,+ versionId: workItem.versionId,+ modelElementId: workItem.elementId,+ modelElementKind: workItem.modelElementKind ?? "partstudio",+ assetBaseName: workItem.assetBaseName+ }),+ workItem.label+ );+ return {+ modelUploadId: attached.modelUploadId,+ thumbnailAttached: attached.thumbnailAttached+ };+ } catch (syncError) {+ if (syncError instanceof OnshapeAssetTooLargeError) {+ console.warn(+ `syncOnshapeBackfillWorkItem: skipping oversized ${workItem.label}: ${syncError.message}`+ );+ return { modelUploadId: null, skippedTooLarge: true };+ }+ throw syncError;+ }+}++// --- Inngest function -------------------------------------------------------+// CONFIGURABLE: runs only when the company has explicitly enabled Onshape asset+// sync (companyIntegration.metadata.assetSyncEnabled === true) and the integration+// is active. Default is OFF — nothing runs unless turned on. Fired via+// trigger("onshape-backfill", { companyId, userId, after? }).++const OnshapeBackfillPayloadSchema = z.object({+ companyId: z.string(),+ userId: z.string(),+ onshapeCompanyId: z.string().optional(),+ after: z.string().optional(),+ pageLimit: z.number().optional()+});++export const onshapeBackfillFunction = inngest.createFunction(+ {+ id: "onshape-backfill",+ // Higher than the usual 3: a 429 now reschedules the run via RetryAfterError+ // (withRateLimitRetry), and that reschedule counts against this budget. A big+ // first-time backfill can hit the rate limit a few times, so give it headroom+ // to ride those out before giving up (a failed run resumes cleanly on re-run —+ // already-synced items are skipped).+ retries: 10,+ // One backfill per company at a time — stops a double-click (or a full run+ // overlapping an incremental reconcile) from racing on the "already synced"+ // check and double-exporting.+ concurrency: { key: "event.data.companyId", limit: 1 }+ },+ { event: "carbon/onshape-backfill" },+ async ({ event, step }) => {+ const payload = OnshapeBackfillPayloadSchema.parse(event.data);+ const carbon = getCarbonServiceRole();++ // Gate check runs on every execution (not inside a step) so flipping the+ // toggle off also kills an in-flight retry.+ if (!(await isOnshapeAssetSyncEnabled(carbon, payload.companyId))) {+ console.log("onshape-backfill: skipped (disabled or inactive)", {+ companyId: payload.companyId+ });+ return { skipped: true as const };+ }++ const onshapeCompanyId =+ payload.onshapeCompanyId ??+ (await step.run("resolve-onshape-company", () =>+ resolveOnshapeCompanyId(carbon, payload)+ ));+ const input = { ...payload, onshapeCompanyId };++ const totals = {+ revisionsScanned: 0,+ synced: 0,+ skippedNoItem: 0,+ skippedAlreadySynced: 0,+ skippedNonModel: 0,+ skippedTooLarge: 0, // export exceeds Carbon's upload limits+ failed: 0+ };+ // A failure streak means something systemic (auth, sustained rate limiting,+ // outage) — abort instead of marching the whole catalog burning quota.+ let consecutiveFailures = 0;+ // Follow Onshape's `next` cursor page by page (offset paging is capped at 100).+ let cursor: string | null = null;+ let pageIndex = 0;++ while (true) {+ const currentCursor: string | null = cursor;+ // Fast memoized step: list one page + match locally. No exports in here.+ const pageResult: OnshapeBackfillPageResult = await step.run(+ `backfill-page-${pageIndex}`,+ () => matchOnshapeBackfillPage(carbon, input, currentCursor)+ );++ totals.revisionsScanned += pageResult.revisionsScanned;+ totals.skippedNoItem += pageResult.skippedNoItem;+ totals.skippedAlreadySynced += pageResult.skippedAlreadySynced;+ totals.skippedNonModel += pageResult.skippedNonModel;++ // One memoized step per matched export+attach, so each Inngest HTTP call+ // stays short and a retry resumes at the first unfinished item. A step+ // that exhausts its own retries throws a catchable error here; count it+ // and keep going unless failures look systemic.+ const optimizeModelUploadIds: string[] = [];+ const syncedModelUploadIds: string[] = [];+ for (const [workIndex, workItem] of pageResult.workItems.entries()) {+ try {+ const attached = await step.run(+ `sync-page-${pageIndex}-item-${workIndex}`,+ () => syncOnshapeBackfillWorkItem(carbon, input, workItem)+ );+ consecutiveFailures = 0;+ if (attached.skippedTooLarge) {+ totals.skippedTooLarge++;+ } else {+ totals.synced++;+ }+ // Every attached model is a RAW export — the assembler compresses it+ // into the viewer GLB via model-optimize.+ if (attached.modelUploadId) {+ 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) {+ syncedModelUploadIds.push(attached.modelUploadId);+ }+ } catch (syncError) {+ console.error(+ `onshape-backfill: ${workItem.label} failed`,+ syncError+ );+ totals.failed++;+ consecutiveFailures++;+ if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {+ throw new Error(+ `onshape-backfill: aborting after ${consecutiveFailures} consecutive failures; last error: ${+ syncError instanceof Error+ ? syncError.message+ : String(syncError)+ }`+ );+ }+ }+ }++ if (optimizeModelUploadIds.length > 0) {+ // Same event the manual upload route fires: assembler → meshopt GLB.+ await step.sendEvent(+ `model-optimize-${pageIndex}`,+ optimizeModelUploadIds.map((modelUploadId) => ({+ name: "carbon/model-optimize" as const,+ data: {+ modelUploadId,+ companyId: payload.companyId,+ userId: payload.userId+ }+ }))+ );+ }++ if (syncedModelUploadIds.length > 0) {+ // Every other model path fires model-thumbnail on upload; keep parity.+ await step.sendEvent(+ `model-thumbnails-${pageIndex}`,+ syncedModelUploadIds.map((modelId) => ({+ name: "carbon/model-thumbnail" as const,+ data: { companyId: payload.companyId, modelId }+ }))+ );+ }++ if (!pageResult.hasMore || !pageResult.nextCursor) {+ break;+ }+ cursor = pageResult.nextCursor;+ pageIndex++;+ }++ return totals;+ }+);diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-matching.test.ts b/packages/jobs/src/inngest/functions/integrations/onshape-matching.test.tsnew file mode 100644index 0000000000..4095f7e82c--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/onshape-matching.test.ts@@ -0,0 +1,77 @@+import { describe, expect, it } from "vitest";+import {+ escapeLikePattern,+ releaseKey,+ sharedNumberSuffix+} from "./onshape-matching";++// These three pure helpers are the entire Onshape→Carbon matching contract:+// releaseKey joins a released revision to item.readableIdWithRevision, and+// sharedNumberSuffix + escapeLikePattern decide which model item a released+// drawing attaches to. A wrong match here attaches CAD/drawings to the wrong+// part, so the edge cases are pinned rather than left to convention.++describe("releaseKey", () => {+ it("appends the revision with a dot separator", () => {+ expect(releaseKey("PRT-002033", "A")).toBe("PRT-002033.A");+ expect(releaseKey("PRT-002033", "A2")).toBe("PRT-002033.A2");+ });++ it("omits the revision when it is '0' (Carbon's default revision)", () => {+ expect(releaseKey("PRT-002033", "0")).toBe("PRT-002033");+ });++ it("omits the revision when it is empty, null, or undefined", () => {+ expect(releaseKey("PRT-002033", "")).toBe("PRT-002033");+ expect(releaseKey("PRT-002033", null)).toBe("PRT-002033");+ expect(releaseKey("PRT-002033", undefined)).toBe("PRT-002033");+ });+});++describe("sharedNumberSuffix", () => {+ it("strips the leading letter prefix, keeping the separator as the anchor", () => {+ expect(sharedNumberSuffix("DRW-002033")).toBe("-002033");+ expect(sharedNumberSuffix("ASM-002033")).toBe("-002033");+ expect(sharedNumberSuffix("DRW_002033")).toBe("_002033");+ });++ it("gives a drawing and its model the same suffix (the join key)", () => {+ expect(sharedNumberSuffix("DRW-002033")).toBe(+ sharedNumberSuffix("PRT-002033")+ );+ });++ it("returns '' for a part number with no letter prefix (no anchor)", () => {+ // Without a separator anchor, "%002033" would suffix-match the WRONG item+ // (e.g. "PRT-1002033"), so an unanchored number must be skipped entirely.+ expect(sharedNumberSuffix("002033")).toBe("");+ });++ it("returns '' when letters run straight into digits (no separator)", () => {+ expect(sharedNumberSuffix("DRW002033")).toBe("");+ });++ it("returns '' for empty or all-letter part numbers", () => {+ expect(sharedNumberSuffix("")).toBe("");+ expect(sharedNumberSuffix("DRW")).toBe("");+ });+});++describe("escapeLikePattern", () => {+ it("leaves values without wildcards untouched", () => {+ expect(escapeLikePattern("-002033")).toBe("-002033");+ });++ it("escapes % and _ so they match literally", () => {+ expect(escapeLikePattern("_002033")).toBe("\\_002033");+ expect(escapeLikePattern("PRT%33")).toBe("PRT\\%33");+ });++ it("escapes backslashes so they can't form escape sequences", () => {+ expect(escapeLikePattern("a\\b")).toBe("a\\\\b");+ });++ it("escapes every occurrence, not just the first", () => {+ expect(escapeLikePattern("_a_%b%")).toBe("\\_a\\_\\%b\\%");+ });+});diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-matching.ts b/packages/jobs/src/inngest/functions/integrations/onshape-matching.tsnew file mode 100644index 0000000000..0af2854b95--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/onshape-matching.ts@@ -0,0 +1,40 @@+// Pure helpers that form the Onshape→Carbon matching contract: how a released+// Onshape revision resolves to a Carbon item. Kept free of heavy imports+// (no inngest/auth/env at module load) so they stay unit-testable — see+// onshape-matching.test.ts.++// Carbon's readableIdWithRevision == readableId when revision is empty/'0', else+// readableId + '.' + revision. Onshape's partNumber/revision map 1:1 to those.+export function releaseKey(+ partNumber: string,+ revision: string | null | undefined+): string {+ return revision && revision !== "0"+ ? `${partNumber}.${revision}`+ : partNumber;+}++// A released drawing is its OWN element (DRW-xxxx) sharing the number of the+// model it documents (PRT-xxxx / ASM-xxxx). Strip the leading letter prefix to+// get the shared suffix (e.g. "DRW-002033" -> "-002033"), used to find the model+// item a drawing PDF should attach to (works for both parts and assemblies).+// The suffix MUST start with a non-alphanumeric separator: it is used as the+// tail of a LIKE pattern, and the separator is what anchors it so "-002033"+// can't match "PRT-1002033". A part number with no letter prefix or no+// separator (e.g. "002033") has no safe anchor — return "" so callers skip it.+export function sharedNumberSuffix(partNumber: string): string {+ const suffix = partNumber.replace(/^[A-Za-z]+/, "");+ if (suffix === partNumber || /^[A-Za-z0-9]/.test(suffix)) {+ return "";+ }+ return suffix;+}++// Escape LIKE/ILIKE wildcards so user-controlled values (part numbers, ids)+// match literally — an unescaped "_" would match any single character.+export function escapeLikePattern(value: string): string {+ return value.replace(+ /[\\%_]/g,+ (specialCharacter) => `\\${specialCharacter}`+ );+}diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.tsnew file mode 100644index 0000000000..388b87673b--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/onshape-revision-sync.ts@@ -0,0 +1,323 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import type { Database } from "@carbon/database";+import {+ getOnshapeClient,+ OnshapeAssetTooLargeError+} from "@carbon/ee/onshape";+import type { SupabaseClient } from "@supabase/supabase-js";+import { z } from "zod";+import { inngest } from "../../client";+import {+ isOnshapeAssetSyncEnabled,+ resolveOnshapeCompanyId,+ withRateLimitRetry+} from "./onshape-backfill";+import {+ escapeLikePattern,+ releaseKey,+ sharedNumberSuffix+} from "./onshape-matching";+import {+ syncOnshapeDrawingAssetsToItem,+ syncOnshapeElementAssetsToItem+} from "./onshape-sync-element";++// Go-forward sync: one released Onshape revision ->+// attach its CAD model to the matching Carbon item. LINK-ONLY (never creates+// items). Driven by the onshape.revision.created webhook, which — unlike+// workflow.transition — carries everything the sync core needs: documentId,+// versionId, elementId, elementType (0/1/2), and partNumber.+//+// The one thing the event does NOT carry is the revision LETTER (e.g. "A2"); it+// gives a revisionId. Carbon's readableIdWithRevision match key needs the letter,+// so we resolve it from the per-part revisions API by matching the released+// version/element back to its revision.++type CarbonClient = SupabaseClient<Database>;++export interface OnshapeRevisionSyncInput {+ companyId: string; // Carbon company+ userId: string; // Onshape integration installer (auth + audit)+ partNumber: string;+ documentId: string;+ versionId: string;+ elementId: string;+ elementType: number; // 0 = part studio, 1 = assembly, 2 = drawing+ revisionId?: string;+ onshapeCompanyId?: string; // resolved via getCompanies if omitted+}++export interface OnshapeRevisionSyncResult {+ synced: boolean;+ skippedReason?:+ | "unknown-element"+ | "no-matching-item"+ | "ambiguous-item"+ | "revision-not-found"+ | "asset-too-large"; // export exceeds Carbon's upload limits — permanent skip+ itemId?: string;+ modelUploadId?: string | null;+ thumbnailAttached?: boolean; // Onshape-rendered thumbnail stored — no fallback event needed+ releaseKey?: string;+}++// Onshape elementType is NUMERIC: 0 = Part Studio, 1 = Assembly, 2 = Drawing.+function modelKindForElementType(+ elementType: number+): "partstudio" | "assembly" | null {+ if (elementType === 1) return "assembly";+ if (elementType === 0) return "partstudio";+ return null;+}++export async function runOnshapeRevisionSync(+ carbon: CarbonClient,+ input: OnshapeRevisionSyncInput+): Promise<OnshapeRevisionSyncResult> {+ const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);+ if (onshape.error || !onshape.client) {+ throw new Error(+ `runOnshapeRevisionSync: getOnshapeClient failed: ${+ onshape.error ?? "no client"+ }`+ );+ }+ const client = onshape.client;++ 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.+ 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);++ if (!releasedRevision) {+ return { synced: false, skippedReason: "revision-not-found" };+ }+ const revision = releasedRevision.revision;++ // DRAWING (elementType 2): released as its own DRW-xxxx element. Export it as a+ // PDF and attach it to the MODEL item sharing its number (PRT-xxxx / ASM-xxxx)+ // at the same revision — never create a DRW-xxxx item.+ if (input.elementType === 2) {+ const suffix = sharedNumberSuffix(input.partNumber);+ if (suffix.length < 2) {+ return { synced: false, skippedReason: "no-matching-item" };+ }+ // Match any model item ending in the shared number at this revision. The+ // leading separator in `suffix` (e.g. "-002033") anchors it so "-002033"+ // doesn't match "-1002033"; LIKE wildcards in the part number are escaped+ // so they match literally.+ const candidates = await carbon+ .from("item")+ .select("id, readableIdWithRevision")+ .eq("companyId", input.companyId)+ .eq("revision", revision)+ .ilike("readableId", `%${escapeLikePattern(suffix)}`);+ if (candidates.error) {+ throw new Error(+ `runOnshapeRevisionSync: drawing item match query failed: ${candidates.error.message}`+ );+ }+ const items = candidates.data ?? [];+ if (items.length === 0) {+ return {+ synced: false,+ skippedReason: "no-matching-item",+ releaseKey: releaseKey(input.partNumber, revision)+ };+ }+ if (items.length > 1) {+ // Multiple models share this number + revision — can't safely pick one.+ return { synced: false, skippedReason: "ambiguous-item" };+ }+ const target = items[0];+ if (!target) {+ return { synced: false, skippedReason: "no-matching-item" };+ }+ try {+ const attached = await syncOnshapeDrawingAssetsToItem(carbon, {+ companyId: input.companyId,+ userId: input.userId,+ itemId: target.id,+ sourceDocument: "Part",+ documentId: input.documentId,+ versionId: input.versionId,+ drawingElementId: input.elementId,+ assetBaseName: target.readableIdWithRevision ?? undefined+ });+ return {+ synced: true,+ itemId: target.id,+ modelUploadId: attached.modelUploadId,+ releaseKey: target.readableIdWithRevision ?? undefined+ };+ } catch (syncError) {+ if (syncError instanceof OnshapeAssetTooLargeError) {+ // Permanent: a retry can't shrink the export. Skip, don't fail.+ console.warn(+ `runOnshapeRevisionSync: skipping oversized drawing ${input.partNumber}: ${syncError.message}`+ );+ return { synced: false, skippedReason: "asset-too-large" };+ }+ throw syncError;+ }+ }++ // MODEL (elementType 0 = part studio, 1 = assembly): export compressed GLB + attach.+ const modelElementKind = modelKindForElementType(input.elementType);+ if (!modelElementKind) {+ return { synced: false, skippedReason: "unknown-element" };+ }++ const key = releaseKey(input.partNumber, revision);++ // LINK-ONLY: attach only to an item that already exists. No match => skip.+ const carbonItem = await carbon+ .from("item")+ .select("id")+ .eq("companyId", input.companyId)+ .eq("readableIdWithRevision", key)+ .maybeSingle();+ if (carbonItem.error) {+ throw new Error(+ `runOnshapeRevisionSync: item match query failed: ${carbonItem.error.message}`+ );+ }+ if (!carbonItem.data) {+ return {+ synced: false,+ skippedReason: "no-matching-item",+ releaseKey: key+ };+ }++ let attached: Awaited<ReturnType<typeof syncOnshapeElementAssetsToItem>>;+ try {+ attached = await syncOnshapeElementAssetsToItem(carbon, {+ companyId: input.companyId,+ userId: input.userId,+ itemId: carbonItem.data.id,+ sourceDocument: "Part", // v1: released items are parts/assemblies+ documentId: input.documentId,+ versionId: input.versionId,+ modelElementId: input.elementId,+ modelElementKind,+ assetBaseName: key+ });+ } catch (syncError) {+ if (syncError instanceof OnshapeAssetTooLargeError) {+ // Permanent: a retry can't shrink the export. Skip, don't fail. The+ // drawing PDF (a separate DRW element/event) still attaches normally.+ console.warn(+ `runOnshapeRevisionSync: skipping oversized model ${key}: ${syncError.message}`+ );+ return {+ synced: false,+ skippedReason: "asset-too-large",+ releaseKey: key+ };+ }+ throw syncError;+ }++ return {+ synced: true,+ itemId: carbonItem.data.id,+ modelUploadId: attached.modelUploadId,+ thumbnailAttached: attached.thumbnailAttached,+ releaseKey: key+ };+}++// --- Inngest function -------------------------------------------------------+// CONFIGURABLE + idempotent. Runs only when the company enabled Onshape asset+// sync (companyIntegration.metadata.assetSyncEnabled === true) and the+// integration is active. Deduped on the Onshape webhook messageId so a+// re-delivery doesn't re-export/re-attach. Fired from the webhook receiver via+// trigger("onshape-revision-sync", { ... }).++const OnshapeRevisionSyncPayloadSchema = z.object({+ companyId: z.string(),+ userId: z.string(),+ messageId: z.string(),+ partNumber: z.string(),+ documentId: z.string(),+ versionId: z.string(),+ elementId: z.string(),+ elementType: z.number(),+ revisionId: z.string().optional(),+ onshapeCompanyId: z.string().optional()+});++export const onshapeRevisionSyncFunction = inngest.createFunction(+ {+ id: "onshape-revision-sync",+ retries: 3,+ idempotency: "event.data.messageId",+ // One in-flight sync per released element; different elements run in parallel.+ concurrency: { key: "event.data.elementId", limit: 1 }+ },+ { event: "carbon/onshape-revision-sync" },+ async ({ event, step }) => {+ const payload = OnshapeRevisionSyncPayloadSchema.parse(event.data);+ const carbon = getCarbonServiceRole();++ // Gate check (shared with the backfill): only run when the company turned+ // asset sync on and the integration is active. Runs every execution so+ // flipping the toggle off also kills an in-flight retry.+ if (!(await isOnshapeAssetSyncEnabled(carbon, payload.companyId))) {+ console.log("onshape-revision-sync: skipped (disabled or inactive)", {+ companyId: payload.companyId,+ partNumber: payload.partNumber+ });+ return { skipped: true as const };+ }++ // Wrap in the 429 backoff (same as the backfill's per-item syncs) so a rate+ // limit during export/poll/download backs off instead of bubbling out.+ const result = await step.run("sync-revision", () =>+ withRateLimitRetry(+ () => runOnshapeRevisionSync(carbon, payload),+ `revision ${payload.partNumber}`+ )+ );++ if (result.synced && result.modelUploadId) {+ // The sync stores the RAW Onshape export; the assembler turns it into+ // the meshopt-compressed viewer GLB (same event the manual upload route+ // fires).+ await step.sendEvent("model-optimize", {+ name: "carbon/model-optimize" as const,+ data: {+ modelUploadId: result.modelUploadId,+ companyId: payload.companyId,+ userId: payload.userId+ }+ });+ }++ if (result.synced && result.modelUploadId && !result.thumbnailAttached) {+ // Fallback only: the sync stores Onshape's server-rendered thumbnail+ // itself; the screenshot pipeline runs just when that fetch failed.+ await step.sendEvent("model-thumbnail", {+ name: "carbon/model-thumbnail" as const,+ data: { companyId: payload.companyId, modelId: result.modelUploadId }+ });+ }++ return result;+ }+);diff --git a/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.tsnew file mode 100644index 0000000000..3b3b704f31--- /dev/null+++ b/packages/jobs/src/inngest/functions/integrations/onshape-sync-element.ts@@ -0,0 +1,290 @@+import { mkdtemp, rm, stat } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import type { Database } from "@carbon/database";+import type { OnshapeClient, OnshapeTranslation } from "@carbon/ee/onshape";+import { getOnshapeClient } from "@carbon/ee/onshape";+import { getFileSizeLimit } from "@carbon/utils";+import type { SupabaseClient } from "@supabase/supabase-js";+import {+ type AttachOnshapeAssetsResult,+ attachModelThumbnail,+ attachOnshapeAssetsToItem,+ type OnshapeModelFile+} from "./onshape-attach";++// Export→download→attach for ONE released Onshape element. Wires the OnshapeClient+// export methods (@carbon/ee) to the Carbon-side attach helper. Flow: create+// translation -> poll to DONE -> download from resultDocumentId/+// resultExternalDataIds -> attach. Poll-with-backoff (real completions take+// seconds); no translation.complete webhook needed.+//+// 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.++type CarbonClient = SupabaseClient<Database>;+type DocumentSourceType = Database["public"]["Enums"]["documentSourceType"];++export interface SyncOnshapeElementInput {+ companyId: string;+ userId: string; // Onshape integration installer (auth + audit)+ itemId: string; // resolved Carbon item (caller guarantees it exists)+ sourceDocument: DocumentSourceType; // e.g. "Part"+ documentId: string;+ 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)+ drawingElementIds?: string[]; // optional PDF drawings (untested path — see client.ts)+ assetBaseName?: string; // filename base (e.g. item part number); falls back to Onshape name+}++const POLL_MAX_ATTEMPTS = 40;+const POLL_INITIAL_DELAY_MS = 2000;+const POLL_MAX_DELAY_MS = 15000;++// Size caps — the SAME limits Carbon enforces on manual uploads (CadModel.tsx /+// document upload), since synced assets land in the same buckets. The raw model+// cap is the temp-staging cap (2.5GB); exports past it are skipped permanently+// (drawing PDFs still attach — they are separate elements). Output size is the+// assembler's problem, not ours.+const RAW_MODEL_MAX_BYTES = getFileSizeLimit("CAD_MODEL_UPLOAD").bytes;+const DOCUMENT_MAX_BYTES = getFileSizeLimit("DOCUMENT_UPLOAD").bytes;++async function waitForTranslation(+ client: OnshapeClient,+ translationId: string+): Promise<OnshapeTranslation> {+ let delay = POLL_INITIAL_DELAY_MS;+ for (let attempt = 0; attempt < POLL_MAX_ATTEMPTS; attempt++) {+ const translation = await client.getTranslation(translationId);+ if (translation.requestState === "DONE") {+ return translation;+ }+ if (translation.requestState === "FAILED") {+ throw new Error(+ `Onshape translation ${translationId} FAILED: ${+ translation.failureReason ?? "unknown"+ }`+ );+ }+ await new Promise((resolve) => setTimeout(resolve, delay));+ delay = Math.min(delay * 1.5, POLL_MAX_DELAY_MS);+ }+ throw new Error(+ `Onshape translation ${translationId} did not finish after ${POLL_MAX_ATTEMPTS} polls`+ );+}++async function downloadTranslationBytes(+ client: OnshapeClient,+ translation: OnshapeTranslation,+ maxBytes: number+): Promise<Uint8Array> {+ const foreignId = translation.resultExternalDataIds?.[0];+ const documentId = translation.resultDocumentId;+ if (!foreignId || !documentId) {+ throw new Error(+ `Onshape translation ${translation.id} DONE but has no resultExternalDataIds/resultDocumentId`+ );+ }+ // Throws OnshapeAssetTooLargeError past the cap — callers treat that as a+ // permanent skip (retrying cannot shrink the asset).+ const buffer = await client.downloadExternalData(documentId, foreignId, {+ maxBytes+ });+ return new Uint8Array(buffer);+}++// The one and only model export path: export GLTF from Onshape and stream it+// to disk (a whole-vehicle export can be >1.5GB — it is never buffered in+// memory). The raw export is attached as-is; the assembler pipeline+// ("carbon/model-optimize", fired by the caller) turns it into the+// meshopt-compressed viewer GLB, so no local compression happens here. STEP+// export was deliberately dropped: real assemblies produce multi-GB STEP+// files, and Onshape stays the CAD system of record. Throws+// OnshapeAssetTooLargeError (from the download helper) past the raw cap;+// callers treat that as a permanent skip.+async function exportRawGltfModel(+ client: OnshapeClient,+ input: SyncOnshapeElementInput,+ scratchDir: string+): Promise<OnshapeModelFile> {+ const gltfTranslation =+ input.modelElementKind === "assembly"+ ? await client.createAssemblyTranslation(+ input.documentId,+ input.versionId,+ input.modelElementId,+ { formatName: "GLTF", storeInDocument: false }+ )+ : await client.createPartStudioTranslation(+ input.documentId,+ input.versionId,+ input.modelElementId,+ { formatName: "GLTF", storeInDocument: false }+ );+ const gltfDone = await waitForTranslation(client, gltfTranslation.id);+ const baseName =+ input.assetBaseName ??+ (typeof gltfDone.name === "string" ? gltfDone.name : "model");+ const foreignId = gltfDone.resultExternalDataIds?.[0];+ const resultDocumentId = gltfDone.resultDocumentId;+ if (!foreignId || !resultDocumentId) {+ throw new Error(+ `Onshape GLTF translation ${gltfDone.id} DONE but has no resultExternalDataIds/resultDocumentId`+ );+ }++ const gltfPath = join(scratchDir, "model.gltf");+ await client.downloadExternalDataToFile(+ resultDocumentId,+ foreignId,+ gltfPath,+ { maxBytes: RAW_MODEL_MAX_BYTES }+ );+ const { size } = await stat(gltfPath);+ return {+ fileName: `${baseName}.gltf`,+ localPath: gltfPath,+ size+ };+}++export async function syncOnshapeElementAssetsToItem(+ carbon: CarbonClient,+ input: SyncOnshapeElementInput+): Promise<AttachOnshapeAssetsResult & { thumbnailAttached: boolean }> {+ const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);+ if (onshape.error || !onshape.client) {+ throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);+ }+ const client = onshape.client;++ const scratchDir = await mkdtemp(join(tmpdir(), "onshape-gltf-"));+ try {+ // Raw GLTF is the only model export (STEP was deliberately dropped — see+ // exportRawGltfModel). The assembler pipeline does the compression; the+ // caller fires "carbon/model-optimize" for the returned modelUploadId.+ // Throws OnshapeAssetTooLargeError past the raw cap; callers treat that as+ // a permanent skip.+ const model = await exportRawGltfModel(client, input, scratchDir);+ const baseName = model.fileName.replace(/\.gltf$/, "");++ // Drawings -> PDF (optional; same translation flow, not yet exercised+ // against a live DRAWING element).+ const documents: { fileName: string; bytes: Uint8Array }[] = [];+ for (const drawingElementId of input.drawingElementIds ?? []) {+ const pdfTranslation = await client.createDrawingTranslation(+ input.documentId,+ input.versionId,+ drawingElementId,+ { formatName: "PDF", storeInDocument: false }+ );+ const pdfDone = await waitForTranslation(client, pdfTranslation.id);+ const pdfBytes = await downloadTranslationBytes(+ client,+ pdfDone,+ DOCUMENT_MAX_BYTES+ );+ documents.push({+ fileName: `${baseName}-${drawingElementId}.pdf`,+ bytes: pdfBytes+ });+ }++ const attached = await attachOnshapeAssetsToItem(carbon, {+ companyId: input.companyId,+ createdBy: input.userId,+ itemId: input.itemId,+ sourceDocument: input.sourceDocument,+ model,+ 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.+ let thumbnailAttached = false;+ if (attached.modelUploadId) {+ try {+ const thumbnail = await client.getElementThumbnail(+ input.documentId,+ input.versionId,+ input.modelElementId+ );+ await attachModelThumbnail(carbon, {+ companyId: input.companyId,+ modelUploadId: attached.modelUploadId,+ pngBytes: new Uint8Array(thumbnail)+ });+ thumbnailAttached = true;+ } catch (thumbnailError) {+ console.warn(+ `syncOnshapeElementAssetsToItem: Onshape thumbnail fetch failed for ${baseName}; falling back to the model-thumbnail job`,+ thumbnailError+ );+ }+ }++ return { ...attached, thumbnailAttached };+ } finally {+ await rm(scratchDir, { recursive: true, force: true });+ }+}++export interface SyncOnshapeDrawingInput {+ companyId: string;+ userId: string; // Onshape integration installer (auth + audit)+ itemId: string; // resolved Carbon item (the model this drawing documents)+ sourceDocument: DocumentSourceType; // e.g. "Part"+ documentId: string;+ versionId: string; // the released version+ drawingElementId: string; // the released DRAWING element to export as PDF+ assetBaseName?: string; // filename base (e.g. the model's readableIdWithRevision)+}++// Export ONE released Onshape DRAWING element as a PDF and attach it as a document+// on the given Carbon item. Drawings are released as their own elements (DRW-xxxx,+// elementType 2) separate from the model, so the caller resolves which item the+// drawing belongs to (by shared part number) and passes it here. No model is+// touched — only a PDF document is added/updated (idempotent via the attach+// helper's replace-not-append rule).+export async function syncOnshapeDrawingAssetsToItem(+ carbon: CarbonClient,+ input: SyncOnshapeDrawingInput+): Promise<AttachOnshapeAssetsResult> {+ const onshape = await getOnshapeClient(carbon, input.companyId, input.userId);+ if (onshape.error || !onshape.client) {+ throw new Error(`getOnshapeClient failed: ${onshape.error ?? "no client"}`);+ }+ const client = onshape.client;++ const pdfTranslation = await client.createDrawingTranslation(+ input.documentId,+ input.versionId,+ input.drawingElementId,+ { formatName: "PDF", storeInDocument: false }+ );+ const pdfDone = await waitForTranslation(client, pdfTranslation.id);+ const pdfBytes = await downloadTranslationBytes(+ client,+ pdfDone,+ DOCUMENT_MAX_BYTES+ );+ const baseName = input.assetBaseName ?? pdfDone.name ?? "drawing";++ return attachOnshapeAssetsToItem(carbon, {+ companyId: input.companyId,+ createdBy: input.userId,+ itemId: input.itemId,+ sourceDocument: input.sourceDocument,+ documents: [{ fileName: `${baseName}.pdf`, bytes: pdfBytes }]+ });+}diff --git a/packages/jobs/src/inngest/index.ts b/packages/jobs/src/inngest/index.tsindex f6d84330ab..af649fc13b 100644--- a/packages/jobs/src/inngest/index.ts+++ b/packages/jobs/src/inngest/index.ts@@ -15,6 +15,8 @@ import {accountingBackfillFunction,jiraSyncFunction,linearSyncFunction,+ onshapeBackfillFunction,+ onshapeRevisionSyncFunction,paperlessPartsFunction,slackDocumentAssignmentUpdateFunction,slackDocumentCreatedFunction,@@ -107,6 +109,8 @@ export const functions = [linearSyncFunction,paperlessPartsFunction,accountingBackfillFunction,+ onshapeBackfillFunction,+ onshapeRevisionSyncFunction,syncExternalAccountingFunction,slackDocumentCreatedFunction,slackDocumentStatusUpdateFunction,diff --git a/packages/lib/src/events.ts b/packages/lib/src/events.tsindex 1d520a8b68..d7e3cb98cc 100644--- a/packages/lib/src/events.ts+++ b/packages/lib/src/events.ts@@ -501,6 +501,33 @@ export type Events = {};};+ // Onshape released-asset backfill / reconcile+ "carbon/onshape-backfill": {+ data: {+ companyId: string;+ userId: string;+ onshapeCompanyId?: string;+ after?: string;+ pageLimit?: number;+ };+ };++ // Onshape go-forward sync: one released revision (from the+ // onshape.revision.created webhook) -> attach assets to the matching item+ "carbon/onshape-revision-sync": {+ data: {+ companyId: string;+ userId: string;+ messageId: string; // Onshape webhook messageId — idempotency key+ partNumber: string;+ documentId: string;+ versionId: string;+ elementId: string;+ elementType: number; // 0 = part studio, 1 = assembly, 2 = drawing+ revisionId?: string;+ };+ };+// Sync external accounting (accepts the full AccountingSyncSchema payload)"carbon/sync-external-accounting": {data: {diff --git a/packages/lib/src/trigger.ts b/packages/lib/src/trigger.tsindex feaecf4507..4fae89743c 100644--- a/packages/lib/src/trigger.ts+++ b/packages/lib/src/trigger.ts@@ -19,6 +19,8 @@ const taskToEvent = {"model-optimize": "carbon/model-optimize",notify: "carbon/notify",onboard: "carbon/onboard",+ "onshape-backfill": "carbon/onshape-backfill",+ "onshape-revision-sync": "carbon/onshape-revision-sync","paperless-parts": "carbon/paperless-parts","post-transactions": "carbon/post-transaction","print-job-deliver": "carbon/print-job-deliver",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 3cee2a1ace..a256831537 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2186,6 +2186,9 @@ importers:'@carbon/database':specifier: workspace:*version: link:../database+ '@carbon/env':+ specifier: workspace:*+ version: link:../env'@carbon/kv':specifier: workspace:*version: link:../kv