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): show what Onshape answered when a panel read fails
Raul32ce65739fd1
diff --git a/.claude/rules/onshape-panel.md b/.claude/rules/onshape-panel.mdindex 13dc309716..94796f0c7f 100644--- a/.claude/rules/onshape-panel.md+++ b/.claude/rules/onshape-panel.md@@ -142,6 +142,7 @@ The gateway rejects a request line over 4,096 bytes, and a PostgREST `.in()` lis## Panel UI- Pages: the push page (labelled Parts, Assembly, or Push on any other element, where it says there is nothing to push), Releases (needs a `documentId`) and Fields (settings update, on a Part Studio or assembly). The Carbon company and Sign out sit on the right.+- Errors carry `diagnostics`, shown by `PanelDiagnostics` behind Show details / Copy details together with the panel's own URL parameters and the Carbon host. Sources: every `onshapeFailure` body (`OnshapeFailureDiagnostics`: the read, Onshape's status, the `message` of its error body via `OnshapeApiError.onshapeMessage`, or the transport error when nothing answered; never the raw body), and the missing-columns refusals of `status`, `plan-assembly` and `plan-release` (the request coordinates, `onshapeApi` from `OnshapeClient.apiOrigin`, the missing columns, `describeBomPayload`: payload keys, header ids, names and property names, row count, template id; never a cell value). `plan-release` returns them per unread BOM beside its warnings, and each route logs the same at warn.- The theme follows Onshape's `theme` action-URL parameter: the `onshape+` layout declares `handle.hostMode` and the root renders that mode. Missing means light.- Part badges: Linked, Conflict (same part number, not linked to this source; a push uses that item), Unlinked, and Released (released in Onshape; its Push is disabled because changes come through a release). Release states: In Carbon, Partial, Not in Carbon. The assembly BOM is the structured tree (`panel/bom-view.ts`).- Moving to another element clears a part or assembly review and the Fields state; a release review survives within the same document.diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.tsindex e310b7d5aa..3b19542389 100644--- a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.ts+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-assembly.ts@@ -6,6 +6,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { PlanItemRow, PlanMappingContext } from "@carbon/ee";import {buildAssemblyPlan,+ describeBomPayload,externalIdForAssembly,externalIdForBomLine,flattenNodes,@@ -33,6 +34,7 @@ import {withRefusedMethods} from "@carbon/ee/onshape";import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";+import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { z } from "zod";@@ -42,6 +44,8 @@ export const config = {runtime: "nodejs"};+const logger = getLogger("erp", "integrations-onshape-panel-plan-assembly");+const payloadSchema = z.object({documentId: z.string().min(1),wv: z.enum(["w", "v"]),@@ -112,8 +116,18 @@ export async function action({ request }: ActionFunctionArgs) {const { root: bomRoot, lines, missingColumns } = parseBomTree(bom);// An empty plan from an unreadable tree would drop every Onshape line.if (missingColumns.length > 0) {+ const diagnostics = {+ request: { documentId, wv, wvId, elementId, configuration, depth },+ onshapeApi: onshape.client.apiOrigin,+ missingColumns,+ bom: describeBomPayload(bom)+ };+ logger.warn("Onshape BOM is missing required columns", {+ companyId,+ ...diagnostics+ });return data(- { error: missingBomColumnsMessage(missingColumns) },+ { error: missingBomColumnsMessage(missingColumns), diagnostics },{ status: 422 });}diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.tsindex b61a11716b..ac7543ca26 100644--- a/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.ts+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.plan-release.ts@@ -11,6 +11,7 @@ import type {} from "@carbon/ee";import {buildReleasePlan,+ describeBomPayload,drawingModels,groupRevisionsIntoReleases,isModelReleaseItem,@@ -34,6 +35,7 @@ import {} from "@carbon/ee/onshape";import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";import { readPartProperties } from "@carbon/ee/onshape.server";+import { getLogger } from "@carbon/logger";import type { ActionFunctionArgs } from "react-router";import { data } from "react-router";import { z } from "zod";@@ -43,6 +45,8 @@ export const config = {runtime: "nodejs"};+const logger = getLogger("erp", "integrations-onshape-panel-plan-release");+const payloadSchema = z.object({documentId: z.string().min(1),releaseId: z.string().min(1)@@ -119,6 +123,8 @@ export async function action({ request }: ActionFunctionArgs) {// A drawing numbered apart from its model is tied to it by the release// package, which lists the model under the drawing. Read only when needed.const warnings: string[] = [];+ /** The BOMs behind the "couldn't read" warnings, for the panel's Details. */+ const unreadBoms: Record<string, unknown>[] = [];let drawingModelByElementId: ReturnType<typeof drawingModels> = new Map();if (drawingItems.some((item) => !releasePartNumbers.includes(item.partNumber))@@ -229,6 +235,26 @@ export async function action({ request }: ActionFunctionArgs) {const { lines, missingColumns } = parseBomTree(bom);if (missingColumns.length > 0) {bomLinesByElementId[bomKey] = null;+ const unread = {+ partNumber: item.partNumber,+ revision: item.revision,+ request: {+ documentId,+ wv: "v",+ wvId: item.versionId,+ elementId: item.elementId,+ configuration: item.configuration ?? null+ },+ missingColumns,+ bom: describeBomPayload(bom)+ };+ unreadBoms.push(unread);+ logger.warn("Onshape BOM is missing required columns", {+ companyId,+ releaseId,+ onshapeApi: onshape.client.apiOrigin,+ ...unread+ });warnings.push(`${item.partNumber} Rev ${item.revision}: ${missingBomColumnsMessage(missingColumns@@ -239,10 +265,21 @@ export async function action({ request }: ActionFunctionArgs) {bomLinesByElementId[bomKey] = lines;} catch (error) {bomLinesByElementId[bomKey] = null;+ const failure = onshapeFailure(error, "bom");+ unreadBoms.push({+ partNumber: item.partNumber,+ revision: item.revision,+ request: {+ documentId,+ wv: "v",+ wvId: item.versionId,+ elementId: item.elementId,+ configuration: item.configuration ?? null+ },+ onshape: failure.body.diagnostics+ });warnings.push(- `${item.partNumber} Rev ${item.revision}: ${- onshapeFailure(error, "bom").body.error- }`+ `${item.partNumber} Rev ${item.revision}: ${failure.body.error}`);}}@@ -399,7 +436,21 @@ export async function action({ request }: ActionFunctionArgs) {}return data(- { planId: saved.planId, expiresAt: saved.expiresAt, plan, warnings },+ {+ planId: saved.planId,+ expiresAt: saved.expiresAt,+ plan,+ warnings,+ ...(unreadBoms.length > 0+ ? {+ diagnostics: {+ request: { documentId, releaseId },+ onshapeApi: onshape.client.apiOrigin,+ unreadBoms+ }+ }+ : {})+ },{ headers: { "Cache-Control": "no-store" } });}diff --git a/apps/erp/app/routes/api+/integrations.onshape.panel.status.ts b/apps/erp/app/routes/api+/integrations.onshape.panel.status.tsindex 663a7006d2..bf6ba73360 100644--- a/apps/erp/app/routes/api+/integrations.onshape.panel.status.ts+++ b/apps/erp/app/routes/api+/integrations.onshape.panel.status.ts@@ -7,6 +7,7 @@ import type { PanelAssemblyLineInput, PanelItemRow } from "@carbon/ee";import {buildAssemblyLineStatuses,buildPartStatuses,+ describeBomPayload,externalIdForAssembly,externalIdForBomLine,metadataProperty,@@ -24,6 +25,7 @@ import {selectInBatches} from "@carbon/ee/onshape";import { requireOnshapePanelPermissions } from "@carbon/ee/onshape/panel-session.server";+import { getLogger } from "@carbon/logger";import type { LoaderFunctionArgs } from "react-router";import { data } from "react-router";@@ -31,6 +33,8 @@ export const config = {runtime: "nodejs"};+const logger = getLogger("erp", "integrations-onshape-panel-status");+/** Carbon status for the current Onshape element: its parts or its BOM. */export async function loader({ request }: LoaderFunctionArgs) {const { client, companyId, userId } = await requireOnshapePanelPermissions(@@ -115,8 +119,18 @@ export async function loader({ request }: LoaderFunctionArgs) {const { root: bomRoot, lines, missingColumns } = parseBomTree(bom);// Without its required columns every line would read "Not in Carbon".if (missingColumns.length > 0) {+ const diagnostics = {+ request: { documentId, wv, wvId, elementId, configuration },+ onshapeApi: onshape.client.apiOrigin,+ missingColumns,+ bom: describeBomPayload(bom)+ };+ logger.warn("Onshape BOM is missing required columns", {+ companyId,+ ...diagnostics+ });return data(- { error: missingBomColumnsMessage(missingColumns) },+ { error: missingBomColumnsMessage(missingColumns), diagnostics },{ status: 422 });}diff --git a/docs/content/docs/integrations/cad.mdx b/docs/content/docs/integrations/cad.mdxindex 07ff8894d4..b7aa4f89c2 100644--- a/docs/content/docs/integrations/cad.mdx+++ b/docs/content/docs/integrations/cad.mdx@@ -392,6 +392,11 @@ the push defaults together.## Troubleshooting the panel+Every error in the panel has **Show details** and **Copy details**: what Carbon+asked Onshape and what Onshape answered, including its status and message, and+for a BOM that can't be read, the column headers Onshape returned. Paste it into+a support request. It never contains a token or a cell value.+| Symptom | Cause | Fix || --- | --- | --- || No Carbon icon in the Onshape right panel | The Onshape user is not subscribed to the **Onshape V2** application, or the extension is missing from it. | Subscribe via the private App Store; check the extension exists with location Element right panel. |diff --git a/packages/ee/src/index.ts b/packages/ee/src/index.tsindex 1b075be195..9a46aa614f 100644--- a/packages/ee/src/index.ts+++ b/packages/ee/src/index.ts@@ -94,8 +94,9 @@ export {isOnshapeIntegrationId,ONSHAPE_INTEGRATION_IDS} from "./onshape/lib/connection";-export type { OnshapeBomNode } from "./onshape/panel/bom";+export type { BomDiagnostics, OnshapeBomNode } from "./onshape/panel/bom";export {+ describeBomPayload,flattenBomTree,metadataProperty,missingBomColumnsMessage,diff --git a/packages/ee/src/onshape/lib/client.ts b/packages/ee/src/onshape/lib/client.tsindex 30b05f4162..09a666e8e1 100644--- a/packages/ee/src/onshape/lib/client.ts+++ b/packages/ee/src/onshape/lib/client.ts@@ -177,12 +177,20 @@ function configurationQuery(configuration?: string | null): string {export class OnshapeApiError extends Error {status?: number;retryAfterSeconds?: number;-- constructor(message: string, status?: number, retryAfterSeconds?: number) {+ /** The `message` of Onshape's error body, when it sent one. */+ onshapeMessage?: string;++ constructor(+ message: string,+ status?: number,+ retryAfterSeconds?: number,+ onshapeMessage?: string+ ) {super(message);this.name = "OnshapeApiError";this.status = status;this.retryAfterSeconds = retryAfterSeconds;+ this.onshapeMessage = onshapeMessage;}}@@ -219,6 +227,11 @@ export class OnshapeClient {});}+ /** The Onshape origin this client calls, e.g. `https://cad.onshape.com`. */+ get apiOrigin(): string {+ return this.baseUrl;+ }+private getAuthHeaders(): Record<string, string> {return {"Content-Type": "application/json",@@ -338,14 +351,18 @@ export class OnshapeClient {return new OnshapeApiError(`Onshape request failed: ${error.message}`);}const parsedRetryAfter = Number(error.response?.headers?.["retry-after"]);+ const data = error.response?.data as unknown;+ const onshapeMessage =+ data && typeof data === "object"+ ? (data as { message?: unknown }).message+ : undefined;return new OnshapeApiError(`Onshape API error (${status}): ${- typeof error.response?.data === "string"- ? error.response.data- : JSON.stringify(error.response?.data)+ typeof data === "string" ? data : JSON.stringify(data)}`,status,- Number.isFinite(parsedRetryAfter) ? parsedRetryAfter : undefined+ Number.isFinite(parsedRetryAfter) ? parsedRetryAfter : undefined,+ typeof onshapeMessage === "string" ? onshapeMessage : undefined);}return error instanceof Error ? error : new Error(String(error));diff --git a/packages/ee/src/onshape/lib/onshape-failure.test.ts b/packages/ee/src/onshape/lib/onshape-failure.test.tsindex 7327567fb1..802748daf1 100644--- a/packages/ee/src/onshape/lib/onshape-failure.test.ts+++ b/packages/ee/src/onshape/lib/onshape-failure.test.ts@@ -10,7 +10,8 @@ class OnshapeApiError extends Error {constructor(message: string,public status?: number,- public retryAfterSeconds?: number+ public retryAfterSeconds?: number,+ public onshapeMessage?: string) {super(message);}@@ -87,6 +88,33 @@ describe("onshapeFailure", () => {expect(failure.body.error).not.toMatch(/stack|secret/);});+ it("puts Onshape's own message in the diagnostics, never its raw body", () => {+ const failure = onshapeFailure(+ new OnshapeApiError(+ 'Onshape API error (403): {"message":"Access denied","stack":"secret"}',+ 403,+ undefined,+ "Access denied"+ ),+ "bom"+ );+ expect(failure.body.diagnostics).toEqual({+ read: "bom",+ onshapeStatus: 403,+ onshapeMessage: "Access denied",+ transport: null+ });+ expect(JSON.stringify(failure.body)).not.toMatch(/stack|secret/);+ });++ it("describes a call that got no response", () => {+ expect(onshapeFailure(timeout).body.diagnostics).toMatchObject({+ onshapeStatus: null,+ onshapeMessage: null,+ transport: "Onshape request failed: timeout of 60000ms exceeded"+ });+ });+it("handles a non-Onshape throw", () => {expect(onshapeFailure(new Error("boom")).status).toBe(502);expect(onshapeFailure("not an error").status).toBe(502);diff --git a/packages/ee/src/onshape/lib/onshape-failure.ts b/packages/ee/src/onshape/lib/onshape-failure.tsindex 3424751825..7cf57aff39 100644--- a/packages/ee/src/onshape/lib/onshape-failure.ts+++ b/packages/ee/src/onshape/lib/onshape-failure.ts@@ -14,12 +14,28 @@ const logger = getLogger("ee", "onshape", "panel");*/export type OnshapeFailure = {status: 404 | 422 | 429 | 502 | 504;- body: { error: string; retryAfterSeconds?: number };+ body: {+ error: string;+ retryAfterSeconds?: number;+ diagnostics: OnshapeFailureDiagnostics;+ };};/** A BOM read gets its own timeout wording: Onshape builds BOMs on demand. */export type OnshapeRead = "bom" | "other";+/**+ * What Onshape answered, for the panel's Details. Onshape's own `message`, never+ * its raw body.+ */+export type OnshapeFailureDiagnostics = {+ read: OnshapeRead;+ onshapeStatus: number | null;+ onshapeMessage: string | null;+ /** No response at all: the client's own description (timeout, network). */+ transport: string | null;+};+export function onshapeFailure(error: unknown,read: OnshapeRead = "other"@@ -29,6 +45,15 @@ export function onshapeFailure(const status =typeof apiError?.status === "number" ? apiError.status : undefined;const message = error instanceof Error ? error.message : String(error);+ const diagnostics: OnshapeFailureDiagnostics = {+ read,+ onshapeStatus: status ?? null,+ onshapeMessage:+ typeof apiError?.onshapeMessage === "string"+ ? apiError.onshapeMessage.slice(0, 500)+ : null,+ transport: status === undefined ? message.slice(0, 300) : null+ };logger.warn("Onshape call failed", { read, status, message });if (status === undefined) {@@ -37,6 +62,7 @@ export function onshapeFailure(return {status: 504,body: {+ diagnostics,error:read === "bom"? "Onshape is still building this BOM. It can take a minute the first time — try again shortly."@@ -47,6 +73,7 @@ export function onshapeFailure(return {status: 502,body: {+ diagnostics,error: "Carbon couldn't reach Onshape. Try again."}};@@ -60,6 +87,7 @@ export function onshapeFailure(return {status: 429,body: {+ diagnostics,error: `Onshape is rate-limiting this connection. Try again in ${retryAfterSeconds ?? 60} seconds.`,@@ -72,6 +100,7 @@ export function onshapeFailure(return {status: 422,body: {+ diagnostics,error:"Onshape rejected Carbon's connection. Reconnect Onshape in Carbon's integration settings."}@@ -82,6 +111,7 @@ export function onshapeFailure(return {status: 404,body: {+ diagnostics,error: "That Onshape document, version or element no longer exists."}};@@ -93,6 +123,7 @@ export function onshapeFailure(return {status: 502,body: {+ diagnostics,error:"Onshape refused the request: the yearly API limit for Carbon's Onshape app is used up. Ask your Carbon administrator to raise it with Onshape."}@@ -102,6 +133,7 @@ export function onshapeFailure(return {status: 502,body: {+ diagnostics,error: `Onshape returned an error (HTTP ${status}). Try again; if it keeps happening, contact support.`}};diff --git a/packages/ee/src/onshape/panel/Panel.tsx b/packages/ee/src/onshape/panel/Panel.tsxindex debd786d2f..e5f8f61197 100644--- a/packages/ee/src/onshape/panel/Panel.tsx+++ b/packages/ee/src/onshape/panel/Panel.tsx@@ -36,7 +36,7 @@ import {TruncatedTooltipText,VStack} from "@carbon/react";-import { formatDate } from "@carbon/utils";+import { datetime, formatDate } from "@carbon/utils";import type { ReactNode } from "react";import { useCallback, useEffect, useMemo, useState } from "react";import {@@ -44,6 +44,7 @@ import {LuChevronRight,LuCircleCheck,LuCircleDashed,+ LuCopy,LuInfo,LuListChecks,LuLock,@@ -169,7 +170,12 @@ export type PanelAssemblyStatus = {};/** forbidden: a Retry cannot fix it, so it renders as a warning with no Retry. */-type LoadFailure = { message: string; forbidden: boolean };+type LoadFailure = {+ message: string;+ forbidden: boolean;+ /** What Carbon and Onshape answered, for the Details section. */+ diagnostics?: unknown;+};// refreshing / refreshFailure: a re-read keeps the rows on screen; only a first// read shows a skeleton.@@ -193,7 +199,12 @@ type PanelStatusState =refreshing?: boolean;refreshFailure?: LoadFailure;}- | { status: "error"; message: string; forbidden?: boolean };+ | {+ status: "error";+ message: string;+ forbidden?: boolean;+ diagnostics?: unknown;+ };type PanelReleasesState =| { status: "idle" }@@ -206,7 +217,12 @@ type PanelReleasesState =refreshing?: boolean;refreshFailure?: LoadFailure;}- | { status: "error"; message: string; forbidden?: boolean };+ | {+ status: "error";+ message: string;+ forbidden?: boolean;+ diagnostics?: unknown;+ };/*** push: the current element. releases: the whole document, so it shows on an@@ -254,7 +270,12 @@ type PanelFieldsState =/** Per-property 422 errors, keyed by onshapePropertyId. */fieldErrors: Record<string, string[]>;}- | { status: "error"; message: string; forbidden?: boolean };+ | {+ status: "error";+ message: string;+ forbidden?: boolean;+ diagnostics?: unknown;+ };// Every push reads these four itself: the Fields page shows them as fixed rows, never as a mapping.const FIXED_PROPERTY_NAMES = new Set([@@ -329,12 +350,16 @@ type PlanResponse<P> = {planId: string;expiresAt: string;plan: P;+ /** plan-release only: what Onshape returned for the BOMs it couldn't read. */+ diagnostics?: unknown;/** plan-release only: assemblies whose BOM could not be read. */warnings?: unknown;};type PanelErrorResponse = {error: string;+ /** What Carbon asked Onshape and what it answered, for the Details section. */+ diagnostics?: unknown;fieldErrors?: ApplyFieldError[];/** too-large: the panel offers a push of the top level only. */code?: "too-large";@@ -427,6 +452,8 @@ type PushOutcome = {text: string;skipped: string[];errors: string[];+ /** What Carbon and Onshape answered, for the Details section. */+ diagnostics?: unknown;/** Done, but worth knowing: a new Draft version, lines taken over. */notes?: string[];};@@ -480,8 +507,8 @@ function releaseOutcomeText(s: ReleasePushSummary): PushOutcome {return { text: releaseResultText(s), skipped: s.skipped, errors: s.errors };}-function failedOutcome(message: string): PushOutcome {- return { text: "", skipped: [], errors: [message] };+function failedOutcome(message: string, diagnostics?: unknown): PushOutcome {+ return { text: "", skipped: [], errors: [message], diagnostics };}function PushOutcomeView({ outcome }: { outcome: PushOutcome }) {@@ -542,6 +569,9 @@ function PushOutcomeView({ outcome }: { outcome: PushOutcome }) {<li key={problem}>{problem}</li>))}</ul>+ {outcome.diagnostics ? (+ <PanelDiagnostics diagnostics={outcome.diagnostics} />+ ) : null}</AlertDescription></Alert>) : null}@@ -632,6 +662,95 @@ function CappedWarningList({);}+/**+ * The Clipboard API first. Inside Onshape's frame the browser can refuse it+ * (the frame is not granted clipboard-write), so a selected textarea and+ * `execCommand("copy")` next, which a click still allows there.+ */+async function copyText(text: string): Promise<boolean> {+ try {+ await navigator.clipboard.writeText(text);+ return true;+ } catch {+ // Refused or unavailable: try the selection fallback.+ }+ const area = document.createElement("textarea");+ area.value = text;+ area.setAttribute("readonly", "");+ area.style.position = "fixed";+ area.style.top = "0";+ area.style.opacity = "0";+ document.body.appendChild(area);+ area.select();+ try {+ return document.execCommand("copy");+ } catch {+ return false;+ } finally {+ area.remove();+ }+}++/**+ * What Carbon asked Onshape and what it answered, plus the panel's own URL+ * parameters, so a failure can be reported as it happened. Never a token.+ */+function PanelDiagnostics({ diagnostics }: { diagnostics: unknown }) {+ const [open, setOpen] = useState(false);+ const [copied, setCopied] = useState(false);+ const [report] = useState(() =>+ JSON.stringify(+ {+ capturedAt: datetime.timestamp(),+ carbonHost: typeof window === "undefined" ? null : window.location.host,+ panel:+ typeof window === "undefined"+ ? {}+ : Object.fromEntries(new URLSearchParams(window.location.search)),+ details: diagnostics+ },+ null,+ 2+ )+ );+ const copy = async () => {+ if (await copyText(report)) {+ setCopied(true);+ } else {+ // Nothing could write the clipboard: show the text to select instead.+ setOpen(true);+ }+ };+ return (+ <div className="mt-2 w-full">+ <HStack spacing={3}>+ <Button+ variant="link"+ size="sm"+ className="h-auto p-0"+ onClick={() => setOpen((current) => !current)}+ >+ {open ? "Hide details" : "Show details"}+ </Button>+ <Button+ variant="link"+ size="sm"+ className="h-auto p-0"+ leftIcon={<LuCopy />}+ onClick={copy}+ >+ {copied ? "Copied" : "Copy details"}+ </Button>+ </HStack>+ {open ? (+ <pre className="mt-1 max-h-64 select-all overflow-auto whitespace-pre-wrap break-all rounded-md bg-muted p-2 font-mono text-[11px] text-foreground">+ {report}+ </pre>+ ) : null}+ </div>+ );+}+/** stale: a failed Refresh over rows still on screen. */function PanelLoadError({title,@@ -664,6 +783,9 @@ function PanelLoadError({{stale ? (<span className="mt-1 block">Showing what was loaded before.</span>) : null}+ {failure.diagnostics ? (+ <PanelDiagnostics diagnostics={failure.diagnostics} />+ ) : null}</AlertDescription>{onRetry ? (<HStack className="mt-2">@@ -772,7 +894,11 @@ export function OnshapePanel({async (token: string) => {if (!canLoadParts) return;setAssemblyTooLarge(null);- const fail = (message: string, forbidden: boolean) =>+ const fail = (+ message: string,+ forbidden: boolean,+ diagnostics?: unknown+ ) =>setParts((current) =>current.status === "ready" ||current.status === "ready-assembly" ||@@ -780,9 +906,9 @@ export function OnshapePanel({? {...current,refreshing: false,- refreshFailure: { message, forbidden }+ refreshFailure: { message, forbidden, diagnostics }}- : { status: "error", message, forbidden }+ : { status: "error", message, forbidden, diagnostics });setParts((current) =>current.status === "ready" ||@@ -807,11 +933,12 @@ export function OnshapePanel({| { kind: "partstudio"; parts: PanelPartStatus[] }| { kind: "assembly"; assembly: PanelAssemblyStatus }| { kind: "other" }- | { error: string };+ | { error: string; diagnostics?: unknown };if (!response.ok || "error" in body) {fail("error" in body ? body.error : `Carbon answered ${response.status}`,- response.status === 403+ response.status === 403,+ "error" in body ? body.diagnostics : undefined);return;}@@ -837,15 +964,19 @@ export function OnshapePanel({const loadReleases = useCallback(async (token: string) => {if (!context.documentId) return;- const fail = (message: string, forbidden: boolean) =>+ const fail = (+ message: string,+ forbidden: boolean,+ diagnostics?: unknown+ ) =>setReleases((current) =>current.status === "ready"? {...current,refreshing: false,- refreshFailure: { message, forbidden }+ refreshFailure: { message, forbidden, diagnostics }}- : { status: "error", message, forbidden }+ : { status: "error", message, forbidden, diagnostics });setReleases((current) =>current.status === "ready"@@ -857,11 +988,12 @@ export function OnshapePanel({const response = await panelFetch(token, `${paths.releases}?${query}`);const body = (await response.json()) as| { releases: PanelRelease[]; releaseManagementAvailable?: boolean }- | { error: string };+ | { error: string; diagnostics?: unknown };if (!response.ok || "error" in body) {fail("error" in body ? body.error : `Carbon answered ${response.status}`,- response.status === 403+ response.status === 403,+ "error" in body ? body.diagnostics : undefined);return;}@@ -966,7 +1098,8 @@ export function OnshapePanel({failedOutcome("error" in body? body.error- : `Carbon answered ${response.status}`+ : `Carbon answered ${response.status}`,+ "error" in body ? body.diagnostics : undefined));return;@@ -1032,7 +1165,8 @@ export function OnshapePanel({failedOutcome("error" in body? body.error- : `Carbon answered ${response.status}`+ : `Carbon answered ${response.status}`,+ "error" in body ? body.diagnostics : undefined));return;@@ -1078,7 +1212,8 @@ export function OnshapePanel({[releaseId]: failedOutcome("error" in body? body.error- : `Carbon answered ${response.status}`+ : `Carbon answered ${response.status}`,+ "error" in body ? body.diagnostics : undefined)}));return;@@ -1089,7 +1224,8 @@ export function OnshapePanel({expiresAt: body.expiresAt,scope: documentScope,plan: body.plan,- warnings: normalizeWarnings(body.warnings)+ warnings: normalizeWarnings(body.warnings),+ diagnostics: body.diagnostics}));} catch (error) {@@ -1280,16 +1416,20 @@ export function OnshapePanel({if (!canLoadParts) return;// A landing commits only while the page still waits for this read: a move to// another element leaves `closed`, which the answer must not undo.- const fail = (message: string, forbidden: boolean) =>+ const fail = (+ message: string,+ forbidden: boolean,+ diagnostics?: unknown+ ) =>setFields((current) =>current.status === "ready" && current.refreshing? {...current,refreshing: false,- refreshFailure: { message, forbidden }+ refreshFailure: { message, forbidden, diagnostics }}: current.status === "loading"- ? { status: "error", message, forbidden }+ ? { status: "error", message, forbidden, diagnostics }: current);setFields((current) =>@@ -1307,11 +1447,12 @@ export function OnshapePanel({const response = await panelFetch(token, `${paths.fields}?${query}`);const body = (await response.json()) as| PanelFieldsData- | { error: string };+ | { error: string; diagnostics?: unknown };if (!response.ok || "error" in body) {fail("error" in body ? body.error : `Carbon answered ${response.status}`,- response.status === 403+ response.status === 403,+ "error" in body ? body.diagnostics : undefined);return;}@@ -2109,7 +2250,12 @@ function PartsSection({refreshing?: boolean;refreshFailure?: LoadFailure;}- | { status: "error"; message: string; forbidden?: boolean };+ | {+ status: "error";+ message: string;+ forbidden?: boolean;+ diagnostics?: unknown;+ };canPush: boolean;pushing: Set<string> | null;locked: boolean;@@ -2162,7 +2308,11 @@ function PartsSection({{parts.status === "error" ? (<PanelLoadErrortitle="Couldn't load part status"- failure={{ message: parts.message, forbidden: !!parts.forbidden }}+ failure={{+ message: parts.message,+ forbidden: !!parts.forbidden,+ diagnostics: parts.diagnostics+ }}onRetry={onRefresh}/>) : null}@@ -2300,7 +2450,8 @@ function ReleasesSection({title="Couldn't load releases"failure={{message: releases.message,- forbidden: !!releases.forbidden+ forbidden: !!releases.forbidden,+ diagnostics: releases.diagnostics}}onRetry={onRefresh}/>@@ -2521,7 +2672,11 @@ function FieldsSection({{header}<PanelLoadErrortitle="Couldn't load properties"- failure={{ message: state.message, forbidden: !!state.forbidden }}+ failure={{+ message: state.message,+ forbidden: !!state.forbidden,+ diagnostics: state.diagnostics+ }}onRetry={onRefresh}/></VStack>@@ -4607,6 +4762,9 @@ function ReleaseReviewSection({<p className="mt-1">Their BOM lines stay as they are. Review again to retry.</p>+ {review.diagnostics ? (+ <PanelDiagnostics diagnostics={review.diagnostics} />+ ) : null}</AlertDescription></Alert>) : null}diff --git a/packages/ee/src/onshape/panel/bom.test.ts b/packages/ee/src/onshape/panel/bom.test.tsindex c3c9fada6f..6dac2489b2 100644--- a/packages/ee/src/onshape/panel/bom.test.ts+++ b/packages/ee/src/onshape/panel/bom.test.ts@@ -4,6 +4,7 @@import { describe, expect, it } from "vitest";import {+ describeBomPayload,firstOwnAssemblyPart,flattenBomTree,missingBomColumnsMessage,@@ -318,3 +319,58 @@ describe("firstOwnAssemblyPart", () => {expect(firstOwnAssemblyPart(null)).toBeNull();});});++describe("describeBomPayload", () => {+ it("reports the headers Onshape sent, with their property names", () => {+ const report = describeBomPayload({+ formatVersion: "1.0",+ templateId: "tpl-1",+ headers: [+ { id: "h-item", name: "Pos.", propertyName: "item" },+ { id: "h-qty", name: "Qty", propertyName: "quantity" }+ ],+ rows: [row("1", "A-1", 1), row("2", "B-1", 2)],+ topLevelAssemblyRow: {}+ });+ expect(report).toEqual({+ payloadKeys: [+ "formatVersion",+ "templateId",+ "headers",+ "rows",+ "topLevelAssemblyRow"+ ],+ headersType: "array",+ headerCount: 2,+ headers: [+ { id: "h-item", name: "Pos.", propertyName: "item" },+ { id: "h-qty", name: "Qty", propertyName: "quantity" }+ ],+ rowCount: 2,+ formatVersion: "1.0",+ templateId: "tpl-1",+ topLevelAssemblyRow: true+ });+ });++ it("says when the headers are missing or not a list", () => {+ expect(describeBomPayload({ rows: [row("1", "A-1", 1)] })).toMatchObject({+ headersType: "missing",+ headerCount: 0,+ rowCount: 1+ });+ expect(describeBomPayload({ headers: {}, rows: [] }).headersType).toBe(+ "object"+ );+ expect(describeBomPayload("<html>").payloadKeys).toEqual([]);+ expect(describeBomPayload(null).headersType).toBe("missing");+ });++ it("never copies a cell value", () => {+ const report = describeBomPayload({+ headers: H,+ rows: [row("1", "SECRET-PART", 1)]+ });+ expect(JSON.stringify(report)).not.toContain("SECRET-PART");+ });+});diff --git a/packages/ee/src/onshape/panel/bom.ts b/packages/ee/src/onshape/panel/bom.tsindex 0fc75a993a..e3d353076a 100644--- a/packages/ee/src/onshape/panel/bom.ts+++ b/packages/ee/src/onshape/panel/bom.ts@@ -244,6 +244,66 @@ export function missingBomColumnsMessage(missingColumns: string[]): string {}. Add ${plural ? "them" : "it"} back to the assembly's BOM table in Onshape, then try again.`;}+/** At most this many headers go into a diagnostics report. */+const DIAGNOSTIC_HEADER_LIMIT = 60;++/**+ * The shape of a BOM response and its column headers, for the panel's Details+ * when a BOM can't be read. Never a cell value.+ */+export type BomDiagnostics = {+ /** Top-level keys of the response. */+ payloadKeys: string[];+ /** "array", "missing", or what `headers` was instead. */+ headersType: string;+ headerCount: number;+ headers: {+ id: string | null;+ name: string | null;+ propertyName: string | null;+ }[];+ rowCount: number;+ formatVersion: string | null;+ templateId: string | null;+ topLevelAssemblyRow: boolean;+};++export function describeBomPayload(payload: unknown): BomDiagnostics {+ const bom =+ payload && typeof payload === "object"+ ? (payload as Record<string, unknown>)+ : {};+ const headers = bom.headers;+ const text = (value: unknown) =>+ typeof value === "string" || typeof value === "number"+ ? String(value)+ : null;+ const headerList = Array.isArray(headers) ? headers : [];+ return {+ payloadKeys: payload && typeof payload === "object" ? Object.keys(bom) : [],+ headersType: Array.isArray(headers)+ ? "array"+ : headers === undefined+ ? "missing"+ : headers === null+ ? "null"+ : typeof headers,+ headerCount: headerList.length,+ headers: headerList.slice(0, DIAGNOSTIC_HEADER_LIMIT).map((header) => {+ const h = (header ?? {}) as Record<string, unknown>;+ return {+ id: text(h.id),+ name: text(h.name),+ propertyName: text(h.propertyName)+ };+ }),+ rowCount: Array.isArray(bom.rows) ? bom.rows.length : 0,+ formatVersion: text(bom.formatVersion),+ templateId: text(bom.templateId),+ topLevelAssemblyRow: !!bom.topLevelAssemblyRow+ };+}+export function flattenBomTree(lines: OnshapeBomNode[]): OnshapeBomNode[] {const out: OnshapeBomNode[] = [];const walk = (list: OnshapeBomNode[]) => {diff --git a/packages/ee/src/onshape/panel/review.ts b/packages/ee/src/onshape/panel/review.tsindex 880e1b1883..9910df68ec 100644--- a/packages/ee/src/onshape/panel/review.ts+++ b/packages/ee/src/onshape/panel/review.ts@@ -57,6 +57,8 @@ export type ReleaseReview = ReviewBase & {makeDefault: boolean;/** Assemblies whose BOM the plan could not read; their lines are empty. */warnings: string[];+ /** What Onshape returned for those BOMs, for the panel's Details. */+ diagnostics?: unknown;};export type ReviewState = PartReview | AssemblyReview | ReleaseReview;@@ -81,6 +83,7 @@ export function createReview(input: {scope: string;plan: PartPlan | AssemblyPlan | ReleasePlan;warnings?: string[];+ diagnostics?: unknown;}): ReviewState {const base: ReviewBase = {planId: input.planId,@@ -111,7 +114,8 @@ export function createReview(input: {changeNotice: plan.changeNotice ? { ...plan.changeNotice } : null,createChangeNotice: plan.changeNotice !== null,makeDefault: plan.makeDefault,- warnings: input.warnings ?? []+ warnings: input.warnings ?? [],+ diagnostics: input.diagnostics};}}