Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

34.5 KB
Raw Blame
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import App from "../App";
import { ApiError } from "../api/aetherisApi";
import { STEP_UPLOAD_LIMIT_BYTES } from "../config/stepUpload";

const apiMocks = vi.hoisted(() => ({
	createDocument: vi.fn(),
	claimStartupStep: vi.fn(),
	composeBlock: vi.fn(),
	listGalleryTemplates: vi.fn(),
	invokeGalleryTemplate: vi.fn(),
	executeBoolean: vi.fn(),
	exportDefinitionStep: vi.fn(),
	getDocumentSummary: vi.fn(),
	importStep: vi.fn(),
	pickBody: vi.fn(),
	prepareBodyDisplay: vi.fn(),
	prepareAssemblyDisplay: vi.fn(),
	tessellateBody: vi.fn(),
	translateBody: vi.fn(),
}));

vi.mock("../api/aetherisApi", async () => {
	const actual = await vi.importActual("../api/aetherisApi");

	return {
		...actual,
		createDocument: apiMocks.createDocument,
		claimStartupStep: apiMocks.claimStartupStep,
		composeBlock: apiMocks.composeBlock,
		listGalleryTemplates: apiMocks.listGalleryTemplates,
		invokeGalleryTemplate: apiMocks.invokeGalleryTemplate,
		executeBoolean: apiMocks.executeBoolean,
		exportDefinitionStep: apiMocks.exportDefinitionStep,
		getDocumentSummary: apiMocks.getDocumentSummary,
		importStep: apiMocks.importStep,
		pickBody: apiMocks.pickBody,
		prepareBodyDisplay: apiMocks.prepareBodyDisplay,
		prepareAssemblyDisplay: apiMocks.prepareAssemblyDisplay,
		tessellateBody: apiMocks.tessellateBody,
		translateBody: apiMocks.translateBody,
	};
});

vi.mock("../viewer/AetherisViewport", () => ({
	AetherisViewport: ({ theme }: { theme?: { id: string } }) => (
		<div data-testid="viewer-viewport" data-theme={theme?.id} />
	),
}));

function setupDocumentApiMocks(): void {
	apiMocks.createDocument.mockResolvedValue({ documentId: "doc-1", name: "Test", volatile: true });
	apiMocks.claimStartupStep.mockResolvedValue(null);
	apiMocks.importStep.mockResolvedValue({ documentId: 'doc-1', definitionId: 'def-2', occurrenceId: 'occ-2', name: 'Imported', diagnostics: [] });
	apiMocks.composeBlock.mockResolvedValue({ stepText: 'STEP', exportPath: 'composed-block.step', source: 'Model ComposedBlock {}', materializationRoute: 'PrismaticSectionStack/Add' });
	apiMocks.getDocumentSummary.mockResolvedValue({
		documentId: "doc-1",
		name: "Test",
		bodyCount: 1,
		bodyIds: ["occ-2"],
		definitionCount: 1,
		occurrences: [
			{
				occurrenceId: "occ-2",
				definitionId: "def-2",
				name: "Imported",
				translation: { x: 0, y: 0, z: 0 },
			},
		],
	});
	apiMocks.tessellateBody.mockResolvedValue({ facePatches: [], edgePolylines: [] });
	apiMocks.prepareBodyDisplay.mockResolvedValue({
		lane: "fallback-only",
		status: "Complete",
		analyticPacket: {
			bodyId: 1,
			analyticFaces: [],
			fallbackFaces: [],
		},
		tessellationFallback: {
			facePatches: [],
			edgePolylines: [],
		},
	});
}

describe("App STEP file upload flow", () => {
	beforeEach(() => {
		vi.clearAllMocks();
		setupDocumentApiMocks();
	});

	afterEach(() => {
		cleanup();
	});

	it("uses viewer tab as default and hides modeling controls until demo tab is selected", () => {
		render(<App />);

		expect(
			screen.getByRole("tab", { name: /STEP 242 Viewer/i }).getAttribute("aria-selected"),
		).toBe("true");
		expect(screen.getByTestId("viewer-viewport")).toBeTruthy();
		expect(screen.getByRole("button", { name: "GRID" }).getAttribute("aria-pressed")).toBe("true");
		expect(screen.getByRole("button", { name: "COORD" }).getAttribute("aria-pressed")).toBe("true");
		expect(screen.queryByText("Create Box")).toBeNull();
		expect(screen.queryByRole("button", { name: "direct-profile" })).toBeNull();
		expect(screen.queryByRole("button", { name: "hexbolt-m1" })).toBeNull();

		fireEvent.click(screen.getByRole("tab", { name: /Modeling Demo/i }));

		expect(screen.getByText("Compose blocks")).toBeTruthy();
		expect(screen.getByRole("button", { name: "Build composed part" })).toBeTruthy();
	});

	it("auto-creates a workspace and shows connected/ready status on startup", async () => {
		render(<App />);

		await screen.findByText("Server: Connected");
		await screen.findByText("Document: Ready");
		expect(apiMocks.createDocument).toHaveBeenCalledTimes(1);
		expect(apiMocks.importStep).not.toHaveBeenCalled();
		expect(apiMocks.composeBlock).not.toHaveBeenCalled();
		expect((screen.getByRole("button", { name: "Refresh Display Data" }) as HTMLButtonElement).disabled).toBe(true);
	});

	it("previews the gallery artifact with its authored export path", async () => {
		apiMocks.listGalleryTemplates.mockResolvedValue([{ id: "Standard.Products.Mechanical.MountingPlate", displayName: "Mounting Plate", parameters: [], artifacts: ["StepAp242"] }]);
		apiMocks.invokeGalleryTemplate.mockResolvedValue({ artifacts: [{ kind: "StepAp242", name: "part.step", exportPath: "products/mounting-plate.step", content: "GENERATED STEP", sha256: "abcdef" }], executionMilliseconds: 10 });
		render(<App />);
		await screen.findByText("Document: Ready");
		fireEvent.click(screen.getByRole("tab", { name: /Product Gallery/i }));
		await screen.findByRole("button", { name: "Generate / Update Part" });
		fireEvent.click(screen.getByRole("button", { name: "Generate / Update Part" }));
		await screen.findByText(/Generated in/);
		expect(apiMocks.importStep).toHaveBeenCalledWith("doc-1", "GENERATED STEP", "products/mounting-plate.step");
		expect(apiMocks.prepareBodyDisplay).toHaveBeenCalledWith("doc-1", "occ-2");
	});

	it("builds the composed part instead of invoking the retired Boolean controls", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");
		fireEvent.click(screen.getByRole("tab", { name: /Modeling Demo/i }));
		expect(screen.queryByRole("button", { name: "Execute Boolean" })).toBeNull();
		fireEvent.click(screen.getByRole("button", { name: "Build composed part" }));
		await screen.findByText(/Composed block built/);
		expect(apiMocks.composeBlock).toHaveBeenCalledWith({ width: 80, depth: 50, height: 8, padWidth: 30, padDepth: 20, padHeight: 12 });
		expect(apiMocks.importStep).toHaveBeenCalledWith("doc-1", "STEP", "composed-block.step");
		expect(apiMocks.executeBoolean).not.toHaveBeenCalled();
	});

	it("switches the complete viewport theme without changing shell geography", () => {
		render(<App />);
		expect(screen.getByTestId("viewer-viewport").getAttribute("data-theme")).toBe("atelier");
		fireEvent.change(screen.getByRole("combobox", { name: "Viewport theme" }), {
			target: { value: "monument" },
		});
		expect(screen.getByTestId("viewer-viewport").getAttribute("data-theme")).toBe("monument");
		expect(screen.getByRole("tab", { name: /STEP 242 Viewer/i })).toBeTruthy();
	});

	it("claims and imports a startup STEP only after the workspace is ready", async () => {
		apiMocks.claimStartupStep.mockResolvedValue({
			path: "C:\\Models\\startup.step",
			fileName: "startup.step",
			stepText: "ISO-10303-21;",
		});
		apiMocks.importStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "startup.step",
			diagnostics: [],
		});
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "startup-hash",
			diagnostics: [],
		});

		render(<App />);

		await waitFor(() => expect(apiMocks.claimStartupStep).toHaveBeenCalledTimes(1));
		await waitFor(() => expect(apiMocks.importStep).toHaveBeenCalledTimes(1));
		expect(apiMocks.createDocument.mock.invocationCallOrder[0]).toBeLessThan(
			apiMocks.claimStartupStep.mock.invocationCallOrder[0],
		);
		expect(apiMocks.importStep).toHaveBeenCalledWith("doc-1", "ISO-10303-21;", "startup.step");
		expect(apiMocks.claimStartupStep).toHaveBeenCalledTimes(1);
	});

	it("loads a startup Firmament assembly into the product tree without treating transforms as Mates", async () => {
		apiMocks.claimStartupStep.mockResolvedValue({
			path: "C:\\Models\\assembly.firmasm",
			fileName: "assembly.firmasm",
			stepText: "Assembly A {}",
			kind: "assembly",
		});
		apiMocks.prepareAssemblyDisplay.mockResolvedValue({
			schema: "aetheris/cadmata-assembly-display/m2",
			name: "A",
			rootOccurrenceStableId: "root",
			definitions: [],
			occurrences: [
				{
					stableId: "root",
					name: "A",
					instancePath: "A",
					parentStableId: null,
					definitionStableId: null,
					kind: "Assembly",
					worldTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
					placementAuthority: "MateDerived",
				},
				{
					stableId: "part",
					name: "ImportedPart",
					instancePath: "A.ImportedPart",
					parentStableId: "root",
					definitionStableId: "def",
					kind: "Part",
					worldTransform: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 10, 0, 0, 1],
					placementAuthority: "ImportedOccurrence",
				},
			],
			mates: [],
			toleranceStackups: [],
			bounds: { minimum: [0, 0, 0], maximum: [11, 1, 1] },
			diagnostics: [],
			performance: { occurrenceCount: 2 },
		});
		render(<App />);
		expect(await screen.findByText(/ImportedPart/)).toBeTruthy();
		expect(
			screen.getByText("No semantic Mates were inferred from occurrence transforms."),
		).toBeTruthy();
		expect(apiMocks.importStep).not.toHaveBeenCalled();
		fireEvent.change(screen.getByTestId("step-import-file-input"), { target: { files: [new File(["STEP"], "replacement.step")] } });
		await screen.findByText("replacement.step");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));
		await screen.findByText(/^Inspectable: Import complete/);
		fireEvent.click(screen.getByRole("button", { name: "Refresh Display Data" }));
		await waitFor(() => expect(apiMocks.prepareBodyDisplay).toHaveBeenCalledTimes(2));
		expect(apiMocks.prepareAssemblyDisplay).toHaveBeenCalledTimes(1);
	});

	it("shows a readable startup STEP load failure", async () => {
		apiMocks.claimStartupStep.mockResolvedValue({
			path: "C:\\Models\\bad.step",
			fileName: "bad.step",
			stepText: "BAD",
		});
		apiMocks.importStep.mockRejectedValue(new ApiError("STEP payload could not be imported.", []));

		render(<App />);

		await waitFor(() => expect(apiMocks.importStep).toHaveBeenCalledTimes(1));
		await waitFor(() =>
			expect(screen.getAllByText("STEP payload could not be imported.").length).toBeGreaterThan(0),
		);
		expect(apiMocks.prepareBodyDisplay).not.toHaveBeenCalled();
	});

	it("keeps the ordinary empty viewer when no startup STEP exists", async () => {
		render(<App />);

		await screen.findByText("Ready. Select a file to import.");
		await waitFor(() => expect(apiMocks.claimStartupStep).toHaveBeenCalledTimes(1));
		expect(apiMocks.importStep).not.toHaveBeenCalled();
	});

	it("keeps canonical hash visible from viewer inspector", async () => {
		apiMocks.importStep.mockResolvedValue({
			importStatus: "Qualified",
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "Imported",
			diagnostics: [],
		});
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "hash-123",
			diagnostics: [],
		});

		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;DATA;"], "part.stp", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("part.stp");

		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		await screen.findByText("hash-123");
	});

	it("updates local file selection state when a file is chosen", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(
			[
				"ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF'));\nENDSEC;",
			],
			"sample.step",
			{ type: "text/plain" },
		);
		fireEvent.change(fileInput, { target: { files: [file] } });

		await screen.findByText("sample.step");
		expect(screen.getByText("Detected schema: AP242")).toBeTruthy();
		expect(screen.getByText("Compatibility: Supported")).toBeTruthy();
	});

	it("disables the previous import while reading a new file and ignores stale header completion", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");
		const input = screen.getByTestId("step-import-file-input");
		const first = new File(["ISO-10303-21;"], "first.step");
		fireEvent.change(input, { target: { files: [first] } });
		await screen.findByText("first.step");
		const importButton = screen.getByRole("button", {
			name: "Import STEP 242",
		}) as HTMLButtonElement;
		expect(importButton.disabled).toBe(false);

		let finishHeader!: (value: string) => void;
		const pendingHeader = new Promise<string>((resolve) => {
			finishHeader = resolve;
		});
		const second = new File(["ISO-10303-21;"], "second.step");
		vi.spyOn(second, "slice").mockReturnValue({
			text: () => pendingHeader,
		} as Blob);
		fireEvent.change(input, { target: { files: [second] } });
		expect(importButton.disabled).toBe(true);
		fireEvent.click(importButton);
		expect(apiMocks.importStep).not.toHaveBeenCalled();

		const latest = new File(["ISO-10303-21;"], "latest.step");
		fireEvent.change(input, { target: { files: [latest] } });
		await screen.findByText("latest.step");
		finishHeader("ISO-10303-21;");
		await pendingHeader;
		await waitFor(() => expect(screen.queryByText("second.step")).toBeNull());
		fireEvent.click(importButton);
		await waitFor(() =>
			expect(apiMocks.importStep).toHaveBeenCalledWith(
				"doc-1",
				"ISO-10303-21;",
				"latest.step",
			),
		);
	});

	it("shows inline validation when non-STEP file is selected", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["hello"], "notes.txt", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });

		await screen.findByText("File selection needs attention");
		expect(
			screen.getByText("Unsupported file type. Please select a .step or .stp file."),
		).toBeTruthy();
		expect(
			(screen.getByRole("button", { name: "Import STEP 242" }) as HTMLButtonElement).disabled,
		).toBe(true);
	});

	it("accepts STEP files above the previous 5 MB threshold when under the configured limit", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;"], "stc_09_like.stp", { type: "text/plain" });
		Object.defineProperty(file, "size", { value: 6 * 1024 * 1024 });

		fireEvent.change(fileInput, { target: { files: [file] } });

		await screen.findByText("stc_09_like.stp");
		expect(screen.queryByText("File selection needs attention")).toBeNull();
	});

	it("rejects STEP files above the configured limit with explicit size details", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;"], "too-large.step", { type: "text/plain" });
		Object.defineProperty(file, "size", { value: STEP_UPLOAD_LIMIT_BYTES + 1024 });

		fireEvent.change(fileInput, { target: { files: [file] } });

		await screen.findByText("File selection needs attention");
		await screen.findByText(/Selected STEP file is too large \(250\.00 MB\)\. Limit is 250 MB\./i);
	});

	it("accepts drag-and-drop STEP files", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const dropzone = screen.getByTestId("step-import-dropzone");
		const file = new File(["ISO-10303-21;"], "dragged.stp", { type: "text/plain" });
		fireEvent.drop(dropzone, {
			dataTransfer: {
				files: [file],
			},
		});

		await screen.findByText("dragged.stp");
	});

	it("maps AP214/AP203 schemas to Experimental compatibility", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const ap214 = new File(
			["ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('AUTOMOTIVE_DESIGN_CC2'));\nENDSEC;"],
			"ap214.step",
			{ type: "text/plain" },
		);
		fireEvent.change(fileInput, { target: { files: [ap214] } });

		await screen.findByText("Detected schema: AP214");
		expect(screen.getByText("Compatibility: Experimental")).toBeTruthy();

		const ap203 = new File(
			["ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('CONFIG_CONTROL_DESIGN'));\nENDSEC;"],
			"ap203.step",
			{ type: "text/plain" },
		);
		fireEvent.change(fileInput, { target: { files: [ap203] } });

		await screen.findByText("Detected schema: AP203");
		expect(screen.getByText("Compatibility: Experimental")).toBeTruthy();
	});

	it("falls back to unknown schema when FILE_SCHEMA is unrecognized", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const unknown = new File(
			["ISO-10303-21;\nHEADER;\nFILE_SCHEMA(('SOME_CUSTOM_SCHEMA'));\nENDSEC;"],
			"unknown.step",
			{ type: "text/plain" },
		);
		fireEvent.change(fileInput, { target: { files: [unknown] } });

		await screen.findByText("Detected schema: Unknown");
		expect(screen.getByText("Compatibility: Not verified")).toBeTruthy();
	});

	it("calls importStep with file contents and refreshes canonical hash", async () => {
		apiMocks.importStep.mockResolvedValue({
			importStatus: "Qualified",
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "Imported",
			diagnostics: [],
		});
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "hash-123",
			diagnostics: [],
		});

		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;DATA;"], "part.stp", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("part.stp");

		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		await waitFor(() => {
			expect(apiMocks.importStep).toHaveBeenCalledWith("doc-1", "ISO-10303-21;DATA;", "part.stp");
		});
		expect(apiMocks.exportDefinitionStep).toHaveBeenCalledWith("doc-1", "def-2");
		await screen.findByText("hash-123");
	});

	it("preserves degraded import status without flooding the viewer with nonfatal diagnostics", async () => {
		apiMocks.importStep.mockResolvedValue({
			importStatus: "Degraded", documentId: "doc-1", definitionId: "def-2", occurrenceId: "occ-2", name: "Screw",
			diagnostics: Array.from({ length: 35 }, (_, i) => ({ code: "Unknown", severity: "Info", source: "Importer.Surface", message: `Spline #${i} reduced within budget; lengthy candidate details.` })),
		});
		render(<App />);
		await screen.findByText("Document: Ready");
		fireEvent.change(screen.getByTestId("step-import-file-input"), { target: { files: [new File(["STEP"], "screw.step")] } });
		await screen.findByText("screw.step");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));
		await screen.findByText(/^Degraded: Import complete\./);
		expect(screen.getByText(/35 informational messages/)).toBeTruthy();
		expect(screen.queryByText(/lengthy candidate details/)).toBeNull();
		expect(screen.getByRole("button", { name: "Download diagnostic log" })).toBeTruthy();
		expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
	});

	it("App_DisplayStatus_ShowsMixedFallbackAsDisplayStatus", async () => {
		apiMocks.importStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "Imported",
			diagnostics: [],
		});
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "hash-123",
			diagnostics: [],
		});
		apiMocks.prepareBodyDisplay.mockResolvedValue({
			lane: "mixed-fallback",
			analyticPacket: {
				bodyId: 1,
				analyticFaces: [
					{
						faceId: 1,
						shellId: 1,
						shellRole: "Outer",
						surfaceGeometryId: 1,
						surfaceKind: "Plane",
						loopCount: 1,
						domainHint: null,
						planeGeometry: null,
						cylinderGeometry: null,
						coneGeometry: null,
						sphereGeometry: null,
						torusGeometry: null,
					},
				],
				fallbackFaces: [
					{
						faceId: 2,
						shellId: 1,
						shellRole: "Outer",
						reason: "UnsupportedTrim",
						surfaceKind: "Plane",
						detail: null,
					},
				],
			},
			tessellationFallback: { facePatches: [], edgePolylines: [] },
			status: "Complete",
			sourceAuthority: "BRep",
			displayAuthority: "DisplayIR",
			lanes: ["AnalyticPatch", "BoundedMesh"],
			displayLanes: [],
			faces: [],
			diagnostics: [],
		});

		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;DATA;"], "ftc06.stp", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("ftc06.stp");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		await screen.findByText("Inspectable: Import complete. Display: mixed analytic + bounded mesh fallback.");
		expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
		expect(screen.queryByText("Import failed")).toBeNull();
	});

	it("reports wireframe-only display fallback separately from import success", async () => {
		apiMocks.importStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "Imported",
			diagnostics: [],
		});
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "hash-123",
			diagnostics: [],
		});
		apiMocks.prepareBodyDisplay.mockResolvedValue({
			lane: "fallback-only",
			analyticPacket: {
				bodyId: 1,
				analyticFaces: [],
				fallbackFaces: [
					{
						faceId: 9,
						shellId: 1,
						shellRole: "Outer",
						reason: "UnsupportedTrim",
						surfaceKind: "Plane",
						detail: null,
					},
				],
			},
			tessellationFallback: { facePatches: [], edgePolylines: [] },
			status: "Partial",
			sourceAuthority: "BRep",
			displayAuthority: "DisplayIR",
			lanes: ["BoundedMesh", "WirePatch"],
			displayLanes: [
				{
					kind: "WirePatch",
					status: "Partial",
					source: "BRep",
					displayAuthority: "DisplayIR",
					implementation: "BRepEdgeWireLowering",
					quality: "PreviewPolyline",
					timeoutMs: null,
					faceCount: 1,
					diagnosticCount: 1,
				},
			],
			faces: [
				{
					faceId: 9,
					shellId: 1,
					surfaceKind: "Plane",
					status: "WireframeOnly",
					patchKind: "WirePatch",
					meshPatch: null,
					analyticPatch: null,
					wirePatch: {
						kind: "WirePatch",
						source: "BRepEdges",
						quality: "PreviewPolyline",
						loops: [
							{
								loopId: 12,
								role: "Outer",
								edges: [
									{
										edgeId: 44,
										points: [
											{ x: 0, y: 0, z: 0 },
											{ x: 1, y: 0, z: 0 },
										],
										sourceCurveKind: "Line3",
										sampleCount: 2,
										diagnostics: [],
									},
								],
							},
						],
					},
					materializationLane: "WirePatch",
					diagnostics: [
						{
							code: "Viewer.Display.WireframeOnly",
							message: "wire",
							faceId: 9,
							surfaceKind: "Plane",
							phase: "BRepEdgeWireLowering",
							suggestedNextAction: null,
						},
					],
				},
			],
			diagnostics: [],
		});

		render(<App />);
		await screen.findByText("Document: Ready");
		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		fireEvent.change(fileInput, {
			target: { files: [new File(["ISO-10303-21;DATA;"], "part.stp", { type: "text/plain" })] },
		});
		await screen.findByText("part.stp");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		expect(
			(
				await screen.findAllByText(
					"Import complete. Display partial: 1 wire-only face(s), 0 diagnostic-only face(s).",
				)
			).length,
		).toBeGreaterThan(0);
		await screen.findByText("Wire-only faces:");
		await screen.findByText("Diagnostic-only faces:");
	});

	it("App_DisplayStatus_ShowsPartialDisplaySeparatelyFromImportFailure", async () => {
		apiMocks.importStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "Imported",
			diagnostics: [],
		});
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "hash-123",
			diagnostics: [],
		});
		apiMocks.prepareBodyDisplay.mockResolvedValue({
			lane: "fallback-only",
			analyticPacket: {
				bodyId: 1,
				analyticFaces: [],
				fallbackFaces: [
					{
						faceId: 9,
						shellId: 1,
						shellRole: "Outer",
						reason: "UnsupportedTrim",
						surfaceKind: "Plane",
						detail: null,
					},
				],
			},
			tessellationFallback: { facePatches: [], edgePolylines: [] },
			status: "Partial",
			sourceAuthority: "BRep",
			displayAuthority: "DisplayIR",
			lanes: ["BoundedMesh", "DiagnosticOnly"],
			displayLanes: [
				{
					kind: "BoundedMesh",
					status: "Partial",
					source: "BRep",
					displayAuthority: "DisplayIR",
					implementation: "BrepDisplayTessellator",
					quality: "Default",
					timeoutMs: 5000,
					faceCount: 0,
					diagnosticCount: 1,
				},
			],
			faces: [
				{
					faceId: 9,
					shellId: 1,
					surfaceKind: "Plane",
					status: "DiagnosticOnly",
					patchKind: "DiagnosticPatch",
					meshPatch: null,
					analyticPatch: null,
					wirePatch: null,
					materializationLane: "BoundedMesh",
					diagnostics: [
						{
							code: "Viewer.Tessellation.Timeout",
							message: "timeout",
							faceId: 9,
							surfaceKind: "Plane",
							phase: "PlanarTriangulationWithHoles",
							suggestedNextAction: null,
						},
					],
				},
			],
			diagnostics: [],
		});

		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;DATA;"], "part.stp", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("part.stp");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		await waitFor(() => {
			expect(apiMocks.prepareBodyDisplay).toHaveBeenCalledWith("doc-1", "occ-2");
		});
		expect(
			(
				await screen.findAllByText(
					"Import complete. Display partial: 0 wire-only face(s), 1 diagnostic-only face(s).",
				)
			).length,
		).toBeGreaterThan(0);
		await screen.findByText("Degraded: Import complete. Display partial: 0 wire-only face(s), 1 diagnostic-only face(s).");
		expect(screen.queryByText("hash-123")).toBeNull();
		expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
		expect(screen.queryByText("Import failed")).toBeNull();
	});

	it("downloads backend STEP text with deterministic filename without mutating hash state", async () => {
		const createObjectUrlSpy = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:download");
		const revokeObjectUrlSpy = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
		const anchorClickSpy = vi
			.spyOn(HTMLAnchorElement.prototype, "click")
			.mockImplementation(() => undefined);
		const appendSpy = vi.spyOn(document.body, "appendChild");

		apiMocks.exportDefinitionStep
			.mockResolvedValueOnce({
				documentId: "doc-1",
				definitionId: "def-2",
				stepText: "ISO-10303-21;HEADER;ENDSEC;",
				canonicalHash: "hash-initial",
				diagnostics: [],
			})
			.mockResolvedValueOnce({
				documentId: "doc-1",
				definitionId: "def-2",
				stepText: "ISO-10303-21;DATA;ENDSEC;",
				canonicalHash: "hash-after-download",
				diagnostics: [],
			});

		render(<App />);
		await screen.findByText("Document: Ready");

		fireEvent.change(screen.getByTestId("step-import-file-input"), { target: { files: [new File(["STEP"], "bracket.step")] } });
		await screen.findByText("bracket.step");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));
		await screen.findByText(/^Inspectable: Import complete/);

		fireEvent.click(screen.getByRole("tab", { name: /STEP 242 Viewer/i }));
		fireEvent.click(screen.getByRole("button", { name: "Export Active (STEP)" }));
		await screen.findByText("hash-initial");

		fireEvent.click(screen.getByRole("button", { name: "Download Canonical 242" }));

		await waitFor(() => {
			expect(apiMocks.exportDefinitionStep).toHaveBeenNthCalledWith(2, "doc-1", "def-2");
		});

		const blob = createObjectUrlSpy.mock.calls[0][0] as Blob;
		expect(await blob.text()).toBe("ISO-10303-21;DATA;ENDSEC;");

		const downloadAnchor = appendSpy.mock.calls.at(-1)?.[0] as HTMLAnchorElement;
		expect(downloadAnchor.download).toBe("bracket.step");
		expect(anchorClickSpy).toHaveBeenCalledTimes(1);
		expect(revokeObjectUrlSpy).toHaveBeenCalledWith("blob:download");

		expect(screen.getByText("hash-initial")).toBeTruthy();
		expect(screen.queryByText("hash-after-download")).toBeNull();
	});

	it("preserves ApiError diagnostics from import failure", async () => {
		apiMocks.importStep.mockRejectedValue(
			new ApiError("Malformed STEP payload.", [
				{
					code: "ValidationFailed",
					severity: "Error",
					message: "Malformed STEP payload.",
					source: "step242.import",
				},
			]),
		);

		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["BAD"], "bad.step", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("bad.step");

		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		await screen.findByText("Import failed");
		await screen.findByText("Malformed STEP payload.");
		await screen.findByText("[Error] ValidationFailed: Malformed STEP payload.");
	});

	it("reports view materialization failure without masquerading as import failure", async () => {
		apiMocks.importStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			occurrenceId: "occ-2",
			name: "Imported",
			diagnostics: [],
		});
		apiMocks.prepareBodyDisplay.mockRejectedValue(
			new ApiError("Display tessellation exceeded the bounded execution budget.", [
				{
					code: "ValidationFailed",
					severity: "Error",
					message: "Display tessellation exceeded the bounded execution budget.",
					source: "Viewer.Tessellation.Timeout",
				},
			]),
		);
		apiMocks.exportDefinitionStep.mockResolvedValue({
			documentId: "doc-1",
			definitionId: "def-2",
			stepText: "ISO-10303-21;",
			canonicalHash: "hash-123",
			diagnostics: [],
		});

		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;DATA;"], "ftc07.stp", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("ftc07.stp");

		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));

		await screen.findByText("Degraded: import retained. View materialization failed.");
		await screen.findByText(
			"[Error] ValidationFailed: Display tessellation exceeded the bounded execution budget.",
		);
		expect(screen.queryByText("Import failed")).toBeNull();
		expect(screen.queryByText("hash-123")).toBeNull();
		expect(apiMocks.exportDefinitionStep).not.toHaveBeenCalled();
	});

	it("preserves ApiError diagnostics from canonical download failure", async () => {
		apiMocks.exportDefinitionStep.mockRejectedValue(
			new ApiError("Export failed.", [
				{
					code: "StepExportFailed",
					severity: "Error",
					message: "Export failed.",
					source: "step242.export",
				},
			]),
		);

		render(<App />);
		await screen.findByText("Document: Ready");
		fireEvent.change(screen.getByTestId("step-import-file-input"), { target: { files: [new File(["STEP"], "bracket.step")] } });
		await screen.findByText("bracket.step");
		fireEvent.click(screen.getByRole("button", { name: "Import STEP 242" }));
		await screen.findByText(/^Inspectable: Import complete/);
		fireEvent.click(screen.getByRole("tab", { name: /STEP 242 Viewer/i }));

		fireEvent.click(screen.getByRole("button", { name: "Download Canonical 242" }));

		await screen.findByText("[Error] StepExportFailed: Export failed.");
	});

	it("keeps file selection while document is still preparing and enables import when ready", async () => {
		let resolveCreate: (value: { documentId: string; name: string; volatile: boolean }) => void =
			() => undefined;
		apiMocks.createDocument.mockImplementationOnce(
			() =>
				new Promise<{ documentId: string; name: string; volatile: boolean }>((resolve) => {
					resolveCreate = resolve;
				}),
		);

		render(<App />);

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;DATA;"], "part.stp", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });

		await screen.findByText("part.stp");
		expect(
			(screen.getByRole("button", { name: "Import STEP 242" }) as HTMLButtonElement).disabled,
		).toBe(true);

		resolveCreate({ documentId: "doc-1", name: "Test", volatile: true });
		await screen.findByText("Document: Ready");

		await waitFor(() => {
			expect(
				(screen.getByRole("button", { name: "Import STEP 242" }) as HTMLButtonElement).disabled,
			).toBe(false);
		});
	});

	it("resets file selection and document-bound state when New Document is pressed", async () => {
		render(<App />);
		await screen.findByText("Document: Ready");

		const fileInput = screen.getByTestId("step-import-file-input") as HTMLInputElement;
		const file = new File(["ISO-10303-21;"], "sample.step", { type: "text/plain" });
		fireEvent.change(fileInput, { target: { files: [file] } });
		await screen.findByText("sample.step");

		fireEvent.click(screen.getByRole("button", { name: "New Document" }));

		await screen.findByText("Drop STEP file here or click to browse");
		expect(screen.getByText("Document: Ready")).toBeTruthy();
		expect(screen.getByText("Ready. Select a file to import.")).toBeTruthy();
		expect(apiMocks.createDocument).toHaveBeenCalledTimes(2);
	});

	it("disables import button unless server connected, document ready, and file selected", async () => {
		apiMocks.createDocument.mockRejectedValueOnce(new ApiError("Server unavailable.", []));
		render(<App />);

		await screen.findByText("Server: Error");
		expect(
			(screen.getByRole("button", { name: "Import STEP 242" }) as HTMLButtonElement).disabled,
		).toBe(true);
	});
});