Interface design document and manual now share one authoritative surface inventory (333 surfaces across 9 categories, gap 0), and every chapter carries real Playwright screenshots of the panels it documents. - tools/fcweb: ui-surface-scan/ui-surface-inventory (deterministic --check), build-ui-doc renders panel catalog, workbench matrix and mapping tables; blank toolbar crops (<1 KB) are skipped and pruned instead of embedded - web/tools/manual: generate-panel-index (ch16), audit-ui-gaps, generate-final-status, generate-gaps-doc; pager is per-chapter so the manual no longer overflows horizontally - manual: 130 screenshot references / 128 PNGs, panel sections for ch02-ch13 - web/src: utility menus stop click propagation (menu reopened on item click); workbench shell gains an OPFS document picker so workbench.html can bind a real document instead of the fixed workbench-document id; Sketcher panel moves from the command column to the main stage Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
244 lines
8.3 KiB
JavaScript
244 lines
8.3 KiB
JavaScript
// Kernel access for the fcweb toolkit.
|
|
//
|
|
// Every probe is an Emscripten build exposing one entry point:
|
|
// fc_web_dispatch_json(requestJson) -> responseJson
|
|
// where the request is `{ cmd, args }`. This module is the only place that
|
|
// touches ccall; everything else speaks in actions.
|
|
//
|
|
// Three probes matter here:
|
|
// FreeCADWebDocumentProbe cmd "part.document"
|
|
// FreeCADWebPartDesignRuntimeProbe cmd "partdesign.document"
|
|
// FreeCADWebAssemblyProbe cmd "assembly.*"
|
|
// (AssemblyRuntimeProbe.cpp compiles into
|
|
// this target, see CMakeLists.txt:798 --
|
|
// the file name is not the artifact name)
|
|
import fs from "node:fs";
|
|
import path from "node:path";
|
|
import { createHash } from "node:crypto";
|
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
|
|
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
const repoRoot = path.resolve(here, "../..");
|
|
|
|
/** Warn once per stem about public/dist drift. */
|
|
const warned = new Set();
|
|
|
|
export const TRACE_SCHEMA = "freecad-web-process-trace/v1";
|
|
|
|
export const STEM_PART = "FreeCADWebDocumentProbe";
|
|
export const STEM_PARTDESIGN = "FreeCADWebPartDesignRuntimeProbe";
|
|
export const STEM_ASSEMBLY = "FreeCADWebAssemblyProbe";
|
|
|
|
export const KERNEL_DIRS = [
|
|
path.join(repoRoot, "web", "public", "kernel"),
|
|
path.join(repoRoot, "web", "dist", "kernel"),
|
|
];
|
|
|
|
/** A kernel reply that came back with ok:false, or a transport failure. */
|
|
export class KernelError extends Error {
|
|
constructor(message, { code = null, action = null, stage = null, reply = null } = {}) {
|
|
super(message);
|
|
this.name = "KernelError";
|
|
this.code = code;
|
|
this.action = action;
|
|
this.stage = stage;
|
|
this.reply = reply;
|
|
}
|
|
}
|
|
|
|
function artifactsIn(directory, stem) {
|
|
const js = path.join(directory, `${stem}.js`);
|
|
const wasm = path.join(directory, `${stem}.wasm`);
|
|
return fs.existsSync(js) && fs.existsSync(wasm) ? { js, wasm } : null;
|
|
}
|
|
|
|
function statKey(file) {
|
|
const stats = fs.statSync(file);
|
|
return `${stats.size}:${Math.round(stats.mtimeMs)}`;
|
|
}
|
|
|
|
/**
|
|
* Find the first kernel directory that ships both the .js and .wasm for `stem`.
|
|
* public/ and dist/ can drift (different build times), so the chosen directory
|
|
* and a freshness key are reported and a mismatch is warned about rather than
|
|
* silently picked.
|
|
*/
|
|
export function locateProbe(stem, dirs = KERNEL_DIRS) {
|
|
const found = [];
|
|
for (const directory of dirs) {
|
|
const artifacts = artifactsIn(directory, stem);
|
|
if (artifacts) found.push({ directory, ...artifacts });
|
|
}
|
|
if (!found.length) {
|
|
throw new KernelError(`no ${stem}.{js,wasm} under ${dirs.join(" or ")}`, { code: "probe_missing" });
|
|
}
|
|
const chosen = found[0];
|
|
const keys = new Set(found.map(entry => statKey(entry.js)));
|
|
if (keys.size > 1 && !warned.has(stem)) {
|
|
warned.add(stem);
|
|
console.warn(`[fcweb] ${stem} differs between kernel directories: ` +
|
|
found.map(entry => `${path.relative(repoRoot, entry.directory)}=${statKey(entry.js)}`).join(", "));
|
|
}
|
|
return { ...chosen, copies: found.length, buildKey: statKey(chosen.js) };
|
|
}
|
|
|
|
/**
|
|
* Instantiate one probe. Always pair with `handle.close()` in a finally block:
|
|
* the probes are pthread builds, and without terminating them Node's event loop
|
|
* never drains.
|
|
*/
|
|
export async function openKernel({ stem, dirs = KERNEL_DIRS, print = () => {}, printErr = () => {} } = {}) {
|
|
if (!stem) throw new KernelError("openKernel requires { stem }", { code: "bad_request" });
|
|
const located = locateProbe(stem, dirs);
|
|
const { loadWasmProbe } = await import(pathToFileURL(path.join(repoRoot, "tools", "wasm-probe-runtime.mjs")).href);
|
|
const { kernel } = await loadWasmProbe(located.directory, stem, { print, printErr });
|
|
let closed = false;
|
|
const handle = {
|
|
kernel,
|
|
stem,
|
|
directory: located.directory,
|
|
buildKey: located.buildKey,
|
|
copies: located.copies,
|
|
get closed() { return closed; },
|
|
/** Idempotent: terminate the pthread pool exactly once. */
|
|
close() {
|
|
if (closed) return;
|
|
closed = true;
|
|
try { kernel.PThread?.terminateAllThreads(); } catch { /* pool already gone */ }
|
|
},
|
|
};
|
|
return handle;
|
|
}
|
|
|
|
/** Raw JSON round-trip. Returns the parsed reply without judging ok. */
|
|
export function dispatch(handle, cmd, args) {
|
|
if (!handle || handle.closed) throw new KernelError("kernel handle is closed", { code: "closed" });
|
|
const request = JSON.stringify({ cmd, args });
|
|
const text = handle.kernel.ccall("fc_web_dispatch_json", "string", ["string"], [request]);
|
|
try {
|
|
return JSON.parse(String(text));
|
|
} catch {
|
|
throw new KernelError(`${cmd}: reply was not JSON (${String(text).slice(0, 160)})`, { code: "bad_reply" });
|
|
}
|
|
}
|
|
|
|
/** Drop the heavy geometry arrays a trace must not carry. */
|
|
export function compactArgs(args) {
|
|
const clone = { ...args };
|
|
delete clone.includeMesh;
|
|
delete clone.schema;
|
|
delete clone.module;
|
|
delete clone.document;
|
|
for (const key of ["geometries", "constraints"]) {
|
|
if (Array.isArray(clone[key])) {
|
|
clone[key] = { count: clone[key].length, sha256: digest(clone[key]) };
|
|
}
|
|
}
|
|
delete clone.mesh;
|
|
return clone;
|
|
}
|
|
|
|
function digest(value) {
|
|
return createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
|
|
}
|
|
|
|
/** Keep only the drawable facts of a reply for the trace. */
|
|
export function summarise(response) {
|
|
const objects = response?.objects ?? [];
|
|
return {
|
|
objectCount: response?.objectCount ?? objects.length,
|
|
tip: objects.length ? objects[objects.length - 1].name : null,
|
|
objects: objects.map(object => ({
|
|
name: object.name,
|
|
label: object.label,
|
|
type: object.type,
|
|
position: object.position,
|
|
volume: object.volume ?? null,
|
|
faceCount: object.faceCount ?? null,
|
|
edgeCount: object.edgeCount ?? null,
|
|
vertexCount: object.vertexCount ?? null,
|
|
})),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* A document session over one kernel handle.
|
|
*
|
|
* `call` injects the schema/module/document header every probe expects and
|
|
* throws on ok:false. `timed` additionally records a trace event, which is what
|
|
* makes a build replayable later without re-running it.
|
|
*/
|
|
export function createSession({ handle, cmd, schema, module, document, extra = {} }) {
|
|
const timings = [];
|
|
const events = [];
|
|
let last = null;
|
|
|
|
const call = (action, args = {}) => {
|
|
const reply = dispatch(handle, cmd, { schema, module, document, action, includeMesh: false, ...extra, ...args });
|
|
if (!reply || reply.ok === false) {
|
|
throw new KernelError(
|
|
`${document} ${action}: ${reply?.error ?? "kernel rejected the call"}`,
|
|
{ code: reply?.code ?? null, action, stage: reply?.stage ?? null, reply },
|
|
);
|
|
}
|
|
last = reply.result;
|
|
return reply.result;
|
|
};
|
|
|
|
const timed = (label, action, args = {}) => {
|
|
const started = performance.now();
|
|
const result = call(action, args);
|
|
const seconds = (performance.now() - started) / 1000;
|
|
timings.push({ label, action, seconds });
|
|
events.push({
|
|
step: events.length + 1,
|
|
label,
|
|
action,
|
|
args: compactArgs(args),
|
|
seconds: Number(seconds.toFixed(4)),
|
|
tips: summarise(result),
|
|
});
|
|
return result;
|
|
};
|
|
|
|
const session = {
|
|
document,
|
|
cmd,
|
|
schema,
|
|
module,
|
|
kernel: handle.kernel,
|
|
handle,
|
|
call,
|
|
timed,
|
|
timings,
|
|
events,
|
|
get last() { return last; },
|
|
trace() {
|
|
return {
|
|
schema: TRACE_SCHEMA,
|
|
document,
|
|
builder: extra.builder ?? null,
|
|
totals: {
|
|
seconds: Number(timings.reduce((sum, item) => sum + item.seconds, 0).toFixed(3)),
|
|
steps: events.length,
|
|
timings,
|
|
},
|
|
events,
|
|
};
|
|
},
|
|
};
|
|
return session;
|
|
}
|
|
|
|
/** Write a session trace through the OPFS contract and mirror it on disk. */
|
|
export async function writeTrace(session, { extra = {} } = {}) {
|
|
const { storeBytes, outRoot } = await import(pathToFileURL(path.join(here, "opfs.mjs")).href);
|
|
const trace = { ...session.trace(), ...extra };
|
|
const json = JSON.stringify(trace, null, 2);
|
|
const stored = storeBytes(`trace-${session.document}.json`, json);
|
|
const local = path.join(outRoot(), "traces", `${session.document}.json`);
|
|
fs.mkdirSync(path.dirname(local), { recursive: true });
|
|
fs.writeFileSync(local, json);
|
|
return { opfs: stored.name, bytes: stored.bytes, sha256: stored.sha256, local, events: trace.events.length };
|
|
}
|