Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel
Refine STEP import display status and viewport fitting
Yuechen Li7032d92e56a5
diff --git a/aetheris.client/src/App.tsx b/aetheris.client/src/App.tsxindex 0dff67e2..4a84949d 100644--- a/aetheris.client/src/App.tsx+++ b/aetheris.client/src/App.tsx@@ -31,12 +31,62 @@ type ServerStatus = 'connecting' | 'connected' | 'disconnected' | 'error';type DocumentStatus = 'creating' | 'ready' | 'error';type ImportStatus = 'idle' | 'creating' | 'importing' | 'success' | 'error';+interface DisplayStatusSummary {+ summary: string;+ wireOnlyFaceCount: number;+ diagnosticOnlyFaceCount: number;+}++interface RefreshDisplayResult {+ preparation: DisplayPreparationResponseDto | null;+ error: ApiError | null;+}+const BOOLEAN_OP_TO_API: Record<BooleanOperationUi, BooleanOperation> = {Union: 'union',Subtract: 'subtract',Intersect: 'intersect',};+function createDisplayStatusSummary(preparation: DisplayPreparationResponseDto | null): DisplayStatusSummary | null {+ if (!preparation) {+ return null;+ }++ const wireOnlyFaceCount = preparation.faces?.filter((face) => face.status === 'WireframeOnly').length ?? 0;+ const diagnosticOnlyFaceCount = preparation.faces?.filter((face) => face.status === 'DiagnosticOnly').length ?? 0;++ if (preparation.status === 'Partial') {+ return {+ summary: `Import complete. Display partial: ${wireOnlyFaceCount} wire-only face(s), ${diagnosticOnlyFaceCount} diagnostic-only face(s).`,+ wireOnlyFaceCount,+ diagnosticOnlyFaceCount,+ };+ }++ if (preparation.lane === 'mixed-fallback') {+ return {+ summary: 'Import complete. Display: mixed analytic + bounded mesh fallback.',+ wireOnlyFaceCount,+ diagnosticOnlyFaceCount,+ };+ }++ if (preparation.lane === 'fallback-only') {+ return {+ summary: 'Import complete. Display: bounded mesh fallback.',+ wireOnlyFaceCount,+ diagnosticOnlyFaceCount,+ };+ }++ return {+ summary: 'Import complete.',+ wireOnlyFaceCount,+ diagnosticOnlyFaceCount,+ };+}+function App() {const [activeTab, setActiveTab] = useState<TopLevelTab>('viewer');const [documentId, setDocumentId] = useState<string | null>(null);@@ -151,9 +201,9 @@ function App() {}}, []);- const refreshSummaryAndActiveTessellation = useCallback(async (targetBodyId?: string, suppressDisplayErrors = false) => {+ const refreshSummaryAndActiveTessellation = useCallback(async (targetBodyId?: string, suppressDisplayErrors = false): Promise<RefreshDisplayResult> => {if (!documentId) {- return null;+ return { preparation: null, error: null };}const summary = await getDocumentSummary(documentId);@@ -168,7 +218,7 @@ function App() {const preparedDisplay = await prepareBodyDisplay(documentId, selected);setDisplayPreparation(preparedDisplay);setTessellation(preparedDisplay.tessellationFallback);- return null;+ return { preparation: preparedDisplay, error: null };} catch (error) {const apiError = error instanceof ApiError? error@@ -179,14 +229,14 @@ function App() {throw apiError;}- return apiError;+ return { preparation: null, error: apiError };}} else {setTessellation(null);setDisplayPreparation(null);}- return null;+ return { preparation: null, error: null };}, [activeBodyId, documentId]);const handleCreateDocument = useCallback(async () => {@@ -368,41 +418,53 @@ function App() {setImportStatus('importing');setImportStatusMessage('Importing STEP…');setIsImporting(true);+ setDiagnostics([]);try {- let displayError: ApiError | null = null;- const didImport = await runAction('Import STEP', async () => {- const stepText = await stepImportFile.text();- if (stepText.trim().length === 0) {- throw new ApiError('Selected STEP file is empty.', []);- }+ setStatus('loading');+ setStatusMessage('Import STEP...');- const imported = await importStep(documentId, stepText);- setStepExportText('');- displayError = await refreshSummaryAndActiveTessellation(imported.occurrenceId, true);- const exported = await exportDefinitionStep(documentId, imported.definitionId);- setStepCanonicalHash(exported.canonicalHash);- setPickStatus('idle');- setPickMessage(`Imported occurrence ${imported.occurrenceId} is now active.`);- setPickDiagnostics([]);- setPickHits([]);- setCopyHashMessage('');- });- const importDisplayError = displayError as ApiError | null;- if (didImport && importDisplayError) {+ const stepText = await stepImportFile.text();+ if (stepText.trim().length === 0) {+ throw new ApiError('Selected STEP file is empty.', []);+ }++ const imported = await importStep(documentId, stepText);+ setStepExportText('');+ const displayRefresh = await refreshSummaryAndActiveTessellation(imported.occurrenceId, true);+ const exported = await exportDefinitionStep(documentId, imported.definitionId);+ setStepCanonicalHash(exported.canonicalHash);+ setPickStatus('idle');+ setPickMessage(`Imported occurrence ${imported.occurrenceId} is now active.`);+ setPickDiagnostics([]);+ setPickHits([]);+ setCopyHashMessage('');++ if (displayRefresh.error) {setStatus('error');- setStatusMessage(`View materialization failed after import: ${importDisplayError.message}`);- setDiagnostics(importDisplayError.diagnostics);+ setStatusMessage(`View materialization failed after import: ${displayRefresh.error.message}`);+ setDiagnostics(displayRefresh.error.diagnostics);setImportStatus('success');setImportStatusMessage('Import complete. View materialization failed.');} else {- setImportStatus(didImport ? 'success' : 'error');- setImportStatusMessage(didImport ? 'Import complete.' : 'Import error: Request failed.');+ setStatus('success');+ setStatusMessage('Import STEP complete.');+ setImportStatus('success');+ setImportStatusMessage(createDisplayStatusSummary(displayRefresh.preparation)?.summary ?? 'Import complete.');}+ } catch (error) {+ const apiError = error instanceof ApiError+ ? error+ : new ApiError((error as Error).message || 'Unexpected error.', []);+ setStatus('error');+ setStatusMessage(apiError.message);+ setDiagnostics(apiError.diagnostics);+ setImportStatus('error');+ setImportStatusMessage(`Import error: ${apiError.message}`);} finally {setIsImporting(false);}- }, [documentId, documentStatus, refreshSummaryAndActiveTessellation, runAction, serverStatus, stepImportFile]);+ }, [documentId, documentStatus, refreshSummaryAndActiveTessellation, serverStatus, stepImportFile]);const handleStepFileAccepted = useCallback((selected: File) => {setStepImportFile(selected);@@ -529,6 +591,7 @@ function App() {error: 'Document: Error',};const importStatusTone = importStatus === 'error' ? 'error' : (importStatus === 'success' ? 'success' : 'neutral');+ const displayStatusSummary = createDisplayStatusSummary(displayPreparation);return (<div className="app-shell">@@ -685,12 +748,12 @@ function App() {<p><strong>Occurrence ID:</strong> {activeBodyId ?? 'None'}</p><p><strong>Display lane:</strong> {displayPreparation?.lane ?? 'None'}</p><p><strong>Display status:</strong> {displayPreparation?.status ?? 'None'}</p>- {displayPreparation?.status === 'Partial' ? <p role="status">Import succeeded. Display partial: display degraded: {displayPreparation.faces?.filter((face) => face.status === 'WireframeOnly').length ?? 0} wire-only face(s), {displayPreparation.faces?.filter((face) => face.status === 'DiagnosticOnly').length ?? 0} diagnostic-only face(s).</p> : null}+ {displayPreparation?.status === 'Partial' && displayStatusSummary ? <p role="status">{displayStatusSummary.summary}</p> : null}<p><strong>Render path:</strong> {displayScene.renderPath}</p><p><strong>Analytic faces:</strong> {displayPreparation?.analyticPacket.analyticFaces.length ?? 0}</p><p><strong>Fallback faces:</strong> {displayPreparation?.analyticPacket.fallbackFaces.length ?? 0}</p>- <p><strong>Wire-only faces:</strong> {displayPreparation?.faces?.filter((face) => face.status === 'WireframeOnly').length ?? 0}</p>- <p><strong>Diagnostic-only faces:</strong> {displayPreparation?.faces?.filter((face) => face.status === 'DiagnosticOnly').length ?? 0}</p>+ <p><strong>Wire-only faces:</strong> {displayStatusSummary?.wireOnlyFaceCount ?? 0}</p>+ <p><strong>Diagnostic-only faces:</strong> {displayStatusSummary?.diagnosticOnlyFaceCount ?? 0}</p><p><strong>Face count:</strong> {tessellation?.facePatches.length ?? 0}</p><p><strong>Edge count:</strong> {tessellation?.edgePolylines.length ?? 0}</p><p><strong>Shell count:</strong> {activeBodyId ? 1 : 0}</p>@@ -797,8 +860,8 @@ function App() {<p><strong>Render path:</strong> {displayScene.renderPath}</p><p><strong>Analytic faces:</strong> {displayPreparation?.analyticPacket.analyticFaces.length ?? 0}</p><p><strong>Fallback faces:</strong> {displayPreparation?.analyticPacket.fallbackFaces.length ?? 0}</p>- <p><strong>Wire-only faces:</strong> {displayPreparation?.faces?.filter((face) => face.status === 'WireframeOnly').length ?? 0}</p>- <p><strong>Diagnostic-only faces:</strong> {displayPreparation?.faces?.filter((face) => face.status === 'DiagnosticOnly').length ?? 0}</p>+ <p><strong>Wire-only faces:</strong> {displayStatusSummary?.wireOnlyFaceCount ?? 0}</p>+ <p><strong>Diagnostic-only faces:</strong> {displayStatusSummary?.diagnosticOnlyFaceCount ?? 0}</p><p><strong>Face patches:</strong> {tessellation?.facePatches.length ?? 0}</p><p><strong>Edge polylines:</strong> {tessellation?.edgePolylines.length ?? 0}</p><h3 className="section-title section-title--sub">Pick Diagnostics (active body only)</h3>diff --git a/aetheris.client/src/__tests__/AetherisViewport.test.tsx b/aetheris.client/src/__tests__/AetherisViewport.test.tsxindex 2fe5c7cf..d08bbdd8 100644--- a/aetheris.client/src/__tests__/AetherisViewport.test.tsx+++ b/aetheris.client/src/__tests__/AetherisViewport.test.tsx@@ -6,7 +6,12 @@ import type { DisplayScene } from '../viewer/displayRenderables';vi.mock('@react-three/fiber', () => ({Canvas: ({ children }: { children: React.ReactNode }) => <div data-testid="canvas">{children}</div>,useFrame: () => undefined,- useThree: () => ({ camera: { position: { x: 0, z: 0 }, zoom: 1 }, gl: { domElement: { addEventListener: vi.fn(), removeEventListener: vi.fn() } } }),+ useThree: () => ({+ camera: { position: { x: 0, z: 0 }, zoom: 1 },+ controls: null,+ size: { width: 800, height: 600 },+ gl: { domElement: { addEventListener: vi.fn(), removeEventListener: vi.fn() } },+ }),}));vi.mock('@react-three/drei', () => ({diff --git a/aetheris.client/src/__tests__/App.test.tsx b/aetheris.client/src/__tests__/App.test.tsxindex ab202652..32593503 100644--- a/aetheris.client/src/__tests__/App.test.tsx+++ b/aetheris.client/src/__tests__/App.test.tsx@@ -281,6 +281,51 @@ describe('App STEP file upload flow', () => {await screen.findByText('hash-123');});+ 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('Import complete. Display: mixed analytic + bounded mesh fallback.');+ 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: [] });@@ -310,13 +355,13 @@ describe('App STEP file upload flow', () => {await screen.findByText('part.stp');fireEvent.click(screen.getByRole('button', { name: 'Import STEP 242' }));- await screen.findByText('Import succeeded. Display partial: display degraded: 1 wire-only face(s), 0 diagnostic-only face(s).');+ 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('reports bounded mesh partial display separately from import success', async () => {+ it('App_DisplayStatus_ShowsPartialDisplaySeparatelyFromImportFailure', async () => {apiMocks.importStep.mockResolvedValue({documentId: 'doc-1',definitionId: 'def-2',@@ -367,8 +412,9 @@ describe('App STEP file upload flow', () => {await waitFor(() => {expect(apiMocks.prepareBodyDisplay).toHaveBeenCalledWith('doc-1', 'occ-2');});- await screen.findByText('Import succeeded. Display partial: display degraded: 0 wire-only face(s), 1 diagnostic-only face(s).');+ expect((await screen.findAllByText('Import complete. Display partial: 0 wire-only face(s), 1 diagnostic-only face(s).')).length).toBeGreaterThan(0);await screen.findByText('hash-123');+ expect(screen.queryByText('Import failed')).toBeNull();});it('downloads backend STEP text with deterministic filename without mutating hash state', async () => {diff --git a/aetheris.client/src/__tests__/displaySceneBounds.test.ts b/aetheris.client/src/__tests__/displaySceneBounds.test.tsnew file mode 100644index 00000000..37eb6810--- /dev/null+++ b/aetheris.client/src/__tests__/displaySceneBounds.test.ts@@ -0,0 +1,143 @@+import { describe, expect, it } from 'vitest';+import type { DisplayScene } from '../viewer/displayRenderables';+import { computeDisplaySceneBounds, computeOrthographicCameraFit } from '../viewer/displaySceneBounds';+import type { RenderSceneData } from '../viewer/tessellationMapper';++const baseScene: DisplayScene = {+ renderables: [],+ sourceAuthority: 'BRep',+ displayAuthority: 'DisplayIR',+ displayLanes: [],+ displayStatus: 'Complete',+};++describe('displaySceneBounds', () => {+ it('computeDisplaySceneBounds_IncludesMeshRenderableVertices', () => {+ const displayScene: DisplayScene = {+ ...baseScene,+ renderables: [{+ kind: 'MeshPatch',+ faceId: 1,+ surfaceKind: 'Plane',+ status: 'Mesh',+ patchKind: 'MeshPatch',+ materializationLane: 'BoundedMesh',+ diagnostics: [],+ mesh: {+ faceId: 1,+ positions: new Float32Array([10, 20, 30, 40, 50, 60, 15, 25, 35]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),+ indices: new Uint32Array([0, 1, 2]),+ },+ }],+ };++ const bounds = computeDisplaySceneBounds(displayScene);++ expect(bounds.isValid).toBe(true);+ expect(bounds.min).toEqual([10, 20, 30]);+ expect(bounds.max).toEqual([40, 50, 60]);+ });++ it('computeDisplaySceneBounds_IncludesAnalyticPreviewVertices', () => {+ const displayScene: DisplayScene = {+ ...baseScene,+ renderables: [{+ kind: 'AnalyticPatch',+ faceId: 2,+ surfaceKind: 'Cylinder',+ status: 'Analytic',+ patchKind: 'AnalyticPatch',+ materializationLane: 'AnalyticPatch',+ diagnostics: [],+ previewMesh: {+ faceId: 2,+ positions: new Float32Array([-5, -2, -1, 7, 3, 11, 1, 0, 2]),+ normals: new Float32Array([0, 1, 0, 0, 1, 0, 0, 1, 0]),+ indices: new Uint32Array([0, 1, 2]),+ },+ }],+ };++ const bounds = computeDisplaySceneBounds(displayScene);++ expect(bounds.min).toEqual([-5, -2, -1]);+ expect(bounds.max).toEqual([7, 3, 11]);+ });++ it('computeDisplaySceneBounds_IncludesWirePatchPoints', () => {+ const displayScene: DisplayScene = {+ ...baseScene,+ renderables: [{+ kind: 'WirePatch',+ faceId: 3,+ surfaceKind: 'Plane',+ status: 'WireframeOnly',+ patchKind: 'WirePatch',+ materializationLane: 'WirePatch',+ diagnostics: [],+ wires: [{ edgeId: 30, points: new Float32Array([-20, 1, 4, 12, 6, 8, 0, -3, 5]) }],+ }],+ };++ const bounds = computeDisplaySceneBounds(displayScene);++ expect(bounds.min).toEqual([-20, -3, 4]);+ expect(bounds.max).toEqual([12, 6, 8]);+ });++ it('computeDisplaySceneBounds_IgnoresDiagnosticOnlyFacesWithoutProxy', () => {+ const displayScene: DisplayScene = {+ ...baseScene,+ renderables: [{+ kind: 'DiagnosticPatch',+ faceId: 4,+ surfaceKind: 'Plane',+ status: 'DiagnosticOnly',+ patchKind: 'DiagnosticPatch',+ materializationLane: 'DiagnosticOnly',+ diagnostics: [{ code: 'Viewer.Tessellation.Timeout', message: 'timeout', faceId: 4, surfaceKind: 'Plane', phase: 'phase', suggestedNextAction: null }],+ }],+ };++ const bounds = computeDisplaySceneBounds(displayScene);++ expect(bounds.isValid).toBe(false);+ });++ it('AetherisViewport_FitsCameraToDisplaySceneBounds', () => {+ const sceneData: RenderSceneData = {+ faces: [],+ edges: [],+ };+ const displayScene: DisplayScene = {+ ...baseScene,+ renderables: [{+ kind: 'MeshPatch',+ faceId: 5,+ surfaceKind: 'Plane',+ status: 'Mesh',+ patchKind: 'MeshPatch',+ materializationLane: 'BoundedMesh',+ diagnostics: [],+ mesh: {+ faceId: 5,+ positions: new Float32Array([1000, 1000, 1000, 1100, 1000, 1000, 1000, 1200, 1000]),+ normals: new Float32Array([0, 0, 1, 0, 0, 1, 0, 0, 1]),+ indices: new Uint32Array([0, 1, 2]),+ },+ }],+ };++ const bounds = computeDisplaySceneBounds(displayScene, sceneData);+ const fit = computeOrthographicCameraFit(bounds, 20, 20);++ expect(fit).not.toBeNull();+ expect(fit?.target).toEqual([1050, 1100, 1000]);+ expect(fit?.position[0]).toBeGreaterThan(1050);+ expect(fit?.position[1]).toBeGreaterThan(1100);+ expect(fit?.position[2]).toBeGreaterThan(1000);+ expect(fit?.zoom).toBeGreaterThan(0);+ expect(fit?.far).toBeGreaterThan(fit?.near ?? 0);+ });+});diff --git a/aetheris.client/src/viewer/AetherisViewport.tsx b/aetheris.client/src/viewer/AetherisViewport.tsxindex a0b109c2..1c763060 100644--- a/aetheris.client/src/viewer/AetherisViewport.tsx+++ b/aetheris.client/src/viewer/AetherisViewport.tsx@@ -5,6 +5,7 @@ import { useEffect, useMemo, useState } from 'react';import type { ReactNode } from 'react';import { BufferAttribute, BufferGeometry, Color, DoubleSide, MeshStandardMaterial, OrthographicCamera, Raycaster, Vector2, Vector3 } from 'three';import type { DisplayScene } from './displayRenderables';+import { computeDisplaySceneBounds, computeOrthographicCameraFit } from './displaySceneBounds';import type { RenderSceneData } from './tessellationMapper';import { selectLogarithmicGridScales } from './logarithmicGrid';@@ -584,6 +585,41 @@ function PickRayCapture({ onPickRay }: { onPickRay?: AetherisViewportProps['onPireturn null;}+function FitCameraToScene({ displayScene, sceneData }: { displayScene: DisplayScene | null; sceneData: RenderSceneData | null }) {+ const { camera, controls, size } = useThree();+ const sceneBounds = useMemo(() => computeDisplaySceneBounds(displayScene, sceneData), [displayScene, sceneData]);++ useEffect(() => {+ if (!(camera instanceof OrthographicCamera) || !sceneBounds.isValid) {+ return;+ }++ const frustumWidth = Math.abs(camera.right - camera.left) || size.width || 1;+ const frustumHeight = Math.abs(camera.top - camera.bottom) || size.height || 1;+ const fit = computeOrthographicCameraFit(sceneBounds, frustumWidth, frustumHeight);++ if (!fit) {+ return;+ }++ camera.position.set(...fit.position);+ camera.zoom = fit.zoom;+ camera.near = fit.near;+ camera.far = fit.far;+ camera.lookAt(...fit.target);+ camera.updateProjectionMatrix();+ camera.updateMatrixWorld(false);++ if (controls && typeof controls === 'object' && 'target' in controls) {+ const orbitControls = controls as { target: Vector3; update?: () => void };+ orbitControls.target.set(...fit.target);+ orbitControls.update?.();+ }+ }, [camera, controls, sceneBounds, size.height, size.width]);++ return null;+}+export function AetherisViewport({displayScene = null,sceneData,@@ -600,6 +636,7 @@ export function AetherisViewport({{/*Negative near value is indeed correct in order to show negative value on grid. Documentation is wrong.*/}<ambientLight intensity={VIEWPORT_THEME.ambientIntensity} /><directionalLight position={[-5, 9, 6]} intensity={VIEWPORT_THEME.directionalIntensity} />+ <FitCameraToScene displayScene={displayScene} sceneData={sceneData} />{showGrid ? <DraftingGrid /> : null}{showAxisGuide ? <AxisGuide /> : null}{displayScene?.renderables.map((renderable) => {diff --git a/aetheris.client/src/viewer/displaySceneBounds.ts b/aetheris.client/src/viewer/displaySceneBounds.tsnew file mode 100644index 00000000..90dea14f--- /dev/null+++ b/aetheris.client/src/viewer/displaySceneBounds.ts@@ -0,0 +1,253 @@+import type { DisplayScene } from './displayRenderables';+import type { RenderSceneData } from './tessellationMapper';++export interface SceneBounds {+ min: [number, number, number];+ max: [number, number, number];+ center: [number, number, number];+ size: [number, number, number];+ diagonal: number;+ radius: number;+ isValid: boolean;+}++export interface OrthographicCameraFit {+ position: [number, number, number];+ target: [number, number, number];+ zoom: number;+ near: number;+ far: number;+}++interface MutableBounds {+ minX: number;+ minY: number;+ minZ: number;+ maxX: number;+ maxY: number;+ maxZ: number;+ pointCount: number;+}++interface Vec3 {+ x: number;+ y: number;+ z: number;+}++const EMPTY_BOUNDS: SceneBounds = {+ min: [0, 0, 0],+ max: [0, 0, 0],+ center: [0, 0, 0],+ size: [0, 0, 0],+ diagonal: 0,+ radius: 0,+ isValid: false,+};++function createBounds(): MutableBounds {+ return {+ minX: Number.POSITIVE_INFINITY,+ minY: Number.POSITIVE_INFINITY,+ minZ: Number.POSITIVE_INFINITY,+ maxX: Number.NEGATIVE_INFINITY,+ maxY: Number.NEGATIVE_INFINITY,+ maxZ: Number.NEGATIVE_INFINITY,+ pointCount: 0,+ };+}++function includePoint(bounds: MutableBounds, x: number, y: number, z: number): void {+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {+ return;+ }++ bounds.minX = Math.min(bounds.minX, x);+ bounds.minY = Math.min(bounds.minY, y);+ bounds.minZ = Math.min(bounds.minZ, z);+ bounds.maxX = Math.max(bounds.maxX, x);+ bounds.maxY = Math.max(bounds.maxY, y);+ bounds.maxZ = Math.max(bounds.maxZ, z);+ bounds.pointCount += 1;+}++function includeTriplets(bounds: MutableBounds, values: Float32Array): void {+ for (let index = 0; index <= values.length - 3; index += 3) {+ includePoint(bounds, values[index], values[index + 1], values[index + 2]);+ }+}++function finalizeBounds(bounds: MutableBounds): SceneBounds {+ if (bounds.pointCount === 0) {+ return EMPTY_BOUNDS;+ }++ const min: [number, number, number] = [bounds.minX, bounds.minY, bounds.minZ];+ const max: [number, number, number] = [bounds.maxX, bounds.maxY, bounds.maxZ];+ const size: [number, number, number] = [+ bounds.maxX - bounds.minX,+ bounds.maxY - bounds.minY,+ bounds.maxZ - bounds.minZ,+ ];+ const center: [number, number, number] = [+ (bounds.minX + bounds.maxX) * 0.5,+ (bounds.minY + bounds.maxY) * 0.5,+ (bounds.minZ + bounds.maxZ) * 0.5,+ ];+ const diagonal = Math.hypot(size[0], size[1], size[2]);++ return {+ min,+ max,+ center,+ size,+ diagonal,+ radius: diagonal > 0 ? diagonal * 0.5 : 0.5,+ isValid: true,+ };+}++function computeTypedBounds(displayScene: DisplayScene | null): SceneBounds {+ if (!displayScene) {+ return EMPTY_BOUNDS;+ }++ const bounds = createBounds();++ for (const renderable of displayScene.renderables) {+ if (renderable.kind === 'AnalyticPatch') {+ includeTriplets(bounds, renderable.previewMesh.positions);+ continue;+ }++ if (renderable.kind === 'MeshPatch') {+ includeTriplets(bounds, renderable.mesh.positions);+ continue;+ }++ if (renderable.kind === 'WirePatch') {+ for (const wire of renderable.wires) {+ includeTriplets(bounds, wire.points);+ }+ }+ }++ return finalizeBounds(bounds);+}++function computeFallbackBounds(sceneData: RenderSceneData | null): SceneBounds {+ if (!sceneData) {+ return EMPTY_BOUNDS;+ }++ const bounds = createBounds();++ for (const face of sceneData.faces) {+ includeTriplets(bounds, face.positions);+ }++ for (const edge of sceneData.edges) {+ includeTriplets(bounds, edge.points);+ }++ return finalizeBounds(bounds);+}++export function computeDisplaySceneBounds(displayScene: DisplayScene | null, sceneData: RenderSceneData | null = null): SceneBounds {+ const typedBounds = computeTypedBounds(displayScene);+ return typedBounds.isValid ? typedBounds : computeFallbackBounds(sceneData);+}++function normalize(vector: Vec3): Vec3 {+ const length = Math.hypot(vector.x, vector.y, vector.z);+ if (length <= 1e-9) {+ return { x: 0, y: 0, z: 1 };+ }++ return {+ x: vector.x / length,+ y: vector.y / length,+ z: vector.z / length,+ };+}++function cross(a: Vec3, b: Vec3): Vec3 {+ return {+ x: (a.y * b.z) - (a.z * b.y),+ y: (a.z * b.x) - (a.x * b.z),+ z: (a.x * b.y) - (a.y * b.x),+ };+}++function dot(a: Vec3, b: Vec3): number {+ return (a.x * b.x) + (a.y * b.y) + (a.z * b.z);+}++function getBoundsCorners(bounds: SceneBounds): Vec3[] {+ const [minX, minY, minZ] = bounds.min;+ const [maxX, maxY, maxZ] = bounds.max;++ return [+ { x: minX, y: minY, z: minZ },+ { x: minX, y: minY, z: maxZ },+ { x: minX, y: maxY, z: minZ },+ { x: minX, y: maxY, z: maxZ },+ { x: maxX, y: minY, z: minZ },+ { x: maxX, y: minY, z: maxZ },+ { x: maxX, y: maxY, z: minZ },+ { x: maxX, y: maxY, z: maxZ },+ ];+}++export function computeOrthographicCameraFit(+ bounds: SceneBounds,+ frustumWidth: number,+ frustumHeight: number,+ viewDirection: [number, number, number] = [1, 1, 1],+): OrthographicCameraFit | null {+ if (!bounds.isValid || frustumWidth <= 0 || frustumHeight <= 0) {+ return null;+ }++ const target: Vec3 = { x: bounds.center[0], y: bounds.center[1], z: bounds.center[2] };+ const forward = normalize({ x: viewDirection[0], y: viewDirection[1], z: viewDirection[2] });+ const worldUp = Math.abs(forward.y) > 0.95 ? { x: 0, y: 0, z: 1 } : { x: 0, y: 1, z: 0 };+ const right = normalize(cross(worldUp, forward));+ const up = normalize(cross(forward, right));++ let projectedHalfWidth = 0;+ let projectedHalfHeight = 0;++ for (const corner of getBoundsCorners(bounds)) {+ const relative = {+ x: corner.x - target.x,+ y: corner.y - target.y,+ z: corner.z - target.z,+ };++ projectedHalfWidth = Math.max(projectedHalfWidth, Math.abs(dot(relative, right)));+ projectedHalfHeight = Math.max(projectedHalfHeight, Math.abs(dot(relative, up)));+ }++ const margin = 1.15;+ const zoom = Math.max(+ 0.01,+ Math.min(+ frustumWidth / (Math.max(projectedHalfWidth * 2, 1e-3) * margin),+ frustumHeight / (Math.max(projectedHalfHeight * 2, 1e-3) * margin),+ ),+ );+ const distance = Math.max(bounds.radius * 4, 6);++ return {+ position: [+ target.x + (forward.x * distance),+ target.y + (forward.y * distance),+ target.z + (forward.z * distance),+ ],+ target: [target.x, target.y, target.z],+ zoom,+ near: 0.01,+ far: Math.max(distance + (bounds.radius * 8), 100),+ };+}diff --git a/docs/display-architecture-x5-threejs-displayir-renderer-cleanup.md b/docs/display-architecture-x5-threejs-displayir-renderer-cleanup.mdindex 24b21fb2..e44bb5bf 100644--- a/docs/display-architecture-x5-threejs-displayir-renderer-cleanup.md+++ b/docs/display-architecture-x5-threejs-displayir-renderer-cleanup.md@@ -64,3 +64,7 @@ DISPLAY-ARCH-X6 — typed DisplayIR API cleanup / remove legacy render-scene ass## X5.1 follow-upDISPLAY-ARCH-X5.1 resolved the imported-occurrence server validation issue by documenting and testing the distinction between direct bounded `/tessellate` mesh lowering and DisplayIR-authoritative `/display/prepare`. The frontend typed renderable architecture from X5 remains unchanged.++## X5.2 follow-up++DISPLAY-QA-X2 kept the X5 typed-renderable contract intact but fixed one remaining frontend legacy assumption: imported-body framing still used a fixed orthographic camera pose instead of bounds derived from typed DisplayIR renderables. X2 added DisplayIR-aware bounds and orthographic fit logic without changing renderable semantics or server authority.diff --git a/docs/display-qa-x1-ftc06-ftc07-local-visual-pass.md b/docs/display-qa-x1-ftc06-ftc07-local-visual-pass.mdindex cb7dabf0..b615b398 100644--- a/docs/display-qa-x1-ftc06-ftc07-local-visual-pass.md+++ b/docs/display-qa-x1-ftc06-ftc07-local-visual-pass.md@@ -1,5 +1,7 @@# DISPLAY-QA-X1: FTC-06 / FTC-07 local visual pass+Follow-up: DISPLAY-QA-X2 fixed the FTC-06 imported-body framing defect and promoted mixed/partial display status into the main UI. See [docs/display-qa-x2-imported-body-framing-status.md](/C:/Users/yuech/source/repos/Aetheris/docs/display-qa-x2-imported-body-framing-status.md).+## 1. Purpose and scopeThis pass validates the current local viewer behavior for FTC-06 and FTC-07 after the DisplayIR architecture milestones, with emphasis on:diff --git a/docs/display-qa-x2-imported-body-framing-status.md b/docs/display-qa-x2-imported-body-framing-status.mdnew file mode 100644index 00000000..a0f10e97--- /dev/null+++ b/docs/display-qa-x2-imported-body-framing-status.md@@ -0,0 +1,179 @@+# DISPLAY-QA-X2: imported-body framing and display status++## 1. Purpose and scope++DISPLAY-QA-X2 fixes the frontend/viewer regression identified in DISPLAY-QA-X1 where FTC-06 imported and prepared display data successfully, but the default viewport framing was so wrong that the model was effectively off-screen. This milestone also fixes the local client production build break in `aetheris.client/src/App.tsx` and promotes mixed/partial display status into the main visible UI.++Scope stayed intentionally narrow:++- frontend DisplayIR-aware bounds and camera fit;+- frontend import/display status messaging;+- frontend TypeScript build repair;+- local FTC-06 / FTC-07 visual QA rerun.++This milestone did not change STEP import/export semantics, BRep topology, DisplayIR server authority, tessellator algorithms, Firmament V2 language/lowering, AIR Region route policy, CIR authority, Firmasm, or CAD feature behavior.++## 2. Relationship to DISPLAY-QA-X1++DISPLAY-QA-X1 established that FTC-06 was not an import-loss problem:++- FTC-06 import succeeded.+- `/display/prepare` succeeded as `mixed-fallback`.+- Backend facts were `161` analytic faces plus `26` fallback faces, `187` total.+- The UI still showed only the drafting grid until extreme manual zoom-out, and even then the model was clipped and offset.++DISPLAY-QA-X2 resolves that frontend framing defect and reruns the local pass with the same FTC corpus files.++## 3. Root cause of FTC-06 bad framing++The root cause was the viewport camera path, not the importer or kernel:++- `aetheris.client/src/viewer/AetherisViewport.tsx` mounted a fixed orthographic camera at `[6, 6, 6]` with a fixed zoom and no fit-to-scene pass.+- The typed DisplayIR path in `displaySceneBuilder.ts` preferred `DisplayScene` renderables and often left legacy `sceneData` null.+- Because the viewport never computed bounds from typed DisplayIR renderables, imported bodies could exist correctly in scene space while the camera target and zoom remained pinned to legacy assumptions around the origin.++In practice, FTC-06 geometry was present, but the initial camera target/zoom was not derived from the imported model's actual bounds.++## 4. Fix++### DisplayIR-aware bounds++Added `aetheris.client/src/viewer/displaySceneBounds.ts` with:++- `computeDisplaySceneBounds(displayScene, sceneData)`+- `computeOrthographicCameraFit(bounds, frustumWidth, frustumHeight, viewDirection)`++Bounds now consider typed DisplayIR geometry first:++- `AnalyticPatch`: analytic preview mesh vertex positions+- `MeshPatch`: bounded-mesh vertex positions+- `WirePatch`: wire polyline points+- `DiagnosticPatch`: ignored unless geometry exists elsewhere++If typed renderables have no geometry, the code falls back to legacy `RenderSceneData`.++### Camera fit++`AetherisViewport.tsx` now mounts a `FitCameraToScene` helper that:++- recomputes bounds from typed DisplayIR renderables or legacy scene fallback;+- centers the orbit target on the bounds center;+- repositions the orthographic camera along the existing isometric viewing direction;+- computes a conservative orthographic zoom from projected bounds size;+- updates `near` / `far` to avoid clipping the imported body.++This is intentionally conservative and does not redesign the viewer camera model.++### Status UI++`App.tsx` now emits first-class import/display summaries:++- mixed fallback: `Import complete. Display: mixed analytic + bounded mesh fallback.`+- partial display: `Import complete. Display partial: N wire-only face(s), M diagnostic-only face(s).`+- materialization failure remains separate from import failure.++Mixed fallback is treated as success, not failure.++## 5. Client build break fix++The local production build failure in `aetheris.client/src/App.tsx` around the old lines `393/394` came from the import flow's mutable `displayError` control flow and TypeScript narrowing.++The import flow was simplified so it now:++- performs the import path directly inside `handleImportStep`;+- uses a structured `RefreshDisplayResult` from `refreshSummaryAndActiveTessellation`;+- sets import success, partial-display, and materialization-failure messaging explicitly.++`npm run build` now passes.++## 6. FTC-06 before/after++### Backend facts++- Import: success+- `/display/prepare`: success+- Display lane: `mixed-fallback`+- Display status: `Complete`+- Analytic faces: `161`+- Fallback faces: `26`+- Face count: `187`+- Edge count: `476`++### UI facts after X2++- The body is visible in the default imported view.+- The body is centered and framed without extreme manual zoom-out.+- The main UI now says `Import complete. Display: mixed analytic + bounded mesh fallback.`+- The inspector still matches backend facts.++### Artifact paths++- Viewport screenshot: [ftc06-imported-display-fixed.png](/C:/Users/yuech/source/repos/Aetheris/artifacts/display-qa-x2/ftc06-imported-display-fixed.png)+- Status screenshot: [ftc06-display-status-fixed.png](/C:/Users/yuech/source/repos/Aetheris/artifacts/display-qa-x2/ftc06-display-status-fixed.png)+- Display response capture: [ftc06-display-prepare.json](/C:/Users/yuech/source/repos/Aetheris/artifacts/display-qa-x2/ftc06-display-prepare.json)++## 7. FTC-07 smoke status++FTC-07 no longer reproduced the old DISPLAY-QA-X1 local outcome during this X2 rerun.++Observed local smoke result:++- Import: success+- `/display/prepare`: success (`200`)+- Display lane: `mixed-fallback`+- Display status: `Partial`+- Main UI message: `Import complete. Display partial: 210 wire-only face(s), 0 diagnostic-only face(s).`+- Analytic faces: `96`+- Fallback faces: `210`+- Inspector face count: `8`+- Edge count: `871`++This is a changed local smoke result, not a frontend framing change. X2 did not modify server-side display semantics or tessellation algorithms.++Artifact paths:++- Viewport screenshot: [ftc07-imported-display-smoke.png](/C:/Users/yuech/source/repos/Aetheris/artifacts/display-qa-x2/ftc07-imported-display-smoke.png)+- Status screenshot: [ftc07-display-status-smoke.png](/C:/Users/yuech/source/repos/Aetheris/artifacts/display-qa-x2/ftc07-display-status-smoke.png)+- Display response capture: [ftc07-display-prepare.json](/C:/Users/yuech/source/repos/Aetheris/artifacts/display-qa-x2/ftc07-display-prepare.json)++## 8. Tests run++Frontend:++```powershell+cd aetheris.client+npm test -- --run src/__tests__/App.test.tsx src/__tests__/displayRenderables.test.ts src/__tests__/displaySceneBuilder.test.ts src/__tests__/AetherisViewport.test.tsx src/__tests__/displaySceneBounds.test.ts+npm run build+```++Solution / server-core smoke:++```powershell+dotnet restore Aetheris.slnx+dotnet build Aetheris.slnx -f net10.0 --no-restore /m:1+dotnet test Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj -f net10.0 --no-build --filter "DisplayIR|BoundedMesh|WirePatch|DisplayPrepare|ViewMaterialization|FTC07|Ftc07|Tessellation|FTC06|Ftc06" --logger "console;verbosity=minimal"+dotnet test Aetheris.Server.Tests/Aetheris.Server.Tests.csproj -f net10.0 --no-build --filter "DisplayIR|BoundedMesh|WirePatch|DisplayPrepare|FTC07|Ftc07|FTC06|Ftc06|KernelApi|ViewMaterialization|Tessellate|Tessellation|StepIo" --logger "console;verbosity=minimal"+dotnet test Aetheris.Kernel.Core.Tests/Aetheris.Kernel.Core.Tests.csproj -f net10.0 --no-build --filter "Step242Ftc06SameSenseRegressionTests|FTC06|Ftc06|same_sense" --logger "console;verbosity=minimal"+dotnet run --project Aetheris.CLI -f net10.0 -- analyze testdata/step242/nist/FTC/nist_ftc_06_asme1_ap242-e2.stp --json+dotnet run --project Aetheris.CLI -f net10.0 -- analyze testdata/step242/nist/FTC/nist_ftc_07_asme1_ap242-e2.stp --json+```++Local visual QA:++```powershell+node scripts/display-qa-x2-playwright.mjs+```++The local rerun used the same script with `AETHERIS_QA_CASE=ftc06` and `AETHERIS_QA_CASE=ftc07` so each capture ran against a fresh server/client pair.++## 9. Remaining limitations++- Camera fit is still an orthographic, isometric, geometry-bounds fit; it is not a full viewer-camera redesign.+- Diagnostic-only faces without geometry remain intentionally excluded from bounds.+- FTC-07 changed locally from X1's materialization failure to a partial mixed-fallback result, but X2 does not explain or claim ownership of that backend behavior change.++## 10. Next milestone recommendation++Recommended next step: a focused FTC-07 follow-up that explains the changed local smoke result and stabilizes the intended server-side behavior for planar / wire degradation reporting.++If the team wants to stay in frontend scope first, the next small slice would be viewer polish around partial-display highlighting and optional explicit wireframe emphasis, not more camera work.diff --git a/scripts/display-qa-x2-playwright.mjs b/scripts/display-qa-x2-playwright.mjsnew file mode 100644index 00000000..ae8f0709--- /dev/null+++ b/scripts/display-qa-x2-playwright.mjs@@ -0,0 +1,218 @@+import fs from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath, pathToFileURL } from 'node:url';++const __filename = fileURLToPath(import.meta.url);+const __dirname = path.dirname(__filename);+const repoRoot = path.resolve(__dirname, '..');+const artifactRoot = path.join(repoRoot, 'artifacts', 'display-qa-x2');+const playwrightModuleSpecifier = process.env.AETHERIS_PLAYWRIGHT_MODULE ?? 'playwright';++const clientUrl = process.env.AETHERIS_CLIENT_URL ?? 'https://127.0.0.1:5173/';+const edgeExecutablePath = process.env.AETHERIS_EDGE_PATH+ ?? 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe';+const selectedCaseId = process.env.AETHERIS_QA_CASE ?? null;++const cases = [+ {+ id: 'ftc06',+ label: 'FTC-06',+ fixturePath: path.join(repoRoot, 'testdata', 'step242', 'nist', 'FTC', 'nist_ftc_06_asme1_ap242-e2.stp'),+ expectedImportStatus: 'Import complete. Display: mixed analytic + bounded mesh fallback.',+ viewportArtifact: 'ftc06-imported-display-fixed.png',+ statusArtifact: 'ftc06-display-status-fixed.png',+ responseArtifact: 'ftc06-display-prepare.json',+ strictExpectedStatus: true,+ },+ {+ id: 'ftc07',+ label: 'FTC-07',+ fixturePath: path.join(repoRoot, 'testdata', 'step242', 'nist', 'FTC', 'nist_ftc_07_asme1_ap242-e2.stp'),+ expectedImportStatus: 'Import complete. View materialization failed.',+ viewportArtifact: 'ftc07-imported-display-smoke.png',+ statusArtifact: 'ftc07-display-status-smoke.png',+ responseArtifact: 'ftc07-display-prepare.json',+ strictExpectedStatus: false,+ },+];+const activeCases = selectedCaseId+ ? cases.filter((testCase) => testCase.id === selectedCaseId)+ : cases;++function ensureEdgeExists() {+ return fs.access(edgeExecutablePath);+}++async function writeJson(targetPath, value) {+ await fs.writeFile(targetPath, `${JSON.stringify(value, null, 2)}\n`, 'utf8');+}++async function loadChromium() {+ const specifier = path.isAbsolute(playwrightModuleSpecifier)+ ? pathToFileURL(playwrightModuleSpecifier).href+ : playwrightModuleSpecifier;+ const module = await import(specifier);+ return module.chromium;+}++async function waitForImportStatus(page, expectedImportStatus, strictExpectedStatus) {+ const statusBox = page.locator('.import-status-box');+ await statusBox.waitFor({ state: 'visible', timeout: 30000 });+ await page.waitForFunction(() => {+ const element = document.querySelector('.import-status-box');+ return Boolean(element && !element.textContent?.includes('Importing STEP'));+ }, null, { timeout: 30000 });++ const importStatusText = await statusBox.innerText();+ if (strictExpectedStatus && !importStatusText.includes(expectedImportStatus)) {+ throw new Error(`Expected import status "${expectedImportStatus}" but saw "${importStatusText}".`);+ }++ return importStatusText;+}++async function run() {+ await ensureEdgeExists();+ await fs.mkdir(artifactRoot, { recursive: true });++ const chromium = await loadChromium();+ const browser = await chromium.launch({+ executablePath: edgeExecutablePath,+ headless: true,+ });++ const context = await browser.newContext({+ ignoreHTTPSErrors: true,+ viewport: { width: 1440, height: 960 },+ });++ const page = await context.newPage();+ const consoleEntries = [];+ const pageErrors = [];+ const requestFailures = [];+ const responseLog = new Map();++ page.on('console', (message) => {+ consoleEntries.push({+ type: message.type(),+ text: message.text(),+ location: message.location(),+ });+ });++ page.on('pageerror', (error) => {+ pageErrors.push({+ name: error.name,+ message: error.message,+ stack: error.stack ?? null,+ });+ });++ page.on('requestfailed', (request) => {+ requestFailures.push({+ url: request.url(),+ method: request.method(),+ failure: request.failure(),+ });+ });++ page.on('response', async (response) => {+ const url = response.url();+ if (!url.includes('/api/v1/documents/')) {+ return;+ }++ if (!url.includes('/import/step') && !url.includes('/display/prepare')) {+ return;+ }++ let bodyText;+ try {+ bodyText = await response.text();+ } catch (error) {+ bodyText = `<<failed to read response body: ${error}>>`;+ }++ responseLog.set(url, {+ url,+ status: response.status(),+ ok: response.ok(),+ bodyText,+ });+ });++ const summary = [];++ try {+ await page.goto(clientUrl, { waitUntil: 'load' });+ await page.getByRole('status').waitFor({ state: 'visible', timeout: 30000 });+ await page.getByText('Document: Ready', { exact: true }).waitFor({ state: 'visible', timeout: 30000 });+ await page.getByText('Ready. Select a file to import.', { exact: true }).waitFor({ state: 'visible', timeout: 30000 });++ for (const testCase of activeCases) {+ await page.getByRole('button', { name: 'New Document' }).click();+ await page.getByText('Ready. Select a file to import.').waitFor({ state: 'visible', timeout: 30000 });++ const fileInput = page.getByTestId('step-import-file-input');+ await fileInput.setInputFiles(testCase.fixturePath);+ await page.getByRole('button', { name: 'Import STEP 242' }).click();+ const importStatusText = await waitForImportStatus(page, testCase.expectedImportStatus, testCase.strictExpectedStatus);++ const viewportFrame = page.locator('.viewport-frame');+ const inspector = page.locator('.audit-panel');+ const displayLane = (await page.locator('.audit-panel p').filter({ hasText: 'Display lane:' }).innerText()).replace('Display lane:', '').trim();+ const displayStatus = (await page.locator('.audit-panel p').filter({ hasText: 'Display status:' }).innerText()).replace('Display status:', '').trim();+ const renderPath = (await page.locator('.audit-panel p').filter({ hasText: 'Render path:' }).innerText()).replace('Render path:', '').trim();+ const analyticFaces = (await page.locator('.audit-panel p').filter({ hasText: 'Analytic faces:' }).innerText()).replace('Analytic faces:', '').trim();+ const fallbackFaces = (await page.locator('.audit-panel p').filter({ hasText: 'Fallback faces:' }).innerText()).replace('Fallback faces:', '').trim();+ const faceCount = (await page.locator('.audit-panel p').filter({ hasText: 'Face count:' }).innerText()).replace('Face count:', '').trim();+ const edgeCount = (await page.locator('.audit-panel p').filter({ hasText: 'Edge count:' }).innerText()).replace('Edge count:', '').trim();++ const viewportPath = path.join(artifactRoot, testCase.viewportArtifact);+ const statusPath = path.join(artifactRoot, testCase.statusArtifact);+ await viewportFrame.screenshot({ path: viewportPath });+ await inspector.screenshot({ path: statusPath });++ const responseEntries = [...responseLog.values()];+ const importResponse = responseEntries.filter((entry) => entry.url.includes('/import/step')).at(-1) ?? null;+ const displayPrepareResponse = responseEntries.filter((entry) => entry.url.includes('/display/prepare')).at(-1) ?? null;++ if (displayPrepareResponse) {+ await fs.writeFile(path.join(artifactRoot, testCase.responseArtifact), `${displayPrepareResponse.bodyText}\n`, 'utf8');+ }++ summary.push({+ caseId: testCase.id,+ fixturePath: testCase.fixturePath,+ importStatusText,+ displayLane,+ displayStatus,+ renderPath,+ analyticFaces,+ fallbackFaces,+ faceCount,+ edgeCount,+ screenshotPaths: {+ viewport: viewportPath,+ status: statusPath,+ },+ importResponse: importResponse+ ? { url: importResponse.url, status: importResponse.status, ok: importResponse.ok }+ : null,+ displayPrepareResponse: displayPrepareResponse+ ? { url: displayPrepareResponse.url, status: displayPrepareResponse.status, ok: displayPrepareResponse.ok }+ : null,+ });+ }+ } finally {+ await writeJson(path.join(artifactRoot, 'playwright-summary.json'), summary);+ await writeJson(path.join(artifactRoot, 'playwright-console.json'), consoleEntries);+ await writeJson(path.join(artifactRoot, 'playwright-pageerrors.json'), pageErrors);+ await writeJson(path.join(artifactRoot, 'playwright-requestfailures.json'), requestFailures);+ await browser.close();+ }++ console.log(JSON.stringify(summary, null, 2));+}++await run();