import assert from 'node:assert/strict'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import { execFileSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { pathToFileURL } from 'node:url'; import { loadWasmProbe } from './wasm-probe-runtime.mjs'; import { playwright } from './part-primitive-business-cases.mjs'; export const sectionId = 'Part:desktop:Part_Section'; export async function runSectionCases(ids) { if (!ids.includes(sectionId)) return []; const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'part-section-')); const directory = path.resolve('docs/current/part-section-business', new Date().toISOString().replace(/[:.]/g, '-')); fs.mkdirSync(directory, { recursive: true }); const result = { capabilityId: sectionId, status: 'failed', cases: [], evidenceFiles: {}, timing: [] }; const stage = name => { const event = { name, at: new Date().toISOString() }; result.timing.push(event); fs.appendFileSync(path.join(directory, 'stages.jsonl'), JSON.stringify(event) + '\n'); process.stderr.write(`Part Section: ${name}\n`); }; const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] }); const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`); const item = (state, name = state.createdObject) => state.objects.find(object => object.name === name); let kernel, browser; try { for (const file of ['tools/part-section-business-cases.mjs', 'tools/part-business-cases.mjs', 'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts', 'web/src/part-make-face-task.tsx', 'web/src/workbench-shell.tsx', 'web/src/scene-viewport.tsx', 'web/src/desktop-command-dispatcher.ts', 'freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp', 'freecad-source/src/Mod/Part/Gui/Command.cpp', 'freecad-source/src/Mod/Part/App/FeaturePartSection.cpp', 'freecad-source/src/Mod/Part/App/FCBRepAlgoAPI_Section.cpp', 'freecad-source/src/Mod/Part/App/FCBRepAlgoAPI_Section.h', ...['js', 'wasm', 'worker.js'].map(extension => `web/public/kernel/FreeCADWebDocumentProbe.${extension}`)]) result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex'); stage('compile-adapter-enter'); execFileSync('web/node_modules/.bin/tsc', ['--target', 'ES2022', '--module', 'ESNext', '--moduleResolution', 'Bundler', '--strict', '--skipLibCheck', '--jsx', 'preserve', '--outDir', temporary, 'web/node_modules/vite/client.d.ts', 'web/src/part-desktop-adapter.ts', 'web/src/part-view-facade.ts'], { stdio: 'pipe' }); const facade = await import(pathToFileURL(path.join(temporary, 'part-document-facade.js'))); const { executePartFixedBoxDesktop } = await import(pathToFileURL(path.join(temporary, 'part-desktop-adapter.js'))); const { FacadeSerialQueue } = await import(pathToFileURL(path.join(temporary, 'facade-envelope.js'))); stage('native-load-enter'); ({ kernel } = await loadWasmProbe('web/public/kernel', 'FreeCADWebDocumentProbe')); stage('native-load-complete'); const queue = new FacadeSerialQueue(); let sequence = 0; const router = { request: (_module, command, payload) => { assert.equal(command, facade.PART_DOCUMENT_COMMAND); return facade.dispatchPartDocument(queue, facade.createPartDocumentRequest(`section-${++sequence}`, payload), kernel); } }; const document = 'SectionBusiness'; const call = async (action, args = {}, name = document) => { const reply = await router.request('Part', facade.PART_DOCUMENT_COMMAND, { schema: facade.PART_DOCUMENT_SCHEMA, module: 'Part', document: name, action, builderInfo: true, includeMesh: true, ...args }); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; }; const source = (object, subelements = []) => ({ documentId: document, object, subelements }); const selection = [source('Base'), source('Tool')]; const execute = args => executePartFixedBoxDesktop(router, 'Part_Section', args, document, () => { throw Error('Desktop Section must preserve selection'); }); const accepted = async args => { const reply = await execute(args); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; }; await call('create'); await call('setBox', { object: 'Base', dimensions: [10, 10, 10] }); await call('setBox', { object: 'Tool', dimensions: [10, 10, 10] }); await call('setPosition', { object: 'Tool', position: [5, 5, 5] }); const fixture = await call('save', { path: '/tmp/SectionBusiness.FCStd' }); await call('create', {}, 'SectionOther'); const other = await call('snapshot', {}, 'SectionOther'); stage('native-section-enter'); const before = await call('snapshot'); const first = await accepted({ selection }); const section = item(first); assert.equal(section.name, 'Section'); assert.equal(section.type, 'Part::Section'); assert.equal(section.base, 'Base'); assert.equal(section.tool, 'Tool'); assert.equal(section.topology.valid, true); assert.equal(section.topology.Edge, 6); assert.equal(section.topology.Face, 0); assert.equal(section.topology.Solid, 0); near(section.topology.length, 30); assert.equal(section.lines.length, 6); assert.equal(section.mesh, undefined); near(section.volume, 0); assert.equal(item(first, 'Base').displayVisibility, false); assert.equal(item(first, 'Tool').displayVisibility, false); near(item(first, 'Base').volume, 1000); near(item(first, 'Tool').volume, 1000); assert.equal(first.undoCount, before.undoCount + 1); assert.deepEqual((await call('undo')).objects, before.objects); assert.deepEqual((await call('redo')).objects, first.objects); assert.deepEqual(await call('snapshot', {}, 'SectionOther'), other); record({ selection, dimensions: [10, 10, 10], toolPosition: [5, 5, 5] }, { section, undoCount: first.undoCount }, 'Section computes six native intersection edges of length 30, stores operand links, hides sources, preserves selection and isolates one-step undo/redo'); const next = await accepted({ selection: [source('Base', ['Face1']), source('Base', ['Face2']), source('Tool', ['Edge1'])] }); assert.equal(next.createdObject, 'Section001'); near(item(next).topology.length, 30); record({ selection: ['Base.Face1', 'Base.Face2', 'Tool.Edge1'] }, { name: next.createdObject, length: item(next).topology.length }, 'Desktop object grouping ignores subelement geometry and assigns a unique native feature name'); for (const args of [{ selection: [] }, { selection: [source('Base')] }, { selection: [source('Base'), source('Missing')] }, { selection: [source('Base'), { documentId: 'SectionOther', object: 'Tool' }] }, { selection, shapes: ['invented'] }, { selection, document: 'SectionOther' }]) { const state = await call('snapshot'); const reply = await execute(args); assert.equal(reply.kind, 'error', JSON.stringify(reply)); assert.deepEqual(await call('snapshot'), state); record(args, { error: reply.error, unchanged: true }, 'Invalid Section input cannot mutate objects or transaction history'); } const moved = await call('setPosition', { object: 'Tool', position: [7, 7, 7] }); near(item(moved, 'Section').topology.length, 18); near(item(moved, 'Section001').topology.length, 18); const disjoint = await call('setPosition', { object: 'Tool', position: [20, 20, 20] }); assert.equal(item(disjoint, 'Section').topology?.Edge ?? 0, 0); assert.equal(item(disjoint, 'Section').lines?.length ?? 0, 0); near(item(await call('undo'), 'Section').topology.length, 18); record({ toolPositions: [[7, 7, 7], [20, 20, 20]], undo: true }, { length: 18, disjointEdges: 0 }, 'Linked source edits recompute Section and an empty intersection removes stale display edges'); const saved = await call('save', { path: '/tmp/SectionSaved.FCStd' }); assert.ok(saved.bytes.byteLength > 1000); await call('close'); const reopened = await call('open', { path: '/tmp/SectionSaved.FCStd', bytes: saved.bytes }); assert.equal(item(reopened, 'Section').base, 'Base'); assert.equal(item(reopened, 'Section').tool, 'Tool'); near(item(reopened, 'Section').topology.length, 18); assert.equal(item(reopened, 'Base').displayVisibility, false); near(item(await call('setPosition', { object: 'Tool', position: [5, 5, 5] }), 'Section').topology.length, 30); record({ actions: ['save', 'close', 'open', 'edit-source'] }, { bytes: saved.bytes.byteLength, length: 30 }, 'FCStd preserves native Section links and source visibility and supports subsequent recomputation'); stage('native-complete'); kernel.PThread?.terminateAllThreads(); kernel = undefined; stage('browser-enter'); browser = await playwright().chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? '/usr/bin/google-chrome', headless: process.env.HEADLESS !== "0", args: ['--no-sandbox', '--disable-dev-shm-usage'] }); const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); page.setDefaultTimeout(20000); const errors = []; page.on('pageerror', error => errors.push(String(error))); await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? 'http://127.0.0.1:5180'}/workbench.html?module=Part&command=Part_Section&document=${document}`); await page.getByLabel('Make section document', { exact: true }).fill(document); await page.getByLabel('Section FCStd file', { exact: true }).setInputFiles({ name: 'SectionBusiness.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(fixture.bytes) }); await page.getByLabel('Section source Base', { exact: true }).check(); assert.equal(await page.getByRole('button', { name: 'Create section', exact: true }).isEnabled(), false); await page.getByLabel('Section source Tool', { exact: true }).check(); await page.getByRole('button', { name: 'Create section', exact: true }).click(); await page.locator('[data-section="Section"]').filter({ hasText: '30.000' }).waitFor(); assert.equal(await page.getByLabel('Section source Base', { exact: true }).isChecked(), true); await page.getByRole('button', { name: 'Section undo', exact: true }).click(); await page.locator('[data-section="Section"]').waitFor({ state: 'detached' }); await page.getByRole('button', { name: 'Section redo', exact: true }).click(); await page.locator('[data-section="Section"]').filter({ hasText: '30.000' }).waitFor(); const capture = async name => { const png = await page.locator('[aria-label="Section geometry"] canvas').screenshot({ path: path.join(directory, name) }); const colors = await page.evaluate(async encoded => { const image = new Image(); image.src = `data:image/png;base64,${encoded}`; await image.decode(); const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0); const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data; const colors = new Set(); for (let i = 0; i < pixels.length; i += 4) colors.add(`${pixels[i]},${pixels[i+1]},${pixels[i+2]}`); return colors.size; }, png.toString('base64')); assert.ok(colors > 8, `Section canvas has only ${colors} colors`); return createHash('sha256').update(png).digest('hex'); }; const initial = await capture('desktop-geometry.png'); const rect = await page.locator('[aria-label="Section geometry"] canvas').boundingBox(); await page.mouse.move(rect.x + rect.width / 2, rect.y + rect.height / 2); await page.mouse.down(); await page.mouse.move(rect.x + rect.width / 2 + 70, rect.y + rect.height / 2 + 30, { steps: 8 }); await page.mouse.up(); assert.notEqual(await capture('rotated-geometry.png'), initial); await page.getByRole('button', { name: 'Save section document', exact: true }).click(); await page.getByRole('link', { name: 'Open section in project', exact: true }).waitFor(); const bytes = await page.evaluate(async () => { const { readDocumentFile } = await import('/src/storage.ts'); return [...new Uint8Array(await readDocumentFile('Section-SectionBusiness.FCStd'))]; }); assert.ok(bytes.length > 1000); await page.screenshot({ path: path.join(directory, 'desktop.png'), fullPage: true }); await page.reload(); await page.getByLabel('Make section document', { exact: true }).fill(document); await page.getByLabel('Section FCStd file', { exact: true }).setInputFiles({ name: 'SectionBusiness.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) }); await page.locator('[data-section="Section"]').filter({ hasText: '30.000' }).waitFor(); await page.getByLabel('Section source Base', { exact: true }).check(); await page.getByLabel('Section source Tool', { exact: true }).check(); await page.getByRole('button', { name: 'Create section', exact: true }).click(); await page.locator('[data-section="Section001"]').filter({ hasText: '30.000' }).waitFor(); await page.setViewportSize({ width: 390, height: 844 }); await capture('mobile-geometry.png'); await page.screenshot({ path: path.join(directory, 'mobile.png'), fullPage: true }); const layout = await page.getByRole('region', { name: 'Section', exact: true }).evaluate(element => ({ width: element.clientWidth, scroll: element.scrollWidth })); assert.ok(layout.scroll <= layout.width + 1, JSON.stringify(layout)); assert.deepEqual(errors, []); for (const name of ['desktop.png', 'desktop-geometry.png', 'rotated-geometry.png', 'mobile.png', 'mobile-geometry.png']) { const file = path.join(directory, name); result.evidenceFiles[path.relative('.', file)] = createHash('sha256').update(fs.readFileSync(file)).digest('hex'); } record({ operations: ['FCStd-open', 'select', 'create', 'undo', 'redo', 'rotate', 'OPFS-save', 'reload', 'FCStd-open', 'create'], viewports: [[1440, 900], [390, 844]] }, { length: 30, restoredBytes: bytes.length, layout }, 'Mounted Section controls dispatch native geometry, retain selection and restore OPFS documents on desktop and mobile'); stage('browser-complete'); result.status = 'passed'; } catch (error) { result.error = [String(error.stack ?? error), error.stdout?.toString(), error.stderr?.toString()].filter(Boolean).join('\n'); } finally { stage('cleanup-enter'); await browser?.close(); kernel?.PThread?.terminateAllThreads(); fs.rmSync(temporary, { recursive: true, force: true }); stage('cleanup-complete'); fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); } return [result]; }