import { executeSandboxMeshImport, SANDBOX_MESH_COMMANDS } from "./sandbox-mesh-import-adapter.js"; import { executeMeasureDocument } from "./measure-document-adapter.js"; import { executeSurfaceDocument } from "./surface-document-adapter.js"; import { executeSandboxArchive } from "./sandbox-archive-adapter.js"; import { prepareRobotWaypointArgs } from "./robot-waypoint-adapter.js"; import { prepareTechDrawCommand, validateTechDrawResponse, techDrawRoutePolicy } from "./techdraw-desktop-adapter.js"; import { executeDraftDesktop } from "./draft-desktop-adapter.js"; import { executeMeshDesktop } from "./mesh-desktop-adapter.js"; import { executeImportDesktop } from "./import-desktop-adapter.js"; import { executeFemDesktop } from "./fem-desktop-adapter.js"; import { prepareCamCommand, validateCamDesktopResponse } from "./cam-desktop-adapter.js"; import { prepareBimDesktopArgs, validateBimDesktopResponse } from "./bim-desktop-adapter.js"; import { validatePartDesktopResponse, executePartFixedBoxDesktop, preparePartDesktopCommand } from "./part-desktop-adapter.js"; import { prepareMaterialDesktopArgs, validateMaterialDesktopResponse } from "./material-desktop-adapter.js"; import { executePartDesignDesktop } from "./partdesign-desktop-adapter.js"; import { executeDockOverlayCommand, DOCK_OVERLAY_COMMANDS } from "./dock-overlay-adapter.js"; import { executeSceneDisplayCommand } from "./scene-command-adapter.js"; import { executeWebDesktop } from "./web-desktop-adapter.js"; import { prepareAssemblyCommand, applyAssemblyResponse } from "./assembly-desktop-adapter.js"; import { createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js"; import { getWebModuleRoute } from "./module-registry.generated.js"; import { WebModuleRouter } from "./module-router.js"; import type { WorkbenchCommandRecord } from "./workbench-command-facade.js"; import { prepareTestCommand, validateTestDesktopResponse, TEST_DESKTOP_ROUTES, testDesktopRoutes } from "./test-desktop-adapter.js"; import { executeSketcherDesktop, prepareSketcherCommand, validateSketcherResponse } from "./sketcher-desktop-adapter.js"; import { executeMeshPartFlatten, executeMeshPartMesher, executeMeshPartCurve, executeMeshPartTrim, prepareMeshPartCommand, validateMeshPartResponse } from "./meshpart-desktop-adapter.js"; import { validateInspectionDesktopResponse } from "./inspection-desktop-adapter.js"; import { TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA, TEMPLATEPYMOD_GROUP_COMMANDS, TEMPLATEPYMOD_GROUP_DEFAULT } from "./templatepymod-python-family-facade.js"; function moduleSlug(module: string): string { return module.toLowerCase().replace(/[^a-z0-9]/g, ""); } function familyRoute(module: string): string | undefined { const route = getWebModuleRoute(module); if (!route) return undefined; return route.commands.find((command) => command.endsWith(".pythonFamilyBatch")) ?? route.commands.find((command) => command.endsWith(".pythonFamily")); } function familySchema(route: string, module: string): string { return route.endsWith(".pythonFamilyBatch") || route === "techdraw.desktopCommand" ? `freecad-web-${moduleSlug(module)}/python-family-batch/v1` : `freecad-web-${moduleSlug(module)}/python-family/v1`; } interface DesktopCommandRoute { id: string; module: string; command: string; canonicalId: string; transport: "direct-command" | "family-batch" | "ui-container" | "browser-ui"; sourcePath?: string; sourceLine?: number; } interface DesktopCommandRouteIndex { schema: "freecad-web-desktop-command-routes/v1"; records: DesktopCommandRoute[]; } function deliverNativeDxf(response: unknown): void { const visited = new Set(); const locate = (value: unknown): Record | undefined => { if (!value || typeof value !== "object" || visited.has(value)) return undefined; visited.add(value); const item = value as Record; if (item.nativeOperationCompleted === true && item.mimeType === "image/vnd.dxf" && item.encoding === "base64" && typeof item.content === "string" && typeof item.filename === "string" && typeof item.byteLength === "number") return item; for (const child of Object.values(item)) { const found = locate(child); if (found) return found; } return undefined; }; const file = locate(response); // Native failures retain their original envelope and never trigger a download. if (!file) return; const binary = atob(file.content as string); if (binary.length === 0 || binary.length !== file.byteLength) throw new Error("Native DXF file length mismatch"); const bytes = Uint8Array.from(binary, (character) => character.charCodeAt(0)); const url = URL.createObjectURL(new Blob([bytes], { type: "image/vnd.dxf" })); const link = document.createElement("a"); try { link.href = url; link.download = (file.filename as string).replace(/[\\/\u0000-\u001f]/g, "_"); link.hidden = true; document.body.appendChild(link); link.click(); } finally { link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 60000); } } /** Routes generated desktop-command records through a module's shared Worker. */ export class DesktopCommandDispatcher { private routeIndex?: Promise>; private spreadsheetHost?: (documentId: string, args: Record) => Promise; setSpreadsheetHost(host?: (documentId: string, args: Record) => Promise): void { this.spreadsheetHost = host; } private readonly activeAssemblies = new Map(); constructor(private readonly router: WebModuleRouter) {} getActiveAssembly(documentId: string): string | undefined { return this.activeAssemblies.get(documentId); } setActiveAssembly(documentId: string, assembly?: string): void { if (assembly) this.activeAssemblies.set(documentId, assembly); else this.activeAssemblies.delete(documentId); } private routes(): Promise> { return this.routeIndex ??= fetch("/api/desktop-command-routes.json").then(async (response) => { if (!response.ok) throw new Error(`desktop command route index failed: HTTP ${response.status}`); const payload = await response.json() as DesktopCommandRouteIndex; if (payload.schema !== "freecad-web-desktop-command-routes/v1" || !Array.isArray(payload.records)) throw new Error("desktop command route index schema mismatch"); return new Map(payload.records.map((route) => [route.id, route])); }); } async execute(record: WorkbenchCommandRecord, args: Record, documentId = "workbench-document", applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise { if (record.module === "TemplatePyMod" && record.command === "TemplatePyGroup") { if (args.action === "cancel" || args.action === "read") return createSuccess("desktop-TemplatePyGroup", { container: "TemplatePyGroup", choices: TEMPLATEPYMOD_GROUP_COMMANDS, defaultCommand: TEMPLATEPYMOD_GROUP_DEFAULT, cancelled: args.action === "cancel" }); const child = args.childCommand ?? TEMPLATEPYMOD_GROUP_DEFAULT; if (!TEMPLATEPYMOD_GROUP_COMMANDS.includes(child as typeof TEMPLATEPYMOD_GROUP_COMMANDS[number])) return createFailure("desktop-TemplatePyGroup", "invalid_arguments", "Unknown group child command"); const module = child === "Std_New" ? "Web" : "TemplatePyMod"; const { childCommand, ...childArgs } = args; return this.execute({ ...record, module, command: String(child), id: `${module}:desktop:${child}` }, child === "Std_New" ? { ...childArgs, runtimeOwner: "PartBox" } : childArgs, documentId, applySelection); } // Keep the Surface entry visible while using MeshPart's native record everywhere internally. if (record.module === "Surface" && record.command === "Surface_CurveOnMesh") record = { ...record, module: "MeshPart", command: "MeshPart_CurveOnMesh", id: "MeshPart:desktop:MeshPart_CurveOnMesh" }; if (record.module === "Inspection" && ["Inspection_VisualInspection", "Inspection_InspectElement"].includes(record.command)) { const response = await this.router.request("Inspection", "inspection.pythonFamilyBatch", { schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId } }], }, documentId); const result = validateInspectionDesktopResponse(record, response, record.id); if (result.kind === "result") { const native = (result.result as any).records[0].result; if (["accept", "undo", "redo", "open"].includes(native?.action)) applySelection?.(native.documentId, native.selection.map((object: string) => ({ documentId: native.documentId, object }))); } return result; } if (args.documentId !== undefined && (typeof args.documentId !== "string" || !args.documentId.trim())) { return createFailure(`desktop-${record.module}`, "invalid_request", "documentId must be a non-empty document identifier", { capabilityId: record.id }); } if ((record.module === "Web" || record.module === "Std") && Object.hasOwn(DOCK_OVERLAY_COMMANDS, record.command) && args.documentId !== undefined && args.documentId !== documentId) { return createFailure(`desktop-${record.module}`, "document_mismatch", "Command document identifiers differ", { capabilityId: record.id }); } documentId = typeof args.documentId === "string" ? args.documentId : documentId; if (record.module === "Sandbox" && record.command === "Std_TestGraphicsView") return createFailure("graphics-scene", "view_host_required", "Open Graphics scene from the mounted Sandbox task to view the active document"); if (record.command === "Std_MassProperties") return executeMeasureDocument(this.router, { ...args, action: "massProperties" }, documentId); if (record.command === "Std_Measure") return executeMeasureDocument(this.router, args, documentId); if (record.module === "Surface" && ["Surface_BlendCurve", "Surface_Filling", "Surface_Sections", "Surface_ExtendFace"].includes(record.command)) { return (await executeSurfaceDocument(this.router, record.command, args, documentId))!; } if (record.module === "Web" || record.module === "Std" || (record.module === "Show" && ["Std_ViewHome", "Std_ViewFitSelection"].includes(record.command))) { const response = executeDockOverlayCommand(record.command, { ...args, documentId }); if (response) return response; } if (record.module === "Web" || record.module === "Std") { const response = executeSceneDisplayCommand(record.command, args, documentId); if (response) return response; } if (record.module === "Spreadsheet" && ["Spreadsheet_SetAlias", "Spreadsheet_AlignLeft", "Spreadsheet_AlignCenter", "Spreadsheet_AlignRight", "Spreadsheet_AlignTop", "Spreadsheet_AlignVCenter", "Spreadsheet_AlignBottom", "Spreadsheet_CreateSheet", "Spreadsheet_Import", "Spreadsheet_Export", "Spreadsheet_StyleBold", "Spreadsheet_StyleItalic", "Spreadsheet_StyleUnderline"].includes(record.command)) { if (!this.spreadsheetHost) return createFailure("spreadsheet-create", "document_owner_required", "Open the project workspace to create a sheet in its native document"); const response = await this.spreadsheetHost(documentId, { ...args, command: record.command }); if (response.kind === "result") { const result = response.result as { documentId: string; createdSheet: string }; if (result.createdSheet) applySelection?.(result.documentId, [{ documentId: result.documentId, object: result.createdSheet }]); } return response; } if (record.module === "Sandbox" && SANDBOX_MESH_COMMANDS.includes(record.command)) return executeSandboxMeshImport(this.router, record, args, documentId); if (record.module === "Sandbox" && record.command === "Sandbox_SaveThread") return executeSandboxArchive(this.router, record, args); args = { ...args, documentId }; if (record.module === "Robot") args = prepareRobotWaypointArgs(record.command, args, documentId); if (record.module === "Robot" && ["Robot_AddToolShape", "Robot_SetHomePos", "Robot_RestoreHomePos"].includes(record.command)) { const selection = Array.isArray(args.selection) ? args.selection : Array.isArray(args.selectedObjects) ? args.selectedObjects.map(object => typeof object === "string" ? { documentId, object } : object) : []; args = { ...args, action: args.action ?? "read", documentId, selection }; } if (record.module === "Robot" && record.command === "Robot_ExportKukaCompact" && !Array.isArray(args.selection)) args = { ...args, selection: [] }; if (record.module === "Import" || record.module === "Part") { const imported = executeImportDesktop(this.router, record.command, args, documentId); if (imported) return imported; } if (record.module === "Web" || record.module === "Std") { const response = executeWebDesktop(this.router, record.command, args, documentId, applySelection); if (response) return response; } if (record.module === "MeshPart" && ["MeshPart_CreateFlatFace", "MeshPart_CreateFlatMesh"].includes(record.command)) return executeMeshPartFlatten(this.router, record, args, documentId, applySelection); if (record.module === "MeshPart" && record.command === "MeshPart_Mesher") return executeMeshPartMesher(this.router, record, args, documentId, applySelection); if (record.module === "MeshPart" && record.command === "MeshPart_CurveOnMesh") return executeMeshPartCurve(this.router, record, args, documentId, applySelection); if (record.module === "MeshPart" && record.command === "MeshPart_TrimByPlane") { const response = await executeMeshPartTrim(this.router, record, args, documentId); if (response.kind === "result") { const value = response.result as any; if (value.trimSelection?.length) applySelection?.(value.document, value.trimSelection.map((object: string) => ({ documentId: value.document, object }))); } return response; } if (record.module === "MeshPart") { const failure = prepareMeshPartCommand(record, args, documentId); if (failure) return failure; } // Keep BIM desktop command preparation at the dispatch boundary so palette, // navigation, and direct callers share the native command contract. if (record.module === "BIM") args = prepareBimDesktopArgs(record, args); if (record.module === "Part") { const result = executePartFixedBoxDesktop(this.router, record.command, args, documentId, applySelection); if (result) return result; const validation = preparePartDesktopCommand(record.command, args, documentId); if (validation) return validation; } const sketcherFailure = prepareSketcherCommand(record, args); if (sketcherFailure) return sketcherFailure; const meshExecution = executeMeshDesktop(this.router, record, args, documentId); if (meshExecution) return meshExecution; const sketcherExecution = executeSketcherDesktop(this.router, record, args, documentId); if (sketcherExecution) return sketcherExecution; if (record.module === "Test") { const failure = prepareTestCommand(record, args); if (failure) return failure; if (!TEST_DESKTOP_ROUTES.includes(record.command as typeof TEST_DESKTOP_ROUTES[number])) return createFailure(`desktop-${record.module}`, "unsupported_command", "Unsupported Test desktop command", { capabilityId: record.id }); if (record.command === "Test_InsertFeature") { if (args.cancelled || args.action === "cancel") return createFailure("desktop-Test", "cancelled", "Insertion cancelled"); const owner = this.router.modelingDocumentOwners.get(documentId); if (!owner || this.router.assemblyModelingDocuments.has(documentId) || this.router.assemblyModelingDocuments.has(owner.document)) return createFailure("desktop-Test", "document_owner_required", "Select an open Part or PartDesign document owned by the modeling workspace"); if (this.spreadsheetHost) return this.spreadsheetHost(documentId, { ...args, command: record.command }); return this.router.request(owner.module, owner.module === "Part" ? "part.document" : "partdesign.document", { schema: owner.module === "Part" ? "freecad-web-part/document/v1" : "freecad-web-partdesign/document/v1", module: owner.module, document: owner.document, action: "insertTestFeature", includeMesh: true, }, documentId); } const endpoint = testDesktopRoutes[record.command as keyof typeof testDesktopRoutes] ?? "test.inspectRegistry"; const response = await this.router.request("Test", endpoint, { schema: "freecad-web/test/v1", module: "Test", action: "desktop-command", sourceEntry: "src/Mod/Test/Init.py", command: record.command, args, }, documentId); return validateTestDesktopResponse(record, response); } if (record.module === "CAM") { const failure = prepareCamCommand(record, args); if (failure) return failure; } if (record.module === "Fem") { const result = executeFemDesktop(this.router, record, args, documentId, applySelection); if (result) return result; } if (record.module === "Draft") { const result = executeDraftDesktop(this.router, record, args, documentId); if (result) return result; } if (record.module === "TemplatePyMod") { args = { ...args, documentId }; const response = await this.router.request("TemplatePyMod", "templatepymod.pythonFamilyBatch", { schema: TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA, module: "TemplatePyMod", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command-initgui", kind: "command", sourcePath: record.sourcePath, args }], }, documentId); return response; } if (record.module === "Material") { args = prepareMaterialDesktopArgs(record.command, args, documentId); if (record.command === "Materials_InspectMaterial" || record.command === "Materials_InspectAppearance") { const owner = this.router.modelingDocumentOwners.get(documentId); if (!owner) return createFailure("desktop-Material", "document_owner_required", "Select an open modeling document"); const selection = Array.isArray(args.selection) ? args.selection : []; if (selection.some((item: any) => item?.documentId !== documentId && item?.documentId !== owner.document)) return createFailure("desktop-Material", "invalid_selection", "Selection belongs to a different document"); args = { ...args, documentId: owner.document, document: owner.document, selection: selection.map((item: any) => ({ ...item, documentId: owner.document })) }; } if (record.command === "Std_SetMaterial" || record.command === "Std_SetAppearance") { const owner = this.router.modelingDocumentOwners.get(documentId); if (!owner) return createFailure("desktop-Material", "document_owner_required", "Select an open modeling document"); if (args.documentId !== documentId && args.documentId !== owner.document) return createFailure("desktop-Material", "invalid_selection", "Selection belongs to a different document"); const selection = Array.isArray(args.selection) ? args.selection : []; if (selection.some((item: any) => item?.documentId !== documentId && item?.documentId !== owner.document)) return createFailure("desktop-Material", "invalid_selection", "Selection belongs to a different document"); const materialAssignment = { ...args, document: owner.document, property: record.command === "Std_SetAppearance" ? "ShapeAppearance" : "ShapeMaterial", selection: selection.map((item: any) => ({ ...item, documentId: owner.document })) }; if (this.spreadsheetHost) return this.spreadsheetHost(documentId, { command: record.command, materialAssignment }); return this.router.request(owner.module, owner.module === "Part" ? "part.document" : "partdesign.document", { schema: owner.module === "Part" ? "freecad-web-part/document/v1" : "freecad-web-partdesign/document/v1", module: owner.module, document: owner.document, action: "materialAssignment", materialAssignment, includeMesh: true, }, documentId); } const response = await this.router.request("Material", "material.pythonFamilyBatch", { schema: "freecad-web-material/python-family-batch/v1", module: "Material", tier: "tier-3-stateful", records: [{ apiId: record.id, name: record.command, family: "desktop-command", sourcePath: record.sourcePath, sourceLine: record.sourceLine, args }], }, documentId); const failure = validateMaterialDesktopResponse(record, response, record.id); return failure ?? response; } if (record.module === "PartDesign") { const result = executePartDesignDesktop(this.router, record.command, args, documentId, applySelection); if (result) return result; } if (record.module === "Assembly") { const prepared = prepareAssemblyCommand(record, args, documentId, this.activeAssemblies); if ("response" in prepared) return prepared.response; args = prepared.args; } if (record.module === "TechDraw") { const prepared = prepareTechDrawCommand(record, args, documentId); if ("response" in prepared) return prepared.response; args = prepared.args; } if (record.module === "ReverseEngineering" && ["Reen_ApproxPlane", "Reen_ApproxCylinder", "Reen_ApproxSphere", "Reen_ApproxPolynomial"].includes(record.command)) { if (args.cancel || args.cancelled || args.action === "cancel") return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch"); const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : []; if (!selection.length || selection.some(item => item.documentId !== documentId || !item.object) || (args.document && args.document !== documentId) || (args.documentId && args.documentId !== documentId)) return createFailure("native-fit", "invalid_selection", "Select geometry in one active native document"); const response = await this.router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch", { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, selection } }], }, documentId); if (response.kind === "result") { const row = (response.result as any).records?.[0]; if (row?.status !== "exposed") return createFailure("native-fit", row?.code || "native_error", row?.message || "Native fitting failed"); if (row.result?.documentChanged) applySelection?.(documentId, row.result.selection.map((object: string) => ({ documentId, object }))); } return response; } if (record.command === "Reen_SegmentationFromComponents" && record.module === "ReverseEngineering") { if (args.cancel || args.cancelled || args.action === "cancel") return createFailure("components-segmentation", "cancelled", "Segmentation cancelled before dispatch"); const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : []; if (!selection.length || selection.some(item => item.documentId !== documentId || !item.object) || (args.document && args.document !== documentId)) return createFailure("components-segmentation", "invalid_selection", "Select meshes in one active native document"); const response = await this.router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch", { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, selection } }], }, documentId); if (response.kind === "result") { const row = (response.result as any).records?.[0]; if (row?.status !== "exposed") return createFailure("components-segmentation", row?.code || "native_error", row?.message || "Native segmentation failed"); if (row.result?.documentChanged) applySelection?.(documentId, row.result.selection.map((object: string) => ({ documentId, object }))); } return response; } if (record.command === "Reen_MeshBoundary" && record.module === "ReverseEngineering") { if (args.cancel || args.cancelled || args.action === "cancel") return createFailure("mesh-boundary", "cancelled", "Mesh boundary cancelled before dispatch"); const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : []; if (!selection.length || selection.some(item => item.documentId !== documentId || !item.object) || (args.document && args.document !== documentId)) return createFailure("mesh-boundary", "invalid_selection", "Select meshes in one active native document"); const response = await this.router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch", { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, selection } }], }, documentId); if (response.kind === "result") { const row = (response.result as any).records?.[0]; if (row?.status !== "exposed") return createFailure("mesh-boundary", row?.code || "native_error", row?.message || "Native mesh boundary failed"); if (row.documentChanged && Array.isArray(row.selection)) applySelection?.(documentId, row.selection.map((object: string) => ({ documentId, object }))); } return response; } if (record.module === "ReverseEngineering" && record.command === "Reen_ViewTriangulation") { if (args.cancel || args.cancelled || args.action === "cancel") return createFailure("structured-triangulation", "cancelled", "Triangulation cancelled before dispatch"); const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : []; const names = selection.map(item => item.object); if (args.runtimeOwner !== "Points" || args.document !== documentId || !names.length || new Set(names).size !== names.length || selection.some(item => item.documentId !== documentId || !item.object) || (Array.isArray(args.objectNames) && (args.objectNames.length !== names.length || args.objectNames.some((name, i) => name !== names[i])))) return createFailure("structured-triangulation", "invalid_selection", "Select structured point clouds in one retained Points document"); const response = await this.router.request("Points", "reverseengineering.pythonFamilyBatch", { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, action: "accept", command: record.command, document: documentId, objectNames: names, selection } }], }, documentId); if (response.kind === "result") { const native = (response.result as any).records?.[0]; if (native?.status !== "exposed") return createFailure("structured-triangulation", native?.code || "native_error", native?.message || "Native triangulation failed"); applySelection?.(native.document, native.selection.map((object: string) => ({ documentId: native.document, object }))); } return response; } if (record.module === "ReverseEngineering" && (record.command === "Reen_ApproxCurve" || record.command === "Reen_ApproxSurface" || record.command === "Reen_PoissonReconstruction")) { if ((args.action !== "accept" && !(record.command === "Reen_ApproxSurface" && args.action === "placement")) || args.cancel || args.cancelled) return createFailure("curve-task", "cancelled", "Use the fitting task Accept control"); const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : []; const objects = Array.isArray(args.objectNames) ? args.objectNames : selection.map(item => item.object); if (args.runtimeOwner !== "Points" || args.document !== documentId || objects.length !== 1 || selection.some(item => item.documentId !== documentId)) return createFailure("curve-task", "invalid_selection", "Select exactly one fitting source in the retained Points document"); const response = await this.router.request("Points", "reverseengineering.pythonFamilyBatch", { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [{ apiId: record.id, name: record.command, family: "desktop-command", args: { ...args, document: documentId, objectNames: objects } }], }, documentId); if (response.kind === "result") { const native = (response.result as any).records?.[0]; if (native?.status !== "exposed") return createFailure("curve-task", native?.code || "native_error", native?.message || "Native fitting failed"); applySelection?.(native.document, native.selection.map((object: string) => ({ documentId: native.document, object }))); } return response; } if (record.module === "Points" && ["Points_Import", "Points_Export", "Points_Convert", "Points_PolyCut", "Points_Merge", "Points_Structure"].includes(record.command)) { if (args.cancel || args.cancelled || args.action === "cancel") return createFailure("points-merge", "cancelled", "Points command cancelled before mutation"); const document = typeof args.document === "string" ? args.document : documentId; const selection = Array.isArray(args.selection) ? args.selection as Array<{ documentId: string; object: string }> : []; if (document !== documentId || selection.some(item => item.documentId !== document)) return createFailure("points-merge", "document_mismatch", "Select point clouds from one document"); const objectNames = Array.isArray(args.objectNames) ? args.objectNames : Array.isArray(args.objects) ? args.objects : selection.map(item => item.object); if ((record.command === "Points_Structure" ? objectNames.length !== 1 : record.command === "Points_Merge" ? objectNames.length < 2 : record.command !== "Points_Import" && objectNames.length === 0) || objectNames.some(name => typeof name !== "string" || !name)) return createFailure("points-merge", "invalid_selection", record.command === "Points_Structure" ? "Select exactly one point cloud" : record.command === "Points_Convert" ? "Select one or more geometry objects" : "Select at least two point clouds"); if (record.command === "Points_Convert") { const tolerance = Number(args.tolerance); if (!Number.isFinite(tolerance) || tolerance <= 0 || tolerance > 10) return createFailure("points-convert", "invalid_tolerance", "Maximum distance must be greater than zero and no greater than 10"); } const response = await this.router.request("Points", "points.desktopBatch", { schema: "freecad-web-points/desktop-batch/v1", module: "Points", records: [{ apiId: record.id, name: record.command, args: { ...args, document, objectNames, includePoints: true } }], }, document); if (response.kind === "result") { const native = (response.result as any).records?.[0]; if (native?.status !== "exposed") return createFailure("points-merge", native?.code || "native_error", native?.message || "Merge failed"); const names = native.selection ?? (native.objectName ? [native.objectName] : native.objectNames ?? []); applySelection?.(native.document, names.map((object: string) => ({ documentId: native.document, object }))); } return response; } let indexed: DesktopCommandRoute | undefined; try { indexed = (await this.routes()).get(record.id); } catch (error) { return createFailure(`desktop-${record.module}`, "route_index_unavailable", error instanceof Error ? error.message : String(error), { capabilityId: record.id }); } const policy = record.module === "TechDraw" ? techDrawRoutePolicy(record.command) : null; const nativeStdViewCommand = record.module === "Std" && [ "Std_AlignToSelection", "Std_AxisCross", "Std_BoxElementSelection", "Std_BoxSelection", "Std_DrawStyle", "Std_FreezeViews", "Std_HideObjects", "Std_HideSelection", "Std_ToggleVisibility", "Std_ToggleTransparency", "Std_ToggleSelectability", "Std_ToggleObjects", "Std_MainFullscreen", "Std_OrthographicCamera", "Std_PerspectiveCamera", "Std_RecallWorkingView", "Std_SceneInspector", "Std_SelBack", "Std_SelBoundingBox", "Std_SelForward", "Std_SelectVisibleObjects", "Std_ShowObjects", "Std_ShowSelection", "Std_ClarifySelection", "Std_DemoMode", "Std_DockOverlay", "Std_DockOverlayAll", "Std_DockOverlayMouseTransparent", "Std_DockOverlayToggle", "Std_DockOverlayToggleBottom", "Std_DockOverlayToggleLeft", "Std_DockOverlayToggleRight", "Std_DockOverlayToggleTop", "Std_DockOverlayToggleTransparent", "Std_DockOverlayTransparentAll", ].includes(record.command); const nativeStackGroup = record.module === "TechDraw" && record.command === "TechDraw_StackGroup"; const partNativeCommand = record.module === "Part" && ["Part_Boolean", "Part_BoxSelection", "Part_Compound", "Part_CompSplitFeatures", "Part_Builder", "Part_Chamfer", "Part_CheckGeometry", "Part_CompCompoundTools", "Part_CompJoinFeatures", "Part_CompOffset", "Part_Export", "Part_Extrude", "Part_Fillet"].includes(record.command); if (indexed?.transport === "ui-container" && !nativeStdViewCommand && !policy?.nativeContainer && !nativeStackGroup && !partNativeCommand) { return createSuccess(`desktop-ui-${record.id}`, { schema: "freecad-web-ui-container/v1", module: record.module, command: record.command, role: "menu-or-toolbar-group", sourcePath: indexed.sourcePath ?? record.sourcePath, sourceLine: indexed.sourceLine ?? record.sourceLine, }); } const executionModule = indexed?.module ?? record.module; if (executionModule === "Part" && record.module !== "Part") { const validation = preparePartDesktopCommand(record.command, args, documentId); if (validation) return validation; } const route = record.module === "TechDraw" && ["TechDraw_LeaderLine", "TechDraw_ProjectionGroup"].includes(record.command) ? "techdraw.desktopCommand" : nativeStdViewCommand ? (indexed?.command ?? familyRoute(executionModule)) : (policy?.familyRoute || nativeStackGroup) && indexed?.transport === "ui-container" ? familyRoute(executionModule) : indexed?.transport === "family-batch" ? familyRoute(executionModule) : indexed?.command ?? familyRoute(executionModule); if (!route) return createFailure(`desktop-${record.module}`, "not_implemented", `${record.module} has no desktop command family route`, { capabilityId: record.id, command: record.command }); const response = indexed?.transport === "direct-command" ? await this.router.request(executionModule, route, { module: executionModule, command: record.command, args }, documentId) : await this.router.request(executionModule, route, { schema: familySchema(route, executionModule), module: executionModule, tier: "tier-1-readonly", records: [{ apiId: indexed?.canonicalId ?? record.id, name: record.command, family: executionModule === "Measure" ? "desktop-command-command" : "desktop-command", sourcePath: indexed?.sourcePath ?? record.sourcePath, sourceLine: indexed?.sourceLine ?? record.sourceLine, args }], }, documentId); // Std_UserInterface is a native command even though its desktop route is // exposed through the shared GUI family. Keep its acceptance semantics in // this command-specific branch so a generic tail status cannot mask it. if (record.command === "Std_UserInterface" && response.kind === "result") { if (!response.result || typeof response.result !== "object" || Array.isArray(response.result)) { return createFailure("desktop-Std", "native_protocol_error", "Std_UserInterface result is invalid", { capabilityId: record.id, response }); } const batch = response.result as { records?: Array<{ apiId?: string; status?: string; code?: string; message?: string }> }; const native = batch.records?.find((item) => item.apiId === (indexed?.canonicalId ?? record.id)); if (!native) return createFailure("desktop-Std", "native_protocol_error", "Std_UserInterface result is missing", { capabilityId: record.id, response }); if (native.status !== "exposed") { return createFailure("desktop-Std", native.code || "native_desktop_command_failed", native.message || "Std_UserInterface command failed", { capabilityId: record.id, response }); } return { ...response, result: { ...response.result, status: "exposed", command: "Std_UserInterface" } }; } if (executionModule === "MeshPart" && indexed?.transport !== "direct-command") { return validateMeshPartResponse(record, response, indexed?.canonicalId ?? record.id); } if (executionModule === "CAM") { return validateCamDesktopResponse(record, response, indexed?.canonicalId ?? record.id); } if (executionModule === "BIM" && indexed?.transport !== "direct-command") { return validateBimDesktopResponse(record, response, indexed?.canonicalId ?? record.id, documentId, applySelection); } if (executionModule === "Material" && indexed?.transport !== "direct-command") { const failure = validateMaterialDesktopResponse(record, response, indexed?.canonicalId ?? record.id); if (failure) return failure; } if (executionModule === "Points" && response.kind === "result") { const batch = response.result as { records?: Array<{ apiId: string; status: string; code?: string; message?: string }> }; const native = batch?.records?.find((item) => item.apiId === (indexed?.canonicalId ?? record.id)); if (!native) return createFailure("desktop-Points", "native_protocol_error", "Points command result is missing", { capabilityId: record.id }); if (native.status !== "exposed") { return createFailure("desktop-Points", native.code || "native_desktop_command_failed", native.message || "Points command failed", { capabilityId: record.id, response }); } } if (executionModule === "Inspection" && indexed?.transport !== "direct-command") { return validateInspectionDesktopResponse(record, response, indexed?.canonicalId ?? record.id); } if (executionModule === "TechDraw" && indexed?.transport !== "direct-command" && response.kind === "result") { const failure = validateTechDrawResponse(record, response, indexed?.canonicalId ?? record.id); if (failure) return failure; } if (executionModule === "Part" && response.kind === "result") { const failure = validatePartDesktopResponse(record, response, indexed?.canonicalId ?? record.id, applySelection); if (failure) return failure; } if (executionModule === "Assembly" && response.kind === "result") { const applied = applyAssemblyResponse(record, response, indexed?.canonicalId ?? record.id, documentId, this.activeAssemblies, applySelection); if (applied.kind === "result") { const batch = applied.result as { records?: Array<{ result?: { documentId?: string; activeBody?: { documentId: string }; bundle?: { files: Array<{ documentId: string }> } } }> }; for (const row of batch.records ?? []) { if (row.result?.activeBody) this.router.assemblyModelingDocuments.add(row.result.activeBody.documentId); for (const file of row.result?.bundle?.files ?? []) this.router.assemblyModelingDocuments.add(file.documentId); } } return applied; } if (executionModule === "TechDraw" && record.command === "TechDraw_ExportPageDXF") { try { deliverNativeDxf(response); } catch (error) { return createFailure(`desktop-${record.module}`, "file_delivery_failed", error instanceof Error ? error.message : String(error), { capabilityId: record.id }); } } if (executionModule === "BIM" && response.kind === "result") { const failure = validateBimDesktopResponse(record, response, indexed?.canonicalId ?? record.id); if (failure) return failure; } return record.module === "Sketcher" ? validateSketcherResponse(record, response) : response; } }