diff --git a/docs/web-parity-matrix.json b/docs/web-parity-matrix.json new file mode 100644 index 00000000..55e9095b --- /dev/null +++ b/docs/web-parity-matrix.json @@ -0,0 +1,1144 @@ +{ + "schema": "freecad-web-parity-matrix/v1", + "source_revision": "2778e3f9c215da48bf0cfd562478d45d624aaa47", + "status_values": [ + "pending", + "in_progress", + "blocked", + "completed" + ], + "module_count": 32, + "rows": [ + { + "module": "Assembly", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 8, + "object_types": [ + "App::Link", + "Assembly::AssemblyLink", + "Assembly::AssemblyObject", + "Assembly::BomGroup", + "Assembly::BomObject", + "Assembly::JointGroup", + "Assembly::SimulationGroup", + "Assembly::ViewGroup" + ], + "format_extensions": [ + ".fcstd" + ], + "python_api_count": 552, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "BIM", + "user_actions": [ + "import/export", + "inspect/source-inventory", + "python-api" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [ + ".brp", + ".dae", + ".dxf", + ".fcstd", + ".ifc", + ".json", + ".obj", + ".stp", + ".svg" + ], + "python_api_count": 2366, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "CAM", + "user_actions": [ + "create/recompute", + "import/export", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 12, + "object_types": [ + "Path::Area", + "Path::Command", + "Path::Feature", + "Path::FeatureArea", + "Path::FeatureAreaView", + "Path::FeatureShape", + "Path::PropertyPath", + "Path::Toolpath", + "Path::Voronoi", + "Path::VoronoiCell", + "Path::VoronoiEdge", + "Path::VoronoiVertex" + ], + "format_extensions": [ + ".fcstd", + ".json", + ".obj", + ".step", + ".svg" + ], + "python_api_count": 2883, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Cloud", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 3, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Draft", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [ + ".dxf", + ".obj", + ".svg" + ], + "python_api_count": 2043, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Fem", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 53, + "object_types": [ + "Fem::Constraint", + "Fem::ConstraintBearing", + "Fem::ConstraintContact", + "Fem::ConstraintDisplacement", + "Fem::ConstraintFixed", + "Fem::ConstraintFluidBoundary", + "Fem::ConstraintForce", + "Fem::ConstraintGear", + "Fem::ConstraintHeatflux", + "Fem::ConstraintInitialTemperature", + "Fem::ConstraintPlaneRotation", + "Fem::ConstraintPressure", + "Fem::ConstraintPulley", + "Fem::ConstraintRigidBody", + "Fem::ConstraintSpring", + "Fem::ConstraintTemperature", + "Fem::ConstraintTransform", + "Fem::DocumentObject", + "Fem::FemAnalysis", + "Fem::FemMesh", + "Fem::FemMeshObject", + "Fem::FemMeshShapeBaseObject", + "Fem::FemMeshShapeNetgenObject", + "Fem::FemMeshShapeObject", + "Fem::FemPostBoxFunction", + "Fem::FemPostCalculatorFilter", + "Fem::FemPostClipFilter", + "Fem::FemPostContoursFilter", + "Fem::FemPostCutFilter", + "Fem::FemPostCylinderFunction", + "Fem::FemPostDataAlongLineFilter", + "Fem::FemPostDataAtPointFilter", + "Fem::FemPostFilter", + "Fem::FemPostFunction", + "Fem::FemPostFunctionProvider", + "Fem::FemPostGroupExtension", + "Fem::FemPostObject", + "Fem::FemPostPlaneFunction", + "Fem::FemPostScalarClipFilter", + "Fem::FemPostSmoothFilterExtension", + "Fem::FemPostSphereFunction", + "Fem::FemPostWarpVectorFilter", + "Fem::FemResultObject", + "Fem::FemSetElementNodesObject", + "Fem::FemSetElementsObject", + "Fem::FemSetFacesObject", + "Fem::FemSetGeometryObject", + "Fem::FemSetNodesObject", + "Fem::FemSetObject", + "Fem::FemSolverObject", + "Fem::PropertyFemMesh", + "Fem::PropertyPostDataObject", + "Fem::WorkerExtension" + ], + "format_extensions": [ + ".brep", + ".json", + ".obj", + ".svg", + ".txt" + ], + "python_api_count": 1305, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Help", + "user_actions": [ + "inspect/source-inventory", + "python-api" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 14, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Import", + "user_actions": [ + "create/recompute", + "import/export", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 2, + "object_types": [ + "App::DocumentObjectGroup", + "App::FeaturePython" + ], + "format_extensions": [ + ".ifc", + ".igs", + ".obj", + ".step", + ".stp" + ], + "python_api_count": 1135, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Inspection", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 3, + "object_types": [ + "Inspection::Feature", + "Inspection::Group", + "Inspection::PropertyDistanceList" + ], + "format_extensions": [], + "python_api_count": 3, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "JtReader", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "save/reopen" + ], + "object_type_count": 1, + "object_types": [ + "App::InventorObject" + ], + "format_extensions": [], + "python_api_count": 0, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Material", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 22, + "object_types": [ + "Materials::Array2D", + "Materials::Array3D", + "Materials::Library", + "Materials::Material", + "Materials::MaterialFilter", + "Materials::MaterialFilterOptions", + "Materials::MaterialLibrary", + "Materials::MaterialLibraryLocal", + "Materials::MaterialManager", + "Materials::MaterialManagerExternal", + "Materials::MaterialManagerLocal", + "Materials::MaterialProperty", + "Materials::MaterialValue", + "Materials::Model", + "Materials::ModelLibrary", + "Materials::ModelLibraryLocal", + "Materials::ModelManager", + "Materials::ModelManagerExternal", + "Materials::ModelManagerLocal", + "Materials::ModelProperty", + "Materials::ModelUUIDs", + "Materials::PropertyMaterial" + ], + "format_extensions": [], + "python_api_count": 178, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Measure", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 11, + "object_types": [ + "Measure::MeasureAngle", + "Measure::MeasureArea", + "Measure::MeasureBase", + "Measure::MeasureDiameter", + "Measure::MeasureDistance", + "Measure::MeasureDistanceDetached", + "Measure::MeasureLength", + "Measure::MeasurePosition", + "Measure::MeasureRadius", + "Measure::Measurement", + "Measure::Result" + ], + "format_extensions": [], + "python_api_count": 31, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Mesh", + "user_actions": [ + "create/recompute", + "import/export", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 31, + "object_types": [ + "Mesh::Cone", + "Mesh::Cube", + "Mesh::Curvature", + "Mesh::Cylinder", + "Mesh::Ellipsoid", + "Mesh::Export", + "Mesh::Feature", + "Mesh::FillHoles", + "Mesh::FixDefects", + "Mesh::FixDeformations", + "Mesh::FixDegenerations", + "Mesh::FixDuplicatedFaces", + "Mesh::FixDuplicatedPoints", + "Mesh::FixIndices", + "Mesh::FixNonManifolds", + "Mesh::FlipNormals", + "Mesh::HarmonizeNormals", + "Mesh::Import", + "Mesh::MeshObject", + "Mesh::MeshSegment", + "Mesh::PropertyCurvatureList", + "Mesh::PropertyMaterial", + "Mesh::PropertyMeshKernel", + "Mesh::PropertyNormalList", + "Mesh::RemoveComponents", + "Mesh::SegmentByMesh", + "Mesh::SetOperations", + "Mesh::Sphere", + "Mesh::Torus", + "Mesh::Transform", + "Mesh::TransformDemolding" + ], + "format_extensions": [ + ".3mf", + ".amf", + ".ast", + ".obj", + ".off", + ".ply", + ".stl" + ], + "python_api_count": 211, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "MeshPart", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 13, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Part", + "user_actions": [ + "create/recompute", + "import/export", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 116, + "object_types": [ + "Attacher::AttachEngine3D", + "Attacher::AttachEngineLine", + "Attacher::AttachEnginePlane", + "Attacher::AttachEnginePoint", + "Part::AttachableObject", + "Part::Boolean", + "Part::Box", + "Part::Chamfer", + "Part::Circle", + "Part::Common", + "Part::Compound", + "Part::Compound2", + "Part::Cone", + "Part::CurveNet", + "Part::CustomFeature", + "Part::Cut", + "Part::Cylinder", + "Part::Ellipse", + "Part::Ellipsoid", + "Part::Extrusion", + "Part::Face", + "Part::FaceMakerBullseye", + "Part::FaceMakerCheese", + "Part::FaceMakerExtrusion", + "Part::FaceMakerRing", + "Part::FaceMakerSimple", + "Part::Feature", + "Part::FeatureExt", + "Part::FeatureGeometrySet", + "Part::FeatureReference", + "Part::Fillet", + "Part::FilletBase", + "Part::Fuse", + "Part::Geom2dArcOfCircle", + "Part::Geom2dArcOfEllipse", + "Part::Geom2dArcOfHyperbola", + "Part::Geom2dArcOfParabola", + "Part::Geom2dBSplineCurve", + "Part::Geom2dBezierCurve", + "Part::Geom2dCircle", + "Part::Geom2dEllipse", + "Part::Geom2dHyperbola", + "Part::Geom2dLine", + "Part::Geom2dLineSegment", + "Part::Geom2dOffsetCurve", + "Part::Geom2dParabola", + "Part::Geom2dPoint", + "Part::Geom2dTrimmedCurve", + "Part::GeomArcOfCircle", + "Part::GeomArcOfEllipse", + "Part::GeomArcOfHyperbola", + "Part::GeomArcOfParabola", + "Part::GeomBSplineCurve", + "Part::GeomBSplineSurface", + "Part::GeomBezierCurve", + "Part::GeomBezierSurface", + "Part::GeomCircle", + "Part::GeomCone", + "Part::GeomCylinder", + "Part::GeomEllipse", + "Part::GeomHyperbola", + "Part::GeomLine", + "Part::GeomLineSegment", + "Part::GeomOffsetCurve", + "Part::GeomOffsetSurface", + "Part::GeomParabola", + "Part::GeomPlane", + "Part::GeomPlateSurface", + "Part::GeomPoint", + "Part::GeomSphere", + "Part::GeomSurfaceOfExtrusion", + "Part::GeomSurfaceOfRevolution", + "Part::GeomToroid", + "Part::GeomTrimmedCurve", + "Part::GeomTrimmedSurface", + "Part::GeometryMigrationExtension", + "Part::Helix", + "Part::ImportBrep", + "Part::ImportIges", + "Part::ImportStep", + "Part::Line", + "Part::Loft", + "Part::Mirroring", + "Part::MultiCommon", + "Part::MultiFuse", + "Part::Offset", + "Part::Offset2D", + "Part::Plane", + "Part::Polygon", + "Part::PreviewExtension", + "Part::Prism", + "Part::PrismExtension", + "Part::ProjectOnSurface", + "Part::PropertyFilletEdges", + "Part::PropertyGeometryList", + "Part::PropertyPartShape", + "Part::PropertyShapeCache", + "Part::PropertyShapeHistory", + "Part::PropertyTopoShapeList", + "Part::Refine", + "Part::RegularPolygon", + "Part::Reverse", + "Part::Revolution", + "Part::RuledSurface", + "Part::Scale", + "Part::Section", + "Part::ShapeSegment", + "Part::Sphere", + "Part::Spiral", + "Part::Spline", + "Part::Sweep", + "Part::Thickness", + "Part::TopoShape", + "Part::Torus", + "Part::Vertex", + "Part::Wedge" + ], + "format_extensions": [ + ".brep", + ".brp", + ".fcstd", + ".iges", + ".igs", + ".obj", + ".step", + ".stp", + ".svg" + ], + "python_api_count": 1191, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "PartDesign", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 65, + "object_types": [ + "PartDesign::AdditiveBox", + "PartDesign::AdditiveCone", + "PartDesign::AdditiveCylinder", + "PartDesign::AdditiveEllipsoid", + "PartDesign::AdditiveHelix", + "PartDesign::AdditiveLoft", + "PartDesign::AdditivePipe", + "PartDesign::AdditivePrism", + "PartDesign::AdditiveSphere", + "PartDesign::AdditiveTorus", + "PartDesign::AdditiveWedge", + "PartDesign::Body", + "PartDesign::Box", + "PartDesign::Chamfer", + "PartDesign::Cone", + "PartDesign::CoordinateSystem", + "PartDesign::Cylinder", + "PartDesign::Draft", + "PartDesign::DressUp", + "PartDesign::Ellipsoid", + "PartDesign::Feature", + "PartDesign::FeatureAddSub", + "PartDesign::FeatureAdditivePython", + "PartDesign::FeatureBase", + "PartDesign::FeatureExtrude", + "PartDesign::FeatureRefine", + "PartDesign::FeatureSubtractivePython", + "PartDesign::Fillet", + "PartDesign::Groove", + "PartDesign::Helix", + "PartDesign::Hole", + "PartDesign::Line", + "PartDesign::LinearPattern", + "PartDesign::Loft", + "PartDesign::Mirrored", + "PartDesign::MultiTransform", + "PartDesign::Pad", + "PartDesign::Pipe", + "PartDesign::Plane", + "PartDesign::Pocket", + "PartDesign::Point", + "PartDesign::PolarPattern", + "PartDesign::Prism", + "PartDesign::ProfileBased", + "PartDesign::Revolution", + "PartDesign::Scaled", + "PartDesign::ShapeBinder", + "PartDesign::Solid", + "PartDesign::Sphere", + "PartDesign::SubShapeBinder", + "PartDesign::SubtractiveBox", + "PartDesign::SubtractiveCone", + "PartDesign::SubtractiveCylinder", + "PartDesign::SubtractiveEllipsoid", + "PartDesign::SubtractiveHelix", + "PartDesign::SubtractiveLoft", + "PartDesign::SubtractivePipe", + "PartDesign::SubtractivePrism", + "PartDesign::SubtractiveSphere", + "PartDesign::SubtractiveTorus", + "PartDesign::SubtractiveWedge", + "PartDesign::Thickness", + "PartDesign::Torus", + "PartDesign::Transformed", + "PartDesign::Wedge" + ], + "format_extensions": [], + "python_api_count": 238, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Plot", + "user_actions": [ + "inspect/source-inventory", + "python-api" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 28, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Points", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 8, + "object_types": [ + "Points::Feature", + "Points::PointKernel", + "Points::PropertyCurvatureList", + "Points::PropertyGreyValue", + "Points::PropertyGreyValueList", + "Points::PropertyNormalList", + "Points::PropertyPointKernel", + "Points::Structured" + ], + "format_extensions": [ + ".obj", + ".ply" + ], + "python_api_count": 12, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "ReverseEngineering", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 3, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Robot", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 6, + "object_types": [ + "Robot::PropertyTrajectory", + "Robot::Robot6Axis", + "Robot::RobotObject", + "Robot::Trajectory", + "Robot::TrajectoryObject", + "Robot::Waypoint" + ], + "format_extensions": [], + "python_api_count": 16, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Sandbox", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 2, + "object_types": [ + "Mesh::Ellipsoid", + "SandboxObject" + ], + "format_extensions": [ + ".ast", + ".obj", + ".stl" + ], + "python_api_count": 30, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Show", + "user_actions": [ + "inspect/source-inventory", + "python-api" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 104, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Sketcher", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 10, + "object_types": [ + "Sketcher::Constraint", + "Sketcher::ExternalGeometryExtension", + "Sketcher::ExternalGeometryFacade", + "Sketcher::GeometryFacade", + "Sketcher::PropertyConstraintList", + "Sketcher::Sketch", + "Sketcher::SketchGeometryExtension", + "Sketcher::SketchObject", + "Sketcher::SketchObjectSF", + "Sketcher::SolverGeometryExtension" + ], + "format_extensions": [], + "python_api_count": 141, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Spreadsheet", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 5, + "object_types": [ + "Spreadsheet::PropertyColumnWidths", + "Spreadsheet::PropertyRowHeights", + "Spreadsheet::PropertySheet", + "Spreadsheet::PropertySpreadsheetQuantity", + "Spreadsheet::Sheet" + ], + "format_extensions": [ + ".csv" + ], + "python_api_count": 63, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Start", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [ + ".fcstd", + ".svg" + ], + "python_api_count": 2, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Surface", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 7, + "object_types": [ + "Surface::Cut", + "Surface::Extend", + "Surface::FeatureBlendCurve", + "Surface::Filling", + "Surface::GeomFillSurface", + "Surface::Sections", + "Surface::Sewing" + ], + "format_extensions": [], + "python_api_count": 10, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "TechDraw", + "user_actions": [ + "create/recompute", + "import/export", + "inspect/source-inventory", + "python-api", + "save/reopen" + ], + "object_type_count": 41, + "object_types": [ + "TechDraw::CenterLine", + "TechDraw::CosmeticEdge", + "TechDraw::CosmeticObject", + "TechDraw::CosmeticVertex", + "TechDraw::DrawBrokenView", + "TechDraw::DrawComplexSection", + "TechDraw::DrawGeomHatch", + "TechDraw::DrawHatch", + "TechDraw::DrawLeaderLine", + "TechDraw::DrawPage", + "TechDraw::DrawParametricTemplate", + "TechDraw::DrawProjGroup", + "TechDraw::DrawProjGroupItem", + "TechDraw::DrawRichAnno", + "TechDraw::DrawSVGTemplate", + "TechDraw::DrawTemplate", + "TechDraw::DrawTile", + "TechDraw::DrawTileWeld", + "TechDraw::DrawView", + "TechDraw::DrawViewAnnotation", + "TechDraw::DrawViewArch", + "TechDraw::DrawViewBalloon", + "TechDraw::DrawViewClip", + "TechDraw::DrawViewCollection", + "TechDraw::DrawViewDetail", + "TechDraw::DrawViewDimExtent", + "TechDraw::DrawViewDimension", + "TechDraw::DrawViewDraft", + "TechDraw::DrawViewImage", + "TechDraw::DrawViewMulti", + "TechDraw::DrawViewSection", + "TechDraw::DrawViewSpreadsheet", + "TechDraw::DrawViewSymbol", + "TechDraw::DrawWeldSymbol", + "TechDraw::FeatureProjection", + "TechDraw::GeomFormat", + "TechDraw::LandmarkDimension", + "TechDraw::PropertyCenterLineList", + "TechDraw::PropertyCosmeticEdgeList", + "TechDraw::PropertyCosmeticVertexList", + "TechDraw::PropertyGeomFormatList" + ], + "format_extensions": [ + ".dxf", + ".svg" + ], + "python_api_count": 247, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "TemplatePyMod", + "user_actions": [ + "inspect/source-inventory", + "python-api" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 244, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Test", + "user_actions": [ + "inspect/source-inventory" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [ + ".fcstd", + ".obj" + ], + "python_api_count": 0, + "gui_dependency": true, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Tux", + "user_actions": [ + "inspect/source-inventory", + "python-api" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 25, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + }, + { + "module": "Web", + "user_actions": [ + "create/recompute", + "inspect/source-inventory", + "save/reopen" + ], + "object_type_count": 0, + "object_types": [], + "format_extensions": [], + "python_api_count": 0, + "gui_dependency": false, + "web_status": "completed", + "source_evidence": { + "workbench": "docs/workbench-inventory.json", + "objects": "docs/object-inventory.json", + "format_api": "docs/format-api-inventory.json" + }, + "regression_entry": "FreeCAD/docs/tasks/FW-P3-001B.md" + } + ] +} diff --git a/tools/generate_api_adapter_fill_manifest.py b/tools/generate_api_adapter_fill_manifest.py new file mode 100644 index 00000000..52add425 --- /dev/null +++ b/tools/generate_api_adapter_fill_manifest.py @@ -0,0 +1,24 @@ +#!/usr/bin/env python3 +"""Generate grouped implementation plans for all remaining planned APIs.""" +from __future__ import annotations +import hashlib +import json +from collections import defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +source_path = ROOT / "docs/p6/python-api-manifest.json" +rows = json.loads(source_path.read_text(encoding="utf-8"))["records"] +selected = [row for row in rows if row["disposition"] == "planned"] +routes = {"Part": ("part.worker.ts", "part.pythonApi"), "PartDesign": ("partdesign-python.worker.ts", "partdesign.pythonApi"), "Sketcher": ("sketcher-python.worker.ts", "sketcher.pythonApi"), "TechDraw": ("techdraw-python.worker.ts", "techdraw.pythonApi"), "Import": ("import.worker.ts", "import.pythonApi"), "Mesh": ("mesh.worker.ts", "mesh.pythonApi"), "Measure": ("measure.worker.ts", "measure.pythonApi"), "Points": ("points.worker.ts", "points.pythonApi"), "Robot": ("robot-python.worker.ts", "robot.pythonApi"), "Surface": ("surface-python.worker.ts", "surface.pythonApi"), "Spreadsheet": ("spreadsheet-python.worker.ts", "spreadsheet.pythonApi"), "Sandbox": ("sandbox-python.worker.ts", "sandbox.pythonApi"), "Material": ("material-python.worker.ts", "material.pythonApi"), "TemplatePyMod": ("templatepymod-python.worker.ts", "templatepymod.pythonApi"), "Plot": ("plot-python.worker.ts", "plot.pythonApi"), "ReverseEngineering": ("reverseengineering-python.worker.ts", "reverseengineering.pythonApi")} +groups = defaultdict(list) +for row in selected: groups[f"{row['module']}:{row['tier']}:{row['family']}"].append(row) +plans = [] +for key, group in sorted(groups.items()): + module, tier, family = key.split(":", 2) + worker, command = routes.get(module, (None, None)) + plans.append({"key": key, "module": module, "tier": tier, "family": family, "count": len(group), "route": {"worker": worker, "command": command}, "adapterStatus": "module_adapter_ready_pending_method" if command else "module_adapter_pending", "apiIds": sorted(row["id"] for row in group)}) +output = {"schema": "freecad-web-api-adapter-fill-manifest/v1", "taskId": "FW-P6-FPA-IMPL-API-ADAPTER-FILL", "source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(source_path.read_bytes()).hexdigest()}, "disposition": "planned", "count": len(selected), "groupCount": len(plans), "groups": plans, "boundaries": ["route readiness is not method-level API completion", "module_adapter_pending groups require native facade/probe before implementation"]} +out = ROOT / "docs/p6/api-adapter-fill-manifest.json" +out.write_text(json.dumps(output, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8") +print(json.dumps({"output": str(out.relative_to(ROOT)), "count": len(selected), "groups": len(plans), "bytes": out.stat().st_size, "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, ensure_ascii=False)) diff --git a/tools/generate_contract_batch.py b/tools/generate_contract_batch.py new file mode 100644 index 00000000..7eaf9d5c --- /dev/null +++ b/tools/generate_contract_batch.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""Run one queued contract family and promote only fully passed real cases.""" +import argparse +import json +import os +import subprocess +import re +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +QUEUE = ROOT / "docs/current/contract-generation-queue.json" +PROGRESS = ROOT / "docs/current/contract-generation-progress.json" + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--module") + parser.add_argument("--family") + parser.add_argument("--apply", action="store_true", help="promote coveredIds only after every selected case passes") + parser.add_argument("--confirm-apply", action="store_true", help="second confirmation required with --apply") + parser.add_argument("--generate", action="store_true", help="write a non-passing skeleton; never updates coveredIds") + args = parser.parse_args() + if args.apply and not args.confirm_apply: parser.error("--apply requires --confirm-apply") + queue = json.loads(QUEUE.read_text()) + batch = next((item for item in queue.get("batches", []) + if (not args.module or item["module"] == args.module) + and (not args.family or item["family"] == args.family)), None) + if not batch: + print(json.dumps({"status": "no_batch", "reason": "no queued family matches"})) + return 2 + if args.generate: + slug = re.sub(r"[^a-z0-9]+", "-", f"{batch['module']}-{batch['family']}".lower()).strip("-") + output = ROOT / "tools/generated-contracts" / f"{slug}.mjs" + output.parent.mkdir(parents=True, exist_ok=True) + ids = json.dumps(batch["ids"], ensure_ascii=False, indent=2) + source = json.dumps(batch.get("commands", []), ensure_ascii=False) + output.write_text("""// Generated contract skeleton. Implement real native/browser assertions before promotion.\nconst ids = %s;\nconst commands = %s;\nconst results = ids.map(capabilityId => ({ capabilityId, status: \"not_implemented\", cases: [{ input: { capabilityId, commands }, assertions: [{ name: \"real business assertion is implemented\", passed: false, actual: \"generation skeleton only\" }] }] }));\nprocess.stdout.write(JSON.stringify({ schema: \"freecad-web-business-cases/v1\", results }) + \"\\n\");\nprocess.exitCode = 1;\n""" % (ids, source)) + try: + progress = json.loads(PROGRESS.read_text()) + except (OSError, json.JSONDecodeError): + progress = {"schema": "freecad-web-contract-generation-progress/v1", "batches": {}} + progress.setdefault("batches", {})[f"{batch['module']}:{batch['family']}"] = { + "status": "skeleton_generated", "path": str(output.relative_to(ROOT)), + "generatedAt": __import__("time").time(), "ids": batch["ids"], "coveredIdsUpdated": False} + PROGRESS.write_text(json.dumps(progress, ensure_ascii=False, indent=2) + "\n") + print(json.dumps({"status": "skeleton_generated", "module": batch["module"], "family": batch["family"], "ids": batch["ids"], "path": str(output.relative_to(ROOT)), "coveredIdsUpdated": False}, ensure_ascii=False)) + return 0 + contract_path = ROOT / "docs/business-acceptance" / f"{batch['module']}.json" + contract = json.loads(contract_path.read_text()) + command = contract.get("command", []) + if batch["module"] == "Part": + command = ["node", "tools/part-family-contract-business-cases.mjs"] + if batch["family"].startswith("product-"): + command = ["node", "tools/web-acceptance-cases.mjs"] + if batch["family"] == "product-extensions": command = ["node", "tools/web-product-extensions-business-cases.mjs"] + if batch["family"].startswith("desktop-command-"): + command = ["node", "tools/desktop-boundary-business-cases-v2.mjs"] + if batch["module"] in {"BIM", "Test", "Assembly", "CAM", "Fem", "Draft", "Sketcher", "TechDraw", "Web"}: + command = ["node", "tools/desktop-restricted-boundary-business-cases.mjs"] + if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepycheckable": + command = ["node", "tools/templatepymod-checkable-business-cases.mjs"] + if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepygroup": + command = ["node", "tools/templatepymod-group-business-cases.mjs"] + if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepygrp": + command = ["node", "tools/templatepymod-grp-business-cases.mjs"] + if batch["module"] == "TemplatePyMod" and batch["family"] == "desktop-command-templatepymod": + command = ["node", "tools/templatepymod-command-business-cases-v2.mjs"] + if batch["module"] == "Draft" and batch["family"] == "create-edit-recompute": + command = ["node", "tools/draft-action-business-cases.mjs"] + if batch["module"] == "Fem" and batch["family"] == "create-edit-recompute": + command = ["node", "tools/fem-action-business-cases.mjs"] + if not isinstance(command, list) or len(command) < 2: + print(json.dumps({"status": "not_ready", "reason": "module contract has no executable command", "batch": batch})) + return 78 + environment = dict(os.environ, FREECAD_BUSINESS_IDS=json.dumps(batch["ids"])) + run = subprocess.run(command, cwd=ROOT, env=environment, capture_output=True, text=True) + try: + report = json.loads(run.stdout) + except json.JSONDecodeError: + report = {"status": "invalid_report", "stdout": run.stdout[-3000:], "stderr": run.stderr[-3000:]} + results = report.get("results", []) if isinstance(report, dict) else [] + passed = {row.get("capabilityId") for row in results if row.get("status") == "passed"} + all_passed = set(batch["ids"]).issubset(passed) and run.returncode == 0 + output = {"status": "passed" if all_passed else "not_ready", "applied": False, + "module": batch["module"], "family": batch["family"], "ids": batch["ids"], + "passedIds": sorted(passed), "exitCode": run.returncode, "reason": report.get("reason"), "stderr": run.stderr[-600:], "stdout": run.stdout[-600:]} + if all_passed and args.apply: + covered = list(dict.fromkeys([*contract.get("coveredIds", []), *batch["ids"]])) + contract["coveredIds"] = covered + contract_path.write_text(json.dumps(contract, ensure_ascii=False, indent=2) + "\n") + try: + progress = json.loads(PROGRESS.read_text()) + except (OSError, json.JSONDecodeError): + progress = {"schema": "freecad-web-contract-generation-progress/v1", "batches": {}} + key = f"{batch['module']}:{batch['family']}" + previous = progress.setdefault("batches", {}).get(key, {}) + progress["batches"][key] = {**previous, "status": "verified_and_applied", "verifiedAt": __import__("time").time(), + "ids": batch["ids"], "passedIds": sorted(passed), "coveredIdsUpdated": True} + PROGRESS.write_text(json.dumps(progress, ensure_ascii=False, indent=2) + "\n") + output["applied"] = True + print(json.dumps(output, ensure_ascii=False)) + return 0 if all_passed else 1 + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/generate_feature_capability_registry.py b/tools/generate_feature_capability_registry.py new file mode 100644 index 00000000..b6b24e11 --- /dev/null +++ b/tools/generate_feature_capability_registry.py @@ -0,0 +1,1484 @@ +#!/usr/bin/env python3 +"""Generate the implementation-first Web capability registry. + +The registry counts user-callable Worker commands, not Python source symbols. +It is intentionally static analysis: runtime validation belongs to the +deferred validation phase or to a focused issue raised during actual use. +""" +from __future__ import annotations + +import ast +import argparse +import json +import re +import subprocess +from collections import Counter +from datetime import datetime, timezone +from functools import lru_cache +from pathlib import Path +from generate_web_workbench_inventory import cpp_gui_commands + + +ROOT = Path(__file__).resolve().parents[1] +REGISTRY_SOURCE = ROOT / "web/src/module-registry.generated.ts" +WORKBENCH_SOURCE = ROOT / "web/src/workbench-shell.tsx" +ARTIFACT_MANIFEST = ROOT / "web/public/modules/manifest.json" +WORKBENCH_MATRIX = ROOT / "docs/p6/workbench-command-matrix.json" +OUTPUT = ROOT / "docs/current/feature-capability-registry.json" +ROUTE_OUTPUT = ROOT / "web/public/api/desktop-command-routes.json" +PROBE_ROOT = ROOT / "freecad-source/src/WebAssembly/FreeCADCoreProbe" +CACHE_PATH = ROOT / "docs/current/feature-capability-cache.json" + + +def file_stamps(paths: set[Path]) -> dict: + result = {} + for path in sorted(paths): + try: + info = path.stat() + result[str(path)] = [info.st_size, info.st_mtime_ns, info.st_ctime_ns] + except FileNotFoundError: + result[str(path)] = None + return result + + +def generation_inputs(command_matrix: dict) -> set[Path]: + paths = {Path(__file__).resolve(), ROOT / "tools/generate_web_workbench_inventory.py", REGISTRY_SOURCE, WORKBENCH_SOURCE, ARTIFACT_MANIFEST, WORKBENCH_MATRIX, + ROOT / "web/src/native-source-policy.ts", ROOT / "web/tools/audit-native-route-policy.mjs"} + paths.update(ROOT / "web/src" / name for name in ("dock-overlay-commands.json", "dock-overlay-adapter.ts", "dock-overlay-host.tsx", "dock-overlay.css", "desktop-command-dispatcher.ts")) + paths.update(ROOT / "web/src" / name for name in ("scene-display-commands.json", "scene-command-adapter.ts", "scene-command-host.ts", "scene-command-host.css", "scene-overlap-picker.ts", "scene-camera-commands.ts", "import-render-bridge.ts", "scene-viewport.tsx")) + paths.update(ROOT / "web/src" / name for name in ("test-desktop-routes.json", "test-mdi-host.tsx", "test-desktop-output.tsx")) + paths.update(ROOT / "web/src" / name for name in ("document-view-routes.json", "web-view-task.tsx", + "web-owner-standard-adapter.ts", "web-standard-command-contract.ts", "web-standard-task.tsx", + "web-website-adapter.ts", "web-website-task.tsx", "web-group-contract.ts", "web-group-adapter.ts", "web-group-task.tsx", + "web-link-contract.ts", "web-source-test-adapter.ts", "bim-relationship-task.tsx", + "web-structure-adapter.ts", "web-structure-contract.ts", "web-structure-task.tsx", "web-link-mutation-task.tsx", + "bim-windows-task.tsx", "bim-windows-contract.ts", "web-open-adapter.ts", "web-open-contract.ts", "web-open-task.tsx")) + # Curve routing depends on the mounted Points fitting controls. + paths.add(ROOT / "web/src/points-merge-task.tsx") + paths.add(ROOT / "web/src/reverseengineering-surface-task.tsx") + paths.add(ROOT / "web/src/reverseengineering-automatic-task.tsx") + paths.add(ROOT / "web/src/reverseengineering-manual-task.tsx") + paths.update(ROOT / "web/src" / name for name in ( + "module-router.ts", "measure-document-adapter.ts", "measure-mass-properties-task.tsx", + "measure-distance-task.tsx")) + paths.add(PROBE_ROOT / "PartDesignDocumentWorkflow.cpp") + paths.add(ROOT / "web/src/techdraw-weld-task.tsx") + paths.add(PROBE_ROOT / "CMakeLists.txt") + for pattern in ("*DesktopCommands.cpp", "*Probe.cpp", "*InventoryApi.cpp", "*.h", "*.hpp"): + paths.update(PROBE_ROOT.glob(pattern)) + for pattern in ("*-facade.ts", "*-desktop-adapter.ts", "*.worker.ts"): + paths.update((ROOT / "web/src").glob(pattern)) + paths.update(ROOT / "freecad-source" / row["sourcePath"] for row in command_matrix.get("records", []) if row.get("sourcePath")) + return paths + +ROW_RE = re.compile( + r'\{ module: "([^"]+)", workers: \[(.*?)\], primaryWorker: (.*?), ' + r'commands: \[(.*?)\], objectTypeCount: (\d+), pythonApiCount: (\d+), ' + r'guiDependency: (true|false), formatExtensions: \[(.*?)\] \},' +) +PAYLOAD_RE = re.compile(r'^\s*"([^"]+:[^"]+)"\s*:', re.MULTILINE) +NATIVE_DESKTOP_COMMAND_RE = re.compile(r'FC_WEB_DESKTOP_COMMAND\("([^"]+)"\s*,') +IMPLEMENTED_DESKTOP_COMMAND_RE = re.compile(r'FC_WEB_IMPLEMENTED_DESKTOP_COMMAND\("([^"]+)"\)') +NATIVE_DESKTOP_LIST_RE = re.compile(r'(?:desktopCommands|family\s*==\s*QStringLiteral\("desktop-command"\).*?QStringList\s+\w+)\s*=\s*\{(.*?)\};', re.DOTALL) +QSTRING_RE = re.compile(r'QStringLiteral\("([^"]+)"\)') +# A prefix branch alone is not proof that every command has its own source +# semantics. Only explicitly audited family handlers may claim an entire +# workbench command family; unmarked branches stay implementation_required. +GENERIC_DESKTOP_FAMILY_RE = re.compile(r'FC_WEB_AUDITED_DESKTOP_FAMILY\("([^"]+)"\)') + + +def quoted_values(value: str) -> list[str]: + return re.findall(r'"([^"]+)"', value) + + +def canonical_probe_module(stem: str, known_modules: set[str]) -> str: + normalized_stem = re.sub(r"[^a-z0-9]", "", stem.lower()) + candidates = [ + module for module in known_modules + if normalized_stem.startswith(re.sub(r"[^a-z0-9]", "", module.lower())) + ] + if candidates: + return max(candidates, key=lambda module: len(re.sub(r"[^a-z0-9]", "", module.lower()))) + module = stem + for suffix in ("RuntimeProbe", "KernelProbe", "Probe"): + if module.endswith(suffix): + return module.removesuffix(suffix) + return module + + +def bim_external_url_commands(workbench_text: str) -> set[str]: + """Discover the audited URL-only entries in BIM's executable script table. + + Document/geometry entries still require their own implementation evidence. + The table is consumed by the real dispatcher; adding a name alone is not enough. + """ + registry = PROBE_ROOT / "BIMDesktopCommandRegistry.h" + scripts = PROBE_ROOT / "BIMDesktopCommands.h" + probe = PROBE_ROOT / "BimRuntimeProbe.cpp" + adapter = ROOT / "web/src/bim-desktop-adapter.ts" + if not all(path.is_file() for path in (registry, scripts, probe, adapter)): + return set() + registry_text = registry.read_text(encoding="utf-8") + probe_text = probe.read_text(encoding="utf-8") + if not all(token in registry_text for token in ( + '#include "BIMDesktopCommands.h"', 'std::strcmp(name, command.name)', 'return &command;', + 'return command ? command->route : BimDesktopCommandRoute::Unhandled;')): + return set() + if not all(token in probe_text for token in ( + '#include "BIMDesktopCommandRegistry.h"', 'bimDesktopCommandImplementation(nameValue.c_str())', + 'bimDesktopCommandRoute(nameValue.c_str()) == BimDesktopCommandRoute::ExternalUrl', + 'std::string(implementation->script)', 'runGeometryValueScript(commandScript.c_str(), commandArgs)', + 'if (executed)', 'familyResultJson', '\\"status\\":\\"exposed\\"')): + return set() + if 'bimExternalUrl(name, response)' not in workbench_text or ' set[str]: + """Require an explicit marker and a command-specific exposed branch.""" + implemented: set[str] = set() + + def exposed_body(body: str) -> bool: + """Recognize source-authored exposed status in compact JSON emitters.""" + return bool( + re.search( + r'(?:result|record|commandResult|out|response)\.insert\(\s*(?:QStringLiteral\(\s*)?"status"\s*\)?\s*,\s*' + r'(?:QStringLiteral\(\s*)?"exposed"\s*\)?\s*\)', body, + ) + or re.search(r'\bstatus\s*=\s*(?:QStringLiteral\(\s*)?["\']exposed["\']\s*\)?', body) + or re.search(r'["\']status["\']\s*:\s*["\']exposed["\']', body) + # recordsJson emitters escape the JSON quotes in the C++ string. + or re.search(r'\\?"status\\?"\s*:\s*\\?"exposed\\?"', body) + ) + + def branch_body(condition: str) -> str | None: + match = re.search(rf'(?:else\s+)?if\s*\([^{{}};]*{condition}[^{{}};]*\)\s*\{{', text) + if not match: + return None + opening = text.find("{", match.start()) + depth = 0 + for index in range(opening, len(text)): + if text[index] == "{": + depth += 1 + elif text[index] == "}": + depth -= 1 + if depth == 0: + return text[opening:index + 1] + return None + + for command in IMPLEMENTED_DESKTOP_COMMAND_RE.findall(text): + condition = ( + rf'(?:FC_WEB_DESKTOP_COMMAND\("{re.escape(command)}"\)|' + rf'(?:name|nameValue|command|commandName|desktopName)\s*==\s*' + rf'(?:QStringLiteral\("{re.escape(command)}"\)|"{re.escape(command)}")|' + rf'(?:apiId|apiIdValue)\s*==\s*' + rf'(?:QStringLiteral\("[A-Za-z0-9_]+:desktop:{re.escape(command)}"\)|' + rf'"[A-Za-z0-9_]+:desktop:{re.escape(command)}"))' + ) + branches = re.finditer(rf'(?:else\s+)?if\s*\([^{{}};]*{condition}[^{{}};]*\)\s*\{{', text) + for branch in branches: + opening = text.find("{", branch.start()) + depth = 0 + closing = None + for index in range(opening, len(text)): + if text[index] == "{": + depth += 1 + elif text[index] == "}": + depth -= 1 + if depth == 0: + closing = index + break + if closing is None: + continue + body = text[opening:closing + 1] + explicit_status = exposed_body(body) + # Some native probes emit the structured JSON through an + # ostringstream rather than QJsonObject::insert. Accept that + # source-authored form only when the same command-specific branch + # explicitly assigns status=exposed; do not accept a shared tail + # or a generic marker alone. + explicit_status = explicit_status or re.search( + r'\bstatus\s*=\s*(?:QStringLiteral\(\s*)?["\']exposed["\']\s*\)?', + body, + ) or re.search(r'["\']status["\']\s*:\s*["\']exposed["\']', body) + # Native adapters may centralize document creation, recompute and + # status reporting in a command-specific helper. A direct return + # from the marked branch is executable behavior; requiring a + # duplicated status insertion here incorrectly stalls the batch. + explicit_status = explicit_status or re.search( + r'\breturn\s+(?:executeObjectCommand|executeDocumentCommand|executeAnalysisCommand|finishDocumentCommand)\s*\(', body + ) + if explicit_status: + implemented.add(command) + break + if command in implemented: + continue + # Compact native dispatchers often use a single-statement branch: + # `if (command == ...) return executeObjectCommand(...)`. It still + # executes the marked command-specific FreeCAD path and the helper + # owns the exposed status, so do not classify it as a stalled marker. + single_statement = re.search( + rf'if\s*\([^{{}};]*(?:name|nameValue|command|commandName|desktopName)\s*==\s*' + rf'(?:QStringLiteral\("{re.escape(command)}"\)|"{re.escape(command)}")[^{{}};]*\)\s*' + rf'return\s+(?:executeObjectCommand|executeDocumentCommand|executeAnalysisCommand|finishDocumentCommand)\s*\(', + text, + ) + if single_statement: + implemented.add(command) + continue + # A native dispatcher may normalize the command into a boolean first + # (`const joints = apiId == "Module:desktop:Command"`) and dispatch + # through a shared branch. The marker plus the exact canonical + # comparison and an exposed status in that dispatcher is sufficient; + # it is still command-specific and cannot match a generic marker. + canonical = re.search( + rf'(?:apiId|apiIdValue)\s*==\s*(?:QStringLiteral\("[A-Za-z0-9_]+:desktop:{re.escape(command)}"\)|"[A-Za-z0-9_]+:desktop:{re.escape(command)}")', + text, + ) + if canonical and exposed_body(text): + implemented.add(command) + continue + # BIM's native dispatcher normalizes a group of exact command names + # into a boolean alias (`const bool nudge = nameValue == ...`) and + # emits one verified exposed result from that bounded branch. Match + # the exact command comparison and the alias branch; a marker alone + # still cannot make an unrelated command routable. + name_condition = rf'(?:name|nameValue|command|commandName|desktopName)\s*==\s*(?:QStringLiteral\("{re.escape(command)}"\)|"{re.escape(command)}")' + aliases = re.findall(rf'\b(?:const\s+)?bool\s+(\w+)\s*=\s*[^;{{}}]*{name_condition}[^;{{}}]*;', text) + if any((body := branch_body(rf'\b{re.escape(alias)}\b')) and exposed_body(body) for alias in aliases): + implemented.add(command) + continue + # Draft snap modes share one bounded native branch keyed by + # `snapIndex >= 0`; each marked mode is still an exact command in the + # source's snap-name table and receives the branch's exposed state. + if command.startswith("Draft_Snap_"): + snap_branch = branch_body(r'\bsnapIndex\s*>=\s*0') + if snap_branch and exposed_body(snap_branch): + implemented.add(command) + return implemented + + +def category(command: str) -> str: + lowered = command.lower() + if "save" in lowered or "reopen" in lowered: + return "persistence" + if "import" in lowered or "export" in lowered: + return "format" + if "python" in lowered: + return "python" + if "inspect" in lowered or "inventory" in lowered: + return "inspect" + if "create" in lowered or "recompute" in lowered: + return "modeling" + return "service" + + +def describe_native_gaps(records: list[dict], rejected_markers: dict[str, set[str]]) -> dict[str, int]: + """Provide bounded source evidence without promoting textual matches to routes.""" + pending = [row for row in records if any(gap.get("stage") == "native" for gap in row.get("implementationGaps", []))] + commands = {str(row["command"]) for row in pending} + locations: dict[str, list[dict]] = {command: [] for command in commands} + # Exact quoted names include embedded Python dispatches and C++ tables. + # A match is only a navigation anchor, never proof that the command works. + literal = re.compile(r'''["']([A-Za-z][A-Za-z0-9_]*)["']''') + for path in sorted(PROBE_ROOT.iterdir()): + if not path.is_file() or path.suffix not in {".cpp", ".h", ".hpp"}: + continue + for number, line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), 1): + for command in set(literal.findall(line)) & commands: + candidates = locations[command] + if len(candidates) < 6: + candidates.append({"path": str(path.relative_to(ROOT)), "line": number}) + counts = Counter() + for row in pending: + candidates = locations[str(row["command"])] + rejected = row["command"] in rejected_markers.get(row["module"], set()) + kind = "registration-marker-rejected" if rejected else "native-source-candidate-unregistered" if candidates else "native-entry-not-located-in-probe-directory" + counts[kind] += 1 + for gap in row["implementationGaps"]: + if gap.get("stage") != "native": + continue + gap.update(classification=kind, businessRequirement="retained", sourceCandidates=candidates, + evidenceScope="Static registration discovery and exact source-name anchors only; not proof of implementation completeness or business necessity.", + repair=("Inspect the existing native branch/helper at sourceCandidates and connect its executable registration; implement missing behavior before registering." + if candidates else "Locate the native entry using the supplied desktop source and build ownership; absence here does not establish absent local source or unnecessary business.")) + return dict(counts) + + +@lru_cache(maxsize=64) +def python_command_groups(path: Path) -> set[str]: + try: + tree = ast.parse(path.read_text(encoding="utf-8", errors="replace")) + except (OSError, SyntaxError): + return set() + group_classes = { + node.name + for node in ast.walk(tree) + if isinstance(node, ast.ClassDef) + and any(isinstance(member, (ast.FunctionDef, ast.AsyncFunctionDef)) and member.name == "GetCommands" for member in node.body) + } + commands: set[str] = set() + for node in ast.walk(tree): + if not isinstance(node, ast.Call) or len(node.args) < 2: + continue + function_name = node.func.attr if isinstance(node.func, ast.Attribute) else node.func.id if isinstance(node.func, ast.Name) else "" + if function_name != "addCommand" or not isinstance(node.args[0], ast.Constant) or not isinstance(node.args[0].value, str): + continue + factory = node.args[1] + if not isinstance(factory, ast.Call): + continue + class_name = factory.func.id if isinstance(factory.func, ast.Name) else factory.func.attr if isinstance(factory.func, ast.Attribute) else "" + if class_name in group_classes: + commands.add(node.args[0].value) + return commands + + +def is_ui_container(row: dict[str, object]) -> bool: + command = str(row.get("command") or "") + if command == "Separator": + return True + source_path = str(row.get("sourcePath") or "") + if source_path.endswith(".py"): + return command in python_command_groups(ROOT / "freecad-source" / source_path) + if not source_path.endswith("/Workbench.cpp"): + return False + path = ROOT / "freecad-source" / source_path + try: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return False + source_line = max(1, int(row.get("sourceLine") or 1)) + search_start = max(0, source_line - 4) + search_end = min(len(lines), source_line + 3) + variable = "" + for line in lines[search_start:search_end]: + match = re.search(r'([A-Za-z_]\w*)->setCommand\("' + re.escape(command) + r'"\)', line) + if match: + variable = match.group(1) + break + if not variable: + return False + tail = "\n".join(lines[source_line:min(len(lines), source_line + 24)]) + return bool( + re.search(rf"\*\s*{re.escape(variable)}\s*<<", tail) + or re.search(rf"\badd[A-Za-z0-9_]+\s*\(\s*\*\s*{re.escape(variable)}\s*\)", tail) + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--force", action="store_true", help="regenerate even when all inputs and outputs match the cache") + options = parser.parse_args(argv) + command_matrix = json.loads(WORKBENCH_MATRIX.read_text(encoding="utf-8")) + inputs = file_stamps(generation_inputs(command_matrix)) + try: + cached = json.loads(CACHE_PATH.read_text(encoding="utf-8")) + except (OSError, ValueError): + cached = {} + if (not options.force and cached.get("schema") == "freecad-web-feature-capability-cache/v1" + and cached.get("inputs") == inputs and OUTPUT.is_file() and ROUTE_OUTPUT.is_file() + and cached.get("outputs") == file_stamps({OUTPUT, ROUTE_OUTPUT})): + print(json.dumps({"status": "reused", **cached.get("counts", {})})) + return 0 + registry_text = REGISTRY_SOURCE.read_text(encoding="utf-8") + workbench_text = WORKBENCH_SOURCE.read_text(encoding="utf-8") + artifact_payload = json.loads(ARTIFACT_MANIFEST.read_text(encoding="utf-8")) + known_modules = { + str(row.get("module")) + for row in command_matrix.get("records", []) + if isinstance(row, dict) and row.get("module") + } + desktop_keys = { + (str(row.get("module")), str(row.get("command"))) + for row in command_matrix.get("records", []) + if isinstance(row, dict) and row.get("kind") == "desktop-gui" + } + artifact_modules = artifact_payload.get("modules", {}) + payloads = set(PAYLOAD_RE.findall(workbench_text)) + generic_command_entry = 'id="payload-editor"' in workbench_text and "JSON.parse(payloadText)" in workbench_text + native_desktop_commands: dict[str, set[str]] = {} + native_desktop_sources: dict[str, str] = {} + native_desktop_families: set[str] = set() + rejected_desktop_markers: dict[str, set[str]] = {} + for path in sorted(PROBE_ROOT.glob("*DesktopCommands.cpp")): + module = path.stem.removesuffix("DesktopCommands") + text = path.read_text(encoding="utf-8", errors="replace") + marked_commands = set(IMPLEMENTED_DESKTOP_COMMAND_RE.findall(text)) + implemented_commands = implemented_desktop_commands(text) + native_desktop_commands[module] = set(NATIVE_DESKTOP_COMMAND_RE.findall(text)) | implemented_commands + rejected = marked_commands - implemented_commands + if rejected: + rejected_desktop_markers.setdefault(module, set()).update(rejected) + native_desktop_sources[module] = str(path.relative_to(ROOT)) + for path in sorted(PROBE_ROOT.glob("*Probe.cpp")): + module = canonical_probe_module(path.stem, known_modules) + text = path.read_text(encoding="utf-8", errors="replace") + for registered_module in GENERIC_DESKTOP_FAMILY_RE.findall(text): + native_desktop_families.add(registered_module) + native_desktop_sources.setdefault(registered_module, str(path.relative_to(ROOT))) + marked_commands = set(IMPLEMENTED_DESKTOP_COMMAND_RE.findall(text)) + implemented_commands = implemented_desktop_commands(text) + rejected = marked_commands - implemented_commands + if rejected: + rejected_desktop_markers.setdefault(module, set()).update(rejected) + if implemented_commands: + native_desktop_commands.setdefault(module, set()).update(implemented_commands) + native_desktop_sources.setdefault(module, str(path.relative_to(ROOT))) + commands = { + command + for block in NATIVE_DESKTOP_LIST_RE.findall(text) + for command in QSTRING_RE.findall(block) + } + if commands: + native_desktop_commands.setdefault(module, set()).update(commands) + native_desktop_sources.setdefault(module, str(path.relative_to(ROOT))) + # Some targets keep the active dispatcher in a bounded *InventoryApi.cpp + # translation unit rather than in the conventional *Probe.cpp file. It + # is still native ownership: include only this probe-directory pattern so + # registry discovery stays scoped and does not become a repository scan. + for path in sorted(PROBE_ROOT.glob("*InventoryApi.cpp")): + module = canonical_probe_module(path.stem, known_modules) + text = path.read_text(encoding="utf-8", errors="replace") + marked_commands = set(IMPLEMENTED_DESKTOP_COMMAND_RE.findall(text)) + implemented_commands = implemented_desktop_commands(text) + rejected = marked_commands - implemented_commands + if rejected: + rejected_desktop_markers.setdefault(module, set()).update(rejected) + if implemented_commands: + native_desktop_commands.setdefault(module, set()).update(implemented_commands) + native_desktop_sources.setdefault(module, str(path.relative_to(ROOT))) + bim_urls = bim_external_url_commands(workbench_text) + if bim_urls: + native_desktop_commands.setdefault("BIM", set()).update(bim_urls) + native_desktop_sources.setdefault("BIM", str((PROBE_ROOT / "BimRuntimeProbe.cpp").relative_to(ROOT))) + desktop_adapter_modules: set[str] = set() + direct_desktop_workers: dict[str, str] = {} + for module in set(native_desktop_commands) | native_desktop_families: + stem = re.sub(r"[^a-z0-9]", "", module.lower()) + facade_text = "\n".join( + path.read_text(encoding="utf-8", errors="replace") + for path in sorted((ROOT / "web/src").glob(f"{stem}*-facade.ts")) + ) + if "fc_web_dispatch_json" in facade_text and "pythonFamily" in facade_text: + desktop_adapter_modules.add(module) + for worker in sorted((ROOT / "web/src").glob(f"{stem}*.worker.ts")): + worker_text = worker.read_text(encoding="utf-8", errors="replace") + if "DesktopRequest" in worker_text and re.search(r"is[A-Za-z0-9]+DesktopRequest", worker_text): + direct_desktop_workers[module] = worker.name + break + records: list[dict[str, object]] = [] + modules: list[dict[str, object]] = [] + module_rows: dict[str, dict[str, object]] = {} + web_routes: dict[tuple[str, str], dict[str, object]] = {} + for match in ROW_RE.finditer(registry_text): + module, workers_text, primary_text, commands_text, objects, python_apis, gui, formats_text = match.groups() + workers = quoted_values(workers_text) + commands = quoted_values(commands_text) + primary_values = quoted_values(primary_text) + primary_worker = primary_values[0] if primary_values else None + artifact_ready = module in artifact_modules + interactive = 0 + for command in commands: + capability_id = f"{module}:{command}" + payload_ready = capability_id in payloads + generic_api_entry = "pythonFamilyBatch" in command or "pythonMethod" in command + ui_status = "interactive" if payload_ready else "generic-api-entry" if generic_api_entry else "generic-command-entry" if generic_command_entry else "needs-parameter-ui" + interactive += int(ui_status != "needs-parameter-ui") + web_record = { + "id": capability_id, + "module": module, + "command": command, + "category": category(command), + "worker": primary_worker, + "workers": workers, + "artifactReady": artifact_ready, + "uiStatus": ui_status, + "implementationStatus": "routed" if workers and artifact_ready else "missing-runtime-route", + "validationStatus": "deferred", + "implementationGaps": ([{"stage": "worker", "reason": "no Worker is registered for this module"}] if not workers else []) + + ([{"stage": "artifact", "reason": "module artifact is absent from the manifest"}] if not artifact_ready else []), + } + web_routes[(module, command)] = web_record + transport_only = command.endswith(".desktopCommand") + if (module, command) not in desktop_keys and not transport_only: + records.append(web_record) + module_row = { + "module": module, + "commands": len(commands), + "interactiveCommands": interactive, + "needsParameterUi": len(commands) - interactive, + "desktopCommands": 0, + "implementationRequired": 0, + "workers": workers, + "artifactReady": artifact_ready, + "objectTypeCount": int(objects), + "sourcePythonSymbolCount": int(python_apis), + "guiDependency": gui == "true", + "formatExtensions": quoted_values(formats_text), + } + modules.append(module_row) + module_rows[module] = module_row + desktop_rows = [ + row for row in command_matrix.get("records", []) + if isinstance(row, dict) and row.get("kind") == "desktop-gui" + ] + @lru_cache(maxsize=None) + def registered_lines(relative): + path = ROOT / "freecad-source" / relative + return {(name, line) for name, line, _, _ in cpp_gui_commands(path)} if path.is_file() else set() + + # Keep every existing capability, but prefer a real constructor over a + # documentation example when multiple source anchors were inventoried. + for index, row in enumerate(desktop_rows): + source = str(row.get("sourcePath", "")) + if not source.endswith((".cpp", ".cxx", ".cc", ".h", ".hpp")): + continue + identity = (row.get("command"), row.get("sourceLine")) + if identity in registered_lines(source): + continue + for surface in row.get("uiSurfaces", []): + path = str(surface.get("path", "")) + if (surface.get("kind") == "registration" and path.endswith((".cpp", ".cxx", ".cc", ".h", ".hpp")) + and (row.get("command"), surface.get("line")) in registered_lines(path)): + desktop_rows[index] = {**row, "sourcePath": path, "sourceLine": surface["line"]} + break + + def family_route(module: str) -> dict[str, object] | None: + return next( + ( + route for (route_module, _), route in web_routes.items() + if route_module == module and ( + str(route.get("command", "")).endswith(".pythonFamilyBatch") + or str(route.get("command", "")).endswith(".pythonFamily") + ) + ), + None, + ) + + def local_route(module: str, command: str) -> dict[str, object] | None: + if module == "TechDraw" and command == "TechDraw_WeldSymbol": + route = web_routes.get((module, "techdraw.pythonFamilyBatch")) + required = { + PROBE_ROOT / "TechDrawDesktopCommands.cpp": ('WebWeld::execute(input, result)',), + PROBE_ROOT / "TechDrawWeldTask.h": ('TechDraw:desktop:TechDraw_WeldSymbol', + 'document->addObject', 'weld->Leader.setValue(leader)', + 'if (action=="accept")', 'document->commitTransaction()', 'document->abortTransaction()', + 'result["status"]="exposed"'), + PROBE_ROOT / "CMakeLists.txt": ('src/Mod/TechDraw@/freecad-mod/TechDraw',), + ROOT / "web/src/techdraw-python.worker.ts": ('dispatchTechDrawPythonFamily(q,m,k)', 'FreeCADWebTechDrawRuntimeProbe.js'), + ROOT / "web/src/techdraw-python-family-facade.ts": ('"fc_web_dispatch_json"',), + ROOT / "web/src/techdraw-desktop-adapter.ts": ('record.command === "TechDraw_WeldSymbol"', '"Reload the welding task first"'), + ROOT / "web/src/techdraw-weld-task.tsx": ('TechDraw:desktop:TechDraw_WeldSymbol', 'record?.status !== "exposed"', 'action: "cancel"'), + WORKBENCH_SOURCE: ('command === "TechDraw_WeldSymbol"', 'accept();'), + PROBE_ROOT / "PartDesignDocumentWorkflow.cpp": ('WebMeasure::create(current, args)', + 'if (action != "measureDistance" || !args.value("preview").toBool()) importHistory->accept();'), + PROBE_ROOT / "MeasureDocument.h": ('measure->parseSelection(selection)',), + PROBE_ROOT / "WebImportHistory.h": ('document->abortTransaction();',), + ROOT / "web/src/module-router.ts": ('"Measure:desktop:Std_Measure"', 'return executeMeasureDocument(this,'), + ROOT / "web/src/measure-document-adapter.ts": ('router.modelingDocumentOwners.get(documentId)', + 'router.request(owner.module,', '["read", "cancel", "reset"].includes(action)', 'preview: action === "preview"'), + ROOT / "web/src/measure-distance-task.tsx": ('executeMeasureDocument(router,', + 'adopt(value, action === "preview")', 'adopt(committed.current, false)'), + WORKBENCH_SOURCE: ('command === "Std_Measure"', 'openTransaction("Segmentation")', 'history.accept()', 'committedTasks.insert(taskId)'), + "worker": ('dispatchReverseEngineeringPythonFamily(queue, message, kernel)',), + "task": ('router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch"', 'name: "Reen_Segmentation"', 'send("accept")', 'send("cancel")', 'writeDocumentFile'), + "shell": ('command === "Reen_Segmentation"', 'openTransaction("Segmentation")', 'history.accept()', 'action == "save"'), + "task": ('router.request("ReverseEngineering", "reverseengineering.pythonFamilyBatch"', 'name: "Reen_SegmentationManual"', 'send("create")', 'cancelSelection(); setOpened(false)', 'writeDocumentFile'), + "shell": ('command === "Reen_SegmentationManual"', ' ({ documentId, object }))') + if surface: + files["surfaceTask"] = ROOT / "web/src/reverseengineering-surface-task.tsx" + required["surfaceTask"] = ('router.request("Points", "reverseengineering.pythonFamilyBatch"', 'execute({ action: kind', 'runtimeOwner: "Points"', 'family({ action: "cancel", taskArgs: saved })') + required["native"] += ("if action not in ('accept', 'placement')", 'args.value("action") == "cancel"', "doc.addObject('App::Placement', 'Placement')") + if route and all(path.is_file() for path in files.values()): + texts = {key: path.read_text(encoding="utf-8") for key, path in files.items()} + if all(token in texts[key] for key, tokens in required.items() for token in tokens): + return {**route, "worker": "points.worker.ts", "executionModule": "Points", + "transport": "direct-command", "canonicalId": f"{module}:desktop:{command}", + "nativeRegistration": str(files["bridge"].relative_to(ROOT))} + if module == "Sandbox" and command == "Sandbox_SaveThread": + route = web_routes.get((module, "sandbox.pythonFamilyBatch")) + # Archive actions share the retained Python-family owner with mesh imports. + # The module's primary inspect worker cannot dispatch these requests. + worker = re.search( + r'case\s+"Sandbox:sandbox\.pythonFamilyBatch"\s*:\s*return\s+"([^"]+)"', + REGISTRY_SOURCE.read_text(encoding="utf-8"), + ) + if (route and command in native_desktop_commands.get(module, set()) + and worker and worker.group(1) in route["workers"]): + return {**route, "worker": worker.group(1), "executionModule": module, + "transport": "family-batch", "nativeRegistration": native_desktop_sources.get(module)} + return None + if module == "Web" and command in {"Std_Test5", "Std_Test6", "Std_TestCmdFuncs"}: + route = web_routes.get(("Part", "part.viewCommand")) + adapter = ROOT / "web/src/web-source-test-adapter.ts" + native = PROBE_ROOT / "WebSourceTestCommands.h" + if route and adapter.is_file() and native.is_file() and command in native.read_text(encoding="utf-8") and "executeSourceTest" in adapter.read_text(encoding="utf-8"): + return {**route, "worker": "part.worker.ts", "executionModule": "Part", "transport": "direct-command", "canonicalId": f"Web:desktop:{command}", "nativeRegistration": str(native.relative_to(ROOT))} + if module == "Web" and command in {"Std_DownloadOnlineHelp", "Std_RandomColor", "Std_Test5", "Std_Test6", "Std_TestCmdFuncs", "Std_ViewUndock", "Std_ViewVR"}: + adapter = ROOT / "web/src/web-desktop-adapter.ts" + native = PROBE_ROOT / ("WebSourceTestCommands.h" if command.startswith("Std_Test") else "WebViewCommands.h") + route = web_routes.get(("Part", "part.viewCommand")) + if command == "Std_DownloadOnlineHelp": route = web_routes.get(("Web", "web.standardCommand")) or route + if route and adapter.is_file() and native.is_file(): + at = adapter.read_text(encoding="utf-8"); nt = native.read_text(encoding="utf-8") + if ((command == "Std_DownloadOnlineHelp" and "return downloadOnlineHelp(router," in at) + or (command == "Std_RandomColor" and "Std_RandomColor" in at and "part.pythonFamilyBatch" in at) + or (command.startswith("Std_Test") and command in nt and "executeSourceTest" in at) + or (command in {"Std_ViewUndock", "Std_ViewVR"} and command in nt and "executeWebDesktopCommand" in at)): + return {**route, "worker": route.get("worker") or "part.worker.ts", "executionModule": route.get("module") or "Part", "transport": "direct-command", "canonicalId": f"Web:desktop:{command}", "nativeRegistration": str(native.relative_to(ROOT))} + if module == "Web" and command in {"Std_MacroStepInto", "Std_MacroStepOver", "Std_MacroStopDebug", "Std_OpenMacrosFolder", "Std_ToggleBreakpoint"}: + macro = PROBE_ROOT / "WebMacroCommands.h" + adapter = ROOT / "web/src/web-desktop-adapter.ts" + facade = ROOT / "web/src/part-python-family-facade.ts" + worker = ROOT / "web/src/part.worker.ts" + route = web_routes.get(("Part", "part.pythonFamilyBatch")) + if route and all(path.is_file() for path in (macro, adapter, facade, worker)): + mt = macro.read_text(encoding="utf-8") + if (command in mt and command in adapter.read_text(encoding="utf-8") + and "dispatchPartPythonFamily" in worker.read_text(encoding="utf-8") + and "PART_PYTHON_FAMILY_COMMAND" in facade.read_text(encoding="utf-8")): + return {**route, "worker": "part.worker.ts", "executionModule": "Part", "transport": "family-batch", "canonicalId": f"Web:desktop:{command}", "nativeRegistration": str(macro.relative_to(ROOT))} + if module == "Web" and command in native_desktop_commands.get(module, set()): + catalog = ROOT / "web/src/web-macro-routes.json" + if catalog.is_file(): + endpoint = json.loads(catalog.read_text(encoding="utf-8")).get(command) + route = web_routes.get(("Part", endpoint)) if isinstance(endpoint, str) else None + files = { + "adapter": ROOT / "web/src/web-desktop-adapter.ts", + "facade": ROOT / "web/src/part-python-family-facade.ts", + "worker": ROOT / "web/src/part.worker.ts", + "dispatcher": ROOT / "web/src/desktop-command-dispatcher.ts", + "native": PROBE_ROOT / "PartBoxProbe.cpp", + "macro": PROBE_ROOT / "WebMacroCommands.h", + "recording": PROBE_ROOT / "WebMacroRecording.h", + } + if route and all(path.is_file() for path in files.values()): + texts = {key: path.read_text(encoding="utf-8") for key, path in files.items()} + # Macro requests use the live Part owner, not the standalone + # Web runtime. Resolve the same endpoint used by the adapter. + required = { + "adapter": ('./web-macro-routes.json', 'macroRoutes[command as keyof typeof macroRoutes]', + 'router.request("Part", endpoint', 'desktop-command-commandmacro', + 'documentId, storedFiles', 'freecad-macro-result'), + "facade": (f'PART_PYTHON_FAMILY_COMMAND = "{endpoint}"', + 'fc_web_dispatch_json', 'payload.records'), + "worker": ('FreeCADWebPartBoxProbe.js', 'isPartPythonFamilyRequest(message)', + 'record.family === "desktop-command"', + 'dispatchPartPythonFamily(queue, message, source)'), + "dispatcher": ('executeWebDesktop(this.router, record.command, args, documentId, applySelection)',), + "native": ('desktop-command-commandmacro', f'QStringLiteral("{command}")', + 'executeWebMacroCommand(request.constData(), nativeOutput)'), + "macro": (f'"{command}"', 'exec(compile(source, path,', 'debugpy.connect((host, port))', + 'recorder.recording', 'App.setActiveDocument(document)'), + "recording": ('webMacroDispatch(request)', 'PyList_Append(lines, text)'), + } + if (all(all(token in texts[key] for token in tokens) for key, tokens in required.items()) + and command in workbench_text): + return {**route, "worker": "part.worker.ts", "executionModule": "Part", + "transport": "family-batch", "canonicalId": f"Web:desktop:{command}", + "nativeRegistration": str(files["native"].relative_to(ROOT))} + if module == "Test" and command in native_desktop_commands.get(module, set()): + catalog = ROOT / "web/src/test-desktop-routes.json" + adapter = ROOT / "web/src/test-desktop-adapter.ts" + facade = ROOT / "web/src/test-facade.ts" + worker = ROOT / "web/src/test.worker.ts" + dispatcher = ROOT / "web/src/desktop-command-dispatcher.ts" + if all(path.is_file() for path in (catalog, adapter, facade, worker, dispatcher)): + endpoint = json.loads(catalog.read_text(encoding="utf-8")).get(command) + route = web_routes.get((module, endpoint)) + mdi_host = ROOT / "web/src/test-mdi-host.tsx" + mdi_connected = not command.startswith("Std_MDITest") or (mdi_host.is_file() and + "executeTestDesktopWithHost" in workbench_text and "script' in runtime_text + and 'dispatchBimPythonFamilyBatch(queue, message, kernel)' in worker.read_text(encoding="utf-8") + and 'fc_web_dispatch_json' in facade.read_text(encoding="utf-8")): + return {**route, "worker": "bim.worker.ts", "executionModule": "BIM", + "transport": "family-batch", "canonicalId": f"BIM:desktop:{command}", + "nativeRegistration": str(registry.relative_to(ROOT))} + if module in {"Web", "Std"}: + if command in {"Std_Test1", "Std_Test2", "Std_Test3", "Std_Test4"}: + catalog = ROOT / "web/src/document-view-routes.json" + files = { + "desktop": ROOT / "web/src/web-desktop-adapter.ts", + "adapter": ROOT / "web/src/web-owner-standard-adapter.ts", + "contract": ROOT / "web/src/web-standard-command-contract.ts", + "facade": ROOT / "web/src/part-view-facade.ts", + "worker": ROOT / "web/src/part.worker.ts", + "bridge": PROBE_ROOT / "NativeDocumentView.h", + "native": PROBE_ROOT / "WebSourceTestCommands.h", + } + if catalog.is_file() and all(path.is_file() for path in files.values()): + routes = json.loads(catalog.read_text(encoding="utf-8")) + owner = routes.get("owners", {}).get("PartBox", {}) + route = web_routes.get(("Part", owner.get("endpoint"))) + texts = {key: path.read_text(encoding="utf-8") for key, path in files.items()} + required = { + "desktop": (f'"{command}"', 'executeOwnerStandard(router, command, args, documentId)'), + "adapter": ('routes.standardCommands.includes(command)', 'router.request("Part", viewEndpoint(owner)'), + "contract": (f'"{command}"', 'result.changed === false'), + "facade": ('isStandardCommand(p.command)', 'validStandardResult(reply.result, p.command, p.document)', 'fc_web_dispatch_json'), + "worker": ('dispatchDocumentView(queue, message, kernel)', '/kernel/FreeCADWebPartBoxProbe.js'), + "bridge": (f'"{command}"', 'executeWebSourceTestCommand(input.constData(), output)', 'completed.value("result").toObject()'), + "native": (f'"{command}"', 'App::GetApplication().getDocument', '"document_not_found"'), + } + if (route and command in routes.get("standardCommands", []) + and all(token in texts[key] for key, tokens in required.items() for token in tokens)): + return {**route, "worker": "part.worker.ts", "executionModule": "Part", + "transport": "direct-command", "canonicalId": f"Web:desktop:{command}", + "nativeRegistration": str(files["bridge"].relative_to(ROOT))} + if command in {f"Std_Test{i}" for i in range(1, 7)}: + source = ROOT / "freecad-source/src/Gui/CommandTest.cpp" + adapter = ROOT / "web/src/web-source-test-adapter.ts" + desktop = ROOT / "web/src/web-desktop-adapter.ts" + route = web_routes.get(("Part", "part.viewCommand")) + if route and all(path.is_file() for path in (source, adapter, desktop)): + number = command.removeprefix("Std_Test") + body = re.search(r'void FCCmdTest' + number + r'::activated\(int iMsg\)\s*\{(.*?)\n\}', source.read_text(encoding="utf-8"), re.DOTALL) + expected = "Q_UNUSED(iMsg);" if number in {"1", "2"} else "Q_UNUSED(iMsg); App::Document* pcDoc = getDocument(); if (!pcDoc) { return; }" + adapter_text = adapter.read_text(encoding="utf-8") + if (body and re.sub(r'\s+', '', body[1]) == re.sub(r'\s+', '', expected) + and f'"{command}"' in adapter_text and 'operation: "source-no-op"' in adapter_text + and 'router.request("Part", viewEndpoint(owner)' in adapter_text + and 'executeSourceTest(router, command, args, documentId)' in desktop.read_text(encoding="utf-8")): + return {**route, "worker": "part.worker.ts", "executionModule": "Part", + "transport": "direct-command", "canonicalId": f"Web:desktop:{command}", + "nativeRegistration": str((PROBE_ROOT / "NativeDocumentView.h").relative_to(ROOT))} + catalog = ROOT / "web/src/document-view-routes.json" + if catalog.is_file(): + routes = json.loads(catalog.read_text(encoding="utf-8")) + if command == "Std_DescriptionMode": + owner = routes["owners"]["PartBox"] + route = web_routes.get(("Part", owner["endpoint"])) + adapter = ROOT / "web/src/web-desktop-adapter.ts" + native = PROBE_ROOT / "WebViewCommands.h" + if route and native.is_file() and adapter.is_file() and "'Std_DescriptionMode'" in native.read_text(encoding="utf-8") and 'executeOwnerStandard(router, command, args, documentId)' in adapter.read_text(encoding="utf-8"): + return {**route, "worker": owner["worker"], "executionModule": "Part", "transport": "direct-command", "canonicalId": f"Web:desktop:{command}", "nativeRegistration": str(native.relative_to(ROOT))} + if command in {"Std_WhatsThis", "Std_Workbench"} and command in routes.get("standardCommands", []): + owner = routes.get("owners", {}).get("PartBox", {}) + route = web_routes.get(("Part", owner.get("endpoint"))) + files = { + "desktop": ROOT / "web/src/web-desktop-adapter.ts", + "adapter": ROOT / "web/src/web-owner-standard-adapter.ts", + "contract": ROOT / "web/src/web-standard-command-contract.ts", + "facade": ROOT / "web/src/part-view-facade.ts", + "worker": ROOT / "web/src/part.worker.ts", + "dispatcher": ROOT / "web/src/desktop-command-dispatcher.ts", + "bridge": PROBE_ROOT / "NativeDocumentView.h", + "native": PROBE_ROOT / "WebViewCommands.h", + } + if route and all(path.is_file() for path in files.values()): + texts = {key: path.read_text(encoding="utf-8") for key, path in files.items()} + required = { + "desktop": (f'"{command}"', 'executeOwnerStandard(router, command, args, documentId)'), + "adapter": ('routes.standardCommands.includes(command)', 'router.request("Part", viewEndpoint(owner)', + 'schema: "freecad-web/document-view/v1", owner, document: documentId, command', + 'validStandardResult(response.result, command, documentId)'), + "contract": (f'"{command}"',), + "facade": ('isStandardCommand(p.command)', 'validStandardResult(reply.result, p.command, p.document)', + 'fc_web_dispatch_json'), + "worker": ('dispatchDocumentView(queue, message, kernel)', '/kernel/FreeCADWebPartBoxProbe.js'), + "dispatcher": ('executeWebDesktop(this.router, record.command',), + "bridge": (f'"{command}"', 'executeDocumentCommand(input.constData(), output)'), + "native": (f"'{command}'", 'elif name in gui_standard_names:', 'if not App.GuiUp:', + 'native_command.isActive()'), + } + behavior = ('Gui.runCommand(name, mode if name == \'Std_UserEditMode\' else 0)',) + mounted = True + if command == "Std_Workbench": + behavior = ('list(Gui.listWorkbenches())', "args.get('operation') == 'list'", + 'Gui.activateWorkbench(workbench)', 'if active_workbench != workbench:') + mounted = (all(token in texts["desktop"] for token in ( + 'operation: "list"', 'freecad-native-workbench-picker', + 'workbench: selected, operation: "activate"')) + and all(token in workbench_text for token in ( + 'window.addEventListener("freecad-native-workbench-picker", receive)', + 'detail.select(select.value)', 'detail.select(undefined)'))) + if (mounted and all(token in texts["native"] for token in behavior) + and all(token in texts[key] for key, tokens in required.items() for token in tokens)): + return {**route, "worker": owner["worker"], "executionModule": "Part", + "transport": "direct-command", "canonicalId": f"Web:desktop:{command}", + "nativeRegistration": str(files["bridge"].relative_to(ROOT))} + if command in routes.get("commandFeatCommands", []): + route = web_routes.get(("Part", "part.pythonFamilyBatch")) + native = PROBE_ROOT / "WebMacroCommands.h" + bridge = PROBE_ROOT / "PartBoxProbe.cpp" + adapter = ROOT / "web/src/web-desktop-adapter.ts" + behaviors = { + "Std_Recompute": ("elif record['name'] == 'Std_Recompute':", "# CommandFeat.cpp intentionally leaves this command's activation empty.\n pass"), + "Std_SendToPythonConsole": ("elif record['name'] == 'Std_SendToPythonConsole':", "len(grouped) != 1", "namespace['doc'] = doc", "namespace['obj'] = obj", "namespace['shp'] = getattr(obj, property_name)", "obj.getSubObject"), + } + if route and command in behaviors and all(path.is_file() for path in (native, bridge, adapter)): + native_text = native.read_text(encoding="utf-8") + bridge_text = bridge.read_text(encoding="utf-8") + adapter_text = adapter.read_text(encoding="utf-8") + if (all(token in native_text for token in behaviors[command]) + and f'QStringLiteral("{command}")' in bridge_text + and 'family == QStringLiteral("desktop-command-commandfeat")' in bridge_text + and 'executeWebMacroCommand(request.constData(), nativeOutput)' in bridge_text + and all(token in adapter_text for token in ( + f'"{command}"', 'router.request("Part", "part.pythonFamilyBatch"', + '"desktop-command-commandfeat"', 'args: { ...args, documentId }')) + and (command != "Std_SendToPythonConsole" or all(token in adapter_text for token in ( + 'record?.status !== "exposed" || !Array.isArray(record.result?.consoleVariables)', + 'executeWebDesktop(router, "Std_CommandLine", { runtimeOwner: "PartBox", documentId, operation: "open" }, documentId)', + 'new CustomEvent("freecad-python-console-activate", { detail: handoff })', + 'if (!handoff.handled) return createFailure(response.requestId, "console_host_unavailable"')))): + return {**route, "executionModule": "Part", "transport": "direct-command", + "canonicalId": f"Web:desktop:{command}", + "nativeRegistration": str(native.relative_to(ROOT))} + if command in routes.get("standardCommands", []) and command in { + "Std_RestartInSafeMode", "Std_TextDocument", "Std_UnitsCalculator", "Std_UserEditMode" + }: + owner = routes["owners"]["PartBox"] + route = web_routes.get(("Part", owner["endpoint"])) + paths = {name: ROOT / "web/src" / name for name in ( + "web-desktop-adapter.ts", "web-standard-command-contract.ts", "web-standard-task.tsx", + "desktop-command-dispatcher.ts", "part-view-facade.ts", "part.worker.ts", "part-save.worker.ts")} + bridge = PROBE_ROOT / "NativeDocumentView.h" + native = PROBE_ROOT / "WebViewCommands.h" + if route and all(path.is_file() for path in [*paths.values(), bridge, native]): + texts = {name: path.read_text(encoding="utf-8") for name, path in paths.items()} + native_text = native.read_text(encoding="utf-8") + # These commands share the document owner's standard-command + # transport. GUI activation failures remain native failures. + behavior = (("elif name == 'Std_TextDocument':", "App::TextDocument") + if command == "Std_TextDocument" else ( + "elif name in gui_standard_names:", "if not App.GuiUp:", + "native_command.isActive()", + "Gui.runCommand(name, mode if name == 'Std_UserEditMode' else 0)")) + if (all(token in native_text for token in behavior) + and f"'{command}'" in native_text + and f'"{command}"' in bridge.read_text(encoding="utf-8") + and "executeDocumentCommand(input.constData(), output)" in bridge.read_text(encoding="utf-8") + and all(token in texts["web-desktop-adapter.ts"] for token in ( + "recomputeCommand || isStandardCommand(command)", + 'router.request("Part", viewEndpoint(owner)', + 'schema: "freecad-web/document-view/v1", owner, document: documentId, command', + "validStandardResult(response.result, command, documentId)", + "freecad-web/document-view-batch/v1")) + and "executeWebDesktop(this.router, record.command" in texts["desktop-command-dispatcher.ts"] + and all("dispatchDocumentView" in texts[name] for name in ("part.worker.ts", "part-save.worker.ts")) + and "validStandardResult" in texts["part-view-facade.ts"] + and f'"{command}"' in texts["web-standard-command-contract.ts"] + and f'command === "{command}"' in texts["web-standard-task.tsx"] + and " item.name === command)' in texts["web-standard-task.tsx"]): + return {**route, "worker": owner["worker"], "executionModule": "Part", "transport": "direct-command", + "canonicalId": f"Web:desktop:{command}", "nativeRegistration": str(bridge.relative_to(ROOT))} + if command in routes.get("commands", []): + if command == "Std_Open": + native = PROBE_ROOT / "WebOpenCommand.h" + files = [ROOT / "web/src" / name for name in ("web-open-adapter.ts", "web-open-contract.ts", "web-open-task.tsx")] + if not all(path.is_file() for path in [native, *files]) or 'setStatus(App::Document::SkipRecompute, checked)" + if required_native not in native or f'"{command}"' not in task or ')', workbench_text)): + return {**route, "worker": worker.name, "executionModule": "Web", "transport": "direct-command", + "nativeRegistration": str(native.relative_to(ROOT))} + if module == "Part" and command in {"Part_Box", "Part_Box2", "Part_Box3"}: + route = web_routes.get((module, "part.document")) + adapter = ROOT / "web/src/part-desktop-adapter.ts" + if route is not None and "part-save.worker.ts" in route.get("workers", []) and adapter.is_file() and "executePartFixedBoxDesktop" in adapter.read_text(encoding="utf-8"): + return {**route, "worker": "part-save.worker.ts", "executionModule": module, "transport": "direct-command", + "nativeRegistration": "freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp"} + if module == "Points" and command in {"Points_Import", "Points_Export", "Points_Convert", "Points_PolyCut", "Points_Merge", "Points_Structure"}: + route = web_routes.get((module, "points.desktopBatch")) + if route is not None: + return {**route, "worker": "points.worker.ts", "executionModule": module, "transport": "family-batch", + "nativeRegistration": "freecad-source/src/WebAssembly/FreeCADCoreProbe/PointsRuntimeProbe.cpp"} + native_supported = command in native_desktop_commands.get(module, set()) + if native_supported and module in direct_desktop_workers: + exact = web_routes.get((module, command)) + if exact is None and module not in desktop_adapter_modules: + # A dedicated desktop facade/worker may intentionally expose + # a command that is not duplicated in module-registry.generated + # (Start is the canonical example). Native ownership plus the + # typed direct worker is sufficient to synthesize the route; + # do not require a second per-command registry entry. + exact = { + "id": f"{module}:{command}", + "module": module, + "command": command, + "worker": direct_desktop_workers[module], + "workers": [], + "artifactReady": module in artifact_modules, + "uiStatus": "generic-command-entry", + "implementationStatus": "routed", + "validationStatus": "deferred", + } + if exact is not None: + return { + **exact, + "worker": direct_desktop_workers[module], + "executionModule": module, + "transport": "direct-command", + "nativeRegistration": native_desktop_sources.get(module), + } + if native_supported and module in desktop_adapter_modules: + route = family_route(module) + if route is not None: + return { + **route, + "executionModule": module, + "transport": "family-batch", + "nativeRegistration": native_desktop_sources.get(module), + } + return None + + local_routes: dict[str, dict[str, object]] = {} + canonical_by_command: dict[str, tuple[dict[str, object], dict[str, object]]] = {} + for row in desktop_rows: + module = str(row.get("module") or "") + command = str(row.get("command") or "") + if is_ui_container(row): + continue + route = local_route(module, command) + if route is None: + continue + if not isinstance(route.get("command"), str) or not route["command"].strip(): + raise ValueError(f"Invalid generated route for {module}:{command}: missing endpoint") + if route.get("transport") != "browser-ui" and not route.get("worker"): + raise ValueError(f"Invalid generated route for {module}:{command}: missing worker") + row_id = str(row.get("id") or f"{module}:desktop:{command}") + local_routes[row_id] = route + current = canonical_by_command.get(command) + owner_hint = command.split("_", 1)[0] if "_" in command else "" + if current is None or (module == owner_hint and str(current[0].get("module")) != owner_hint): + canonical_by_command[command] = (row, route) + + desktop_route_records: list[dict[str, object]] = [] + for row in desktop_rows: + module = str(row.get("module") or "") + command = str(row.get("command") or "") + if not module or not command: + continue + record_id = str(row.get("id") or f"{module}:desktop:{command}") + ui_container = is_ui_container(row) + portable_route = local_routes.get(record_id) + canonical = canonical_by_command.get(command) if "_" in command else None + canonical_row = row + if portable_route is None and canonical is not None: + canonical_row, portable_route = canonical + implementation_ready = ui_container or portable_route is not None + execution_module = str(portable_route.get("executionModule") or module) if portable_route else module + execution_family_route = family_route(execution_module) + transport = str(portable_route.get("transport") or "family-batch") if portable_route else "family-batch" + execution_route = portable_route or execution_family_route + route_payload = ({ + "module": module, + "command": command, + "worker": None, + "nativeRegistration": None, + "canonicalId": record_id, + "transport": "ui-container", + } if ui_container else { + "module": execution_module, + "command": execution_route.get("command") if execution_route else portable_route.get("command"), + "worker": execution_route.get("worker") if execution_route else portable_route.get("worker"), + "nativeRegistration": portable_route.get("nativeRegistration"), + "canonicalId": portable_route.get("canonicalId", f"{execution_module}:desktop:{command}"), + "transport": transport, + **({"browserHandler": portable_route["browserHandler"], "nativeOperationRequired": False} + if transport == "browser-ui" else {}), + }) if implementation_ready and (ui_container or portable_route) else None + records.append( + { + "id": record_id, + "module": module, + "command": command, + "category": "navigation" if ui_container else category(command), + "kind": "desktop-gui", + "uiRole": "container" if ui_container else "command", + "worker": route_payload.get("worker") if route_payload else None, + "workers": module_rows.get(module, {}).get("workers", []), + "artifactReady": module in artifact_modules, + "uiStatus": "react-navigation" if ui_container else "generic-command-entry" if implementation_ready else "needs-react-workflow", + "implementationStatus": "routed" if implementation_ready else "implementation_required", + "validationStatus": "deferred", + "sourcePath": row.get("sourcePath"), + "sourceLine": row.get("sourceLine"), + "uiSurfaces": row.get("uiSurfaces", []), + "capabilityReason": "FreeCAD Workbench menu/toolbar container rendered by React" if ui_container else row.get("capabilityReason"), + "route": route_payload, + "implementationGaps": [] if implementation_ready else [{ + "stage": "native" if command not in native_desktop_commands.get(module, set()) else "transport", + "reason": "no command-specific native implementation is registered" if command not in native_desktop_commands.get(module, set()) else "native command has no matching Worker/Facade route", + "sourcePath": row.get("sourcePath"), "sourceLine": row.get("sourceLine"), + "repair": "complete this command's real business behavior and route; registration alone is insufficient", + }], + } + ) + if route_payload: + desktop_route_records.append( + { + "id": record_id, + "appearanceModule": module, + "desktopCommand": command, + "sourcePath": canonical_row.get("sourcePath"), + "sourceLine": canonical_row.get("sourceLine"), + **route_payload, + } + ) + if module in module_rows: + module_rows[module]["desktopCommands"] = int(module_rows[module]["desktopCommands"]) + 1 + module_rows[module]["implementationRequired"] = int(module_rows[module]["implementationRequired"]) + int(not implementation_ready) + native_gap_kinds = describe_native_gaps(records, rejected_desktop_markers) + policy_run = subprocess.run( + ["node", str(ROOT / "web/tools/audit-native-route-policy.mjs")], + input=json.dumps({"records": records}), text=True, capture_output=True, check=True, + cwd=ROOT, timeout=30, + ) + blocked_routes = json.loads(policy_run.stdout)["blocked"] + for row in records: + if row["id"] in blocked_routes: + row["runtimeRouteBlock"] = blocked_routes[row["id"]] + row.setdefault("implementationGaps", []).append({"stage": "policy", "reason": blocked_routes[row["id"]]["message"], + "sourcePath": "web/src/native-source-policy.ts"}) + row["implementationStatus"] = "implementation_required" + row["uiStatus"] = "needs-react-workflow" + for module_row in modules: + module_row["implementationRequired"] = sum( + row["module"] == module_row["module"] and row["implementationStatus"] != "routed" + for row in records + ) + statuses = Counter(str(row["uiStatus"]) for row in records) + payload = { + "schema": "freecad-web-feature-capability-registry/v1", + "generatedAt": datetime.now(timezone.utc).isoformat(), + "strategy": "feature-first-deferred-validation", + "sources": { + "routes": "web/src/module-registry.generated.ts", + "workbench": "web/src/workbench-shell.tsx", + "artifacts": "web/public/modules/manifest.json", + "pythonSymbols": "docs/format-api-inventory.json", + }, + "counts": { + "modules": len(modules), + "commands": len(records), + "routed": sum(row["implementationStatus"] == "routed" for row in records), + "implementationRequired": sum(row["implementationStatus"] == "implementation_required" for row in records), + "interactive": statuses["interactive"], + "genericApiEntry": statuses["generic-api-entry"], + "genericCommandEntry": statuses["generic-command-entry"], + "reactNavigation": statuses["react-navigation"], + "needsParameterUi": statuses["needs-parameter-ui"], + "needsReactWorkflow": statuses["needs-react-workflow"], + "artifactModules": sum(bool(row["artifactReady"]) for row in modules), + "validationDeferred": len(records), + }, + "diagnostics": { + "nativeGapKinds": native_gap_kinds, + "blockedRuntimeRoutes": blocked_routes, + "familyMarkersRequireExplicitCommands": sorted(native_desktop_families), + "rejectedDesktopMarkers": { + module: sorted(commands) + for module, commands in sorted(rejected_desktop_markers.items()) + }, + "rejectedMarkerReason": "marker requires a command-specific branch that explicitly inserts status=exposed", + }, + "modules": modules, + "records": records, + "boundaries": [ + "This registry tracks Web capabilities and routes, not Python source symbols.", + "Routed or interactive is an implementation state, not a validation pass.", + "Runtime issues reopen only the affected capability; they do not trigger a full API gate.", + ], + } + OUTPUT.parent.mkdir(parents=True, exist_ok=True) + temporary = OUTPUT.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + temporary.replace(OUTPUT) + route_payload = { + "schema": "freecad-web-desktop-command-routes/v1", + "generatedAt": payload["generatedAt"], + "records": desktop_route_records, + } + ROUTE_OUTPUT.parent.mkdir(parents=True, exist_ok=True) + route_temporary = ROUTE_OUTPUT.with_suffix(".tmp") + route_temporary.write_text(json.dumps(route_payload, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8") + route_temporary.replace(ROUTE_OUTPUT) + if file_stamps(generation_inputs(command_matrix)) == inputs: + cache_temporary = CACHE_PATH.with_suffix(".tmp") + cache_temporary.write_text(json.dumps({"schema": "freecad-web-feature-capability-cache/v1", "inputs": inputs, + "outputs": file_stamps({OUTPUT, ROUTE_OUTPUT}), "counts": payload["counts"]}) + "\n", encoding="utf-8") + cache_temporary.replace(CACHE_PATH) + print(json.dumps({"status": "generated", **payload["counts"]}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/generate_python_api_runtime_evidence.py b/tools/generate_python_api_runtime_evidence.py new file mode 100644 index 00000000..07075562 --- /dev/null +++ b/tools/generate_python_api_runtime_evidence.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Index native Python API names from passing P6 runtime evidence.""" +from __future__ import annotations + +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +P6 = ROOT / "docs/p6" +OUT = P6 / "python-api-runtime-evidence.json" + + +def names(value): + if isinstance(value, str): + return [item.strip() for item in value.replace("\n", ",").split(",") if item.strip()] + if isinstance(value, list): + return [str(item).strip() for item in value if str(item).strip()] + if isinstance(value, dict): + result = [] + for item in value.values(): + result.extend(names(item)) + return result + return [] + + +evidence = {} +for path in sorted(P6.glob("*.json")): + try: + report = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + result_value = report.get("result", report.get("status")) + if not isinstance(result_value, str) or result_value not in {"pass", "passed", "completed"}: + continue + action = report.get("action") + explicit_python = action == "python-api" or "python" in path.stem.lower() + if not explicit_python: + continue + module = report.get("module") + if not isinstance(module, str) or not module: + stem = path.stem.lower() + inferred = [("meshpart", "MeshPart"), ("points", "Points"), ("sketcher", "Sketcher"), ("techdraw", "TechDraw"), ("robot", "Robot"), ("measure", "Measure"), ("surface", "Surface"), ("spreadsheet", "Spreadsheet"), ("inspection", "Inspection"), ("sandbox", "Sandbox")] + module = next((value for token, value in inferred if token in stem), None) + if not isinstance(module, str) or not module: + continue + found = [] + def walk(value, key=""): + if isinstance(value, dict): + for child_key, child in value.items(): + if child_key.lower() in {"apinames", "pythonapi", "pythonapinames", "api_names"}: + found.extend(names(child)) + walk(child, child_key) + elif isinstance(value, list): + for child in value: + walk(child, key) + walk(report) + for name in found: + normalized = name.strip() + if normalized: + key = f"{module}:{normalized}" + evidence.setdefault(key, []).append(str(path.relative_to(ROOT))) + +report = { + "schema": "freecad-web-python-api-runtime-evidence/v1", + "policy": "only passing python-api-named runtime artifacts are indexed; source-only inventory is excluded", + "names": [{"module": key.split(":", 1)[0], "name": key.split(":", 1)[1], "artifacts": sorted(set(paths))} for key, paths in sorted(evidence.items())], + "count": len(evidence), +} +OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") +print(json.dumps({"output": str(OUT.relative_to(ROOT)), "names": len(evidence)}, ensure_ascii=False)) diff --git a/tools/generate_python_family_adapter_manifest.py b/tools/generate_python_family_adapter_manifest.py new file mode 100644 index 00000000..c247d2d5 --- /dev/null +++ b/tools/generate_python_family_adapter_manifest.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Generate an implementation-stage adapter map for one module+tier batch.""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + +ADAPTERS = { + "Assembly": ("assembly.worker.ts", "assembly.pythonFamily", "src/WebAssembly/FreeCADCoreProbe/AssemblyRuntimeProbe.cpp"), + "BIM": ("bim.worker.ts", "bim.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/BimRuntimeProbe.cpp"), + "CAM": ("cam.worker.ts", "cam.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/CAMRuntimeProbe.cpp"), + "Draft": ("draft.worker.ts", "draft.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp"), + "Fem": ("fem.worker.ts", "fem.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/FemGenericFamilyProbe.cpp"), + "Import": ("import.worker.ts", "import.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/ImportRuntimeProbe.cpp"), + "Material": ("material.worker.ts", "material.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MaterialKernelProbe.cpp"), + "Measure": ("measure.worker.ts", "measure.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MeasureRuntimeProbe.cpp"), + "Mesh": ("mesh.worker.ts", "mesh.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MeshRuntimeProbe.cpp"), + "MeshPart": ("meshpart.worker.ts", "meshpart.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/MeshPartRuntimeProbe.cpp"), + "Part": ("part.worker.ts", "part.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PartBoxProbe.cpp"), + "PartDesign": ("partdesign-python.worker.ts", "partdesign.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PartDesignRuntimeProbe.cpp"), + "Plot": ("plot-python.worker.ts", "plot.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PlotRuntimeProbe.cpp"), + "Points": ("points.worker.ts", "points.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/PointsRuntimeProbe.cpp"), + "ReverseEngineering": ("reverseengineering-python.worker.ts", "reverseengineering.pythonFamilyBatch", "src/Mod/ReverseEngineering/InitGui.py"), + "Robot": ("robot-python.worker.ts", "robot.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/RobotRuntimeProbeFixed.cpp"), + "Sandbox": ("sandbox-python.worker.ts", "sandbox.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SandboxRuntimeProbe.cpp"), + "Show": ("show-python.worker.ts", "show.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/ShowRuntimeProbe.cpp"), + "Sketcher": ("sketcher-python.worker.ts", "sketcher.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SketcherProbe.cpp"), + "Spreadsheet": ("spreadsheet-python.worker.ts", "spreadsheet.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SpreadsheetRuntimeProbe.cpp"), + "Surface": ("surface-python.worker.ts", "surface.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/SurfaceFamilyProbe.cpp"), + "TechDraw": ("techdraw-python.worker.ts", "techdraw.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/TechDrawRuntimeProbe.cpp"), + "TemplatePyMod": ("templatepymod-python.worker.ts", "templatepymod.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/TemplatePyModRuntimeProbe.cpp"), +} + +parser = argparse.ArgumentParser() +parser.add_argument("module") +parser.add_argument("tier") +parser.add_argument("--output") +args = parser.parse_args() +if args.module not in ADAPTERS: + raise SystemExit(f"no adapter mapping for {args.module}") +manifest_path = ROOT / "docs/p6/python-api-manifest.json" +rows = json.loads(manifest_path.read_text(encoding="utf-8"))["records"] +selected = [row for row in rows if row["module"] == args.module and row["tier"] == args.tier] +worker, command, native_source = ADAPTERS[args.module] +records = [{"apiId": row["id"], "name": row["name"], "kind": row["kind"], "family": row["family"], "sourcePath": row.get("evidence", {}).get("path"), "route": command, "adapterStatus": "module_adapter_ready_pending_method", "disposition": row["disposition"]} for row in selected] +output = { + "schema": "freecad-web-python-family-adapter-manifest/v1", + "taskId": f"FW-P6-FPA-IMPL-{args.module.upper()}-{args.tier.upper().replace('-', '_')}", + "source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest()}, + "module": args.module, + "tier": args.tier, + "count": len(records), + "route": {"worker": worker, "command": command, "nativeSource": native_source}, + "records": records, + "boundaries": ["module adapter readiness is not method-level parameter/return evidence", "original disposition is preserved until the matching coverage gate"], +} +short_tier = {"tier-1-readonly": "tier1", "tier-2-pure": "tier2", "tier-3-stateful": "tier3"}.get(args.tier, args.tier.replace("-", "")) +out = ROOT / (args.output or f"docs/p6/{args.module.lower()}-{short_tier}-adapter-manifest.json") +out.write_text(json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") +print(json.dumps({"output": str(out.relative_to(ROOT)), "module": args.module, "tier": args.tier, "count": len(records), "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, ensure_ascii=False)) diff --git a/tools/generate_tier1_readonly_adapter_manifest.py b/tools/generate_tier1_readonly_adapter_manifest.py new file mode 100644 index 00000000..f62cb7fc --- /dev/null +++ b/tools/generate_tier1_readonly_adapter_manifest.py @@ -0,0 +1,34 @@ +#!/usr/bin/env python3 +"""Generate grouped implementation metadata for Tier-1 readonly APIs.""" +from __future__ import annotations + +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +source_path = ROOT / "docs/p6/python-api-manifest.json" +rows = json.loads(source_path.read_text(encoding="utf-8"))["records"] +selected = [row for row in rows if row["tier"] == "tier-1-readonly"] +routes = { + "Measure": ("measure.worker.ts", "measure.pythonApi", "src/Mod/Measure/App/AppMeasure.cpp"), + "Mesh": ("mesh.worker.ts", "mesh.pythonApi", "src/Mod/Mesh/App/AppMesh.cpp"), + "Sketcher": ("sketcher-python.worker.ts", "sketcher.pythonApi", "src/Mod/Sketcher/App/AppSketcher.cpp"), + "Robot": ("robot-python.worker.ts", "robot.pythonApi", "src/Mod/Robot/App/AppRobot.cpp"), + "Points": ("points.worker.ts", "points.pythonApi", "src/Mod/Points/App/AppPointsPy.cpp"), + "Cloud": ("cloud.worker.ts", "cloud.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/CloudKernelProbe.cpp:644"), + "Draft": ("draft.worker.ts", "draft.pythonFamilyBatch", "src/WebAssembly/FreeCADCoreProbe/DraftRuntimeProbe.cpp:285"), +} +groups: dict[str, dict[str, object]] = defaultdict(lambda: {"apiIds": [], "families": Counter()}) +for row in selected: + groups[row["module"]]["apiIds"].append(row["id"]) + groups[row["module"]]["families"][row["family"]] += 1 +modules = [] +for module, group in sorted(groups.items()): + route = routes.get(module, (None, None, None)) + modules.append({"module": module, "count": len(group["apiIds"]), "families": dict(sorted(group["families"].items())), "route": {"worker": route[0], "command": route[1], "nativeSource": route[2]}, "apiIds": sorted(group["apiIds"])}) +output = {"schema": "freecad-web-tier1-readonly-adapter-manifest/v1", "taskId": "FW-P6-FPA-IMPL-TIER1-READONLY", "source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(source_path.read_bytes()).hexdigest()}, "tier": "tier-1-readonly", "count": len(selected), "modules": modules, "boundaries": ["grouped readonly route readiness is not method-level return evidence", "original disposition is preserved until F1 coverage"]} +out = ROOT / "docs/p6/tier1-readonly-adapter-manifest.json" +out.write_text(json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") +print(json.dumps({"output": str(out.relative_to(ROOT)), "count": len(selected), "modules": len(modules), "sha256": hashlib.sha256(out.read_bytes()).hexdigest()}, ensure_ascii=False)) diff --git a/tools/generate_web_feature_task_packets.py b/tools/generate_web_feature_task_packets.py new file mode 100644 index 00000000..48895f72 --- /dev/null +++ b/tools/generate_web_feature_task_packets.py @@ -0,0 +1,507 @@ +#!/usr/bin/env python3 +"""Generate small, module-local P6 task packets from the source-backed matrix.""" + +from __future__ import annotations + +import json +import hashlib +import re +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +MATRIX = ROOT / "docs" / "web-parity-matrix.json" +OUT = ROOT / "docs" / "tasks" / "p6" +STATE = ROOT / "docs" / "current" / "task-state.json" + +MODULE_IDS = { + "Assembly": "ASM", + "BIM": "BIM", + "CAM": "CAM", + "Cloud": "CLD", + "Draft": "DFT", + "Fem": "FEM", + "Help": "HLP", + "Import": "IMP", + "Inspection": "INS", + "JtReader": "JTR", + "Material": "MAT", + "Measure": "MEA", + "Mesh": "MSH", + "MeshPart": "MSP", + "Part": "PRT", + "PartDesign": "PDN", + "Plot": "PLT", + "Points": "PTS", + "ReverseEngineering": "REV", + "Robot": "ROB", + "Sandbox": "SDB", + "Show": "SHW", + "Sketcher": "SKT", + "Spreadsheet": "SPR", + "Start": "STR", + "Surface": "SUR", + "TechDraw": "TDR", + "TemplatePyMod": "TPM", + "Test": "TST", + "Tux": "TUX", + "Web": "WEB", +} + +PRIMARY_ACTION = { + "Assembly": "create/recompute", + "BIM": "import/export", + "CAM": "create/recompute", + "Cloud": "create/recompute", + "Draft": "create/recompute", + "Fem": "create/recompute", + "Help": "inspect/source-inventory", + "Import": "import/export", + "Inspection": "create/recompute", + "JtReader": "create/recompute", + "Material": "create/recompute", + "Measure": "create/recompute", + "Mesh": "create/recompute", + "MeshPart": "create/recompute", + "Part": "create/recompute", + "PartDesign": "create/recompute", + "Plot": "inspect/source-inventory", + "Points": "create/recompute", + "ReverseEngineering": "create/recompute", + "Robot": "create/recompute", + "Sandbox": "create/recompute", + "Show": "inspect/source-inventory", + "Sketcher": "create/recompute", + "Spreadsheet": "create/recompute", + "Start": "create/recompute", + "Surface": "create/recompute", + "TechDraw": "create/recompute", + "TemplatePyMod": "inspect/source-inventory", + "Test": "inspect/source-inventory", + "Tux": "inspect/source-inventory", + "Web": "create/recompute", +} + + +def load_state() -> dict: + if not STATE.exists(): + return {"default_status": "planned", "tasks": {}, "module_status": {}} + return json.loads(STATE.read_text(encoding="utf-8")) + + +STATE_DATA = load_state() + + +def task_status(task_id: str) -> str: + return STATE_DATA.get("tasks", {}).get(task_id, STATE_DATA.get("default_status", "planned")) + + +def module_status(module: str, fallback: str) -> str: + return STATE_DATA.get("module_status", {}).get(module, fallback) + + +def write_generated(path: Path, content: str) -> None: + """Write the generated prefix while preserving a manually recorded result section.""" + if path.exists(): + old = path.read_text(encoding="utf-8") + marker = "\n## 结果\n" + if marker in old and marker not in content: + content = content.rstrip() + old[old.index(marker):] + path.write_text(content.rstrip() + "\n", encoding="utf-8") + + +def slug(module: str) -> str: + return re.sub(r"[^a-z0-9]+", "-", module.lower()).strip("-") + + +def action_slug(action: str) -> str: + return re.sub(r"[^a-z0-9]+", "-", action.lower()).strip("-") + + +def module_index(module: str, row: dict) -> str: + code = MODULE_IDS[module] + action = PRIMARY_ACTION[module] + objects = ", ".join(row.get("object_types", [])[:8]) or "无已枚举对象;以源码入口和模块 API 为主" + if len(row.get("object_types", [])) > 8: + objects += f"(另有 {len(row['object_types']) - 8} 个,完整清单见 object-inventory.json)" + formats = ", ".join(row.get("format_extensions", [])) or "无格式入口" + api = row.get("python_api_count", 0) + gui = "需要 GUI 依赖" if row.get("gui_dependency") else "不需要 GUI 依赖" + actions = ", ".join(row.get("user_actions", [])) + followups = [action for action in row.get("user_actions", []) if action != action_primary(module)] + followup_text = ", ".join(f"`{action}`" for action in followups) or "无" + action_rows = [] + for action_number, action_name in enumerate(row.get("user_actions", []), start=1): + if action_name == action: + target = f"{slug(module)}/FW-P6-{code}-C.md" + role = "首切片 C-G" + else: + target = f"{slug(module)}/FW-P6-{code}-ACT-{action_number:02d}.md" + role = "后续拆分合同" + action_rows.append(f"| `{action_name}` | {role} | [{target.rsplit('/', 1)[-1]}]({target}) |") + action_table = "\n".join(action_rows) + action_predecessors = [ + f"`FW-P6-{code}-ACT-{number:02d}-G`" + for number, action_name in enumerate(row.get("user_actions", []), start=1) + if action_name != action + ] + final_predecessor = f"`FW-P6-{code}-X`" + (" + " + " + ".join(action_predecessors) if action_predecessors else "") + links = "\n".join( + f"| [FW-P6-{code}-{letter}]({slug(module)}/FW-P6-{code}-{letter}.md) | {title} | {prev} |" + for letter, title, prev in [ + ("A", "源码边界探针", "FW-P6-000"), + ("B", "运行时注册与依赖闭包", f"FW-P6-{code}-A + FW-P6-001"), + ("C", "一个主要内核动作", f"FW-P6-{code}-B"), + ("D", "重算、非法输入与恢复", f"FW-P6-{code}-C"), + ("E", "Worker/Facade 消息合同", f"FW-P6-{code}-D + FW-P6-002"), + ("F", "Chrome 最小浏览器切片", f"FW-P6-{code}-E + FW-P6-003"), + ("G", "持久化或模块边界证据", f"FW-P6-{code}-F"), + ("X", "首切片出口", f"FW-P6-{code}-G"), + ("Y", "完整动作出口", final_predecessor), + ] + ) + package_status = module_status(module, row.get("web_status", "pending")) + # Module parity uses `pending`; executable task cards use `planned`. + package_task_status = "planned" if package_status == "pending" else package_status + web_status_note = ( + "Web 状态已由 Y gate 晋级为 `completed`;边界见对应 module-gate 产物。" + if package_status == "completed" + else "Web 状态保持 `pending`,直到本包的 Y 卡通过。" + ) + return f"""# FW-P6-{code}:{module} 功能扩展任务包 + +本文件只做模块范围和原子卡索引;执行时读取当前原子卡,不读取本包其他卡。 + +## 范围快照 + +- 状态:`{package_task_status}` +- 来源:`docs/web-parity-matrix.json`,源码 revision 由 `FW-P6-000` 锁定 +- 主要动作:`{action}` +- 对象规模:`{row.get('object_type_count', 0)}`;代表入口:{objects} +- 格式入口:{formats} +- Python API 计数:`{api}`;GUI:{gui} +- 对标动作全集:{actions} +- {web_status_note} + +首个 C-G 切片只覆盖 `{action}`。后续动作:{followup_text};每个后续动作必须在 Y 前完成自己的拆分卡和 C-G 子链,不能因为首个切片通过就把模块标为 `completed`。 + +## 动作级入口 + +| 动作 | 角色 | 入口 | +|---|---|---| +{action_table} + +## 原子卡 + +| 卡 | 合同 | 直接前置 | +|---|---|---| +{links} + +顺序:`A → B → C → D → E → F → G → X`;随后完成动作级卡,最后执行 `Y`。失败只新增同目录 `R` 恢复卡,不复制原卡全文。 +""" + + +def atomic_card(module: str, row: dict, letter: str) -> str: + code = MODULE_IDS[module] + name = slug(module) + prefix = f"FW-P6-{code}" + titles = { + "A": "源码边界探针", + "B": "运行时注册与依赖闭包", + "C": "一个主要内核动作", + "D": "重算、非法输入与恢复", + "E": "Worker/Facade 消息合同", + "F": "Chrome 最小浏览器切片", + "G": "持久化或模块边界证据", + "X": "首切片出口", + "Y": "完整动作出口", + } + prev = { + "A": "`FW-P6-000`", + "B": f"`{prefix}-A`、`FW-P6-001`", + "C": f"`{prefix}-B`", + "D": f"`{prefix}-C`", + "E": f"`{prefix}-D`、`FW-P6-002`", + "F": f"`{prefix}-E`、`FW-P6-003`", + "G": f"`{prefix}-F`", + "X": f"`{prefix}-G`", + "Y": f"`{prefix}-X`", + }[letter] + if letter == "Y": + action_predecessors = [ + f"`{prefix}-ACT-{number:02d}-G`" + for number, action_name in enumerate(row.get("user_actions", []), start=1) + if action_name != PRIMARY_ACTION[module] + ] + if action_predecessors: + prev += " + " + " + ".join(action_predecessors) + task_type = {"A": "probe", "F": "slice", "X": "gate", "Y": "gate"}.get(letter, "contract") + bodies = { + "A": f"""- 合同:确认 `{module}` 的 CMake target、App/Gui 分界、直接依赖、类型注册入口和主要动作源码入口。 +- 输入:`workbench-inventory.json`、`object-inventory.json`、`src/Mod/{module}/`。 +- 命令/方法:在 `freecad-source` 上运行 `rg -n "BUILD_|Init|addObject|registerType|PyInit" src/Mod/{module}`,再对命中的 CMake 与源码行做最小闭包记录。 +- 产物:`docs/p6/{name}-source-boundary.json` 与日志。 +- 验收:每个入口有文件和行号;条件编译、缺失依赖和 GUI 符号单独列出;不把源码存在写成运行时通过。 +- 不包含:代码修改、浏览器测试、完整 API 迁移。""", + "B": f"""- 合同:在独立 WASM probe 中完成 `{module}` 初始化、类型可见性和重复初始化检查。 +- 输入:A 的边界 JSON、模块 App CMake、共享模块加载合同。 +- 命令/方法:复制现有最小 Web probe 的 configure/build/run 流程;只替换模块 target 和一个代表类型;连续执行初始化两次并保存新的 build/smoke 日志,不覆盖成功证据。 +- 产物:`docs/p6/{name}-runtime.json`、构建日志和 WASM SHA-256。 +- 验收:初始化计数为 1;重复调用不重复注册;缺失依赖返回结构化错误;无未声明 GUI/动态库符号。 +- 不包含:主要动作、Facade、Chrome UI。""", + "C": f"""- 合同:只验证一个最小 `{PRIMARY_ACTION[module]}` 合同,固定输入、输出和对象句柄。 +- 输入:B 的 WASM、固定 fixture、对应源码 API;对象模块用代表类型,格式模块用一个最小样例。 +- 命令/方法:从 A 的主要动作入口选择一个 deterministic fixture;在 C ABI/Worker probe 中执行一次成功路径和一次资源释放,记录输入 hash、结果摘要和返回码。 +- 产物:`docs/p6/{name}-kernel.json` 与 smoke 日志。 +- 验收:成功结果可重复;对象/几何/格式摘要符合源码语义;异常转为稳定错误码和消息;资源可释放。 +- 不包含:第二个动作、全量对象覆盖、GUI 交互。""", + "D": f"""- 合同:覆盖一次重算/校验边界和一个非法输入,失败后保留上一次有效状态。 +- 输入:C 的成功 fixture;只读模块改为缺少资源/不支持输入边界。 +- 命令/方法:复用 C 的同一进程,先记录成功快照,再注入一个字段级非法值或缺失资源;校验错误 code、旧状态 hash、重复回放结果。 +- 产物:`docs/p6/{name}-recovery.json` 与日志。 +- 验收:错误定位到字段或步骤;有效对象/文件 hash 不污染;重复执行一致;缓存失败不升级为主流程失败。 +- 不包含:跨文档事务、并发修改、性能预算。""", + "E": f"""- 合同:把 C/D 的一个动作接入 request id、typed result、错误和取消语义。 +- 输入:共享 Facade envelope、D 的 fixture 和错误样例。 +- 命令/方法:为一个 action 增加 typed request/result schema;顺序发送 success、expected error、duplicate id、cancel 四个 request,保存 Worker trace。 +- 产物:`docs/p6/{name}-facade.json`、schema 测试和 Worker 日志。 +- 验收:请求严格串行且可关联;JS 不持有原生指针;成功/失败/重复 request 均有固定结果;取消不破坏文档状态。 +- 不包含:完整 UI、插件系统、跨工作台组合。""", + "F": f"""- 合同:在 Google Chrome 固定版本和 viewport 下完成一个真实 `{PRIMARY_ACTION[module]}` 用户动作回放。 +- 输入:Facade bundle、固定 fixture、Chrome harness;只执行 Chrome,不切换 Firefox/WebKit/Safari。 +- 命令/方法:调用 `FW-P6-003` harness 启动入口,拦截所有外部请求,执行 ready→action→expected-error→reset,并保存 console/network/截图证据。 +- 产物:`docs/p6/{name}-chrome.json`、控制台/网络日志和截图(如适用)。 +- 验收:ready、动作结果、错误路径和 Worker 消息通过;外部请求为 0;运行时异常为 0;证据含 Chrome 版本、模式和 viewport。 +- 不包含:非 Chrome 兼容矩阵、移动适配、完整 UI。""", + "G": f"""- 合同:有保存/重开动作时验证一个最小 FCStd round-trip;否则验证 manifest/资源/只读重放边界。 +- 输入:F 的成功状态、P2.3 FCStd 合同、模块 fixture。 +- 命令/方法:有 `save/reopen` 时按 P2.3 的临时文件、hash、关闭、重开、对象/属性校验顺序执行;无该动作时运行资源 manifest 和只读重放检查。 +- 产物:`docs/p6/{name}-persistence.json` 与日志。 +- 验收:保存/重开对象和属性可校验;不适用时明确原因,不伪造通过;错误后旧状态仍有效。 +- 不包含:跨版本迁移、全量格式覆盖、升级回滚。""", + "X": f"""- 合同:汇总本包 A-G 的独立证据,关闭 `{module}` 的首切片 gate。 +- 输入:A-G JSON/日志、源码 revision、共享 gate 报告。 +- 命令/方法:逐项读取本包 A-G 产物,核对 revision、输入/输出 hash、Chrome 证据和未覆盖动作;生成机器可读结果后再写人读 gate。 +- 产物:`docs/p6/{name}-gate.md` 与 JSON。 +- 验收:首个动作的每个原子合同有命令、输入、产物、hash 和结论;本卡只关闭首切片,不修改完整模块状态;其他动作保持 `pending`。 +- 不包含:其他模块、全量发布 gate、法律或性能结论。""", + "Y": f"""- 合同:汇总首切片和全部动作级子链,决定 `{module}` 是否可以从 `pending` 晋级。 +- 输入:X 的首切片 gate、所有动作级卡及其 C-G 子链产物、源码 revision。 +- 命令/方法:逐动作核对源码入口、成功/错误/Chrome/持久化证据;任一声明动作缺证据即保持 `pending`,不得用动作计数推断完成。 +- 产物:`docs/p6/{name}-module-gate.md` 与 JSON。 +- 验收:本模块声明的 {len(row.get('user_actions', []))} 个动作全部有独立结论;未实现或不适用项显式列出;只有本卡可以晋级该模块 Web 状态。 +- 不包含:其他模块、全量发布 gate、法律或性能结论。""", + }[letter] + return f"""# {prefix}-{letter}:{module} {titles[letter]} + +> 最小执行上下文:只读取本卡、直接前置 {prev} 和本卡列出的产物。浏览器步骤只允许 Google Chrome。 + +- 状态:`{task_status(f"{prefix}-{letter}")}` +- 类型:`{task_type}` +- 前置:{prev} +{bodies} +- 失败恢复:保留首个错误、命令、输入 hash 和部分产物;恢复卡命名 `{prefix}-{letter}-R1`,不得覆盖成功证据。 +""" + + +def action_card(module: str, action_name: str, action_number: int) -> str: + code = MODULE_IDS[module] + name = slug(module) + prefix = f"FW-P6-{code}-ACT-{action_number:02d}" + action_id = action_slug(action_name) + extra_prerequisite = { + "python-api": ";Python 运行时前置 `FW-P4-006-G`", + "save/reopen": ";持久化证据前置 `freecad-p2.3-persistence-transaction-gate.md`", + }.get(action_name, "") + return f"""# {prefix}:{module} `{action_name}` 动作拆分合同 + +> 这是动作级拆分卡,不等于功能已实现。完成本卡后,必须按卡内的 C→D→E→F→G 子链继续执行;只读取本卡、`FW-P6-{code}-B` 和本卡产物。 + +- 状态:`{task_status(prefix)}` +- 类型:`contract` +- 前置:`FW-P6-{code}-B`{extra_prerequisite};若首切片已完成,复用其 WASM、loader 和 fixture 约束。 +- 合同:为 `{action_name}` 冻结一个可观察用户动作的输入、源码入口、结果摘要、错误边界、Worker request 和 Chrome 回放验收。 +- 输入:`{name}-source-boundary.json`、对象/格式/API inventory 中与该动作对应的行、共享 Facade envelope 和 Chrome harness。 +- 命令/方法:先在源码中定位动作入口,再写固定 fixture;把实现拆成 `{prefix}-C`(内核)、`{prefix}-D`(错误/恢复)、`{prefix}-E`(Facade)、`{prefix}-F`(Chrome)、`{prefix}-G`(持久化或适用边界)。 +- 产物:`docs/p6/{name}-action-{action_number:02d}-{action_id}.json`,以及上述子卡各自的日志和 hash。 +- 验收:动作有唯一 request id、成功和预期错误结果、无外部网络请求;未完成子链时本动作保持 `pending`。 +- 不包含:其他动作、工作台 gate、全量对象覆盖、跨版本迁移。 +- 失败恢复:只记录首个源码/fixture/schema 错误,新增 `{prefix}-R1`;不复制或覆盖首切片证据。 +""" + + +def action_child_card(module: str, action_name: str, action_number: int, letter: str) -> str: + code = MODULE_IDS[module] + name = slug(module) + prefix = f"FW-P6-{code}-ACT-{action_number:02d}" + titles = { + "C": "内核动作", + "D": "错误与恢复", + "E": "Facade 接入", + "F": "Chrome 回放", + "G": "持久化或适用边界", + } + prev = { + "C": f"`{prefix}`、`FW-P6-{code}-B`", + "D": f"`{prefix}-C`", + "E": f"`{prefix}-D`、`FW-P6-002`", + "F": f"`{prefix}-E`、`FW-P6-003`", + "G": f"`{prefix}-F`", + }[letter] + bodies = { + "C": f"""- 合同:执行 `{action_name}` 的一个 deterministic 内核输入,返回对象/格式/API 摘要。 +- 输入:动作拆分卡、B 的 WASM、动作 fixture 和源码入口。 +- 命令/方法:单进程执行成功路径、释放路径和重复回放;记录输入 hash、结果 hash、错误 code。 +- 产物:`docs/p6/{name}-action-{action_number:02d}-kernel.json` 与 smoke 日志。 +- 验收:结果可重复,异常结构化,资源释放;不实现其他动作。""", + "D": f"""- 合同:为 `{action_name}` 注入一个字段级非法输入或缺少资源并保持旧状态。 +- 输入:`{prefix}-C` 成功快照和错误 fixture。 +- 命令/方法:成功→非法→恢复三段回放,比较旧状态 hash 和诊断字段。 +- 产物:`docs/p6/{name}-action-{action_number:02d}-recovery.json` 与日志。 +- 验收:首个错误可定位,旧状态未污染,重复回放一致。""", + "E": f"""- 合同:把 `{action_name}` 接入通用 request id、typed result、error 和 cancel。 +- 输入:`{prefix}-D`、共享 envelope、成功和错误样例。 +- 命令/方法:顺序发送 success、expected error、duplicate id、cancel;保存 Worker trace。 +- 产物:`docs/p6/{name}-action-{action_number:02d}-facade.json` 与 schema 日志。 +- 验收:请求可关联且严格串行;JS 不持有原生指针;取消不污染文档。""", + "F": f"""- 合同:在 Chrome 固定版本和 viewport 下回放真实 `{action_name}`。 +- 输入:`{prefix}-E` bundle、fixture、`FW-P6-003` harness。 +- 命令/方法:ready→action→expected-error→reset,拦截外部请求并保存 console/network/截图。 +- 产物:`docs/p6/{name}-action-{action_number:02d}-chrome.json` 与日志。 +- 验收:Chrome 版本、模式、viewport 齐全;外部请求和非预期异常为 0。""", + "G": f"""- 合同:为 `{action_name}` 完成 FCStd round-trip,或记录该动作不适用的边界证据。 +- 输入:`{prefix}-F` 成功状态、P2.3 合同和 fixture。 +- 命令/方法:有保存动作时执行临时文件、hash、关闭、重开、对象/属性校验;否则执行 manifest/只读重放。 +- 产物:`docs/p6/{name}-action-{action_number:02d}-persistence.json` 与日志。 +- 验收:对象/属性或“不适用”原因可校验;不伪造未覆盖能力。""", + }[letter] + task_type = "slice" if letter == "F" else "contract" + return f"""# {prefix}-{letter}:{module} `{action_name}` {titles[letter]} + +> 最小执行上下文:只读取本卡、直接前置 {prev} 和本卡产物。浏览器只允许 Google Chrome。 + +- 状态:`{task_status(f"{prefix}-{letter}")}` +- 类型:`{task_type}` +- 前置:{prev} +{bodies} +- 不包含:其他用户动作、完整工作台 gate、跨版本迁移。 +- 失败恢复:保留首个错误、输入 hash 和 trace;新增 `{prefix}-{letter}-R1`,不覆盖成功证据。 +""" + + +def action_primary(module: str) -> str: + return PRIMARY_ACTION[module] + + +def main() -> None: + data = json.loads(MATRIX.read_text(encoding="utf-8")) + rows = {row["module"]: row for row in data["rows"]} + missing = set(MODULE_IDS) - set(rows) + if missing: + raise SystemExit(f"matrix missing modules: {sorted(missing)}") + OUT.mkdir(parents=True, exist_ok=True) + index = [ + "# P6 功能扩展任务索引", + "", + "> P3 gate 已完成的是源码盘点,不是 32 个工作台的 Web 实现。P6 按工作台建立独立任务包;每个包内部再拆为 A-G、X 首切片和 Y 完整出口。", + "> 当前 32 个模块声明了 115 个用户动作;每个包先做一个首切片,其他动作必须继续拆独立合同,不能用首切片冒充完整对标。", + "> 状态由 `docs/current/task-state.json` 统一维护;本索引和卡片是生成投影。", + "> 机器可读文件清单和数量校验见 [`manifest.json`](manifest.json)。", + "> 矩阵更新后依次运行生成器、`sync_web_task_state.py` 和 `validate_web_context.py`;不要手改生成结构。", + "", + "## 共享前置", + "", + "| 编号 | 合同 | 产物 |", + "|---|---|---|", + "| [FW-P6-000](../FW-P6-000.md) | 锁定源码、矩阵、构建和 Chrome 环境 | `docs/p6/baseline.json` |", + "| [FW-P6-001](../FW-P6-001.md) | 模块初始化、类型注册和依赖错误 | `docs/p6/module-loader.json` |", + "| [FW-P6-002](../FW-P6-002.md) | Worker/Facade 通用消息 envelope | `docs/p6/facade-envelope.json` |", + "| [FW-P6-003](../FW-P6-003.md) | Chrome 回放 harness 和证据格式 | `docs/p6/chrome-harness.json` |", + "", + "## 工作台任务包", + "", + "| 包 | 模块 | 模块状态 | 首个动作 | 全部动作 | 对象 | 格式 | Python API | 直接前置 |", + "|---|---|---|---|---|---:|---|---:|---|", + ] + for module in MODULE_IDS: + row = rows[module] + code = MODULE_IDS[module] + index.append( + f"| [FW-P6-{code}](FW-P6-{slug(module)}.md) | `{module}` | " + f"`{module_status(module, row.get('web_status', 'pending'))}` | `{PRIMARY_ACTION[module]}` | " + f"{', '.join(row['user_actions'])} | {row['object_type_count']} | " + f"{', '.join('`'+x+'`' for x in row['format_extensions']) or '-'} | " + f"{row['python_api_count']} | `FW-P6-000`, `001`, `002`, `003` |" + ) + index += [ + "", + "## 原子步骤语义", + "", + "| 步骤 | 单一合同 | 不读取的内容 |", + "|---|---|---|", + "| A | 源码边界探针 | 其他模块实现、浏览器日志 |", + "| B | WASM 初始化和类型注册 | 主要动作、UI |", + "| C | 一个主要内核动作 | 第二个动作、全量对象 |", + "| D | 重算/非法输入/恢复 | 并发和性能 |", + "| E | Worker/Facade 消息 | 完整 UI 和插件 |", + "| F | Chrome 用户动作 | 非 Chrome 浏览器 |", + "| G | FCStd round-trip 或适用边界 | 跨版本迁移 |", + "| X | 首切片 gate | 其他模块和发布 gate |", + "| Y | 完整动作 gate | 其他模块和发布 gate |", + "", + "失败恢复卡使用同一包内的 `R` 后缀,例如 `FW-P6-PRT-C-R1`;恢复卡只记录首个错误、最小修复和重放命令,不复制原卡全文。", + ] + write_generated(OUT / "INDEX.md", "\n".join(index)) + for module, row in rows.items(): + module_slug = slug(module) + write_generated(OUT / f"FW-P6-{module_slug}.md", module_index(module, row)) + module_dir = OUT / module_slug + module_dir.mkdir(parents=True, exist_ok=True) + for letter in "ABCDEFGXY": + write_generated( + module_dir / f"FW-P6-{MODULE_IDS[module]}-{letter}.md", + atomic_card(module, row, letter), + ) + for action_number, action_name in enumerate(row.get("user_actions", []), start=1): + if action_name == PRIMARY_ACTION[module]: + continue + write_generated( + module_dir / f"FW-P6-{MODULE_IDS[module]}-ACT-{action_number:02d}.md", + action_card(module, action_name, action_number), + ) + for letter in "CDEFG": + write_generated( + module_dir / f"FW-P6-{MODULE_IDS[module]}-ACT-{action_number:02d}-{letter}.md", + action_child_card(module, action_name, action_number, letter), + ) + files = sorted(str(path.relative_to(ROOT)) for path in OUT.rglob("*.md")) + manifest = { + "schema": "freecad-web-p6-task-packet-manifest/v1", + "source_matrix": str(MATRIX.relative_to(ROOT)), + "source_matrix_sha256": hashlib.sha256(MATRIX.read_bytes()).hexdigest(), + "module_count": len(rows), + "declared_action_count": sum(len(row.get("user_actions", [])) for row in rows.values()), + "module_index_count": len(rows), + "atomic_card_count": len(rows) * 9, + "action_split_card_count": sum( + len([action for action in row.get("user_actions", []) if action != PRIMARY_ACTION[module]]) + for module, row in rows.items() + ), + "action_child_card_count": sum( + 5 * len([action for action in row.get("user_actions", []) if action != PRIMARY_ACTION[module]]) + for module, row in rows.items() + ), + "markdown_file_count": len(files), + "files": files, + "shared_prerequisites": [ + "docs/tasks/FW-P6-000.md", + "docs/tasks/FW-P6-001.md", + "docs/tasks/FW-P6-002.md", + "docs/tasks/FW-P6-003.md", + ], + } + (OUT / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/tools/inventory_desktop_ui_parity.py b/tools/inventory_desktop_ui_parity.py new file mode 100644 index 00000000..a12ccbcd --- /dev/null +++ b/tools/inventory_desktop_ui_parity.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +"""Inventory desktop UI surfaces and group Web parity work by shared owners. + +This is a source inventory, not a validation or acceptance check. It records +the existing desktop GUI anchors, Web mounted surfaces, policy gap counts and +the native build targets that can own a package. The output is deliberately +separate from module-batch-manifest.json, whose status and selection belong to +the outer scheduler planner. +""" +from __future__ import annotations + +import json +import re +from datetime import datetime, timezone +from pathlib import Path +from policy_io import atomic_write + +ROOT = Path(__file__).resolve().parents[1] +DOCS = ROOT / "docs/current" +SOURCE = ROOT / "freecad-source/src/Mod" +WEB = ROOT / "web/src" +POLICY = DOCS / "execution-policy.json" +OUT_JSON = DOCS / "desktop-ui-parity-inventory.json" +OUT_MD = DOCS / "DESKTOP_UI_PARITY_PACKAGE_PLAN_20260922.md" + +MODULES = [ + "Part", "PartDesign", "Sketcher", "Spreadsheet", "TechDraw", "Surface", + "Draft", "Mesh", "MeshPart", "BIM", "Fem", "CAM", "Assembly", "Measure", + "Material", "Points", "Robot", "ReverseEngineering", "Inspection", + "Import", "Cloud", "JtReader", "Start", "Help", "Plot", "Show", "Sandbox", + "TemplatePyMod", "Test", "Tux", "Web", +] + +TARGET_RE = re.compile(r"FreeCADWeb[A-Za-z0-9_]+Probe") +COMMAND_RE = re.compile(r"\b(?:Cmd|Command)[A-Za-z0-9_]+") + + +def read(path: Path) -> str: + try: + return path.read_text(encoding="utf-8", errors="replace") + except OSError: + return "" + + +def files(directory: Path, suffix: str | None = None) -> list[str]: + if not directory.is_dir(): + return [] + values = [str(p.relative_to(ROOT)) for p in directory.rglob("*") if p.is_file()] + if suffix: + values = [value for value in values if value.endswith(suffix)] + return sorted(values) + + +def web_files(module: str) -> list[str]: + aliases = { + "PartDesign": "partdesign-", "TechDraw": "techdraw-", "MeshPart": "meshpart-", + "ReverseEngineering": "reverseengineering-", + "TemplatePyMod": "templatepymod-", + } + prefix = aliases.get(module, module.lower() + "-") + return sorted(str(path.relative_to(ROOT)) for path in WEB.glob(f"{prefix}*") if path.is_file()) + + +def command_source(module: str) -> list[str]: + return desktop_sources(module)["commandSources"] + + +def desktop_sources(module: str) -> dict: + # Python workbenches put panels/commands outside Gui; Web also owns the + # application-wide C++ GUI. A missing Gui directory is not missing UI. + roots = [SOURCE / module] + if module == "Web": + roots.append(ROOT / "freecad-source/src/Gui") + paths = sorted({name for root in roots for name in files(root) + if Path(name).suffix in {".cpp", ".h", ".py", ".ui"} + and not any(part.lower() in {"tests", "test", "resources", "__pycache__"} + for part in Path(name).parts[5:-1])}) + # Designer UI files intentionally include Resources/panels/preferences. + ui_files = sorted({name for root in roots for name in files(root, ".ui")}) + commands, workbenches, panels, properties, preferences = [], [], [], [], [] + for name in paths: + path = Path(name) + lower = path.name.lower() + if path.suffix == ".py": + text = read(ROOT / name) + if re.search(r"\b(?:addCommand|addWorkbench|appendMenu|appendToolbar|appendContextMenu)\s*\(", text): + commands.append(name) + if lower == "initgui.py" or re.search(r"\b(?:appendMenu|appendToolbar)\s*\(", text): + workbenches.append(name) + if "task" in lower or "panel" in lower or re.search(r"\b(?:showDialog|QDialog)\s*\(", text): + panels.append(name) + if "viewprovider" in lower or "property" in lower: + properties.append(name) + if "pref" in lower or re.search(r"\baddPreferencePage\s*\(", text): + preferences.append(name) + elif path.suffix in {".cpp", ".h"} and ("Gui" in path.parts or module == "Web"): + if lower.startswith("command") or lower.endswith("workbench.cpp"): + commands.append(name) + if lower.endswith("workbench.cpp"): + workbenches.append(name) + if lower.startswith(("task", "dlg")) or "dialog" in lower: + panels.append(name) + if lower.startswith(("property", "viewprovider")): + properties.append(name) + if "settings" in lower or "pref" in lower: + preferences.append(name) + return {"sourceRoots": [str(root.relative_to(ROOT)) for root in roots if root.is_dir()], + "commandSources": commands, "workbenchSources": workbenches, + "taskAndDialogUi": ui_files, "taskAndDialogSources": panels, + "propertyAndViewSources": properties, "preferenceSources": preferences} + + +def native_targets(module: str, cmake_text: str) -> list[str]: + if module == "Web": + return sorted(set(TARGET_RE.findall(cmake_text)) & { + "FreeCADWebWebRuntimeProbe", "FreeCADWebDocumentProbe", "FreeCADWebWorkbenchCommandProbe"}) + if module == "Part": + return sorted(name for name in set(TARGET_RE.findall(cmake_text)) + if re.fullmatch(r"FreeCADWeb(?:Part(?:Box|DesktopCommand|GeometryFamily|Io)|Document)Probe", name)) + aliases = {"Fem": "Fem", "PartDesign": "PartDesign", + "MeshPart": "MeshPart", "TechDraw": "TechDraw", "ReverseEngineering": "ReverseEngineering", + "Assembly": "Assembly"} + needle = aliases.get(module, module) + return sorted({name for name in TARGET_RE.findall(cmake_text) if needle.lower() in name.lower()}) + + +def package_for(module: str) -> str: + if module in {"Part", "PartDesign", "Sketcher"}: + return "ui-primary-modeling-workspace" + if module in {"Spreadsheet", "TechDraw"}: + return "ui-document-editors-output" + if module in {"Mesh", "MeshPart", "Surface", "Draft"}: + return "ui-geometry-workbench-tasks" + if module in {"BIM", "Fem", "CAM", "Assembly"}: + return "ui-domain-workbench-tasks" + if module in {"Material", "Measure", "Points", "Robot", "ReverseEngineering", "Inspection"}: + return "ui-analysis-and-inspection-tasks" + return "ui-shell-preferences-and-utility" + + +def main() -> int: + cmake = read(ROOT / "freecad-source/src/WebAssembly/FreeCADCoreProbe/CMakeLists.txt") + try: + policy = json.loads(POLICY.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + policy = {} + gaps = policy.get("confirmedGapRepairs", []) if isinstance(policy, dict) else [] + gap_counts: dict[str, dict[str, int]] = {} + for row in gaps: + if not isinstance(row, dict): + continue + module = str(row.get("module") or "") + if not module: + continue + status = str(row.get("status") or "open") + gap_counts.setdefault(module, {})[status] = gap_counts.setdefault(module, {}).get(status, 0) + 1 + + shared_sources = [ + "web/src/project-shell.tsx", "web/src/workbench-shell.tsx", + "web/src/desktop-command-dispatcher.ts", "web/src/persistent-toolbar-workspace.tsx", + "web/src/web-desktop-adapter.ts", "web/src/css.ts", + ] + inventory = [] + for module in MODULES: + gui = SOURCE / module / "Gui" + desktop = desktop_sources(module) + ui_files = desktop["taskAndDialogUi"] + command_files = desktop["commandSources"] + command_text = "\n".join(read(ROOT / path) for path in command_files) + web_owned = web_files(module) + task_files = [path for path in web_owned if path.endswith("-task.tsx") or path.endswith("-task.ts")] + adapter_files = [path for path in web_owned if "adapter" in Path(path).name or "facade" in Path(path).name] + imports = [] + for host in ("web/src/project-shell.tsx", "web/src/workbench-shell.tsx", "web/src/partdesign-workspace-component.tsx"): + for line, text in enumerate(read(ROOT / host).splitlines(), 1): + if "import" in text and any(Path(name).stem in text for name in web_owned if name.endswith(".tsx")): + imports.append({"path": host, "line": line, "source": text.strip()}) + inventory.append({ + "module": module, + "package": package_for(module), + "desktop": { + **desktop, + "guiDirectory": str(gui.relative_to(ROOT)), + "guiDirectoryExists": gui.is_dir(), + "commandSymbolCount": len(set(COMMAND_RE.findall(command_text))), + "countMeaning": "Source search symbols only; not command coverage or completion", + }, + "web": { + "ownedFiles": web_owned, + "taskPanels": task_files, + "adaptersAndFacades": adapter_files, + "candidateSharedShells": [path for path in shared_sources if (ROOT / path).is_file()], + "componentImportAnchors": imports, + "importMeaning": "Imports locate code; imports do not prove mounted or usable routes", + }, + "nativeBuildTargets": native_targets(module, cmake), + "gapStatusCounts": gap_counts.get(module, {}), + "uiCoverage": {area: "source_indexed_not_compared" for area in ( + "menus", "toolbars_buttons", "tasks_control_panels", "properties", + "dialogs_preferences", "context_menus", "status_feedback", "shortcuts_focus_styles")}, + "retainedGapKeys": [row.get("key") for row in gaps if row.get("module") == module], + "registration": { + "sourceGapLedger": "docs/current/execution-policy.json:confirmedGapRepairs[]", + "discoveryRecords": "docs/current/operator-gap-discovery/run-*.json", + "implementationRecord": "docs/current/operator-gap--implementation.json or README.md", + "statusRule": "implemented_unvalidated; validation remains disabled", + }, + }) + + packages = [ + { + "id": "ui-shell-preferences-and-utility", + "modules": [m["module"] for m in inventory if m["package"] == "ui-shell-preferences-and-utility"], + "sharedFrontendOwners": ["project-shell.tsx", "workbench-shell.tsx", "persistent-toolbar-workspace.tsx", "web-desktop-adapter.ts"], + "nativeTargets": ["FreeCADWebDocumentProbe", "FreeCADWebWorkbenchCommandProbe"], + "surfaceScope": ["application menus", "workbench selector", "toolbar layout", "status/error feedback", "preferences/dialog host", "context menu host"], + "buildScope": "frontend Vite bundle once; native target only when shared owner or command registry changes", + }, + { + "id": "ui-primary-modeling-workspace", + "modules": ["Part", "PartDesign", "Sketcher"], + "sharedFrontendOwners": ["project-shell.tsx", "partdesign-workspace-component.tsx", "workbench-shell.tsx", "desktop-command-dispatcher.ts"], + "nativeTargets": ["FreeCADWebDocumentProbe", "FreeCADWebPartBoxProbe", "FreeCADWebPartDesignRuntimeProbe", "FreeCADWebSketcherProbe", "FreeCADWebPartDesktopCommandProbe"], + "surfaceScope": ["modeling menus/toolbars", "shared task panels", "tree/property pages", "selection and viewport handoff", "accept/cancel/history"], + "buildScope": "group changed native owners by configured tree; one -j8 build per affected tree, then one frontend build", + }, + { + "id": "ui-document-editors-output", + "modules": ["Spreadsheet", "TechDraw"], + "sharedFrontendOwners": ["spreadsheet-sheet-editor.tsx", "project-shell.tsx", "workbench-shell.tsx", "web-print-adapter.ts"], + "nativeTargets": ["FreeCADWebSpreadsheetRuntimeProbe", "FreeCADWebTechDrawRuntimeProbe", "FreeCADWebDocumentProbe"], + "surfaceScope": ["sheet/page menus", "table/page task panels", "cell/page property dialogs", "print/export/preview", "context actions"], + "buildScope": "reuse current retained owners; build only changed Spreadsheet/TechDraw targets and one frontend bundle", + }, + { + "id": "ui-geometry-workbench-tasks", + "modules": ["Mesh", "MeshPart", "Surface", "Draft"], + "sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"], + "nativeTargets": ["FreeCADWebMeshRuntimeProbe", "FreeCADWebMeshPartRuntimeProbe", "FreeCADWebSurfaceRuntimeProbe", "FreeCADWebDraftRuntimeProbe"], + "surfaceScope": ["workbench menus/toolbars", "geometry task dialogs", "property editors", "selection filters", "preview/apply/cancel feedback"], + "buildScope": "one target build per changed native owner; shared Web route and frontend build once", + }, + { + "id": "ui-domain-workbench-tasks", + "modules": ["BIM", "Fem", "CAM", "Assembly"], + "sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"], + "nativeTargets": ["FreeCADWebBimRuntimeProbe", "FreeCADWebFemGenericFamilyProbe", "FreeCADWebCAMProbe", "FreeCADWebAssemblyProbe", "FreeCADWebAssemblyKernelProbe"], + "surfaceScope": ["domain menus/toolbars", "task panels", "property/preferences dialogs", "context menus", "job/progress/status feedback"], + "buildScope": "group native changes by actual configured owner target; no unrelated module rebuild", + }, + { + "id": "ui-analysis-and-inspection-tasks", + "modules": ["Material", "Measure", "Points", "Robot", "ReverseEngineering", "Inspection"], + "sharedFrontendOwners": ["workbench-shell.tsx", "desktop-command-dispatcher.ts", "*-desktop-adapter.ts", "*-task.tsx"], + "nativeTargets": ["FreeCADWebMaterialRuntimeProbe", "FreeCADWebMeasureRuntimeProbe", "FreeCADWebPointsRuntimeProbe", "FreeCADWebRobotRuntimeProbe", "FreeCADWebReverseEngineeringRuntimeProbe", "FreeCADWebInspectionRuntimeProbe"], + "surfaceScope": ["command menus", "selection/property dialogs", "task panels", "result/status presentation", "cancel/recovery semantics"], + "buildScope": "shared frontend bundle; build only native targets whose source owner changed", + }, + ] + result = { + "schema": "freecad-web-desktop-ui-parity-inventory/v1", + "generatedAt": datetime.now(timezone.utc).isoformat(), + "mode": "source-inventory-no-validation", + "coverageMeaning": "Source index only. Eight UI surfaces per module remain explicitly unassessed by this index. Reuse keyed implementation records; do not re-open completed work solely for missing comparisons.", + "buildTargetMeaning": "Candidate targets only, never a build list. Resolve changed file consumers and published build trees in web/tools/sync-assets.mjs before necessary native -j8 builds.", + "objective": "Desktop UI parity packages grouped by shared workbench owners and native build targets", + "registration": { + "policy": "docs/current/execution-policy.json", + "confirmedGapKey": "operator-gap-", + "packageRecord": "docs/current/desktop-ui-parity-package-records.json", + "implementationStatus": "implemented_unvalidated", + }, + "sharedFrontendOwners": shared_sources, + "packages": packages, + "modules": inventory, + } + atomic_write(OUT_JSON, result) + + lines = [ + "# 桌面 UI 对标包计划(2026-09-22)", + "", + "本文件是源码盘点和分包基线,不是验证报告。调度器继续保持单一实例;`module-batch-manifest.json` 的状态、选择和批次 ID 仍由外层规划器维护。", + "主线:桌面 FreeCAD UI → Web FreeCAD UI 完全功能与样式对标。覆盖 C++ GUI、Python InitGui/命令/任务面板、Designer .ui 和应用公共 GUI。文件存在、import、命令符号和构建成功均不代表入口已挂载或整模块已对标。", + "每模块保留菜单、工具栏按钮、任务/控制面板、属性页、对话框/偏好、右键菜单、状态反馈、快捷键/焦点/样式八类覆盖状态;未比较项不自动制造缺口,只沿具体源码路由查缺。六个大类是索引目录,实际实施包仍按共享文档所有者/适配器/构建目标聚合。", + "", + "## 统一路由骨架", + "", + "每个包都沿用:桌面 `Workbench.cpp/Command.cpp` 注册 → Web `project-shell.tsx` 或 `workbench-shell.tsx` 菜单/工具栏 → React 任务面板、属性页或对话框 → `DesktopCommandDispatcher` 与模块 adapter/facade → 原生 Document owner/WASM → 树、视口、状态栏和历史反馈。", + "", + "共享前端所有者:`project-shell.tsx`、`workbench-shell.tsx`、`persistent-toolbar-workspace.tsx`、`desktop-command-dispatcher.ts`、`web-desktop-adapter.ts`。", + "", + "## 分包", + "", + ] + for package in packages: + lines.extend([ + f"### `{package['id']}`", + f"模块:{', '.join(package['modules'])}", + f"构建目标:{', '.join(package['nativeTargets'])}", + f"对标面:{ '、'.join(package['surfaceScope']) }。", + f"接续规则:{package['buildScope']}。", + "", + ]) + lines.extend([ + "## 缺口登记方式", + "", + "具体缺口仍登记在 `docs/current/execution-policy.json` 的 `confirmedGapRepairs[]`,每条必须有桌面源码锚点、Web 路由入口、原生 owner、对标范围、具体剩余限制和实现记录。多个同一工作台/构建目标的缺口使用同一个 `functionalPackage`,在一个回合集中修改;不要为单个按钮单独创建包。", + "", + "状态只使用 `open`、`implemented_unvalidated` 或真实阻塞状态;不运行测试、烟测、浏览器检查、截图、验收或独立类型检查。必要构建仅使用受影响目标和原生 `-j8`,前端使用现有 Vite 配置。", + "", + "详细机器可读盘点见 [`desktop-ui-parity-inventory.json`](desktop-ui-parity-inventory.json)。包状态见 [`desktop-ui-parity-package-records.json`](desktop-ui-parity-package-records.json)。", + ]) + OUT_MD.write_text("\n".join(lines) + "\n", encoding="utf-8") + print(json.dumps({"inventory": str(OUT_JSON.relative_to(ROOT)), "plan": str(OUT_MD.relative_to(ROOT)), "modules": len(inventory), "packages": len(packages)}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/module-support-combined-business-cases.mjs b/tools/module-support-combined-business-cases.mjs new file mode 100644 index 00000000..e085e9f7 --- /dev/null +++ b/tools/module-support-combined-business-cases.mjs @@ -0,0 +1,100 @@ +import { execFileSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; + +const root = process.cwd(); +const ids = JSON.parse(process.env.FREECAD_BUSINESS_IDS || '[]'); +const groups = new Map(); +const add = (script, selected) => { + if (!selected.length) return; + const output = execFileSync(process.execPath, [`tools/${script}`], { + cwd: root, + env: { ...process.env, FREECAD_BUSINESS_IDS: JSON.stringify(selected) }, + encoding: 'utf8', + }); + const report = JSON.parse(output); + for (const result of report.results || []) groups.set(result.capabilityId, result); +} +const support = { + Assembly: new Set(['Assembly:assembly.inspectPythonApi', 'Assembly:assembly.inspectSourceInventory', 'Assembly:assembly.nativeTypeProbe', 'Assembly:assembly.pythonFamily']), + BIM: new Set(['BIM:bim.inspectPythonApi', 'BIM:bim.inspectSourceInventory', 'BIM:bim.nativeProbe', 'BIM:bim.pythonFamily', 'BIM:bim.pythonFamilyBatch']), + Mesh: new Set(['Mesh:mesh.inspectSourceInventory', 'Mesh:mesh.pythonApi', 'Mesh:mesh.pythonFamilyBatch']), + Points: new Set(['Points:points.inspectSource', 'Points:points.pythonApi', 'Points:points.pythonFamilyBatch']), + TemplatePyMod: new Set(['TemplatePyMod:templatepymod.inspectSourceInventory', 'TemplatePyMod:templatepymod.pythonApi', 'TemplatePyMod:templatepymod.pythonFamilyBatch']), + Cloud: new Set(['Cloud:cloud.inspectSourceInventory', 'Cloud:cloud.inspectPythonApi', 'Cloud:cloud.pythonFamilyBatch']), + Start: new Set(['Start:start.inspectSourceInventory', 'Start:start.pythonApi']), + CAM: new Set(['CAM:cam.inspectPythonApi', 'CAM:cam.inspectSourceInventory', 'CAM:cam.pythonFamilyBatch']), + Help: new Set(['Help:help.inspectSourceInventory', 'Help:help.pythonApi']), + Plot: new Set(['Plot:plot.pythonApi', 'Plot:plot.pythonFamilyBatch']), + Robot: new Set(['Robot:robot.inspectSourceInventory', 'Robot:robot.pythonApi', 'Robot:robot.pythonFamilyBatch']), + Sandbox: new Set(['Sandbox:sandbox.inspectSourceInventory', 'Sandbox:sandbox.pythonApi', 'Sandbox:sandbox.pythonFamilyBatch']), + Inspection: new Set(['Inspection:inspection.createRecompute', 'Inspection:inspection.inspectPythonApi', 'Inspection:inspection.inspectSourceInventory', 'Inspection:inspection.pythonFamilyBatch', 'Inspection:inspection.saveReopen']), + Material: new Set(['Material:material.inspectSourceInventory', 'Material:material.pythonApi', 'Material:material.pythonFamilyBatch']), +}; +const moduleOf = id => id.split(':', 1)[0]; +for (const module of Object.keys(support)) { + const selected = ids.filter(id => support[module].has(id)); + const scripts = { + Assembly: 'assembly-business-cases.mjs', BIM: 'bim-supporting-business-cases.mjs', + Mesh: 'mesh-supporting-business-cases.mjs', + Points: 'points-supporting-business-cases.mjs', TemplatePyMod: 'templatepymod-supporting-business-cases.mjs', + Cloud: 'cloud-supporting-business-cases.mjs', Start: 'start-supporting-business-cases.mjs', CAM: 'cam-supporting-business-cases.mjs', Help: 'help-supporting-business-cases.mjs', Inspection: 'inspection-supporting-business-cases.mjs', Material: 'material-supporting-business-cases.mjs', Plot: 'plot-supporting-business-cases.mjs', Robot: 'robot-supporting-business-cases.mjs', Sandbox: 'sandbox-supporting-business-cases.mjs', + }; + add(scripts[module], selected); +} +const aliasId = 'Start:Start:desktop:Start_Start'; +const rest = ids.filter(id => !groups.has(id) && id !== aliasId); +const restBy = new Map(); +for (const id of rest) { + const module = moduleOf(id); + if (!restBy.has(module)) restBy.set(module, []); + restBy.get(module).push(id); +} +for (const [module, selected] of restBy) { + if (module === 'Fem' && selected.includes('Fem:fem.action')) { + add('fem-action-business-cases.mjs', selected.filter(id => id === 'Fem:fem.action')); + const remainingFem = selected.filter(id => id !== 'Fem:fem.action'); + if (!remainingFem.length) continue; + selected.splice(0, selected.length, ...remainingFem); + } + if (module === 'Fem') { + add('fem-business-cases.mjs', selected); + continue; + } + let script; + if (module === 'Assembly') script = selected.includes('Assembly:desktop:Separator') ? 'assembly-desktop-separator-v2.mjs' : 'assembly-business-cases.mjs'; + else if (module === 'BIM') script = 'bim-create-edit-business-cases.mjs'; + else if (module === 'Mesh') script = 'mesh-desktop-command-business-cases.mjs'; + else if (module === 'Points') script = selected.some(id => ['Points:points.createRecompute', 'Points:points.saveReopen', 'Points:points.desktopBatch', 'Points:desktop:Points_Merge', 'Points:desktop:Points_Structure', 'business-format:Points:export:.obj', 'business-format:Points:import:.ply', 'Points:desktop:Points_Import', 'Points:desktop:Points_Export'].includes(id)) ? 'points-business-cases.mjs' : 'points-document-business-cases.mjs'; + else if (module === 'TemplatePyMod') script = 'templatepymod-checkable-business-cases.mjs'; + else if (module === 'Cloud') script = selected.includes('Cloud:cloud.restore') ? 'cloud-restore-business-cases-v2.mjs' : 'cloud-save-business-cases.mjs'; + else if (module === 'Draft') script = selected.includes('Draft:draft.action') ? 'draft-action-business-cases.mjs' : 'draft-business-cases.mjs'; + else if (module === 'JtReader') script = 'jtreader-business-cases.mjs'; + else if (module === 'Start') script = 'start-business-cases.mjs'; + else if (module === 'CAM') script = 'cam-business-cases.mjs'; + else if (module === 'Material') script = 'material-business-cases.mjs'; + else if (module === 'Robot') script = 'robot-business-cases.mjs'; + else if (module === 'Sandbox') script = 'sandbox-business-cases.mjs'; + else if (module === 'Fem') script = selected.includes('Fem:fem.action') ? 'fem-action-business-cases.mjs' : 'fem-desktop-command-business-cases.mjs'; + else { continue; } + add(script, selected); +} +// The duplicated Start requirement is an alias of the canonical matrix ID. +if (ids.includes('Start:Start:desktop:Start_Start')) { + const matrix = JSON.parse(fs.readFileSync(path.join(root, 'docs/p6/workbench-command-matrix.json'), 'utf8')); + const find = value => { + if (value && typeof value === 'object') { + if (value.id === 'Start:desktop:Start_Start') return value; + for (const child of Object.values(value)) { const found = find(child); if (found) return found; } + } + }; + const actual = find(matrix); + groups.set('Start:Start:desktop:Start_Start', { + capabilityId: 'Start:Start:desktop:Start_Start', status: actual?.disposition === 'restricted' ? 'passed' : 'failed', + cases: [{ input: { evidence: 'docs/p6/workbench-command-matrix.json', canonicalId: 'Start:desktop:Start_Start' }, actual, + assertions: [{ name: 'Start alias resolves to the canonical restricted command boundary', passed: actual?.disposition === 'restricted' }] }], + }); +} +const results = ids.map(id => groups.get(id) || { capabilityId: id, status: 'failed', cases: [], error: 'no route for selected business ID' }); +process.stdout.write(JSON.stringify({ schema: 'freecad-web-business-cases/v1', results }) + '\n'); +process.exitCode = results.length === ids.length && results.every(result => result.status === 'passed') ? 0 : 1; diff --git a/tools/part-circle-vertex-picking-business-cases.mjs b/tools/part-circle-vertex-picking-business-cases.mjs new file mode 100644 index 00000000..9180aabe --- /dev/null +++ b/tools/part-circle-vertex-picking-business-cases.mjs @@ -0,0 +1,372 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { playwright } from './part-primitive-business-cases.mjs'; +import { checkEdgeLocation } from './part-edge-location-business-cases.mjs'; +import { checkPrimitiveExpressions } from './part-primitive-expression-business-cases.mjs'; + +export const runPrimitiveExpressionCases = ids => runCircleVertexPickingCases(ids, true); + +export async function runCircleVertexPickingCases(ids, expressionsOnly = false) { + const capabilityId = 'Part:desktop:Part_Primitives'; + if (!ids.includes(capabilityId)) return []; + const directory = path.resolve('docs/current/part-circle-vertex-picking-business', new Date().toISOString().replace(/[:.]/g, '-')); + fs.mkdirSync(directory, { recursive: true }); + const result = { capabilityId, status: 'failed', cases: [], stages: [], evidenceFiles: {}, + remaining: [], + deferredCases: ['runCircleThreePointCases', 'runCylinderSkewCases', 'runLegacyPrimitiveTaskCases', 'runAdditionalPrimitiveCases', + 'runWedgePrimitiveCases', 'runHelixSpiralCases', 'runPrimitivePlacementCases', 'runPrimitiveContainerCases'] }; + const stage = name => { result.stages.push({ name, at: new Date().toISOString() }); process.stderr.write(`Circle vertex picking: ${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 points = [[-10, 0, 0], [0, 0, 10], [10, 0, 0]]; + let browser; + try { + for (const file of ['tools/part-circle-vertex-picking-business-cases.mjs', 'tools/part-primitive-business-cases.mjs', + 'tools/part-edge-location-business-cases.mjs', + 'tools/part-primitive-expression-business-cases.mjs', + 'web/src/part-primitives-task.tsx', 'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts', + 'web/src/scene-viewport.tsx', 'web/src/workbench-shell.tsx', + 'freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp', + ...['js', 'wasm', 'worker.js'].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)]) + result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex'); + stage('browser-native-load-enter'); + browser = await playwright().chromium.launch({ headless: process.env.HEADLESS !== "0", executablePath: process.env.FREECAD_CHROME ?? '/usr/bin/google-chrome', + args: ['--no-sandbox', '--disable-dev-shm-usage'] }); + const page = await browser.newPage({ viewport: { width: 1440, height: 1000 } }); + 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_Primitives&document=CirclePick`); + const panel = page.locator('section[aria-label="Part primitives"]'); + const click = async name => { + name = ({ 'Create primitive': 'Create', 'Apply primitive': 'OK' })[name] ?? name; + await page.evaluate(() => { window.circlePickBefore = window.__freecadWorkbenchState?.response; }); + await panel.getByRole('button', { name, exact: true }).click(); + if (['New document', 'Primitives undo', 'Primitives redo'].includes(name)) + await panel.getByRole('button', { name: 'Read primitives document', exact: true }).click(); + await page.waitForFunction(() => window.__freecadWorkbenchState?.response && window.__freecadWorkbenchState.response !== window.circlePickBefore); + const reply = await page.evaluate(() => window.__freecadWorkbenchState.response); + assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; + }; + await panel.getByLabel('Primitives document', { exact: true }).fill('CirclePick'); + await click('New document'); stage('browser-native-load-complete'); + stage('browser-primitive-expressions-enter'); + await checkPrimitiveExpressions({ page, panel, click, record, persist: expressionsOnly }); + stage('browser-primitive-expressions-complete'); + if (expressionsOnly) result.deferredCases.push('runCircleVertexPickingCases'); + if (!expressionsOnly) { + stage('browser-edge-location-enter'); + await checkEdgeLocation({ page, panel, click, record, result, directory }); + stage('browser-edge-location-complete'); + for (let i = 0; i < points.length; ++i) { + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Vertex'); + await panel.getByLabel('Primitive object', { exact: true }).fill(`Point${i + 1}`); + for (let axis = 0; axis < 3; ++axis) + await panel.getByLabel(`Primitive ${['X', 'Y', 'Z'][axis]}`, { exact: true }).fill(String(points[i][axis])); + const state = await click('Create'); + assert.deepEqual(state.objects.find(o => o.name === `Point${i + 1}`).primitivePoint, points[i]); + } + const before = await click('Read primitives document'); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle'); + await panel.getByLabel('Primitive object', { exact: true }).fill('PickedArc'); + await panel.getByLabel('Circle definition', { exact: true }).selectOption('points'); + const canvas = panel.locator('[aria-label="Primitives geometry"] canvas'); + // Project fixture vertices using the viewport's initial camera solely to locate mouse clicks. + const pick = async (index, point) => { + const button = panel.getByRole('button', { name: `Pick circle point ${index + 1} from a vertex`, exact: true }); + await button.click(); assert.equal(await button.getAttribute('aria-pressed'), 'true'); + await canvas.scrollIntoViewIfNeeded(); + const size = await canvas.boundingBox(); + const position = await page.evaluate(async ({ point, width, height }) => { + const THREE = await import('/node_modules/three/build/three.module.js'); + const center = new THREE.Vector3(0, 0, 5), radius = Math.hypot(20, 0, 10); + const camera = new THREE.PerspectiveCamera(45, width / height, radius / 10000, radius * 100); + camera.up.set(0, 0, 1); + camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7)); + camera.lookAt(center); camera.updateMatrixWorld(); + const projected = new THREE.Vector3(...point).project(camera); + return [(projected.x + 1) * width / 2, (1 - projected.y) * height / 2]; + }, { point, width: size.width, height: size.height }); + await canvas.click({ position: { x: position[0], y: position[1] } }); + await page.waitForFunction(({ index, point }) => point.every((value, axis) => + Number(document.querySelector(`[aria-label="Circle point ${index + 1} ${['X', 'Y', 'Z'][axis]}"]`).value) === value), { index, point }); + assert.equal(await button.getAttribute('aria-pressed'), 'false'); + assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Circle'); + assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'PickedArc'); + }; + for (let index = 0; index < 3; ++index) await pick(index, points[index]); + assert.deepEqual(await click('Read primitives document'), before); + const created = await click('Create'); + const check = state => { + const arc = state.objects.find(o => o.name === 'PickedArc'); + assert.equal(arc?.type, 'Part::Circle'); assert.equal(arc.topology.valid, true); + assert.equal(arc.topology.Edge, 1); near(arc.parameters.Radius, 10); + near(arc.parameters.Angle2 - arc.parameters.Angle1, 180); + const line = arc.lines[0]; + line[0].forEach((value, axis) => near(value, points[0][axis])); + line.at(-1).forEach((value, axis) => near(value, points[2][axis])); + assert.ok(line.some(point => Math.abs(point[2] - 10) < 0.1)); + assert.deepEqual(state.objects.filter(o => o.name !== 'PickedArc'), before.objects); + return arc; + }; + check(created); assert.equal(created.undoCount, before.undoCount + 1); + assert.deepEqual((await click('Primitives undo')).objects, before.objects); + check(await click('Primitives redo')); + record({ points, route: 'mounted viewport pointer events' }, { arc: check(created), undoCount: created.undoCount }, + 'Three native vertices are picked without changing object/type or document; OCCT creates the oriented arc with expected radius/endpoints and atomic undo/redo'); + await panel.getByRole('button', { name: 'Pick circle point 1 from a vertex', exact: true }).click(); + const cancelled = await click('Cancel'); check(cancelled); assert.equal(cancelled.undoCount, created.undoCount); + assert.equal(await panel.getByRole('button', { name: 'Pick circle point 1 from a vertex', exact: true }).getAttribute('aria-pressed'), 'false'); + await panel.getByRole('button', { name: 'Save primitives document', exact: true }).click(); + await panel.getByLabel('Saved primitives file').waitFor(); + const bytes = await page.evaluate(async () => { + const { readDocumentFile } = await import('/src/storage.ts'); + return Array.from(new Uint8Array(await readDocumentFile('Primitives-CirclePick.FCStd'))); + }); + assert.ok(bytes.length > 0); await page.reload(); + await panel.getByLabel('Primitives document', { exact: true }).fill('CirclePick'); + await panel.getByLabel('Primitives FCStd file', { exact: true }).setInputFiles({ name: 'picked.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) }); + await panel.locator('[data-primitive-object="PickedArc"]').waitFor(); + check(await click('Read primitives document')); + for (const [label, viewport] of [['desktop', { width: 1440, height: 1000 }], ['mobile', { width: 390, height: 844 }]]) { + await page.setViewportSize(viewport); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle'); + await panel.getByLabel('Primitive object', { exact: true }).fill('PickedArc'); + await panel.getByLabel('Circle definition', { exact: true }).selectOption('points'); + if (label === 'mobile') await pick(1, points[1]); + const bounds = await panel.evaluate(node => ({ width: node.clientWidth, scroll: node.scrollWidth })); + assert.ok(bounds.scroll <= bounds.width + 1); + const png = await canvas.screenshot({ path: path.join(directory, `${label}-canvas.png`) }); + 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 context = canvas.getContext('2d'); context.drawImage(image, 0, 0); + const pixels = context.getImageData(0, 0, canvas.width, canvas.height).data, values = new Set(); + for (let index = 0; index < pixels.length; index += 4) values.add(`${pixels[index]},${pixels[index + 1]},${pixels[index + 2]}`); + return values.size; + }, png.toString('base64')); + assert.ok(colors > 1, `Blank ${label} canvas`); + const screenshot = path.join(directory, `${label}.png`); await page.screenshot({ path: screenshot, fullPage: true }); + result.evidenceFiles[screenshot] = createHash('sha256').update(fs.readFileSync(screenshot)).digest('hex'); + } + record({ cancel: true, opfs: true, mobilePick: true }, { bytes: bytes.length }, + 'Cancel disarms vertex picking without native mutation; OPFS FCStd reload retains geometry, and desktop/mobile canvases render with mobile vertex picking'); + stage('browser-surface-picking-enter'); + await page.setViewportSize({ width: 1440, height: 1000 }); + await panel.getByLabel('Primitives document', { exact: true }).fill('SurfacePick'); + await click('New document'); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Plane'); + await panel.getByLabel('Primitive Length', { exact: true }).fill('20'); + await panel.getByLabel('Primitive Width', { exact: true }).fill('20'); + await click('Create'); + const planeState = await click('Read primitives document'); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle'); + await panel.getByLabel('Primitive object', { exact: true }).fill('SurfaceArc'); + await panel.getByLabel('Circle definition', { exact: true }).selectOption('points'); + const surfacePoints = [[5, 10, 0], [10, 15, 0], [15, 10, 0]], picked = []; + for (let index = 0; index < 3; ++index) { + if (index === 1) await page.setViewportSize({ width: 390, height: 844 }); + if (index === 2) await page.setViewportSize({ width: 1440, height: 1000 }); + const button = panel.getByRole('button', { name: `Pick circle point ${index + 1} on geometry`, exact: true }); + await button.click(); + await canvas.scrollIntoViewIfNeeded(); + const size = await canvas.boundingBox(); + const position = await page.evaluate(async ({ point, width, height }) => { + const THREE = await import('/node_modules/three/build/three.module.js'); + const center = new THREE.Vector3(10, 10, 0), radius = Math.hypot(20, 20); + const camera = new THREE.PerspectiveCamera(45, width / height, radius / 10000, radius * 100); + camera.up.set(0, 0, 1); + camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7)); + camera.lookAt(center); camera.updateMatrixWorld(); + const projected = new THREE.Vector3(...point).project(camera); + return [(projected.x + 1) * width / 2, (1 - projected.y) * height / 2]; + }, { point: surfacePoints[index], width: size.width, height: size.height }); + await canvas.click({ position: { x: position[0], y: position[1] } }); + await page.waitForFunction(index => document.querySelector(`[aria-label="Pick circle point ${index + 1} on geometry"]`) + ?.getAttribute('aria-pressed') === 'false', index); + const point = await Promise.all(['X', 'Y', 'Z'].map(async axis => Number(await panel.getByLabel(`Circle point ${index + 1} ${axis}`, { exact: true }).inputValue()))); + point.forEach((value, axis) => assert.ok(Math.abs(value - surfacePoints[index][axis]) < 0.1, JSON.stringify({ point, expected: surfacePoints[index] }))); + picked.push(point); + assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'SurfaceArc'); + assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Circle'); + } + assert.deepEqual(await click('Read primitives document'), planeState); + const surfaceState = await click('Create'); + const surfaceArc = surfaceState.objects.find(o => o.name === 'SurfaceArc'); + assert.equal(surfaceArc.type, 'Part::Circle'); assert.equal(surfaceArc.topology.valid, true); + assert.equal(surfaceArc.topology.Edge, 1); assert.ok(Math.abs(surfaceArc.parameters.Radius - 5) < 0.1); + surfaceArc.lines[0][0].forEach((value, axis) => near(value, picked[0][axis])); + surfaceArc.lines[0].at(-1).forEach((value, axis) => near(value, picked[2][axis])); + assert.ok(surfaceArc.lines[0].some(point => Math.hypot(...point.map((value, axis) => value - picked[1][axis])) < 0.1)); + assert.equal(surfaceState.undoCount, planeState.undoCount + 1); + assert.deepEqual((await click('Primitives undo')).objects, planeState.objects); + assert.deepEqual((await click('Primitives redo')).objects, surfaceState.objects); + const surfaceScreenshot = path.join(directory, 'surface-picking.png'); + await canvas.screenshot({ path: surfaceScreenshot }); + result.evidenceFiles[surfaceScreenshot] = createHash('sha256').update(fs.readFileSync(surfaceScreenshot)).digest('hex'); + record({ surfacePoints, route: 'mounted desktop/mobile surface pointer events' }, { picked, arc: surfaceArc }, + 'Surface picks preserve the draft object and document; native OCCT creates an arc through the picked positions with analytic radius and atomic undo/redo'); + stage('browser-subelement-vertices-enter'); + await panel.getByLabel('Primitives document', { exact: true }).fill('SubelementPick'); + await click('New document'); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Plane'); + for (const field of ['Length', 'Width']) await panel.getByLabel(`Primitive ${field}`, { exact: true }).fill('20'); + await panel.getByLabel('Primitive position Z', { exact: true }).fill('4'); + await panel.getByLabel('Primitive axis X', { exact: true }).fill('1'); + await panel.getByLabel('Primitive axis Z', { exact: true }).fill('0'); + await panel.getByLabel('Primitive rotation angle', { exact: true }).fill('90'); + await click('Create'); + const vertexState = await click('Read primitives document'); + const plane = vertexState.objects.find(o => o.name === 'Plane'); + assert.equal(plane.topology.Vertex, 4); assert.equal(plane.vertices.length, 4); + const corners = [[0, 0, 4], [20, 0, 4], [20, 0, 24], [0, 0, 24]]; + for (const corner of corners) assert.ok(plane.vertices.some(point => point.every((value, axis) => Math.abs(value - corner[axis]) < 1e-6))); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Circle'); + await panel.getByLabel('Primitive object', { exact: true }).fill('CornerArc'); + await panel.getByLabel('Circle definition', { exact: true }).selectOption('points'); + const clickWorld = async (point, offset = 0) => { + await canvas.scrollIntoViewIfNeeded(); const size = await canvas.boundingBox(); + const position = await page.evaluate(async ({ point, width, height }) => { + const THREE = await import('/node_modules/three/build/three.module.js'); + const center = new THREE.Vector3(10, 0, 14), radius = Math.hypot(20, 20); + const camera = new THREE.PerspectiveCamera(45, width / height, radius / 10000, radius * 100); + camera.up.set(0, 0, 1); + camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7)); + camera.lookAt(center); camera.updateMatrixWorld(); + const p = new THREE.Vector3(...point).project(camera); + return [(p.x + 1) * width / 2, (1 - p.y) * height / 2]; + }, { point, width: size.width, height: size.height }); + await canvas.click({ position: { x: position[0] + offset, y: position[1] } }); + }; + for (let index = 0; index < 3; ++index) { + await page.setViewportSize(index === 1 ? { width: 390, height: 844 } : { width: 1440, height: 1000 }); + const button = panel.getByRole('button', { name: `Pick circle point ${index + 1} from a vertex`, exact: true }); + await button.click(); + const beforePoint = await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Circle point ${index + 1} ${axis}`, { exact: true }).inputValue())); + await clickWorld([10, 0, 14]); + assert.equal(await button.getAttribute('aria-pressed'), 'true'); + assert.deepEqual(await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Circle point ${index + 1} ${axis}`, { exact: true }).inputValue())), beforePoint); + await clickWorld(corners[index], 3); + await page.waitForFunction(index => document.querySelector(`[aria-label="Pick circle point ${index + 1} from a vertex"]`) + ?.getAttribute('aria-pressed') === 'false', index); + for (const [axis, label] of ['X', 'Y', 'Z'].entries()) near(Number(await panel.getByLabel(`Circle point ${index + 1} ${label}`, { exact: true }).inputValue()), corners[index][axis]); + assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'CornerArc'); + assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Circle'); + } + assert.deepEqual(await click('Read primitives document'), vertexState); + const cornerState = await click('Create'); + const cornerArc = cornerState.objects.find(o => o.name === 'CornerArc'); + assert.equal(cornerArc.topology.valid, true); assert.equal(cornerArc.topology.Edge, 1); + near(cornerArc.parameters.Radius, Math.sqrt(200)); near(cornerArc.parameters.Angle2 - cornerArc.parameters.Angle1, 180); + cornerArc.lines[0][0].forEach((value, axis) => near(value, corners[0][axis])); + cornerArc.lines[0].at(-1).forEach((value, axis) => near(value, corners[2][axis])); + assert.equal(cornerState.undoCount, vertexState.undoCount + 1); + assert.deepEqual((await click('Primitives undo')).objects, vertexState.objects); + assert.deepEqual((await click('Primitives redo')).objects, cornerState.objects); + const vertexScreenshot = path.join(directory, 'subelement-vertices.png'); + await canvas.screenshot({ path: vertexScreenshot }); + result.evidenceFiles[vertexScreenshot] = createHash('sha256').update(fs.readFileSync(vertexScreenshot)).digest('hex'); + record({ corners, placement: plane.primitivePlacement, pixelOffset: 3 }, { vertices: plane.vertices, arc: cornerArc }, + 'Desktop/mobile clicks snap to exact transformed OCCT subelement vertices; face interiors cannot satisfy the vertex gate; native arc geometry and atomic history are preserved'); + stage('browser-subelement-vertices-complete'); + stage('browser-location-picking-enter'); + assert.deepEqual((await click('Primitives undo')).objects, vertexState.objects); + const locationBaseline = await click('Read primitives document'); + await panel.getByLabel('Primitive type', { exact: true }).selectOption('Box'); + await panel.getByLabel('Primitive object', { exact: true }).fill('LocatedBox'); + for (const [field, value] of [['Length', 2], ['Width', 3], ['Height', 4]]) + await panel.getByLabel(`Primitive ${field}`, { exact: true }).fill(String(value)); + await panel.getByRole('button', { name: 'Reset primitive placement', exact: true }).click(); + await panel.getByLabel('Primitive rotation angle', { exact: true }).fill('90'); + const locationButton = panel.getByRole('button', { name: 'Pick primitive location', exact: true }); + const placementFields = async key => Promise.all(['X', 'Y', 'Z'].map(async axis => + Number(await panel.getByLabel(`Primitive ${key} ${axis}`, { exact: true }).inputValue()))); + await locationButton.click(); + let location; + for (const [label, viewport, target] of [ + ['desktop', { width: 1440, height: 1000 }, [5, 0, 10]], + ['mobile', { width: 390, height: 844 }, [15, 0, 20]], + ]) { + await page.setViewportSize(viewport); + await clickWorld(target); + location = await placementFields('position'); + location.forEach((value, axis) => assert.ok(Math.abs(value - target[axis]) < 0.15)); + (await placementFields('axis')).forEach((value, axis) => near(value, [0, -1, 0][axis])); + assert.equal(await panel.getByLabel('Primitive rotation angle', { exact: true }).inputValue(), '90'); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'true'); + assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'LocatedBox'); + assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Box'); + await canvas.click({ position: { x: 5, y: 5 } }); + assert.deepEqual(await placementFields('position'), location); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'true'); + assert.deepEqual(await click('Read primitives document'), locationBaseline); + const screenshot = path.join(directory, `location-${label}.png`); + await page.screenshot({ path: screenshot, fullPage: true }); + result.evidenceFiles[screenshot] = createHash('sha256').update(fs.readFileSync(screenshot)).digest('hex'); + } + for (const [viewport, corner] of [ + [{ width: 1440, height: 1000 }, corners[0]], + [{ width: 390, height: 844 }, corners[2]], + ]) { + await page.setViewportSize(viewport); + for (const [axis, value] of [['X', 1], ['Y', 0], ['Z', 0]]) + await panel.getByLabel(`Primitive axis ${axis}`, { exact: true }).fill(String(value)); + await clickWorld(corner, 3); + location = await placementFields('position'); + location.forEach((value, axis) => near(value, corner[axis])); + (await placementFields('axis')).forEach((value, axis) => near(value, [0, -1, 0][axis])); + assert.equal(await panel.getByLabel('Primitive rotation angle', { exact: true }).inputValue(), '90'); + assert.equal(await panel.getByLabel('Primitive object', { exact: true }).inputValue(), 'LocatedBox'); + assert.equal(await panel.getByLabel('Primitive type', { exact: true }).inputValue(), 'Box'); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'true'); + assert.deepEqual(await click('Read primitives document'), locationBaseline); + } + record({ corners: [corners[0], corners[2]], pixelOffset: 3 }, { location, axis: await placementFields('axis') }, + 'Desktop/mobile location picks snap to transformed native vertices and replace a stale draft axis with the rotated plane normal without changing draft identity, angle, native objects or history'); + await canvas.click({ button: 'right', position: { x: 5, y: 5 } }); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'false'); + assert.deepEqual(await placementFields('position'), location); + await locationButton.click(); await page.keyboard.press('Escape'); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'false'); + await locationButton.click(); await locationButton.click(); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'false'); + await locationButton.click(); + assert.deepEqual(await click('Cancel'), locationBaseline); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'false'); + assert.deepEqual(await placementFields('position'), [0, 0, 0]); + // Cancel resets dimensions, so restore the independent analytic fixture. + for (const [field, value] of [['Length', 2], ['Width', 3], ['Height', 4]]) + await panel.getByLabel(`Primitive ${field}`, { exact: true }).fill(String(value)); + await panel.getByLabel('Primitive rotation angle', { exact: true }).fill('90'); + await locationButton.click(); await clickWorld([15, 0, 20]); + await clickWorld(corners[2], 3); + location = await placementFields('position'); + const locatedState = await click('Create'); + const locatedBox = locatedState.objects.find(item => item.name === 'LocatedBox'); + assert.equal(await locationButton.getAttribute('aria-pressed'), 'false'); + assert.equal(locatedBox.type, 'Part::Box'); assert.equal(locatedBox.topology.valid, true); + near(locatedBox.volume, 24); + locatedBox.primitivePlacement.position.forEach((value, axis) => near(value, location[axis])); + locatedBox.primitivePlacement.axis.forEach((value, axis) => near(value, [0, -1, 0][axis])); + near(locatedBox.primitivePlacement.angle, 90); + for (const [axis, offsets] of [[0, [-4, 0]], [1, [0, 3]], [2, [0, 2]]]) { + near(Math.min(...locatedBox.vertices.map(point => point[axis])), location[axis] + offsets[0]); + near(Math.max(...locatedBox.vertices.map(point => point[axis])), location[axis] + offsets[1]); + } + assert.deepEqual(locatedState.objects.filter(item => item.name !== 'LocatedBox'), locationBaseline.objects); + assert.equal(locatedState.undoCount, locationBaseline.undoCount + 1); + assert.deepEqual((await click('Primitives undo')).objects, locationBaseline.objects); + assert.deepEqual((await click('Primitives redo')).objects, locatedState.objects); + record({ targets: [[5, 0, 10], [15, 0, 20], corners[2]], angle: 90, dimensions: [2, 3, 4] }, { location, box: locatedBox }, + 'Surface and planar vertex location picking copy world position and normal; misses and cancellation preserve native state; create at the native vertex yields analytic rotated OCCT vertices and atomic history'); + stage('browser-location-picking-complete'); + } + assert.deepEqual(errors, []); + stage('browser-complete'); result.status = 'passed'; + } catch (error) { result.error = { code: 'circle_vertex_picking_failed', message: error.stack || String(error) }; } + finally { + if (browser) await browser.close(); stage('browser-cleanup-complete'); + fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2)); + } + return [result]; +} diff --git a/tools/part-desktop-alias-cases.mjs b/tools/part-desktop-alias-cases.mjs new file mode 100644 index 00000000..50348482 --- /dev/null +++ b/tools/part-desktop-alias-cases.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import { registerHooks } from "node:module"; +import { fileURLToPath } from "node:url"; +import ts from "../web/node_modules/typescript/lib/typescript.js"; + +const hooks = registerHooks({ + resolve(specifier, context, next) { + if (specifier.endsWith("?worker&url")) + return { url: `data:text/javascript,export default ${JSON.stringify(specifier)}`, shortCircuit: true }; + if (specifier.startsWith(".") && specifier.endsWith(".js") && context.parentURL?.includes("/web/src/")) + return next(specifier.slice(0, -3) + ".ts", context); + return next(specifier, context); + }, + load(url, context, next) { + if (url.endsWith(".ts")) return { format: "module", shortCircuit: true, + source: ts.transpileModule(fs.readFileSync(fileURLToPath(url), "utf8"), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext }, + }).outputText }; + return next(url, context); + }, +}); +const { DesktopCommandDispatcher } = await import("../web/src/desktop-command-dispatcher.ts"); +const index = JSON.parse(fs.readFileSync("web/public/api/desktop-command-routes.json", "utf8")); +globalThis.fetch = async () => ({ ok: true, json: async () => index }); +const calls = []; +const dispatcher = new DesktopCommandDispatcher({ request: async (...args) => { + calls.push(args); + return { kind: "error", requestId: "native-boundary", error: { code: "test_boundary" } }; +} }); +for (const command of ["Part_CheckGeometry", "Part_Builder"]) { + const record = { id: `Part:desktop:${command}`, module: "Part", command }; + for (const args of [{}, { activeTask: true }, { selection: [{ documentId: "Other", object: "Box" }] }]) { + const response = await dispatcher.execute(record, args, "Current"); + assert.equal(response.kind, "error"); + assert.equal(response.error.code, "invalid_request"); + } + assert.equal(calls.length, command === "Part_Builder" ? 1 : 0); + const args = command === "Part_CheckGeometry" + ? { selection: [{ documentId: "Current", object: "Box" }] } + : { points: [[0, 0, 0], [1, 0, 0], [0, 1, 0]] }; + await dispatcher.execute(record, args, "Current"); + const [module, route, payload, document] = calls.at(-1); + assert.equal(module, "Part"); + assert.equal(route, "part.pythonFamilyBatch"); + assert.equal(document, "Current"); + assert.equal(payload.records[0].apiId, `Part:desktop:${command}`); +} +console.log("PASS: six invalid alias requests rejected before Worker dispatch; two valid requests preserve canonical Part routing. No native business acceptance claimed."); +hooks.deregister(); diff --git a/tools/part-projection-business-cases.mjs b/tools/part-projection-business-cases.mjs new file mode 100644 index 00000000..05dfdcdc --- /dev/null +++ b/tools/part-projection-business-cases.mjs @@ -0,0 +1,300 @@ +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 projectionId = 'Part:desktop:Part_ProjectionOnSurface'; +export { runLinkedProjectionCases as runProjectionCases } from './part-linked-projection-business-cases.mjs'; +export async function runLegacyProjectionCases(ids) { + if (!ids.includes(projectionId)) return []; + const directory = path.resolve('docs/current/part-projection-business', new Date().toISOString().replace(/[:.]/g, '-')); + const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'part-projection-business-')); + fs.mkdirSync(directory, { recursive: true }); + const result = { capabilityId: projectionId, status: 'failed', cases: [], stages: [], evidenceFiles: {} }; + const stage = name => { result.stages.push({ name, at: new Date().toISOString() }); process.stderr.write(`Projection: ${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}`); + let kernel, browser; + try { + for (const file of ['tools/part-projection-business-cases.mjs', 'web/src/part-projection-task.tsx', + 'web/src/part-desktop-adapter.ts', 'web/src/part-document-facade.ts', 'web/src/workbench-shell.tsx', 'web/src/scene-viewport.tsx', + 'freecad-source/src/WebAssembly/FreeCADCoreProbe/PartProjectionDocument.h', + 'freecad-source/src/Mod/Part/App/FeatureProjectOnSurface.cpp', 'freecad-source/src/Mod/Part/Gui/DlgProjectionOnSurface.cpp', + ...['js', 'wasm', 'worker.js'].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)]) + result.evidenceFiles[file] = createHash('sha256').update(fs.readFileSync(file)).digest('hex'); + stage('adapter-compile-enter'); + execFileSync(path.resolve('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 adapter = 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(process.env.FREECAD_PART_DOCUMENT_BUSINESS_BUILD ?? '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(`projection-${++sequence}`, payload), kernel); + } }; + const document = 'ProjectionBusiness'; + const request = (action, args = {}, owner = document) => router.request('Part', facade.PART_DOCUMENT_COMMAND, { + schema: facade.PART_DOCUMENT_SCHEMA, module: 'Part', document: owner, action, builderInfo: true, includeMesh: true, ...args }); + const call = async (action, args = {}, owner = document) => { + const reply = await request(action, args, owner); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; + }; + const python = source => { + const reply = JSON.parse(kernel.ccall('fc_web_dispatch_json', 'string', ['string'], [JSON.stringify({ cmd: 'part.documentViewCommand', args: { + owner: 'DocumentProbe', document, command: 'Std_CommandLine', parameters: { operation: 'submit', source: `exec(${JSON.stringify(source)})` }, + } })])); + assert.equal(reply.ok, true, JSON.stringify(reply)); assert.equal(reply.result.stderr, '', JSON.stringify(reply)); + }; + const link = (object, subelement) => ({ documentId: document, object, subelements: [subelement] }); + let selected; + const execute = args => adapter.executePartFixedBoxDesktop(router, 'Part_ProjectionOnSurface', args, document, + (owner, selection) => { assert.equal(owner, document); selected = selection; }); + const accepted = async args => { const reply = await execute(args); assert.equal(reply.kind, 'result', JSON.stringify(reply)); return reply.result; }; + const feature = (state, name = state.createdObject) => { const item = state.objects.find(o => o.name === name); assert.ok(item, `Missing ${name}`); return item; }; + await call('create'); + python(`import FreeCAD as App, Part\nd=App.getDocument('${document}')\ndef add(name,shape):\n obj=d.addObject('Part::Feature',name)\n obj.Shape=shape\n return obj\nadd('Support',Part.makePlane(20,20))\nadd('Source',Part.makePlane(4,3,App.Vector(2,2,5)))\nadd('Edge',Part.makeLine(App.Vector(2,2,5),App.Vector(6,2,5)))\nd.recompute()`); + const fixture = await call('save', { path: '/tmp/ProjectionFixture.FCStd' }); + await call('create', {}, 'ProjectionOther'); + const other = await call('snapshot', {}, 'ProjectionOther'); + const base = { support: link('Support', 'Face1'), selection: [link('Source', 'Face1')], direction: [0, 0, -1], mode: 'Faces', height: 0, offset: 0 }; + stage('native-projection-enter'); + const before = await call('readProjection'); + const created = await accepted(base); const item = feature(created); const name = item.name; + assert.equal(item.type, 'Part::ProjectOnSurface'); assert.equal(item.topology.valid, true); + near(item.topology.area, 12); near(item.volume, 0); + assert.deepEqual(item.projection, base); assert.ok(item.dependencies.includes('Support')); assert.ok(item.dependencies.includes('Source')); + assert.deepEqual(selected, [{ documentId: document, object: name }]); + assert.equal(created.undoCount, before.undoCount + 1); + assert.deepEqual((await call('undo')).objects, before.objects); + assert.deepEqual((await call('redo')).objects, created.objects); + assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); + record(base, { type: item.type, topology: item.topology, links: item.projection }, + 'Native face projection has analytic area, source/support dependencies, selection and atomic undo/redo without changing another document'); + const solidArgs = { ...base, action: 'edit', object: name, mode: 'All', height: 2 }; + const solid = feature(await accepted(solidArgs)); near(solid.volume, 24); assert.equal(solid.topology.valid, true); + const zRange = item => { + const z = item.mesh.positions.filter((_value, index) => index % 3 === 2); + return [Math.min(...z), Math.max(...z)]; + }; + const unshifted = zRange(solid); + for (const offset of [-1, 1.5]) { + const shifted = feature(await accepted({ ...solidArgs, offset })); + near(shifted.volume, 24); assert.equal(shifted.projection.offset, offset); + zRange(shifted).forEach((z, index) => near(z, unshifted[index] - offset)); + record({ offset, direction: base.direction }, { boundsZ: zRange(shifted), volume: shifted.volume }, + 'Signed offset translates the native solid along the normalized projection direction while retaining volume'); + } + const multiple = feature(await accepted({ ...solidArgs, selection: [...base.selection, link('Edge', 'Edge1')] })); + near(multiple.volume, 24); assert.equal(multiple.projection.selection.length, 2); + assert.ok(multiple.dependencies.includes('Edge')); assert.ok(multiple.topology.Edge > solid.topology.Edge); + await accepted(solidArgs); + record({ mode: 'All', sources: ['Source.Face1', 'Edge.Edge1'] }, { topology: multiple.topology, links: multiple.projection }, + 'All mode retains both the extruded face and separately projected edge with native source links'); + const moved = await call('setPosition', { object: 'Source', position: [1, 0, 0] }); near(feature(moved, name).volume, 24); + assert.notDeepEqual(feature(moved, name).mesh.positions, solid.mesh.positions); + const stable = await call('readProjection'); + for (const args of [{ direction: [0, 0, 0] }, { height: -1 }, { mode: 'Unknown' }, { selection: [] }, + { support: link('Support', 'Face99') }, { selection: [link('Missing', 'Edge1')] }, + { selection: [{ ...link('Source', 'Face1'), documentId: 'ProjectionOther' }] }, + { activeTask: true }, { action: 'edit', object: 'Support' }, { document: 'ProjectionOther' }, + { action: 'edit', object: name, selection: [link(name, 'Face1')] }]) { + const reply = await execute({ ...base, ...args }); assert.equal(reply.kind, 'error', JSON.stringify(reply)); + assert.deepEqual(await call('readProjection'), stable); assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); + record(args, reply.error, 'Invalid projection input rejects without changing geometry, links or history'); + } + const edge = feature(await accepted({ ...base, mode: 'Edges', selection: [link('Edge', 'Edge1')] })); + assert.equal(edge.topology.valid, true); assert.equal(edge.topology.Edge, 1); near(edge.topology.length, 4); + const wireArgs = { ...base, mode: 'Edges', selection: [link('Source', 'Wire1')] }; + const wire = feature(await accepted(wireArgs)); + assert.equal(wire.topology.valid, true); assert.equal(wire.topology.Edge, 4); near(wire.topology.length, 14); + assert.deepEqual(wire.projection.selection, wireArgs.selection); + record(wireArgs, { topology: wire.topology, links: wire.projection }, + 'Native wire projection retains the source wire reference and its analytic rectangular perimeter'); + const nativeStable = await call('readProjection'); + for (const invalid of [{ direction: [0, 0, 0] }, { direction: ['0', 0, -1] }, { height: -1 }, + { offset: '1' }, { mode: 'Unknown' }, { selection: [] }, { support: link('Support', 'Face99') }, + { selection: [link('Missing', 'Edge1')] }, { selection: [link('Source', 'Face1'), link('Source', 'Face1')] }, + { selection: [{ ...link('Source', 'Face1'), documentId: 'ProjectionOther' }] }, + { selection: [link(name, 'Face1')] }]) { + const args = { document, action: 'editProjection', object: name, ...base, ...invalid }; + const reply = JSON.parse(kernel.ccall('fc_web_dispatch_json', 'string', ['string'], [JSON.stringify({ cmd: 'part.document', args })])); + assert.equal(reply.ok, false, JSON.stringify(reply)); + assert.deepEqual(await call('readProjection'), nativeStable); + assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); + record(args, { code: reply.code, error: reply.error }, + 'Direct native malformed projection rejects and rolls back geometry, dependency links and history in both documents'); + } + python(`dependent=d.addObject('Part::Compound','ProjectionDependent')\ndependent.Links=[d.getObject('${name}')]\nindirect=d.addObject('Part::Compound','ProjectionIndirect')\nindirect.Links=[dependent]\nd.recompute()`); + const cycleBefore = await call('readProjection'); + for (const invalid of [{ selection: [link('ProjectionIndirect', 'Face1')] }, { support: link('ProjectionIndirect', 'Face1') }]) { + const args = { ...solidArgs, ...invalid }; + const rejected = await execute(args); assert.equal(rejected.kind, 'error', JSON.stringify(rejected)); + assert.match(rejected.error.message, /cycle/i); + assert.deepEqual(await call('readProjection'), cycleBefore); + assert.deepEqual(await call('snapshot', {}, 'ProjectionOther'), other); + record(args, rejected.error, 'Indirect source and support cycles reject without changing geometry, dependencies or undo history'); + } + const savedState = await call('readProjection'); + const saved = await call('save', { path: '/tmp/ProjectionBusiness.FCStd' }); await call('close'); + const opened = await call('open', { path: '/tmp/ProjectionBusiness.FCStd', bytes: saved.bytes }); + assert.deepEqual(opened.objects, savedState.objects); + near(feature(await accepted({ ...solidArgs, height: 3 })).volume, 36); + const cancelBefore = await call('readProjection'); assert.equal((await accepted({ action: 'cancel' })).cancelled, true); + assert.deepEqual((await call('readProjection')).objects, cancelBefore.objects); + record({ height: [2, 3], edgeLength: 4, actions: ['source-move', 'save', 'close', 'open', 'edit', 'cancel'] }, + { volume: 36, bytes: saved.bytes.byteLength }, 'Projection extrusion, edge geometry, source recompute, FCStd links and subsequent edits retain native semantics'); + stage('native-curved-support-enter'); + python(`d=App.getDocument('${document}')\ncurved=d.addObject('Part::Cylinder','CurvedSupport')\ncurved.Radius=5\ncurved.Height=10\ncurved.Angle=90\nadd('CurvedSource',Part.makeLine(App.Vector(10,3,2),App.Vector(10,3,5)))\nd.recompute()`); + const curvedArgs = { support: link('CurvedSupport', 'Face1'), selection: [link('CurvedSource', 'Edge1')], + direction: [-1, 0, 0], mode: 'Edges', height: 0, offset: 0 }; + const curved = feature(await accepted(curvedArgs)); + const checkCurved = (item, radius) => { + assert.equal(item.topology.valid, true); assert.equal(item.topology.Edge, 1); near(item.topology.length, 3); + assert.deepEqual(item.projection, curvedArgs); + assert.ok(item.dependencies.includes('CurvedSupport')); assert.ok(item.dependencies.includes('CurvedSource')); + const points = item.lines.flat(); assert.ok(points.length >= 2); + for (const point of points) { near(point[0], Math.sqrt(radius ** 2 - 9)); near(point[1], 3); } + near(Math.min(...points.map(p => p[2])), 2); near(Math.max(...points.map(p => p[2])), 5); + }; + checkCurved(curved, 5); + python('curved.Radius=6\nd.recompute()'); + checkCurved(feature(await call('readProjection'), curved.name), 6); + const curvedSaved = await call('save', { path: '/tmp/CurvedProjection.FCStd' }); await call('close'); + checkCurved(feature(await call('open', { path: '/tmp/CurvedProjection.FCStd', bytes: curvedSaved.bytes }), curved.name), 6); + python(`d=App.getDocument('${document}')\nd.getObject('CurvedSupport').Radius=7\nd.recompute()`); + checkCurved(feature(await call('readProjection'), curved.name), 7); + record(curvedArgs, { topology: curved.topology, lines: curved.lines, editedRadii: [6, 7], savedBytes: curvedSaved.bytes.byteLength }, + 'Curved native support produces the analytic cylindrical intersection, preserves links through FCStd and recomputes radius edits after reopen'); + stage('native-complete'); kernel.PThread?.terminateAllThreads(); kernel = undefined; stage('native-cleanup-complete'); + 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 } }); + const errors = []; page.on('pageerror', error => errors.push(String(error))); + stage('browser-enter'); + await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? 'http://127.0.0.1:5180'}/workbench.html?module=Part&command=Part_ProjectionOnSurface&document=${document}`); + const panel = page.getByRole('region', { name: 'Projection on surface task', exact: true }); + const upload = bytes => panel.getByLabel('Projection FCStd file', { exact: true }).setInputFiles({ name: 'Projection.FCStd', mimeType: 'application/octet-stream', buffer: Buffer.from(bytes) }); + await upload(fixture.bytes); + for (const [title, object, element] of [['Support', 'Support', 'Face1'], ['Source 1', 'Source', 'Face1']]) { + await panel.getByLabel(`${title} object`, { exact: true }).selectOption(object); + await panel.getByLabel(`${title} element`, { exact: true }).selectOption(element); + } + for (const [axis, index] of [['X', 0], ['Y', 1], ['Z', 2]]) { + for (const sign of [1, -1]) { + await panel.getByRole('button', { name: `Toggle projection ${axis} direction`, exact: true }).click(); + const direction = await Promise.all(['X', 'Y', 'Z'].map(axis => panel.getByLabel(`Projection direction ${axis}`, { exact: true }).inputValue())); + assert.deepEqual(direction.map(Number), [0, 1, 2].map(i => i === index ? sign : 0)); + } + } + await panel.getByLabel('Projection mode', { exact: true }).selectOption('Faces'); + await panel.getByRole('button', { name: 'Create projection', exact: true }).click(); + await panel.getByRole('button', { name: 'Apply changes', exact: true }).waitFor(); + const browserResult = async height => { + await page.waitForFunction(expected => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => o.projection?.height === expected) + && !document.querySelector('button.run')?.disabled, height); + const state = await page.evaluate(() => window.__freecadWorkbenchState.response.result); + const item = feature(state); near(item.volume, 12 * height); assert.equal(item.topology.valid, true); return item; + }; + await browserResult(0); + const cameraButton = panel.getByRole('button', { name: 'Use projection camera direction', exact: true }); + const readDirection = async () => Promise.all(['X', 'Y', 'Z'].map(async axis => Number(await panel.getByLabel(`Projection direction ${axis}`, { exact: true }).inputValue()))); + await cameraButton.click(); + const initialCamera = await readDirection(); + const norm = Math.hypot(1, -1, 0.8); + initialCamera.forEach((value, index) => near(value, [-1 / norm, 1 / norm, -0.8 / norm][index])); + const canvas = panel.getByLabel('Projection geometry', { exact: true }).locator('canvas'); + await canvas.scrollIntoViewIfNeeded(); + const bounds = await canvas.boundingBox(); assert.ok(bounds); + await page.mouse.move(bounds.x + bounds.width * 0.5, bounds.y + bounds.height * 0.5); + await page.mouse.down(); + await page.mouse.move(bounds.x + bounds.width * 0.65, bounds.y + bounds.height * 0.55, { steps: 12 }); + await page.mouse.up(); + await cameraButton.click(); + const orbitedCamera = await readDirection(); near(Math.hypot(...orbitedCamera), 1); + assert.ok(orbitedCamera.some((value, index) => Math.abs(value - initialCamera[index]) > 0.01)); + record({ action: 'camera-direction', orbit: [0.15, 0.05] }, { initialCamera, orbitedCamera }, + 'Projection direction follows the initial and interactively orbited viewport camera'); + // Restore the vertical projection used by the analytic extrusion checks below. + for (const [axis, value] of [['X', 0], ['Y', 0], ['Z', -1]]) + await panel.getByLabel(`Projection direction ${axis}`, { exact: true }).fill(String(value)); + await panel.getByLabel('Projection mode', { exact: true }).selectOption('All'); + await panel.getByLabel('Projection height', { exact: true }).fill('2'); + await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await browserResult(2); + await panel.getByRole('button', { name: 'Projection undo', exact: true }).click(); + await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '0'); + await panel.getByRole('button', { name: 'Projection redo', exact: true }).click(); + await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '2'); + const single = await browserResult(2); + await panel.getByRole('button', { name: 'Add projection source', exact: true }).click(); + await panel.getByLabel('Source 2 object', { exact: true }).selectOption('Edge'); + await panel.getByLabel('Source 2 element', { exact: true }).selectOption('Edge1'); + await panel.getByLabel('Projection offset', { exact: true }).fill('1.5'); + await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); + await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => + o.projection?.selection.length === 2 && o.projection.offset === 1.5)); + const combined = await browserResult(2); + assert.ok(combined.dependencies.includes('Edge')); + assert.ok(combined.topology.Edge > single.topology.Edge); + zRange(combined).forEach((z, index) => near(z, zRange(single)[index] - 1.5)); + record({ route: 'mounted projection task', source: 'Edge.Edge1', offset: 1.5 }, + { topology: combined.topology, projection: combined.projection, boundsZ: zRange(combined) }, + 'Browser source addition and signed offset update native topology, dependencies and geometric bounds'); + await panel.getByRole('button', { name: 'Remove source 2', exact: true }).click(); + await panel.getByLabel('Projection offset', { exact: true }).fill('0'); + await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); + await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.result?.objects?.some(o => + o.projection?.selection.length === 1 && o.projection.offset === 0)); + const restored = await browserResult(2); + assert.deepEqual(restored.projection, single.projection); + assert.deepEqual(restored.topology, single.topology); + assert.ok(!restored.dependencies.includes('Edge')); + await panel.getByRole('button', { name: 'Save projection document', exact: true }).click(); + await panel.getByRole('status').filter({ hasText: `Projection-${document}.FCStd` }).waitFor(); + const bytes = await page.evaluate(async name => { const { readDocumentFile } = await import('/src/storage.ts'); + return [...new Uint8Array(await readDocumentFile(`Projection-${name}.FCStd`))]; }, document); + assert.ok(bytes.length > 0); + for (const [width, height] of [[1440, 900], [390, 844]]) { + await page.setViewportSize({ width, height }); + const file = path.join(directory, `projection-${width}.png`); + const png = await panel.locator('canvas').screenshot({ path: file }); + const colors = await page.evaluate(async base64 => { + const image = new Image(); image.src = `data:image/png;base64,${base64}`; 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); assert.ok(await panel.evaluate(e => e.scrollWidth <= e.clientWidth + 1)); + result.evidenceFiles[path.relative(process.cwd(), file)] = createHash('sha256').update(png).digest('hex'); + } + await panel.getByRole('button', { name: 'Close projection task', exact: true }).click(); + await panel.getByRole('button', { name: 'Apply changes', exact: true }).waitFor({ state: 'detached' }); + await page.reload(); await upload(bytes); + await panel.getByLabel('Projection feature', { exact: true }).selectOption(name); + await page.waitForFunction(() => document.querySelector('[aria-label="Projection height"]')?.value === '2'); + await panel.getByLabel('Projection height', { exact: true }).fill('3'); + await panel.getByRole('button', { name: 'Apply changes', exact: true }).click(); await browserResult(3); + assert.deepEqual(errors, []); + record({ command: 'Part_ProjectionOnSurface', viewports: [1440, 390], actions: ['create', 'edit', 'undo', 'redo', 'OPFS-save', 'reload', 'FCStd-open', 'edit'] }, + { volume: 36, bytes: bytes.length }, 'Mounted projection task dispatches linked geometry, persists editable FCStd through OPFS and renders desktop/mobile geometry without overflow'); + stage('browser-complete'); + result.status = 'not_implemented'; + result.remaining = [ + 'Desktop preview transaction: create on task activation, recompute live edits, commit on accept and abort all task edits on reject', + 'Viewport subelement selection gates', + 'Linked-object projection coverage', + ]; + } catch (error) { result.error = String(error.stack ?? error); process.stderr.write(result.error + '\n'); } + finally { + kernel?.PThread?.terminateAllThreads(); await browser?.close(); fs.rmSync(temporary, { recursive: true, force: true }); stage('cleanup-complete'); + } + fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify(result, null, 2) + '\n'); + return [result]; +} diff --git a/tools/part-section-business-cases.mjs b/tools/part-section-business-cases.mjs new file mode 100644 index 00000000..153d323a --- /dev/null +++ b/tools/part-section-business-cases.mjs @@ -0,0 +1,173 @@ +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]; +} diff --git a/tools/part-section-cut-container-business-cases.mjs b/tools/part-section-cut-container-business-cases.mjs new file mode 100644 index 00000000..e2f2101a --- /dev/null +++ b/tools/part-section-cut-container-business-cases.mjs @@ -0,0 +1,810 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { playwright } from "./part-primitive-business-cases.mjs"; + +// Isolate the uncolored-base/colored-tool boundary without replaying the +// already recorded placement, cutter-size, opacity and lifecycle scenarios. +export const runSectionCutFaceAlphaCases = ids => runSectionCutToolColorCases(ids, true); +export const runSectionCutFragmentColorCases = ids => runSectionCutToolColorCases(ids, true, true); +export const runSectionCutFragmentTransparencyCases = ids => runSectionCutToolColorCases(ids, true, true, true); +export const runSectionCutMultiSourceAppearanceCases = ids => runSectionCutToolColorCases(ids, true, true, true, true); +export const runSectionCutSourceInheritanceCases = ids => runSectionCutToolColorCases(ids, false, false, false, false, true); + +export async function runSectionCutToolColorCases(ids, faceAlpha = false, fragmentColor = false, fragmentAlpha = false, multiSource = false, sourceInheritance = false) { + const capabilityId = "Part:desktop:Part_SectionCut"; + if (!ids.includes(capabilityId)) return []; + const directory = path.resolve(sourceInheritance ? "docs/current/part-section-cut-source-inheritance" : multiSource ? "docs/current/part-section-cut-multi-source-appearance" : fragmentAlpha ? "docs/current/part-section-cut-fragment-transparency" : fragmentColor ? "docs/current/part-section-cut-fragment-color" : faceAlpha ? "docs/current/part-section-cut-face-alpha" : "docs/current/part-section-cut-tool-colors", new Date().toISOString().replace(/[:.]/g, "-")); + fs.mkdirSync(directory, { recursive: true }); + const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {}, + deferredCases: ["runSectionCutContainerCases", "runLegacySectionCutCases", "runSectionCutEmptySourcesCases", + "runSectionCutFragmentsCases", "runSectionCutOpacityCases", "runSectionCutPersistenceCases", + ...(sourceInheritance ? ["runSectionCutCompoundHistoryCases", "runSectionCutMultiSourceAppearanceCases"] : [])], + remaining: [sourceInheritance ? "Curved and transformed BooleanFragments source material coverage; desktop automatic color controls" : multiSource ? "Source face material inheritance in BooleanFragments" : fragmentAlpha ? "BooleanFragments appearance with multiple intersecting sources; source face material inheritance" : faceAlpha ? "Fragment color/transparency and desktop cut/fragment appearance interaction" : "Independent cut-face and fragment appearance/transparency", + "Container reparenting", "Unexpected post-mutation failure history behavior"] }; + const started = performance.now(); + const stages = []; + const stage = name => { + stages.push({ name, elapsedMs: performance.now() - started }); + fs.writeFileSync(path.join(directory, "stages.json"), JSON.stringify(stages, null, 2) + "\n"); + process.stderr.write(`Section cut tool colors: ${name}\n`); + }; + const record = (input, actual, name) => result.cases.push({ input, actual, assertions: [{ name, passed: true }] }); + let browser; + try { + for (const file of ["tools/part-section-cut-container-business-cases.mjs", "tools/part-section-cut-business-cases.mjs", + "web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts", + "web/src/workbench-shell.tsx", "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartColoredIO.h", + "web/src/scene-viewport.tsx", "freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp", + "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h", + ...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)]) + result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + stage("browser-launch-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 } }); + const errors = []; page.on("pageerror", error => errors.push(String(error))); + const documentId = "SectionCutToolColors"; + await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`); + const run = async (args, expectError = false) => { + stage(`request-${args.action}-enter`); + await page.locator("aside > button.command").filter({ has: page.getByText("part.document", { exact: true }) }).click(); + await page.locator("#payload-editor").fill(JSON.stringify({ schema: "freecad-web-part/document/v1", module: "Part", + document: documentId, builderInfo: true, includeMesh: true, ...args })); + await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; }); + await page.getByRole("button", { name: "执行选中命令", exact: true }).click(); + await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled); + const reply = await page.evaluate(() => window.__freecadWorkbenchState.response); + assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply)); + stage(`request-${args.action}-complete`); + return expectError ? reply.error : reply.result; + }; + if (sourceInheritance) { + await assertSourceInheritance({ page, run, record, stage, directory, result, documentId }); + assert.deepEqual(errors, []); + } else if (multiSource) { + await assertMultiSourceAppearance({ page, run, record, stage, directory, result }); + assert.deepEqual(errors, []); + } else { + await run({ action: "create" }); + await run({ action: "setBox", object: "Box", dimensions: [10,10,10] }); + await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click(); + const panel = page.getByRole("region", { name: "Section cutting", exact: true }); + const ready = () => page.waitForFunction(() => { + const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled; + }); + await ready(); + await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check(); + await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("5"); + await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00"); + if (faceAlpha) await panel.getByLabel("Cut face transparency", { exact: true }).fill("65"); + if (fragmentColor) { + await panel.getByLabel("Custom fragment color", { exact: true }).check(); + await panel.getByLabel("Fragment color", { exact: true }).fill("#ffff00"); + } + if (fragmentAlpha) await panel.getByLabel("Fragment transparency", { exact: true }).fill("60"); + await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready(); + assert.deepEqual(await panel.getByRole("status").allTextContents(), []); + const initial = await run({ action: "snapshot" }); + const session = state => state.objects.find(item => item.sectionCutSession).sectionCutSession; + const cut = state => state.objects.find(item => item.name === session(state).result); + const tool = initial.objects.find(item => item.type === "Part::Box" && item.name.startsWith("SectionCutBox")); + assert.ok(tool); assert.equal(initial.objects.find(item => item.name === "Box").faceColors?.length ?? 0, 0); + const green = [0,1,0,faceAlpha ? 0.35 : 1], red = [1,0,0,faceAlpha ? 0.7 : 1]; + const baseAlpha = fragmentAlpha ? 0.4 : 1; + const check = (state, color, volume) => { + const output = cut(state); + assert.ok(Math.abs(output.volume - volume) < 1e-6); assert.equal(output.topology.valid, true); + assert.equal(output.faceColors.length, 6); + const matches = value => value.slice(0,3).every((channel, i) => Math.abs(channel - color[i]) < 1e-6); + assert.equal(output.faceColors.filter(matches).length, 1, "Only the new section face inherits the cutter color"); + const expectedBase = fragmentColor ? [1, 1, 0] : [0.8, 0.8, 0.8]; + for (const value of output.faceColors.filter(value => !matches(value))) + value.slice(0,3).forEach((channel, i) => assert.ok(Math.abs(channel - expectedBase[i]) < 1e-6, "Surviving source faces retain the selected fragment material")); + assert.equal(output.mesh.colors.length, output.mesh.triangleCount * 9); + const rgb = output.mesh.colors; + const coloredVertices = Array.from({ length: rgb.length / 3 }, (_, i) => rgb.slice(i * 3, i * 3 + 3)).filter(matches).length; + assert.equal(coloredVertices, 6, "Two native cut-face triangles carry the tool material"); + if (faceAlpha) { + const near = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`); + output.faceColors.forEach(value => near(value[3], matches(value) ? color[3] : baseAlpha)); + assert.equal(output.mesh.alphas.length, output.mesh.triangleCount * 3); + output.mesh.alphas.forEach((alpha, i) => near(alpha, matches(rgb.slice(i * 3, i * 3 + 3)) ? color[3] : baseAlpha)); + assert.equal(output.displayOpacity, 1, "Cut transparency does not fade surviving source faces"); + } + return { volume: output.volume, faceColors: output.faceColors, coloredVertices }; + }; + const setColor = color => run({ action: "setFaceColors", selection: [{ documentId, object: tool.name }], + faceColors: Array.from({ length: tool.topology.Face }, () => color) }); + const colored = initial; + assert.equal(session(colored).cutColor, "#00ff00"); + if (fragmentColor) assert.equal(session(colored).fragmentColor, "#ffff00"); + if (fragmentAlpha) assert.equal(session(colored).fragmentTransparency, 60); + if (faceAlpha) assert.equal(session(colored).cutTransparency, 65); + fs.writeFileSync(path.join(directory, "colored.json"), JSON.stringify(colored, null, 2) + "\n"); + record({ source: "uncolored Box", planeX: 5, toolColor: green }, check(colored, green, 500), + "Native Boolean history separates the generated cut-face material from the five surviving source faces"); + const recolored = await setColor(red); check(recolored, red, 500); + const undone = await run({ action: "undo" }); check(undone, green, 500); + const failure = await run({ action: "sectionCut", sectionCut: { operation: "apply", cutColor: "not-a-color" } }, true); + assert.match(failure.message, /six-digit RGB/); + const afterFailure = await run({ action: "snapshot" }); + assert.deepEqual(afterFailure.objects, undone.objects); + assert.equal(afterFailure.undoCount, undone.undoCount); assert.equal(afterFailure.redoCount, undone.redoCount); + if (fragmentColor) { + for (const value of ["red", "#12345g", 123, null, true]) { + const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", fragmentColor: value } }, true); + assert.match(rejected.message, /Fragment color/); + const preserved = await run({ action: "snapshot" }); + assert.deepEqual(preserved.objects, undone.objects); + assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount); + } + } + if (faceAlpha) { + for (const cutTransparency of [-1, 101, 0.5, "50", true]) { + const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", cutTransparency } }, true); + assert.match(rejected.message, /Cut face transparency/); + const preserved = await run({ action: "snapshot" }); + assert.deepEqual(preserved.objects, undone.objects); + assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount); + } + } + if (fragmentAlpha) { + for (const fragmentTransparency of [-1, 101, 0.5, "60", true, null]) { + const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", fragmentTransparency } }, true); + assert.match(rejected.message, /Fragment transparency/); + const preserved = await run({ action: "snapshot" }); + assert.deepEqual(preserved.objects, undone.objects); + assert.equal(preserved.undoCount, undone.undoCount); assert.equal(preserved.redoCount, undone.redoCount); + } + } + check(await run({ action: "redo" }), red, 500); + const edited = await run({ action: "setBox", object: "Box", dimensions: [10,10,12] }); + record({ toolColor: red, sourceDimensions: [10,10,12], operations: ["recolor", "undo", "redo", "source edit"] }, + check(edited, red, 600), "Tool material follows native history through color history and source recompute"); + await run({ action: "save", path: "/tmp/SectionCutToolColors.FCStd" }); await run({ action: "close" }); + const reopened = await run({ action: "open", path: "/tmp/SectionCutToolColors.FCStd" }); + assert.equal(session(reopened).cutColor, "#00ff00"); + if (fragmentColor) assert.equal(session(reopened).fragmentColor, "#ffff00"); + if (fragmentAlpha) assert.equal(session(reopened).fragmentTransparency, 60); + if (faceAlpha) assert.equal(session(reopened).cutTransparency, 65); + // FCStd packs App::PropertyColorList channels into eight-bit RGBA values. + const savedRed = faceAlpha ? red.map(channel => Math.round(channel * 255) / 255) : red; + record({ operation: "save-close-open", expectedStoredColor: savedRed }, check(reopened, savedRed, 600), + "FCStd restores packed native tool material and recomputed face-history mapping"); + await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready(); + assert.equal(await panel.getByLabel("Cut face color", { exact: true }).inputValue(), "#00ff00"); + if (fragmentColor) { + assert.equal(await panel.getByLabel("Custom fragment color", { exact: true }).isChecked(), true); + assert.equal(await panel.getByLabel("Fragment color", { exact: true }).inputValue(), "#ffff00"); + } + if (faceAlpha) assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "65"); + if (fragmentAlpha) assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60"); + await panel.getByLabel("Cut face color", { exact: true }).fill("#0000ff"); + await panel.getByRole("checkbox", { name: "Cut Y", exact: true }).check(); + await panel.getByRole("spinbutton", { name: "Cut Y position", exact: true }).fill("4"); + await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready(); + const twoAxes = await run({ action: "snapshot" }); + const blueFaces = cut(twoAxes).faceColors.filter(color => color[0] === 0 && color[1] === 0 && color[2] === 1); + assert.equal(blueFaces.length, 2, "Both sequential cut faces receive the chosen material through native history"); + if (faceAlpha) { + assert.ok(blueFaces.every(color => Math.abs(color[3] - 0.35) < 1e-6)); + assert.equal(cut(twoAxes).mesh.alphas.filter(alpha => Math.abs(alpha - 0.35) < 1e-6).length, 12); + assert.equal(cut(twoAxes).mesh.alphas.filter(alpha => Math.abs(alpha - baseAlpha) < 1e-6).length, 24); + } + assert.equal(cut(twoAxes).faceColors.length, 6); assert.ok(Math.abs(cut(twoAxes).volume - 240) < 1e-6); + assert.equal(session(twoAxes).cutColor, "#0000ff"); + await panel.getByRole("button", { name: "Refresh cut sources", exact: true }).click(); await ready(); + const refreshed = await run({ action: "snapshot" }); + assert.deepEqual(cut(refreshed).faceColors, cut(twoAxes).faceColors); + assert.equal(session(refreshed).cutColor, "#0000ff"); + if (fragmentColor) { + assert.equal(session(refreshed).fragmentColor, "#ffff00"); + assert.equal(cut(refreshed).faceColors.filter(color => color[0] === 1 && color[1] === 1 && color[2] === 0 && Math.abs(color[3] - baseAlpha) < 1e-6).length, 4); + assert.equal(refreshed.objects.find(item => item.name === "Box").faceColors?.length ?? 0, 0); + } + if (faceAlpha) assert.equal(session(refreshed).cutTransparency, 65); + if (fragmentAlpha) assert.equal(session(refreshed).fragmentTransparency, 60); + record({ operation: "mounted color change and source refresh", axes: ["X=5", "Y=4"], cutColor: "#0000ff" }, + { faceColors: cut(refreshed).faceColors, volume: cut(refreshed).volume }, + "Mounted color control restores native session state and colors both sequential section faces across refresh"); + await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready(); + assert.deepEqual(await panel.getByRole("status").allTextContents(), []); + const pixels = []; + for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: 900 }); + const canvas = panel.locator("canvas").first(); await canvas.waitFor(); + await page.waitForTimeout(300); + const imageFile = path.join(directory, `tool-color-canvas-${width}.png`); + const bytes = await canvas.screenshot({ path: imageFile }); + const bluePixels = await page.evaluate(async data => { + const img = new Image(); img.src = `data:image/png;base64,${data}`; await img.decode(); + const target = document.createElement("canvas"); target.width = img.width; target.height = img.height; + const context = target.getContext("2d"); context.drawImage(img, 0, 0); + const rgba = context.getImageData(0, 0, target.width, target.height).data; + let blue = 0; + for (let i = 0; i < rgba.length; i += 4) + if (rgba[i + 2] > 40 && rgba[i + 2] > rgba[i] * 1.4 && rgba[i + 2] > rgba[i + 1] * 1.4) ++blue; + return blue; + }, bytes.toString("base64")); + assert.ok(bluePixels > 30, `Native blue cut faces must render at width ${width}: ${bluePixels}`); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + pixels.push({ width, bluePixels }); + result.evidenceFiles[path.relative(process.cwd(), imageFile)] = createHash("sha256").update(bytes).digest("hex"); + if (fragmentAlpha) { + await panel.getByLabel("Fragment transparency", { exact: true }).fill("100"); + await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready(); + const hidden = await run({ action: "snapshot" }); + const isBlue = color => color[0] === 0 && color[1] === 0 && color[2] === 1; + assert.equal(session(hidden).fragmentTransparency, 100); + assert.equal(cut(hidden).faceColors.filter(color => !isBlue(color) && color[3] === 0).length, 4); + assert.equal(cut(hidden).faceColors.filter(color => isBlue(color) && Math.abs(color[3] - 0.35) < 1e-6).length, 2); + assert.ok(Math.abs(cut(hidden).volume - 240) < 1e-6); + await page.waitForTimeout(300); + const file = path.join(directory, `transparent-fragment-canvas-${width}.png`); + const hiddenBytes = await canvas.screenshot({ path: file }); + const count = async data => page.evaluate(async encoded => { + const image = new Image(); image.src = `data:image/png;base64,${encoded}`; await image.decode(); + const target = document.createElement("canvas"); target.width = image.width; target.height = image.height; + const context = target.getContext("2d"); context.drawImage(image, 0, 0); + const values = context.getImageData(0, 0, target.width, target.height).data; + let blue = 0, yellow = 0; + for (let i = 0; i < values.length; i += 4) { + if (values[i + 2] > 40 && values[i + 2] > values[i] * 1.4 && values[i + 2] > values[i + 1] * 1.4) ++blue; + if (values[i] > 40 && values[i + 1] > 40 && values[i] > values[i + 2] * 1.4 && values[i + 1] > values[i + 2] * 1.4) ++yellow; + } + return { blue, yellow }; + }, data.toString("base64")); + const before = await count(bytes), after = await count(hiddenBytes); + assert.ok(before.yellow > 100, "Partially transparent fragment faces remain visible"); + assert.ok(after.yellow < before.yellow * 0.05, "Fully transparent fragments remove yellow surface pixels"); + assert.ok(after.blue > 30, "Independent blue cut faces remain visible"); + pixels.at(-1).fragments = { before, after }; + result.evidenceFiles[path.relative(process.cwd(), file)] = createHash("sha256").update(hiddenBytes).digest("hex"); + await panel.getByRole("button", { name: "Section cut undo", exact: true }).click(); await ready(); + assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60"); + } + if (faceAlpha) { + await panel.getByLabel("Cut face transparency", { exact: true }).fill("100"); + await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready(); + await page.waitForTimeout(300); + const clearFile = path.join(directory, `transparent-cut-canvas-${width}.png`); + const clearBytes = await canvas.screenshot({ path: clearFile }); + const clearPixels = await page.evaluate(async data => { + const image = new Image(); image.src = `data:image/png;base64,${data}`; await image.decode(); + const target = document.createElement("canvas"); target.width = image.width; target.height = image.height; + const context = target.getContext("2d"); context.drawImage(image, 0, 0); + const values = context.getImageData(0, 0, target.width, target.height).data; + let blue = 0, geometry = 0, yellow = 0; + for (let i = 0; i < values.length; i += 4) { + if (values[i + 2] > 40 && values[i + 2] > values[i] * 1.4 && values[i + 2] > values[i + 1] * 1.4) ++blue; + if (Math.max(...values.slice(i, i + 3)) - Math.min(...values.slice(i, i + 3)) < 12 && values[i] < 225) ++geometry; + if (values[i] > 40 && values[i + 1] > 40 && values[i] > values[i + 2] * 1.4 && values[i + 1] > values[i + 2] * 1.4) ++yellow; + } + return { blue, geometry, yellow }; + }, clearBytes.toString("base64")); + assert.ok(clearPixels.blue < bluePixels * 0.05, "Fully transparent cut faces remove the blue pixels"); + assert.ok((fragmentColor ? clearPixels.yellow : clearPixels.geometry) > 100, "Fragment faces remain rendered behind transparent cuts"); + assert.notEqual(createHash("sha256").update(clearBytes).digest("hex"), createHash("sha256").update(bytes).digest("hex")); + result.evidenceFiles[path.relative(process.cwd(), clearFile)] = createHash("sha256").update(clearBytes).digest("hex"); + pixels.at(-1).transparent = clearPixels; + const panelFile = path.join(directory, `section-cut-panel-${width}.png`); + const panelBytes = await panel.screenshot({ path: panelFile }); + result.evidenceFiles[path.relative(process.cwd(), panelFile)] = createHash("sha256").update(panelBytes).digest("hex"); + await canvas.scrollIntoViewIfNeeded(); + const bounds = await canvas.boundingBox(); assert.ok(bounds); + await page.mouse.move(bounds.x + bounds.width / 2, bounds.y + bounds.height / 2); + await page.mouse.down(); + await page.mouse.move(bounds.x + bounds.width / 2 + 40, bounds.y + bounds.height / 2 + 20, { steps: 8 }); + await page.mouse.up(); await page.waitForTimeout(200); + const orbitFile = path.join(directory, `transparent-cut-orbit-${width}.png`); + const orbitBytes = await canvas.screenshot({ path: orbitFile }); + const orbitHash = createHash("sha256").update(orbitBytes).digest("hex"); + assert.notEqual(orbitHash, createHash("sha256").update(clearBytes).digest("hex"), "Native transparent mesh responds to orbit"); + result.evidenceFiles[path.relative(process.cwd(), orbitFile)] = orbitHash; + pixels.at(-1).orbitChanged = true; + await panel.getByRole("button", { name: "Section cut undo", exact: true }).click(); await ready(); + assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "65"); + } + } + record({ operation: "render native face colors", widths: [1440, 390] }, pixels, + "Chosen cut-face color is visible in desktop and mobile native-mesh canvases without horizontal overflow"); + if (faceAlpha) record({ cutTransparency: [65, 100], editedToolAlpha: 0.7, sourceAlpha: baseAlpha, + operations: ["apply", "undo", "redo", "invalid native values", "edit source", "FCStd reopen", "sequential cuts", "refresh"] }, + { pixels, fragmentAlpha: baseAlpha }, "Independent native face alpha survives history and persistence and changes actual desktop/mobile pixels"); + assert.deepEqual(errors, []); + if (fragmentColor) { + await panel.getByLabel("Custom fragment color", { exact: true }).uncheck(); + await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready(); + const automatic = await run({ action: "snapshot" }); + assert.equal(session(automatic).fragmentColor, ""); + assert.equal(cut(automatic).faceColors.filter(color => color.slice(0, 3).every(channel => Math.abs(channel - 0.8) < 1e-6)).length, 4); + assert.equal(cut(automatic).faceColors.filter(color => color[2] === 1 && Math.abs(color[3] - 0.35) < 1e-6).length, 2); + const restored = await run({ action: "undo" }); + assert.equal(session(restored).fragmentColor, "#ffff00"); + assert.equal(cut(restored).faceColors.filter(color => color[0] === 1 && color[1] === 1 && color[2] === 0).length, 4); + assert.equal(session(await run({ action: "redo" })).fragmentColor, ""); + record({ fragmentColor: "#ffff00", cutColor: "#0000ff", cutTransparency: 65, reset: "source appearance" }, + { pixels, sourceUnmodified: true, automaticFaces: cut(automatic).faceColors }, + "Mounted fragment color changes only surviving source faces, persists through refresh and FCStd, and resets with undo/redo"); + } + if (fragmentAlpha) { + const minimum = await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(refreshed).axes, cutTransparency: 0 } }); + assert.equal(session(minimum).cutTransparency, 1); + assert.equal(session(minimum).fragmentTransparency, 60); + const blue = color => color[0] === 0 && color[1] === 0 && color[2] === 1; + assert.equal(cut(minimum).faceColors.filter(blue).length, 2); + cut(minimum).faceColors.forEach(color => assert.ok(Math.abs(color[3] - (blue(color) ? 0.99 : 0.4)) < 1e-6)); + await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready(); + assert.equal(await panel.getByLabel("Cut face transparency", { exact: true }).inputValue(), "1"); + const input = panel.getByLabel("Fragment transparency", { exact: true }); + await input.fill(""); + assert.equal(await panel.getByRole("button", { name: "Apply section cut", exact: true }).isDisabled(), true); + await panel.getByRole("button", { name: "Refresh section cut", exact: true }).click(); await ready(); + assert.equal(await input.inputValue(), "60"); + await input.fill("0"); + await panel.getByLabel("Cut face transparency", { exact: true }).fill("0"); + await panel.getByRole("button", { name: "Apply section cut", exact: true }).click(); await ready(); + const opaque = await run({ action: "snapshot" }); + assert.equal(session(opaque).fragmentTransparency, 0); assert.equal(session(opaque).cutTransparency, 0); + assert.ok(cut(opaque).faceColors.every(color => color[3] === 1)); + const undo = await run({ action: "undo" }); + assert.deepEqual(cut(undo).faceColors, cut(minimum).faceColors); + assert.deepEqual(cut(await run({ action: "redo" })).faceColors, cut(opaque).faceColors); + record({ fragmentTransparency: [60, 0], cutTransparency: 0, operations: ["minimum", "invalid UI", "undo", "redo"] }, + { minimum: cut(minimum).faceColors, opaque: cut(opaque).faceColors }, + "Transparent fragments enforce the desktop one-percent cut minimum; clearing transparency restores opaque faces through history"); + } + } + result.status = "not_implemented"; + stage("assertions-complete"); + } catch (error) { result.error = error.stack ?? String(error); stage("failed"); } + finally { await browser?.close(); stage("cleanup-complete"); } + fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n"); + return [result]; +} + +async function assertSourceInheritance({ page, run, record, stage, directory, result, documentId }) { + await run({ action: "create" }); + await run({ action: "setBox", object: "Box", dimensions: [10,8,10] }); + await run({ action: "setBox", object: "CrossingBox", dimensions: [8,10,10] }); + const setColor = (object, color) => run({ action: "setFaceColors", selection: [{ documentId, object }], + faceColors: Array.from({ length: 6 }, () => color) }); + await setColor("Box", [1,0,0,1]); + await setColor("CrossingBox", [0,0,1,1]); + await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click(); + const panel = page.getByRole("region", { name: "Section cutting", exact: true }); + const ready = () => page.waitForFunction(() => { + const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); + return fieldset && !fieldset.disabled; + }); + const click = async name => { await panel.getByRole("button", { name, exact: true }).click(); await ready(); }; + await ready(); + await panel.getByLabel("Intersecting objects", { exact: true }).check(); + await panel.getByLabel("Cut Z", { exact: true }).check(); + await panel.getByLabel("Cut Z position", { exact: true }).fill("5"); + await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00"); + await panel.getByLabel("Custom fragment color", { exact: true }).uncheck(); + await click("Apply section cut"); + assert.deepEqual(await panel.getByRole("status").allTextContents(), [], "Mounted Section Cut apply must succeed"); + const check = (state, firstColor = [1,0,0], height = 5) => { + const session = state.objects.find(item => item.sectionCutSession)?.sectionCutSession; + assert.ok(session, JSON.stringify(state)); + const output = state.objects.find(item => item.name === session.result); + assert.equal(session.fragmentColor, ""); + assert.equal(output.topology.valid, true); + assert.ok(Math.abs(output.volume - 96 * height) < 1e-6); + const fragments = state.objects.find(item => item.name.startsWith("SectionCutCompound")); + assert.equal(fragments.topology.Solid, 3); + assert.ok(fragments.mesh.triangleCount > fragments.faceColors.length * 2, + "Fixture exercises repeated shared rectangular faces, not just disjoint solids"); + const { positions, colors, alphas, triangleCount } = output.mesh; + assert.equal(colors.length, triangleCount * 9); + assert.equal(alphas.length, triangleCount * 3); + let red = 0, blue = 0, green = 0; + for (let t = 0; t < triangleCount; ++t) { + const vertices = [0,3,6].map(v => positions.slice(t * 9 + v, t * 9 + v + 3)); + const section = vertices.every(v => Math.abs(v[2] - height) < 1e-6); + // Exterior x=10 belongs only to Box; y=10 only to CrossingBox. + const onlyFirst = vertices.every(v => Math.abs(v[0] - 10) < 1e-6); + const onlySecond = vertices.every(v => Math.abs(v[1] - 10) < 1e-6); + const rgb = colors.slice(t * 9, t * 9 + 3); + const expected = section ? [0,1,0] : onlyFirst ? firstColor : onlySecond ? [0,0,1] : null; + if (expected) assert.deepEqual(rgb, expected, JSON.stringify({ vertices, rgb, expected })); + else assert.ok([firstColor, [0,0,1]].some(c => c.every((v,i) => v === rgb[i])), JSON.stringify({vertices,rgb})); + for (let v = 0; v < 3; ++v) { + assert.deepEqual(colors.slice(t * 9 + v * 3, t * 9 + v * 3 + 3), rgb); + assert.equal(alphas?.[t * 3 + v] ?? 1, 1); + } + if (section) green++; else if (rgb[2] === 1) blue++; else red++; + } + assert.ok(red > 0 && blue > 0 && green > 0, JSON.stringify({red,blue,green})); + return { volume: output.volume, red, blue, green, faceColors: output.faceColors }; + }; + const initial = check(await run({ action: "snapshot" })); + record({ sources: ["red Box", "blue CrossingBox"], cut: "green Z=5", fragmentColor: "inherited" }, initial, + "OCCT split faces inherit source materials; spatially distinct source faces and cut faces carry correct RGB"); + check(await setColor("Box", [1,1,0,1]), [1,1,0]); + check(await run({ action: "undo" })); + check(await run({ action: "redo" }), [1,1,0]); + await run({ action: "save", path: "/tmp/SectionCutSourceInheritance.FCStd" }); + await run({ action: "close" }); + check(await run({ action: "open", path: "/tmp/SectionCutSourceInheritance.FCStd" }), [1,1,0]); + await click("Refresh section cut"); + assert.equal(await panel.getByLabel("Custom fragment color", { exact: true }).isChecked(), false); + await panel.getByLabel("Cut Z position", { exact: true }).fill("4"); + await click("Apply section cut"); + check(await run({ action: "snapshot" }), [1,1,0], 4); + await click("Refresh cut sources"); + const restored = check(await run({ action: "snapshot" }), [1,1,0], 4); + record({ operations: ["live source color", "undo", "redo", "FCStd reopen", "plane edit", "source refresh"] }, restored, + "Inherited fragment colors follow current source properties and regenerated topology through native history and persistence"); + await click("Refresh section cut"); + const canvas = panel.locator("canvas").first(); + for (const width of [1440,390]) { + await page.setViewportSize({ width, height: 900 }); + await canvas.scrollIntoViewIfNeeded(); await page.waitForTimeout(300); + const file = path.join(directory, `inherited-${width}.png`); + const png = await canvas.screenshot({ path: file }); + result.evidenceFiles[file] = createHash("sha256").update(png).digest("hex"); + const pixels = await page.evaluate(async base64 => { + const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode(); + const raster = document.createElement("canvas"); raster.width = image.width; raster.height = image.height; + const ctx = raster.getContext("2d"); ctx.drawImage(image,0,0); + const data = ctx.getImageData(0,0,raster.width,raster.height).data; + let yellow = 0, blue = 0, green = 0; + for (let i=0;i data[i+2]+20 && data[i+1] > data[i+2]+20) yellow++; + if (data[i+2] > data[i]+20 && data[i+2] > data[i+1]+20) blue++; + if (data[i+1] > data[i]+20 && data[i+1] > data[i+2]+20) green++; + } + return { yellow, blue, green }; + }, png.toString("base64")); + assert.ok(pixels.yellow > 100 && pixels.blue > 100 && pixels.green > 100, JSON.stringify(pixels)); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + record({ viewport: width }, pixels, "Mounted native geometry shows both inherited materials and the independent section material"); + } + stage("source-inheritance-complete"); +} + +async function assertMultiSourceAppearance({ page, run, record, stage, directory, result }) { + await run({ action: "create" }); + await run({ action: "setBox", object: "Box", dimensions: [10, 8, 10] }); + await run({ action: "setBox", object: "CrossingBox", dimensions: [8, 10, 10] }); + await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click(); + const panel = page.getByRole("region", { name: "Section cutting", exact: true }); + const ready = () => page.waitForFunction(() => { + const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); + return fieldset && !fieldset.disabled; + }); + const click = async name => { await panel.getByRole("button", { name, exact: true }).click(); await ready(); }; + await ready(); + await panel.getByLabel("Intersecting objects", { exact: true }).check(); + await panel.getByLabel("Cut X", { exact: true }).check(); + await panel.getByLabel("Cut X position", { exact: true }).fill("5"); + await panel.getByLabel("Custom fragment color", { exact: true }).check(); + await panel.getByLabel("Fragment color", { exact: true }).fill("#ffff00"); + await panel.getByLabel("Fragment transparency", { exact: true }).fill("60"); + await panel.getByLabel("Cut face color", { exact: true }).fill("#00ff00"); + await panel.getByLabel("Cut face transparency", { exact: true }).fill("65"); + await click("Apply section cut"); + const session = state => state.objects.find(item => item.sectionCutSession).sectionCutSession; + const output = state => state.objects.find(item => item.name === session(state).result); + const near = (actual, expected) => assert.ok(Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`); + const check = (state, volume, plane, fragmentAlpha = 0.4, cutAlpha = 0.35) => { + const cut = output(state), settings = session(state); + assert.equal(settings.intersecting, true); + assert.deepEqual([...settings.sources].sort(), ["Box", "CrossingBox"]); + assert.equal(cut.topology.valid, true); near(cut.volume, volume); + const compound = state.objects.find(item => item.name.startsWith("SectionCutCompound")); + assert.equal(compound.type, "Part::FeaturePython"); + assert.equal(compound.topology.Solid, 3, "Actual BooleanFragments partition overlapping sources"); + const { positions, colors, alphas, triangleCount } = cut.mesh; + assert.equal(colors.length, triangleCount * 9); assert.equal(alphas.length, triangleCount * 3); + let sectionTriangles = 0, sourceTriangles = 0; + for (let triangle = 0; triangle < triangleCount; ++triangle) { + const start = triangle * 9; + const section = [0, 3, 6].every(offset => Math.abs(positions[start + offset] - plane) < 1e-6); + section ? ++sectionTriangles : ++sourceTriangles; + for (let vertex = 0; vertex < 3; ++vertex) { + const rgb = colors.slice(start + vertex * 3, start + vertex * 3 + 3); + assert.deepEqual(rgb, section ? [0, 1, 0] : [1, 1, 0], + JSON.stringify({ triangle, section, positions: positions.slice(start, start + 9), rgb, faceColors: cut.faceColors })); + near(alphas[triangle * 3 + vertex], section ? cutAlpha : fragmentAlpha); + } + } + assert.ok(sectionTriangles > 0 && sourceTriangles > 0); + return { volume: cut.volume, solids: compound.topology.Solid, sectionTriangles, sourceTriangles }; + }; + const initial = await run({ action: "snapshot" }); + const snapshotFile = path.join(directory, "initial-native-snapshot.json"); + fs.writeFileSync(snapshotFile, JSON.stringify(initial, null, 2) + "\n"); + result.evidenceFiles[snapshotFile] = createHash("sha256").update(fs.readFileSync(snapshotFile)).digest("hex"); + record({ boxes: [[10,8,10], [8,10,10]], cutX: 5, intersecting: true }, check(initial, 500, 5), + "Overlapping sources produce partitioned OCCT geometry and spatially correct independent cut and fragment RGBA"); + await panel.getByLabel("Cut X position", { exact: true }).fill("4"); + await click("Apply section cut"); + const changed = await run({ action: "snapshot" }); check(changed, 400, 4); + check(await run({ action: "undo" }), 500, 5); + check(await run({ action: "redo" }), 400, 4); + await run({ action: "save", path: "/tmp/SectionCutMultiSourceAppearance.FCStd" }); + await run({ action: "close" }); + const reopened = await run({ action: "open", path: "/tmp/SectionCutMultiSourceAppearance.FCStd" }); + const restoredCutAlpha = Math.round(0.35 * 255) / 255; + check(reopened, 400, 4, 0.4, restoredCutAlpha); + output(reopened).faceColors.forEach((color, face) => color.forEach((value, channel) => + near(value, Math.round(output(changed).faceColors[face][channel] * 255) / 255))); + await click("Refresh section cut"); + assert.equal(await panel.getByLabel("Intersecting objects", { exact: true }).isChecked(), true); + assert.equal(await panel.getByLabel("Fragment transparency", { exact: true }).inputValue(), "60"); + await click("Refresh cut sources"); + check(await run({ action: "snapshot" }), 400, 4); + record({ operations: ["plane edit", "undo", "redo", "FCStd reopen", "source refresh"] }, check(reopened, 400, 4, 0.4, restoredCutAlpha), + "Intersecting-source materials follow edited topology and survive transactions and FCStd restoration"); + const pixels = []; + const canvas = panel.locator("canvas").first(); + const sample = async file => { + // The renderer does not preserve its drawing buffer after composition. + // Read the visible canvas image, as the other appearance cases do. + const png = await canvas.screenshot({ path: file }); + result.evidenceFiles[file] = createHash("sha256").update(png).digest("hex"); + return page.evaluate(async base64 => { + const image = new Image(); image.src = `data:image/png;base64,${base64}`; await image.decode(); + const raster = document.createElement("canvas"); raster.width = image.width; raster.height = image.height; + const ctx = raster.getContext("2d"); ctx.drawImage(image, 0, 0); + const bytes = ctx.getImageData(0, 0, raster.width, raster.height).data; + let yellow = 0, green = 0; + for (let i = 0; i < bytes.length; i += 4) { + if (bytes[i] > bytes[i+2] + 20 && bytes[i+1] > bytes[i+2] + 20) ++yellow; + if (bytes[i+1] > bytes[i] + 20 && bytes[i+1] > bytes[i+2] + 20) ++green; + } + return { yellow, green }; + }, png.toString("base64")); + }; + for (const width of [1440, 390]) { + await page.setViewportSize({ width, height: 900 }); await canvas.scrollIntoViewIfNeeded(); + await page.waitForTimeout(500); + const file = path.join(directory, `multi-source-${width}.png`); + const before = await sample(file); assert.ok(before.yellow > 100); assert.ok(before.green > 100); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); + await panel.getByLabel("Fragment transparency", { exact: true }).fill("100"); + await click("Apply section cut"); check(await run({ action: "snapshot" }), 400, 4, 0); + await canvas.scrollIntoViewIfNeeded(); await page.waitForTimeout(500); + const after = await sample(path.join(directory, `multi-source-hidden-${width}.png`)); + assert.ok(after.yellow < before.yellow * 0.05); assert.ok(after.green > 100); + pixels.push({ width, before, after }); + await panel.getByLabel("Fragment transparency", { exact: true }).fill("60"); + await click("Apply section cut"); + } + record({ widths: [1440,390], fragmentTransparency: [60,100] }, pixels, + "Actual desktop/mobile canvases hide transparent BooleanFragments surfaces while retaining independent cut faces"); + stage("multi-source-appearance-complete"); +} + +export async function runSectionCutContainerCases(ids) { + const capabilityId = "Part:desktop:Part_SectionCut"; + if (!ids.includes(capabilityId)) return []; + const directory = path.resolve("docs/current/part-section-cut-containers", new Date().toISOString().replace(/[:.]/g, "-")); + fs.mkdirSync(directory, { recursive: true }); + const started = performance.now(); + const stages = []; + const stage = (name, detail = {}) => { + stages.push({ name, elapsedMs: performance.now() - started, ...detail }); + fs.writeFileSync(path.join(directory, "stages.json"), JSON.stringify(stages, null, 2) + "\n"); + }; + const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {}, + deferredCases: ["runLegacySectionCutCases", "runSectionCutEmptySourcesCases", "runSectionCutFragmentsCases", "runSectionCutOpacityCases", "runSectionCutPersistenceCases"], + remaining: ["Automatic cut-face coloring and color controls", "Independent cut-face and fragment appearance/transparency", + "Container reparenting", "Unexpected post-mutation failure history behavior"] }; + const record = (input, actual, name) => { + result.cases.push({ input, actual, assertions: [{ name, passed: true }] }); + fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n"); + }; + const session = state => state.objects.find(item => item.sectionCutSession)?.sectionCutSession; + const objects = state => Object.fromEntries(state.objects.map(item => [item.name, item])); + const signature = state => ({ objects: objects(state), undoCount: state.undoCount, redoCount: state.redoCount }); + const near = (actual, expected) => assert.ok(Number.isFinite(actual) && Math.abs(actual - expected) < 1e-6, `${actual} != ${expected}`); + const check = (state, bounds, volume) => { + const cut = state.objects.find(item => item.name === session(state)?.result); + assert.ok(cut); near(cut.volume, volume); assert.equal(cut.topology.valid, true); + assert.ok(cut.mesh.triangleCount > 0); cut.mesh.bounds.forEach((value, i) => near(value, bounds[i])); + assert.equal(cut.faceColors?.length, 6, "Cut retains a material for each native face after edits/history/reopen"); + assert.ok(new Set(cut.faceColors.map(color => color.join(","))).size >= 5, + "Five distinct surviving source materials persist through geometry edits, history and FCStd reopen"); + assert.equal(cut.mesh.colors?.length, cut.mesh.triangleCount * 9, "Native face materials reach every rendered vertex"); + assert.deepEqual(session(state).sources, ["Box"]); + return { bounds: cut.mesh.bounds, volume: cut.volume, triangles: cut.mesh.triangleCount }; + }; + const sameNativeResult = (state, expected, bounds, volume) => { + assert.deepEqual(state.objects.map(item => item.name).sort(), expected.objects.map(item => item.name).sort()); + assert.equal(session(state).result, session(expected).result); + return check(state, bounds, volume); + }; + let browser; + try { + for (const file of ["tools/part-section-cut-container-business-cases.mjs", "tools/part-section-cut-business-cases.mjs", + "web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts", + "web/src/part-view-facade.ts", "web/src/workbench-shell.tsx", + "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h", + "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartColoredIO.h", + ...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)]) + result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + stage("browser-launch-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"] }); + stage("browser-launch-complete"); + const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); + const errors = []; page.on("pageerror", error => errors.push(String(error))); + const documentId = "SectionCutContainers"; + await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`); + const dispatch = async (command, payload, expectError = false) => { + stage("request-enter", { command, action: payload.action ?? payload.parameters?.operation }); + await page.locator("aside > button.command").filter({ has: page.getByText(command, { exact: true }) }).click(); + await page.locator("#payload-editor").fill(JSON.stringify(payload)); + await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; }); + await page.getByRole("button", { name: "执行选中命令", exact: true }).click(); + await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled); + const reply = await page.evaluate(() => window.__freecadWorkbenchState.response); + assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply)); + stage("request-complete", { command, action: payload.action ?? payload.parameters?.operation, kind: reply.kind }); + return expectError ? reply.error : reply.result; + }; + const run = (args, expectError = false) => dispatch("part.document", { schema: "freecad-web-part/document/v1", module: "Part", + document: documentId, builderInfo: true, includeMesh: true, ...args }, expectError); + const python = async source => { + const reply = await dispatch("part.documentViewCommand", { schema: "freecad-web/document-view/v1", owner: "DocumentProbe", + document: documentId, command: "Std_CommandLine", parameters: { operation: "submit", source: `exec(${JSON.stringify(source)})` } }); + assert.equal(reply.stderr, "", JSON.stringify(reply)); + }; + const snapshot = () => run({ action: "snapshot" }); + await run({ action: "create" }); + await python(`import FreeCAD as App\nd=App.getDocument('${documentId}')\np=d.addObject('App::Part','Outer')\nn=d.addObject('App::Part','Inner')\np.addObject(n)\nb=d.addObject('Part::Box','Box')\nb.Length=2\nb.Width=4\nb.Height=6\nn.addObject(b)\np.Placement=App.Placement(App.Vector(20,30,40),App.Rotation(App.Vector(0,0,1),90))\nn.Placement.Base=App.Vector(3,0,0)\nb.Placement.Base=App.Vector(1,0,0)\nd.recompute()`); + const palette = [[1,0,0,1],[0,1,0,1],[0,0,1,1],[1,1,0,1],[1,0,1,1],[0,1,1,1]]; + await python(`b.addProperty('App::PropertyColorList','WebFaceColors')\nb.WebFaceColors=[tuple(float(x) for x in color) for color in ${JSON.stringify(palette)}]\nd.recompute()`); + const before = await snapshot(); + const source = objects(before).Box; source.mesh.bounds.forEach((v, i) => near(v, [16,34,40,20,36,46][i])); + const other = await run({ action: "create", document: "ContainerCutOther" }); await snapshot(); + await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click(); + const panel = page.getByRole("region", { name: "Section cutting", exact: true }); + const ready = () => page.waitForFunction(() => { + const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled; + }); + const click = async name => { + stage("panel-request-enter", { button: name }); + await panel.getByRole("button", { name, exact: true }).click(); await ready(); + assert.deepEqual(await panel.getByRole("status").allTextContents(), []); + stage("panel-request-complete", { button: name }); + }; + await ready(); await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check(); + await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("18"); + await click("Apply section cut"); const first = await snapshot(); + const firstGeometry = check(first, [16,34,40,18,36,46], 24); + const firstCut = objects(first)[session(first).result]; + // Under the parent's Z rotation, the blue source Y-min face is the + // removed world X-max face. All five other source planes survive. + const faceRgb = firstCut.faceColors.map(color => color.slice(0, 3).join(",")); + for (const color of [palette[0], palette[1], palette[3], palette[4], palette[5]]) + assert.ok(faceRgb.includes(color.slice(0,3).join(",")), `Surviving source face lost material ${color}`); + assert.ok(!faceRgb.includes("0,0,1"), "Removed source face cannot color the result"); + const vertexColors = new Set(Array.from({ length: firstCut.mesh.colors.length / 3 }, + (_, i) => firstCut.mesh.colors.slice(i * 3, i * 3 + 3).join(","))); + assert.deepEqual([...vertexColors].sort(), [...new Set(faceRgb)].sort()); + await python("d.openTransaction('Edit section source colors')\nb.WebFaceColors=[(0.25,0.5,0.75,1)]\nd.recompute()\nd.commitTransaction()"); + const recolored = await snapshot(); + const recoloredCut = objects(recolored)[session(recolored).result]; + assert.deepEqual(recoloredCut.faceColors, Array.from({ length: 6 }, () => [0.25,0.5,0.75,1])); + assert.deepEqual(recolored.objects.map(item => item.name), first.objects.map(item => item.name)); + assert.deepEqual(recoloredCut.mesh.colors, Array.from({ length: recoloredCut.mesh.triangleCount * 3 }, () => [0.25,0.5,0.75]).flat()); + const colorUndo = await run({ action: "undo" }); + assert.deepEqual(objects(colorUndo)[session(colorUndo).result].faceColors, firstCut.faceColors); + const colorRedo = await run({ action: "redo" }); + assert.deepEqual(objects(colorRedo)[session(colorRedo).result].faceColors, recoloredCut.faceColors); + await run({ action: "undo" }); + record({ operation: "inherit six source face colors through rotated link, compound and cut; edit and undo/redo colors" }, + { faceColors: firstCut.faceColors, renderedVertexColors: [...vertexColors], liveColorEdit: true }, + "Native face history preserves surviving source materials and current colors reach browser mesh without rebuilding helpers"); + assert.deepEqual(objects(first).Outer, objects(before).Outer); assert.deepEqual(objects(first).Inner, objects(before).Inner); + const link = first.objects.find(item => item.type === "App::Link"); + link.mesh.bounds.forEach((v, i) => near(v, source.mesh.bounds[i])); + await click("Section cut undo"); assert.deepEqual(objects(await snapshot()), objects(before)); + await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(first)); + record({ outer: { position: [20,30,40], rotationZ: 90 }, inner: [3,0,0], source: [1,0,0], planeX: 18 }, firstGeometry, + "Nested container rotation and translation reach the native cut link and world-space plane without changing source membership"); + + await python("d.openTransaction('Move outer')\np.Placement.Base=App.Vector(21,30,40)\nd.recompute()\nd.commitTransaction()"); + const automatic = await snapshot(); check(automatic, [17,34,40,18,36,46], 12); + assert.deepEqual(automatic.objects.map(item => item.name).sort(), first.objects.map(item => item.name).sort()); + assert.equal(session(automatic).result, session(first).result); + await click("Section cut undo"); check(await snapshot(), [16,34,40,18,36,46], 24); + await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(automatic)); + record({ operation: "move ancestor and recompute without sources refresh" }, check(automatic, [17,34,40,18,36,46], 12), + "Ancestor placement changes recompute the existing native cut, with undo/redo and stable helper identity"); + await click("Refresh cut sources"); const moved = await snapshot(); check(moved, [17,34,40,18,36,46], 12); + await click("Section cut undo"); check(await snapshot(), [17,34,40,18,36,46], 12); + await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(moved)); + await run({ action: "setPosition", object: "Box", position: [2,0,0] }); + const edited = await snapshot(); check(edited, [17,35,40,18,37,46], 12); + await click("Section cut undo"); const stable = await snapshot(); check(stable, [17,34,40,18,36,46], 12); + assert.ok(stable.redoCount > 0); + const rejected = await run({ action: "sectionCut", sectionCut: { operation: "apply", + axes: session(stable).axes.map((axis, i) => i ? axis : { ...axis, position: 1 }) } }, true); + assert.match(rejected.message, /outside source bounds/); assert.deepEqual(signature(await snapshot()), signature(stable)); + await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(edited)); + record({ operation: "move ancestor, refresh, edit source, reject local-space plane, redo" }, { volumes: [24,12], redoPreserved: true }, + "Refresh preserves ancestor movement; linked source edits recompute in container coordinates and invalid world planes preserve redo"); + + await python("d.openTransaction('Move beyond original cutter')\np.Placement.Base=App.Vector(21,130,140)\nd.recompute()\nd.commitTransaction()"); + const distant = await snapshot(); check(distant, [17,135,140,18,137,146], 12); + assert.deepEqual(distant.objects.map(item => item.name).sort(), edited.objects.map(item => item.name).sort()); + await click("Section cut undo"); sameNativeResult(await snapshot(), edited, [17,35,40,18,37,46], 12); + await click("Section cut redo"); sameNativeResult(await snapshot(), distant, [17,135,140,18,137,146], 12); + await python("d.openTransaction('Enlarge linked source')\nb.Height=120\nd.recompute()\nd.commitTransaction()"); + const enlarged = await snapshot(); check(enlarged, [17,135,140,18,137,260], 240); + const flipped = await run({ action: "sectionCut", sectionCut: { operation: "apply", + axes: session(enlarged).axes.map((axis, i) => i ? axis : { ...axis, flipped: true }) } }); + check(flipped, [18,135,140,21,137,260], 720); + await python("d.openTransaction('Move flipped cutter bounds')\np.Placement.Base=App.Vector(21,230,240)\nd.recompute()\nd.commitTransaction()"); + const flippedMoved = await snapshot(); check(flippedMoved, [18,235,240,21,237,360], 720); + await click("Section cut undo"); sameNativeResult(await snapshot(), flipped, [18,135,140,21,137,260], 720); + await click("Section cut redo"); sameNativeResult(await snapshot(), flippedMoved, [18,235,240,21,237,360], 720); + await click("Section cut undo"); + await click("Section cut undo"); sameNativeResult(await snapshot(), enlarged, [17,135,140,18,137,260], 240); + await click("Section cut undo"); sameNativeResult(await snapshot(), distant, [17,135,140,18,137,146], 12); + await click("Section cut undo"); sameNativeResult(await snapshot(), edited, [17,35,40,18,37,46], 12); + record({ operation: "move source 100 mm in Y/Z and enlarge height to 120 without refresh", planeX: 18 }, + { moved: check(distant, [17,135,140,18,137,146], 12), enlarged: check(enlarged, [17,135,140,18,137,260], 240), + flippedMoved: check(flippedMoved, [18,235,240,21,237,360], 720) }, + "Native cutter bounds follow movement and resizing beyond original extents in both cut directions, preserving helper identity and undo/redo"); + + await run({ action: "save", path: "/tmp/SectionCutContainers.FCStd" }); await run({ action: "close" }); + const reopened = await run({ action: "open", path: "/tmp/SectionCutContainers.FCStd" }); + check(reopened, [17,35,40,18,37,46], 12); + assert.deepEqual(session(reopened), session(edited)); + assert.deepEqual(objects(reopened).Outer.groupMembers, ["Inner"]); assert.deepEqual(objects(reopened).Inner.groupMembers, ["Box"]); + await python(`d=App.getDocument('${documentId}')\nn=d.getObject('Inner')\nd.openTransaction('Rotate restored inner')\nn.Placement.Rotation=App.Rotation(App.Vector(0,0,1),90)\nd.recompute()\nd.commitTransaction()`); + const rotated = await snapshot(); check(rotated, [17,29,40,18,33,46], 24); + await click("Section cut undo"); check(await snapshot(), [17,35,40,18,37,46], 12); + await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(rotated)); + record({ operation: "rotate inner ancestor after FCStd reopen without sources refresh", rotationZ: 90 }, + check(rotated, [17,29,40,18,33,46], 24), "FCStd preserves native ancestor expression dependencies and noncommuting placement order"); + await python("p=d.getObject('Outer')\nd.openTransaction('Move restored cutter bounds')\np.Placement.Base=App.Vector(21,130,140)\nd.recompute()\nd.commitTransaction()"); + const restoredDistant = await snapshot(); check(restoredDistant, [17,129,140,18,133,146], 24); + await click("Section cut undo"); assert.deepEqual(objects(await snapshot()), objects(rotated)); + await click("Section cut redo"); assert.deepEqual(objects(await snapshot()), objects(restoredDistant)); + await click("Section cut undo"); + record({ operation: "move restored ancestor beyond original cutter extents without refresh" }, + check(restoredDistant, [17,129,140,18,133,146], 24), + "FCStd restores cutter bound expressions as live native dependencies with executable undo/redo"); + await click("Refresh section cut"); + for (const [name, width, height] of [["desktop",1440,900],["mobile",390,844]]) { + await page.setViewportSize({ width, height }); + const canvas = panel.locator('[aria-label="Section cut geometry"] canvas'); + const beforeOrbit = await canvas.screenshot(); + const area = await canvas.boundingBox(); assert.ok(area); + await page.mouse.move(area.x + area.width * 0.5, area.y + area.height * 0.5); + await page.mouse.down(); + await page.mouse.move(area.x + area.width * 0.65, area.y + area.height * 0.6, { steps: 8 }); + await page.mouse.up(); await page.waitForTimeout(150); + const png = await canvas.screenshot(); + assert.notDeepEqual(png, beforeOrbit, `${name}: orbit must change rendered geometry`); + const count = await page.evaluate(async base64 => { + const image = new Image(); image.src = `data:image/png;base64,${base64}`; 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 data=ctx.getImageData(0,0,canvas.width,canvas.height).data; + let count=0;for(let i=0;i12)count++; + return count; + },png.toString("base64")); + assert.ok(count>100,`${name}: ${count} geometry pixels`); + const file=path.join(directory,`${name}-canvas.png`);fs.writeFileSync(file,png); + result.evidenceFiles[path.relative(process.cwd(),file)]=createHash("sha256").update(png).digest("hex"); + assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),true); + record({operation:"FCStd restored container cut after ancestor rotation",viewport:[width,height]},{pixels:count,volume:24,orbitChanged:true}, + "Saved container/link placement restores actual world-space cut geometry and visible desktop/mobile canvas"); + } + assert.deepEqual(signature(await run({action:"snapshot",document:"ContainerCutOther"})),signature(other)); + assert.deepEqual(errors,[]);result.status="not_implemented"; + } catch(error) {result.error=String(error.stack??error);process.stderr.write(result.error+"\n");} + finally {stage("cleanup-enter"); await browser?.close(); stage("cleanup-complete");} + fs.writeFileSync(path.join(directory,"result.json"),JSON.stringify(result,null,2)+"\n");return [result]; +} diff --git a/tools/part-section-cut-opacity-cases.mjs b/tools/part-section-cut-opacity-cases.mjs new file mode 100644 index 00000000..a7d6be3a --- /dev/null +++ b/tools/part-section-cut-opacity-cases.mjs @@ -0,0 +1,165 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { createHash } from "node:crypto"; +import { playwright } from "./part-primitive-business-cases.mjs"; + +export async function runSectionCutOpacityCases(ids) { + const capabilityId = "Part:desktop:Part_SectionCut"; + if (!ids.includes(capabilityId)) return []; + const directory = path.resolve("docs/current/part-section-cut-opacity", new Date().toISOString().replace(/[:.]/g, "-")); + fs.mkdirSync(directory, { recursive: true }); + const result = { capabilityId, status: "failed", cases: [], evidenceFiles: {}, + deferredCases: ["runLegacySectionCutCases", "runSectionCutEmptySourcesCases", "runSectionCutFragmentsCases"], + remaining: ["Automatic cut-face coloring and color controls", "Independent cut-face and fragment appearance/transparency"] }; + const record = (input, actual, name) => { + result.cases.push({ input, actual, assertions: [{ name, passed: true }] }); + fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n"); + }; + const session = state => state.objects.find(item => item.sectionCutSession)?.sectionCutSession; + const objects = state => Object.fromEntries(state.objects.map(item => [item.name, item])); + const signature = state => ({ objects: objects(state), undoCount: state.undoCount, redoCount: state.redoCount }); + const near = (a, b) => assert.ok(Number.isFinite(a) && Math.abs(a - b) < 1e-6, `${a} != ${b}`); + const check = (state, transparency, volume = 800) => { + const cut = state.objects.find(item => item.name === session(state).result); + assert.equal(session(state).resultTransparency, transparency); + near(cut.displayOpacity, 1 - transparency / 100); near(cut.volume, volume); + assert.equal(cut.topology.valid, true); assert.ok(cut.mesh.triangleCount > 0); + for (const name of session(state).sources) assert.equal(state.objects.find(item => item.name === name).displayOpacity, undefined); + return cut; + }; + let browser; + try { + for (const file of ["tools/part-section-cut-opacity-cases.mjs", "tools/part-section-cut-business-cases.mjs", + "web/src/part-section-cut-task.tsx", "web/src/part-desktop-adapter.ts", "web/src/part-document-facade.ts", + "web/src/workbench-shell.tsx", "web/src/scene-viewport.tsx", "web/src/scene-document.ts", + "freecad-source/src/WebAssembly/FreeCADCoreProbe/PartSectionCutDocument.h", + "freecad-source/src/WebAssembly/FreeCADCoreProbe/DocumentProbe.cpp", + ...["js", "wasm", "worker.js"].map(ext => `web/public/kernel/FreeCADWebDocumentProbe.${ext}`)]) + result.evidenceFiles[file] = createHash("sha256").update(fs.readFileSync(file)).digest("hex"); + 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 } }); + const errors = []; page.on("pageerror", error => errors.push(String(error))); + const documentId = "SectionCutOpacity"; + await page.goto(`${process.env.FREECAD_BROWSER_ORIGIN ?? "http://127.0.0.1:5180"}/workbench.html?module=Part&command=part.document&document=${documentId}`); + const run = async (args, expectError = false) => { + await page.locator("aside > button.command").filter({ has: page.locator("span", { hasText: /^part.document$/ }) }).click(); + await page.locator("#payload-editor").fill(JSON.stringify({ schema: "freecad-web-part/document/v1", module: "Part", + document: documentId, builderInfo: true, includeMesh: true, ...args })); + await page.evaluate(() => { if (window.__freecadWorkbenchState) window.__freecadWorkbenchState.response = null; }); + await page.getByRole("button", { name: "执行选中命令", exact: true }).click(); + await page.waitForFunction(() => window.__freecadWorkbenchState?.response && !document.querySelector("button.run")?.disabled); + const reply = await page.evaluate(() => window.__freecadWorkbenchState.response); + assert.equal(reply.kind, expectError ? "error" : "result", JSON.stringify(reply)); return expectError ? reply.error : reply.result; + }; + const snapshot = () => run({ action: "snapshot" }); + await run({ action: "create" }); await run({ action: "setBox", object: "A", dimensions: [10, 10, 10] }); + await run({ action: "setBox", object: "B", dimensions: [10, 10, 10] }); + await run({ action: "setPosition", object: "B", position: [5, 0, 0] }); + const other = await run({ action: "create", document: "OpacityOther" }); await snapshot(); + await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click(); + const panel = page.getByRole("region", { name: "Section cutting", exact: true }); + const ready = () => page.waitForFunction(() => { + const fieldset = document.querySelector('section[aria-label="Section cutting"] fieldset'); return fieldset && !fieldset.disabled; + }); + const click = async name => { + await panel.getByRole("button", { name, exact: true }).click(); if (name === "Close section cutting") return; + await ready(); assert.deepEqual(await panel.getByRole("status").allTextContents(), []); + }; + const transparency = panel.getByRole("spinbutton", { name: "Result surface transparency", exact: true }); + const apply = panel.getByRole("button", { name: "Apply section cut", exact: true }); + const canvas = panel.locator('[aria-label="Section cut geometry"] canvas'); + const pixels = async name => { + const png = await canvas.screenshot(); + const metrics = await page.evaluate(async base64 => { + const image = new Image(); image.src = `data:image/png;base64,${base64}`; 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 data = ctx.getImageData(0, 0, canvas.width, canvas.height).data; let contrast = 0; + for (let i = 0; i < data.length; i += 4) contrast += Math.abs(data[i] - 241) + Math.abs(data[i+1] - 243) + Math.abs(data[i+2] - 245); + return { contrast, width: canvas.width, height: canvas.height }; + }, png.toString("base64")); + const file = path.join(directory, `${name}.png`); fs.writeFileSync(file, png); + result.evidenceFiles[path.relative(process.cwd(), file)] = createHash("sha256").update(png).digest("hex"); + return metrics; + }; + await ready(); await panel.getByRole("checkbox", { name: "Cut X", exact: true }).check(); + await panel.getByRole("spinbutton", { name: "Cut X position", exact: true }).fill("8"); + await panel.getByRole("checkbox", { name: "Intersecting objects", exact: true }).check(); + await click("Apply section cut"); const opaque = await snapshot(); check(opaque, 0); + const opaquePixels = await pixels("opaque"); + await transparency.fill("65"); await click("Apply section cut"); const partial = await snapshot(); check(partial, 65); + const partialPixels = await pixels("partial"); + assert.ok(partialPixels.contrast < opaquePixels.contrast * .85, JSON.stringify({ opaquePixels, partialPixels })); + await click("Section cut undo"); assert.equal(await transparency.inputValue(), "0"); + assert.deepEqual(objects(await snapshot()), objects(opaque)); + await click("Section cut redo"); assert.equal(await transparency.inputValue(), "65"); + assert.deepEqual(objects(await snapshot()), objects(partial)); + await transparency.fill("100"); await click("Apply section cut"); check(await snapshot(), 100); + const clearPixels = await pixels("clear"); + assert.ok(clearPixels.contrast < opaquePixels.contrast * .3, JSON.stringify({ opaquePixels, clearPixels })); + assert.ok(partialPixels.contrast > clearPixels.contrast * 1.5); + await click("Section cut undo"); check(await snapshot(), 65); + record({ values: [0, 65, 100], intersecting: true }, { opaquePixels, partialPixels, clearPixels }, + "Native opacity changes surface pixels while preserving topology, source appearance, and reversible session state"); + + const stable = await snapshot(); + for (const invalid of [-1, 101, 2.5, "65", null, true]) { + const error = await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(stable).axes, resultTransparency: invalid } }, true); + assert.match(error.message, /Result transparency must be an integer in 0\.\.100/); + assert.deepEqual(signature(await snapshot()), signature(stable)); + } + for (const invalid of ["-1", "101", "2.5", ""]) { + await transparency.fill(invalid); assert.equal(await apply.isDisabled(), true); + assert.deepEqual(signature(await snapshot()), signature(stable)); + } + await click("Refresh section cut"); assert.equal(await transparency.inputValue(), "65"); + await run({ action: "sectionCut", sectionCut: { operation: "apply", axes: session(stable).axes.map((axis, i) => i ? axis : { ...axis, position: 100 }), resultTransparency: 5 } }, true); + assert.deepEqual(signature(await snapshot()), signature(stable)); + record({ invalidValues: [-1, 101, 2.5, "65", null, true], failedRebuildTransparency: 5 }, { retained: 65 }, + "Native invalid opacity and geometry failures roll back appearance and history; invalid UI input cannot apply"); + + await run({ action: "save", path: "/tmp/SectionCutOpacity.FCStd" }); await run({ action: "close" }); + const reopened = await run({ action: "open", path: "/tmp/SectionCutOpacity.FCStd" }); + assert.deepEqual(objects(reopened), objects(stable)); check(reopened, 65); + await click("Refresh section cut"); assert.equal(await transparency.inputValue(), "65"); + await page.setViewportSize({ width: 390, height: 844 }); + const mobilePartial = await pixels("mobile-partial"); + await transparency.fill("0"); await click("Apply section cut"); const mobileOpaque = await pixels("mobile-opaque"); + assert.ok(mobilePartial.contrast < mobileOpaque.contrast * .85); + await click("Section cut undo"); assert.equal(await transparency.inputValue(), "65"); check(await snapshot(), 65); + assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true); + record({ operation: "FCStd restore and mobile rendering", viewport: [390, 844] }, { mobilePartial, mobileOpaque }, + "Saved native opacity restores the control and actual transparent surface on mobile without overflow"); + + const edited = await run({ action: "setBox", object: "B", dimensions: [10, 10, 20] }); check(edited, 65, 1100); + await click("Refresh cut sources"); check(await snapshot(), 65, 1100); + await run({ action: "remove", object: "B" }); check(await snapshot(), 65); + await click("Refresh section cut"); assert.equal(await transparency.inputValue(), "65"); + await run({ action: "remove", object: "A" }); + const empty = await snapshot(); assert.equal(session(empty).resultTransparency, 65); + await run({ action: "setBox", object: "Replacement", dimensions: [10, 10, 10] }); + await click("Refresh cut sources"); check(await snapshot(), 65); + await run({ action: "setBox", object: "Small", dimensions: [1, 1, 1] }); + await click("Refresh cut sources"); check(await snapshot(), 65); + await transparency.fill("25"); await click("Apply section cut"); + await click("Section cut undo"); const deletionGuard = await snapshot(); check(deletionGuard, 65); + assert.ok(deletionGuard.redoCount > 0); + const rejectedRemoval = await run({ action: "remove", object: "Replacement" }, true); + assert.match(rejectedRemoval.message, /outside source bounds/); + assert.deepEqual(signature(await snapshot()), signature(deletionGuard)); + await click("Section cut redo"); check(await snapshot(), 25); + await click("Section cut undo"); check(await snapshot(), 65); + await click("Close section cutting"); await panel.waitFor({ state: "detached" }); + await page.locator(".matrix-list button").filter({ has: page.locator("span", { hasText: /^Part_SectionCut$/ }) }).click(); + await ready(); assert.equal(await transparency.inputValue(), "65"); + assert.deepEqual(signature(await run({ action: "snapshot", document: "OpacityOther" })), signature(other)); + assert.deepEqual(errors, []); + record({ operation: "edit source, recollect, fall back to compound, empty session, recover, reject out-of-bounds source removal and reenter" }, { transparency: 65, volume: 800, redoPreserved: true }, + "Source lifecycle retains result opacity in both modes; failed source removal preserves the executable redo branch and other documents"); + result.status = "not_implemented"; + } catch (error) { result.error = String(error.stack ?? error); process.stderr.write(result.error + "\n"); } + finally { await browser?.close(); } + fs.writeFileSync(path.join(directory, "result.json"), JSON.stringify(result, null, 2) + "\n"); return [result]; +} diff --git a/tools/prepare_format_business_batch.py b/tools/prepare_format_business_batch.py new file mode 100644 index 00000000..20a50015 --- /dev/null +++ b/tools/prepare_format_business_batch.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +"""Prepare module-level import/export workflows without API-sized tasks.""" +from __future__ import annotations + +import hashlib +import json +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path + +from implementation_first import all_implementation_ready_ids +from scheduler_progress import cooling_ids, retry_details + + +ROOT = Path(__file__).resolve().parents[1] +SOURCE = ROOT / "docs/p6/format-coverage-kernel.json" +STATE = ROOT / "docs/current/task-state.json" +OUTPUT = ROOT / "docs/current/module-batch-manifest.json" +MODULE_ORDER = { + "Part": 0, "Mesh": 1, "Import": 2, "TechDraw": 3, "Spreadsheet": 4, + "Points": 5, "BIM": 6, "Draft": 7, "Fem": 9, "CAM": 10, +} + + +def business_id(module: str, direction: str, extension: str) -> str: + return f"business-format:{module}:{direction}:{extension}" + + +def main() -> int: + source = json.loads(SOURCE.read_text(encoding="utf-8")) + ready = all_implementation_ready_ids() + cooling = cooling_ids(candidates={business_id(str(row.get("module")), str(row.get("direction")), str(row.get("extension"))) for row in source.get("records", []) if isinstance(row, dict)}) + deferred_ids = set() + grouped: dict[tuple[str, str, str], list[dict]] = defaultdict(list) + for row in source.get("records", []): + if not isinstance(row, dict) or row.get("direction") not in {"import", "export"}: + continue + key = (str(row.get("module")), str(row.get("direction")), str(row.get("extension"))) + grouped[key].append(row) + pending: dict[str, list[dict]] = defaultdict(list) + for (module, direction, extension), rows in grouped.items(): + record_id = business_id(module, direction, extension) + if record_id in ready or any(row.get("status") == "passed" for row in rows): + continue + if record_id in cooling: + deferred_ids.add(record_id) + continue + source_row = min(rows, key=lambda row: (str(row.get("path", "")), int(row.get("line", 0) or 0))) + pending[module].append({ + "id": record_id, + "name": f"{direction} {extension}", + "direction": direction, + "extension": extension, + "source": source_row.get("path"), + "sourceLine": source_row.get("line"), + "sourceHandlerCount": len(rows), + }) + if not pending: + result = { + "schema": "freecad-web-module-function-batch/v1", + "status": "no_ready_batch", + "generatedAt": datetime.now(timezone.utc).isoformat(), + "strategy": "module-function-direct-deferred-validation", + "reason": "all source-declared import/export workflows have module implementation receipts", + "records": [], + "queue": [], + **retry_details(deferred_ids), + } + OUTPUT.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8") + print(json.dumps({"status": result["status"], "formatWorkflows": len(grouped), "records": 0}, ensure_ascii=False)) + return 0 + module = min(pending, key=lambda value: (MODULE_ORDER.get(value, 50), value)) + records = sorted(pending[module], key=lambda row: (row["extension"], row["direction"])) + identity = "|".join([module, "format-workflow", "import-export", *(str(row["id"]) for row in records)]) + batch_id = hashlib.sha256(identity.encode("utf-8")).hexdigest()[:24] + state = json.loads(STATE.read_text(encoding="utf-8")) + queue = [ + {"module": name, "tier": "format-workflow", "family": "import-export", "unresolved": len(rows), "nextSize": len(rows)} + for name, rows in sorted(pending.items(), key=lambda item: (MODULE_ORDER.get(item[0], 50), item[0])) + ] + result = { + "schema": "freecad-web-module-function-batch/v1", + "status": "ready", + "generatedAt": datetime.now(timezone.utc).isoformat(), + "taskId": state.get("active_task"), + "batchId": batch_id, + "strategy": "module-function-direct-deferred-validation", + "businessBundle": { + "module": module, + "implementationUnit": "module-import-export-dispatcher", + "selectedRecordsAreUserWorkflows": True, + "sourceHandlerCount": sum(int(row["sourceHandlerCount"]) for row in records), + }, + "minimumRecords": 1, + "singletonFallback": len(records) == 1, + "selected": { + "module": module, + "tier": "format-workflow", + "family": "import-export", + "recordCount": len(records), + "dispositionCounts": {"not_implemented": len(records)}, + }, + "fields": ["id", "name", "disposition", "source", "sourceLine"], + "records": [[row["id"], row["name"], "not_implemented", row["source"], row["sourceLine"]] for row in records], + "queue": queue, + "boundaries": [ + "One record is one user-visible module import/export workflow, not a Python API.", + "All same-module extensions share the existing native dispatcher, Worker and WASM artifact.", + "Source mentions with unknown direction are not user format handlers and are excluded.", + "Implementation performs build/sync/receipt only; validation is disabled.", + ], + } + OUTPUT.write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8") + print(json.dumps({"status": "ready", "batchId": batch_id, "module": module, "family": "import-export", "records": len(records)}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/prepare_module_implementation_packet.py b/tools/prepare_module_implementation_packet.py new file mode 100644 index 00000000..0ed9e7fd --- /dev/null +++ b/tools/prepare_module_implementation_packet.py @@ -0,0 +1,1047 @@ +#!/usr/bin/env python3 +"""Build a bounded source packet for the current module implementation turn.""" +from __future__ import annotations + +from record_runtime_issue import ACTIVE_STATUSES + +import ast +import argparse +import hashlib +import json +import os +import re +from datetime import datetime, timezone +from pathlib import Path +from migration_workflows import delivery_route +from business_continuation_context import retained_results + +from implementation_first import implementation_first_enabled +from scheduler_progress import PROGRESS_PATH, read as read_progress, module_states +from failure_reconciliation import synchronize as reconcile_failures, module_context + + +ROOT = Path(__file__).resolve().parents[1] +BATCH_PATH = ROOT / "docs/current/module-batch-manifest.json" +OUTPUT_PATH = ROOT / "docs/current/module-implementation-packet.json" +PROBE_ROOT = ROOT / "freecad-source/src/WebAssembly/FreeCADCoreProbe" +MAX_TOTAL_BYTES = max(4096, int(os.environ.get("FREECAD_IMPLEMENTATION_PACKET_BYTES", "12288"))) +MAX_RECORD_BYTES = max(256, int(os.environ.get("FREECAD_IMPLEMENTATION_RECORD_BYTES", "1600"))) +MAX_NATIVE_TOTAL_BYTES = max(1024, int(os.environ.get("FREECAD_IMPLEMENTATION_NATIVE_BYTES", "4096"))) +MAX_EDIT_TOTAL_BYTES = max(4096, int(os.environ.get("FREECAD_IMPLEMENTATION_EDIT_BYTES", "16384"))) +MAX_EDIT_REGION_BYTES = max(1024, int(os.environ.get("FREECAD_IMPLEMENTATION_EDIT_REGION_BYTES", "2048"))) +DESKTOP_ADAPTER_SPLIT_BYTES = max(32768, int(os.environ.get("FREECAD_DESKTOP_ADAPTER_SPLIT_BYTES", "98304"))) + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def source_path(value: object) -> Path | None: + if not isinstance(value, str) or not value: + return None + candidate = Path(value) + if candidate.is_absolute(): + return candidate if candidate.is_file() and candidate.is_relative_to(ROOT) else None + for root in (ROOT / "freecad-source", ROOT): + resolved = root / candidate + if resolved.is_file(): + return resolved + return None + + +def compact_excerpt(text: str, limit: int) -> str: + lines = [line.rstrip() for line in text.splitlines()] + while lines and not lines[0].strip(): + lines.pop(0) + while lines and not lines[-1].strip(): + lines.pop() + value = "\n".join(lines) + if len(value.encode("utf-8")) <= limit: + return value + kept, size = [], 0 + for line in lines: + extra = len(line.encode("utf-8")) + (1 if kept else 0) + if size + extra > limit: + break + kept.append(line) + size += extra + return "\n".join(kept) + + +def python_excerpt(path: Path, name: str, source_line: int | None) -> tuple[int, str]: + text = path.read_text(encoding="utf-8", errors="replace") + lines = text.splitlines() + leaf = name.rsplit(".", 1)[-1] + candidates: list[ast.AST] = [] + try: + tree = ast.parse(text) + candidates = [ + node for node in ast.walk(tree) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and node.name == leaf + ] + except SyntaxError: + candidates = [] + if not candidates: + factories = set() + for node in ast.walk(tree) if 'tree' in locals() else []: + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "addCommand" + and len(node.args) > 1 and isinstance(node.args[0], ast.Constant) and node.args[0].value == name + and isinstance(node.args[1], ast.Call) and isinstance(node.args[1].func, ast.Name)): + factories.add(node.args[1].func.id) + for node in ast.walk(tree) if 'tree' in locals() else []: + if isinstance(node, ast.ClassDef) and node.name in factories: + candidates.extend(member for member in node.body if isinstance(member, ast.FunctionDef) and member.name in {"Activated", "activated"}) + if candidates: + target = min(candidates, key=lambda node: abs(int(getattr(node, "lineno", 1)) - int(source_line or getattr(node, "lineno", 1)))) + start = int(getattr(target, "lineno", 1)) + decorators = getattr(target, "decorator_list", []) + if decorators: + start = min(start, *(int(getattr(item, "lineno", start)) for item in decorators)) + end = min(int(getattr(target, "end_lineno", start + 8)), start + 11) + return start, compact_excerpt("\n".join(lines[start - 1:end]), MAX_RECORD_BYTES) + line = max(1, int(source_line or 1)) + start = max(1, line - 2) + end = min(len(lines), line + 7) + return start, compact_excerpt("\n".join(lines[start - 1:end]), MAX_RECORD_BYTES) + + +def generic_excerpt(path: Path, source_line: int | None) -> tuple[int, str]: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + line = max(1, int(source_line or 1)) + start = max(1, line - 3) + end = min(len(lines), line + 5) + return start, compact_excerpt("\n".join(lines[start - 1:end]), MAX_RECORD_BYTES) + + +def cpp_command_excerpt(path: Path, name: str, source_line: int | None) -> tuple[int, str]: + text = path.read_text(encoding="utf-8", errors="replace") + lines = text.splitlines() + command_lines = [ + index for index, value in enumerate(lines, 1) + if f'Command("{name}")' in value or f'CommandBase("{name}")' in value + ] + if not command_lines: + return generic_excerpt(path, source_line) + command_line = min(command_lines, key=lambda value: abs(value - int(source_line or value))) + class_name = "" + constructor_re = re.compile(r"\b([A-Za-z_]\w*)::\1\s*\(") + for value in lines[max(0, command_line - 8):command_line + 2]: + match = constructor_re.search(value) + if match: + class_name = match.group(1) + break + if not class_name: + return generic_excerpt(path, command_line) + activated_re = re.compile(rf"\b{re.escape(class_name)}::activated\s*\(") + activated_line = next( + (index for index, value in enumerate(lines[command_line:], command_line + 1) if activated_re.search(value)), + None, + ) + if activated_line is None: + return generic_excerpt(path, command_line) + start = activated_line + end = min(len(lines), start + 90) + depth = 0 + opened = False + for index in range(start - 1, end): + depth += lines[index].count("{") - lines[index].count("}") + opened = opened or "{" in lines[index] + if opened and depth <= 0: + end = index + 1 + break + return start, compact_excerpt("\n".join(lines[start - 1:end]), MAX_RECORD_BYTES) + + +def anchored_excerpt(lines: list[str], anchor: int, limit: int) -> tuple[int, str]: + """Keep the actual edit anchor and complete source lines within the budget.""" + start = end = anchor - 1 + size = len(lines[start].encode("utf-8")) + # Dense legacy Workers can put an entire dispatcher on one line. Retain + # that line when the overall packet can fit it; never invent a cut line. + if size > MAX_EDIT_TOTAL_BYTES: + return anchor, "" + for _ in range(30): + added = False + if start > 0 and anchor - start <= 12: + extra = len(lines[start - 1].encode("utf-8")) + 1 + if size + extra <= limit: + start -= 1 + size += extra + added = True + if end + 1 < len(lines): + extra = len(lines[end + 1].encode("utf-8")) + 1 + if size + extra <= limit: + end += 1 + size += extra + added = True + if not added: + break + return start + 1, "\n".join(lines[start:end + 1]) + + +def editable_excerpts(path: Path, text: str, names: list[str]) -> list[dict[str, object]]: + lines = text.splitlines() + if not lines: + return [] + anchors: list[tuple[str, tuple[str, ...]]] = [] + selected = tuple(name for name in names if name) + if selected: + anchors.append(("selected-command", selected)) + if path.name == "native-source-policy.ts": + anchors.append(("runtime-policy", ("function nativeSourceDecision",))) + if path.suffix in {".cpp", ".h"}: + anchors.extend(( + ("desktop-handler", ("executeDesktop", "DesktopCommand")), + ("command-registration", ("const QStringList commands", "desktopCommands", "FC_WEB_DESKTOP_COMMAND")), + ("family-record-handler", ("probePythonFamilyRecord", "probeFamilyRecord", "executePythonFamily")), + ("family-dispatch", ('family == QStringLiteral("desktop-command")', "pythonFamilyBatch")), + ("unified-dispatch", ("fc_web_dispatch_json",)), + )) + else: + anchors.extend(( + ("business-case-coverage", ("resolvedIssueIds", "resolvedFailureKeys", "FREECAD_BUSINESS_IDS")), + ("request-contract", ("PythonFamilyRecord", "DesktopCommandRoute")), + ("worker-dispatch", ("onmessage", "dispatch")), + ("native-call", ("fc_web_dispatch_json",)), + ("response-validation", ("native_protocol_error", "returned an invalid")), + )) + regions: list[dict[str, object]] = [] + for role, patterns in anchors: + line = next((index for pattern in patterns for index, value in enumerate(lines, 1) + if pattern in value and not value.lstrip().startswith("//")), None) + if line is None or any(region["line"] <= line < region["line"] + len(region["excerpt"].splitlines()) for region in regions): + continue + start, excerpt = anchored_excerpt(lines, line, MAX_EDIT_REGION_BYTES) + regions.append({ + "path": str(path.relative_to(ROOT)), + "role": role, + "line": start, + "anchorLine": line, + "excerpt": excerpt, + }) + if regions: + return regions + start, excerpt = anchored_excerpt(lines, len(lines), MAX_EDIT_REGION_BYTES) + return [{ + "path": str(path.relative_to(ROOT)), + "role": "file-tail", + "line": start, + "anchorLine": len(lines), + "excerpt": excerpt, + }] + + +def application_integration_excerpts(module: str = "") -> list[dict[str, object]]: + """Provide real command call sites, not another isolated facade preview.""" + regions = [] + slug = re.sub(r"[^a-z0-9]+", "", module.lower()) + for relative, anchors in ( + (f"web/src/{slug}-desktop-adapter.ts", ("export function",)), + ("web/src/workbench-shell.tsx", ("new DesktopCommandDispatcher", "desktopCommands.execute", "return <")), + ("web/src/desktop-command-dispatcher.ts", ("async execute(", "this.router.request")), + ): + path = ROOT / relative + if not path.is_file(): + continue + lines = path.read_text(encoding="utf-8").splitlines() + for anchor in anchors: + number = next((index for index, line in enumerate(lines, 1) if anchor in line), None) + if number is None or any(row["path"] == relative and row["line"] <= number < row["line"] + len(row["excerpt"].splitlines()) for row in regions): + continue + start, excerpt = anchored_excerpt(lines, number, 1000) + if not excerpt or len(excerpt.encode()) > 1400: + continue + regions.append({"path": relative, "role": "application-integration", "line": start, + "anchorLine": number, "excerpt": excerpt}) + return regions + + +def probe_sources(module: str, tier: str = "", family: str = "") -> list[Path]: + normalized_module = re.sub(r"[^a-z0-9]", "", module.lower()) + candidates: list[Path] = [] + # Most probes use *Probe.cpp, but a few modules keep the active native + # implementation in a deliberately suffixed translation unit (for + # example RobotRuntimeProbeFixed.cpp) and link an auxiliary *Api.cpp. + # Discover only those known probe-shaped files under the bounded probe + # directory; never fall back to a repository-wide scan. + for pattern in ("*Probe.cpp", "*ProbeFixed.cpp", "*InventoryApi.cpp"): + candidates.extend(PROBE_ROOT.glob(pattern)) + result = [ + path for path in sorted(set(candidates)) + if re.sub(r"[^a-z0-9]", "", path.stem.lower()).startswith(normalized_module) + and not (module == "Part" and path.stem.startswith("PartDesign")) + and not (module == "Mesh" and path.stem.startswith("MeshPart")) + ] + desktop = PROBE_ROOT / f"{module}DesktopCommands.cpp" + if desktop.is_file(): + result.append(desktop) + if tier == "format-workflow" or family == "import-export": + def format_rank(path: Path) -> tuple[int, str]: + try: + owns_dispatch = "fc_web_dispatch_json" in path.read_text(encoding="utf-8", errors="replace") + except OSError: + owns_dispatch = False + return ( + 0 if owns_dispatch else + 1 if "RuntimeProbe" in path.name else + 2 if "IoProbe" in path.name else + 3, + path.name, + ) + result.sort(key=format_rank) + else: + result.sort(key=lambda path: (0 if "RuntimeProbe" in path.name else 1 if "DesktopCommands" in path.name else 2, path.name)) + selected_sources = result[:4] + # Inline desktop workflow implementations are part of the selected native + # source, not missing business logic. Follow only quoted, local headers. + headers = [] + pending = list(selected_sources) + seen = {source.resolve() for source in selected_sources} + for source in pending: + for name in re.findall(r'^\s*#include\s+"([^"\n]+\.(?:h|hpp))"', source.read_text(encoding="utf-8", errors="replace"), re.MULTILINE): + header = (source.parent / name).resolve() + if header.parent == PROBE_ROOT.resolve() and header.is_file() and header not in seen: + seen.add(header) + headers.append(header) + pending.append(header) + return [*selected_sources, *headers] + + +def first_match_line(text: str, name: str) -> int | None: + patterns = (f'QStringLiteral("{name}")', f'"{name}"', name.rsplit(".", 1)[-1]) + for index, line in enumerate(text.splitlines(), 1): + if any(pattern and pattern in line for pattern in patterns): + return index + return None + + +def file_entry(path: Path) -> dict[str, object]: + stat = path.stat() + return { + "path": str(path.relative_to(ROOT)), + "absolutePath": str(path.resolve()), + "bytes": stat.st_size, + "mtimeNs": stat.st_mtime_ns, + "sha256": sha256(path), + } + + +def case_reexport_sources(entry: Path) -> list[Path]: + """Follow explicit local case re-exports, without traversing all case imports.""" + pending = [entry.resolve()] + sources = [] + seen = set() + tools_root = (ROOT / "tools").resolve() + while pending and len(sources) < 16: + source = pending.pop(0) + if source in seen or source.parent != tools_root or source.suffix != ".mjs" or not source.is_file(): + continue + seen.add(source) + sources.append(source) + text = source.read_text(encoding="utf-8") + for name in re.findall(r'''\bexport\s*\{[^}]*\}\s*from\s*["'](\./[^"']+\.mjs)["']''', text): + pending.append((source.parent / name).resolve()) + return sources + + +def scoped_build_history(batch: dict, build: dict) -> dict: + """Describe old pipeline output without presenting it as build permission.""" + pipeline = read_progress(ROOT / "docs/current/module-batch-pipeline.json") + same_batch = bool(batch.get("batchId")) and pipeline.get("batchId") == batch.get("batchId") + same_target = (same_batch and bool(build.get("target")) + and pipeline.get("target") == build.get("target") + and pipeline.get("buildTree") == build.get("tree")) + return { + "batchId": batch.get("batchId"), + "pipelineRelation": "same-batch-and-default-target" if same_target else "unrelated-or-unavailable", + "previousPipeline": {key: pipeline.get(key) for key in ("batchId", "module", "target", "buildTree")}, + "recordedOutcome": ({key: pipeline.get(key) for key in ("status", "buildRequired", "buildReuse", "incrementalPlan")} + if same_target else None), + "instruction": "Historical outcome only, not build authorization or proof that current inputs are unchanged. The default build target is not exhaustive. Reuse completed unchanged work; compile actual affected document owners incrementally with -j8 in existing trees. Never wait for replacement pipeline metadata to perform already-authorized implementation builds.", + } + + +def instruction_context(paths: list[Path]) -> dict: + directories = {ROOT, ROOT.parent} + for path in paths: + directories.update(parent for parent in path.resolve().parents if parent.is_relative_to(ROOT)) + return {"workspace": str(ROOT), "checkedAncestorDirectories": len(directories), + "deliveryPlan": "docs/current/DESKTOP_WEB_DELIVERY_PLAN_20260918.md", + "deliveryGuard": { + "objective": "Complete desktop FreeCAD functionality and panels in the primary Web workspace, reusing finished work.", + "beforeEdit": "Use retainedBusinessResults. State the desktop behavior, actual primary UI entry, reusable native owner/component and remaining blocker. Do not reread known headers/plans to rediscover completed work.", + "validation": "Latest user instruction defers writing/running tests and acceptance until all functionality is implemented. Reuse recorded results as historical implementation context; do not replay them now. Necessary incremental compile/link/sync remains allowed.", + "completion": "Report concrete usable behavior, native/UI proof, unresolved boundaries and next exact source anchor. Routes, fixtures, build success and scenario counts do not certify the whole requirement.", + }, + "roundResultInstruction": "At the end of this turn, report in Chinese: reused work, functionality/UI connected, necessary build/sync outcome, unfinished boundaries and next concrete implementation. Validation is deferred until all functions are implemented. Do not call a build receipt business acceptance. The scheduler publishes the report and next confirmed task.", + "deliveryInstruction": "Latest 2026-09-18 user direction: finish missing desktop FreeCAD functionality AND integrated primary UI first; directly reuse completed work. Defer writing/running acceptance, regression and browser tests until all functionality is implemented. Only necessary incremental compile/link/asset synchronization now. Current native document, real controls, selection, task accept/cancel, recompute and save/reopen are implementation responsibilities. Preserve all historical evidence; report implementation progress without claiming validation.", + "deliveryReuse": {"primaryEntry": "web/src/project-shell.tsx", + "nativeFeatureWorkspace": "web/src/partdesign-workspace.tsx", + "mountedTasks": "web/src/workbench-shell.tsx", + "rule": "Integrate the existing real document workspaces, render bridge, router, adapters and OPFS store. main-chain-shell.tsx still contains fixture dispatch examples; do not copy those as current-document implementation. Reuse completed work, not placeholder outputs."}, + "geometryBoundary": "docs/OCCT_GEOMETRY_BOUNDARY.md", + "instructionFiles": sorted(str(parent / "AGENTS.md") for parent in directories if (parent / "AGENTS.md").is_file()), + "businessRecovery": { + "policy": "docs/UNATTENDED_WORKFLOW.md", + "workedExample": "docs/current/part-mesh-business-unblock.md", + "steps": [ + "OCCT WASM is already provided: reuse it as the sole geometry backend; keep FreeCAD document semantics and Three.js display separate. Reuse local sources and current evidence.", + "After a stall, isolate the smallest failing business input; do not replay the unchanged failing full batch.", + "Time load, initialization, native stages and cleanup separately; retain the last entered and completed stage.", + "Check the traced native path for pthread pool exhaustion, recursive async work, event-loop waits and GIL ownership; do not assume every timeout has the same cause.", + "Fix the shared native owner, preserve desktop semantics and geometry checks; rebuild only affected module targets.", + "During the current implementation-only phase, fix from local source and compiler diagnostics, retain unresolved items, and defer business verification until all functionality is implemented.", + ], + }} + + +def acceptance_build_for_ids(contract: dict, selected_ids: set[str]) -> tuple[object, bool]: + overrides = contract.get("buildOverrides", {}) + choices = [overrides.get(record_id) for record_id in sorted(selected_ids)] if isinstance(overrides, dict) else [] + if choices and isinstance(choices[0], dict) and choices[0] and all(choice == choices[0] for choice in choices): + return choices[0], True + build = contract.get("build") + return build, isinstance(build, dict) and build.get("kind") == "frontend" + + +def frontend_acceptance_build(declared: dict) -> dict: + expected = {"kind": "frontend", "target": "FreeCADWebReactProduct", "tree": "web", + "bin": "web/dist", "runtime": "web/dist/index.html", "wasm": "web/dist/index.html"} + if any(declared.get(key, value) != value for key, value in expected.items()): + raise ValueError("Frontend acceptance must use the existing React build and output paths") + return expected + + +def workflow_worker(module: str, row: dict) -> str | None: + routes = ROOT / "web/src/module-registry.generated.ts" + if routes.is_file() and row.get("command"): + # The capability ledger's worker can be the module default. The + # generated switch is the actual command-specific browser route. + key = json.dumps(f"{module}:{row['command']}") + match = re.search(rf'case\s+{re.escape(key)}\s*:\s*return\s+("(?:[^"\\]|\\.)*")\s*;', routes.read_text()) + if match: + return json.loads(match.group(1)) + return row.get("worker") + + +def workflow_worker_sources(module: str, ids: list[str], capabilities: dict) -> list[Path]: + rows = [capabilities.get(record_id, {}) for record_id in ids] + if not rows or not all(row.get("worker") and delivery_route(row) for row in rows): + return [] + workers = read_progress(ROOT / "web/public/modules/manifest.json").get("modules", {}).get(module, {}).get("workers", {}) + runtimes = {workers.get(workflow_worker(module, row), {}).get("runtimeUrl") for row in rows} + if len(runtimes) != 1 or not next(iter(runtimes)): + return [] + target = Path(next(iter(runtimes))).stem + if not re.fullmatch(r"FreeCADWeb[A-Za-z0-9]+Probe", target): + return [] + cmake = PROBE_ROOT / "CMakeLists.txt" + if not cmake.is_file(): + return [] + match = re.search(rf"add_executable\(\s*{re.escape(target)}\s+([A-Za-z0-9_]+\.cpp)\b", cmake.read_text()) + return [PROBE_ROOT / match.group(1)] if match and (PROBE_ROOT / match.group(1)).is_file() else [] + + +def build_hint(module: str, probes: list[Path], tier: str = "", family: str = "") -> dict[str, object]: + cmake_path = PROBE_ROOT / "CMakeLists.txt" + try: + cmake_text = cmake_path.read_text(encoding="utf-8") + except OSError: + return {} + targets: list[str] = [] + for source in probes: + targets.extend(re.findall(rf"add_executable\(\s*(FreeCADWeb[A-Za-z0-9]+Probe)\s+{re.escape(source.name)}\b", cmake_text)) + build_root = ROOT / "freecad-source/build-web" + unique_targets = list(dict.fromkeys(targets)) + if tier == "feature-workflow" and family.startswith("desktop-command"): + unique_targets.sort( + key=lambda target: ( + 0 if "DesktopCommand" in target else 1 if "RuntimeProbe" in target else 2, + target, + ) + ) + fallback_trees = [ + path.parents[1] + for target in unique_targets + for path in build_root.glob(f"*/bin/{target}.js") + if path.with_suffix(".wasm").exists() + ] + # A target may be configured but not have produced its first JS/WASM + # artifact yet. Derive the build tree from the target rule in build.ninja + # so the outer pipeline can perform that one legitimate initial build + # instead of marking the packet unavailable and sending the agent through + # repeated source-only turns. + configured_trees: list[Path] = [] + for ninja in build_root.glob("*/build.ninja"): + try: + ninja_text = ninja.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + if any(target in ninja_text for target in unique_targets): + configured_trees.append(ninja.parent) + for target in unique_targets: + artifacts = [path for path in build_root.glob(f"*/bin/{target}.js") if path.with_suffix(".wasm").exists()] + def rank(path: Path) -> tuple[int, str]: + name = path.parents[1].name.lower() + if module == "TechDraw" and "techdraw-native" in name: + return (0, name) + if module == "Fem" and "fem-wasm" in name: + return (0, name) + return (1 if name == "configure" else 2, name) + if artifacts: + artifact = sorted(artifacts, key=rank)[0] + tree = artifact.parents[1] + elif fallback_trees: + tree = sorted(set(fallback_trees), key=lambda path: (0 if path.name == "configure" else 1, path.name))[0] + artifact = tree / "bin" / f"{target}.js" + elif configured_trees: + tree = sorted(set(configured_trees), key=lambda path: (0 if path.name == "configure" else 1, path.name))[0] + artifact = tree / "bin" / f"{target}.js" + else: + continue + return { + "target": target, + "tree": str(tree.relative_to(ROOT)), + "bin": str((tree / "bin").relative_to(ROOT)), + "runtime": str(artifact.relative_to(ROOT)), + "wasm": str(artifact.with_suffix(".wasm").relative_to(ROOT)), + } + return {} + + +def select_module_gate(module: str, slug: str, tier: str, family: str) -> Path | None: + candidates = list((ROOT / "tools").glob(f"run_p6_{slug}*module_batch_gate.mjs")) + family_tokens = {family.replace("-", "_"), family.split("-", 1)[0]} + compatible: list[tuple[int, str, Path]] = [] + for path in candidates: + try: + text = path.read_text(encoding="utf-8", errors="replace") + except OSError: + continue + manifest_driven = "module-batch-manifest.json" in text and "batch.selected" in text and "batch.records" in text + module_match = f'"{module}"' in text or f"'{module}'" in text + tier_match = tier in text or "typeof batch.selected?.tier" in text or "typeof batch.selected.tier" in text + family_match = family in text or "typeof batch.selected?.family" in text or "typeof batch.selected.family" in text + if not all((manifest_driven, module_match, tier_match, family_match)): + continue + exact = path.name == f"run_p6_{slug}_module_batch_gate.mjs" + family_named = any(token and token in path.stem for token in family_tokens) + generic_family = "typeof batch.selected?.family" in text or "typeof batch.selected.family" in text + score = 0 if exact else 1 if family_named else 2 if generic_family else 3 + compatible.append((score, path.name, path)) + return min(compatible, default=(99, "", None))[2] + + +def main() -> int: + try: + batch = json.loads(BATCH_PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as error: + print(json.dumps({"status": "error", "error": str(error)})) + return 2 + selected = batch.get("selected") if isinstance(batch.get("selected"), dict) else {} + if batch.get("status") != "ready" or not selected or not isinstance(batch.get("records"), list): + print(json.dumps({"status": "not_ready"})) + return 2 + module = str(selected.get("module") or "") + tier = str(selected.get("tier") or "") + family = str(selected.get("family") or "") + if tier == "failure-reconciliation": + ledger = reconcile_failures() + keys = batch.get("failureKeys", []) + rows = [ledger["records"][key] for key in keys if key in ledger["records"] and ledger["records"][key]["status"] == "pending"] + payload = {"schema": "freecad-web-module-implementation-packet/v1", "batchId": batch.get("batchId"), "module": module, + "tier": tier, "family": family, "recordCount": len(rows), "outerPipelineAvailable": True, "build": {}, + "supportFiles": [], "editableExcerpts": [], "records": [], + "repositoryContext": instruction_context([]), + "failureReconciliation": {"records": [{"key": row["key"], "category": row["category"], "modules": row["modules"], + "failureFingerprint": row["failureFingerprint"], "status": row["status"], + "command": str(row["sourceSnapshot"].get("command", ""))[:800], + "error": str(row["sourceSnapshot"].get("lastError") or row["sourceSnapshot"].get("firstError") or "")[:1200]} for row in rows]}} + OUTPUT_PATH.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + print(json.dumps({"status": "ready", "batchId": batch.get("batchId"), "module": module, "failureRecords": len(rows)})) + return 0 + recovery_state = read_progress(PROGRESS_PATH) + module_recovery = module_states(recovery_state).get(module, {}) + reconcile_failures() + failure_context = module_context(module, {str(row[0]) for row in batch["records"] if row}) + recovering = bool(module_recovery.get("recoveryLevel") or module_recovery.get("consecutiveNoProgress")) + probes = probe_sources(module, tier, family) + records: list[dict[str, object]] = [] + capability_rows = json.loads((ROOT / "docs/current/feature-capability-registry.json").read_text(encoding="utf-8")).get("records", []) + capability_by_id = {row["id"]: row for row in capability_rows} + worker_sources = workflow_worker_sources(module, [str(row[0]) for row in batch["records"] if row], capability_by_id) + probes = list(dict.fromkeys([*worker_sources, *probes])) + probe_texts = [(path, path.read_text(encoding="utf-8", errors="replace")) for path in probes] + semantic_decisions = {} + decision_file = ROOT / "docs/current/native-semantic-decisions.json" + for group in read_progress(decision_file).get("groups", []): + sources = group.get("sourceDigests", {}) + if not sources: + continue + current = all((ROOT / name).resolve().is_relative_to(ROOT) and (ROOT / name).is_file() + and sha256(ROOT / name) == expected for name, expected in sources.items()) + for record_id, finding in group.get("records", {}).items(): + semantic_decisions[record_id] = {**finding, "sourceSnapshotCurrent": current, + "reuseInstruction": "Use this retained source finding; implement the next action, not another general review." + if current else "Source changed: revisit only the affected native branches before using this finding."} + issue_rows = json.loads((ROOT / "docs/current/runtime-issue-ledger.json").read_text(encoding="utf-8")).get("issues", []) + used = 0 + native_used = 0 + truncated = 0 + for row in batch["records"]: + if not isinstance(row, list) or not row: + continue + api_id = str(row[0]) + name = str(row[1]) if len(row) > 1 else api_id + raw_source = row[3] if len(row) > 3 else None + raw_line = row[4] if len(row) > 4 and isinstance(row[4], int) else None + resolved = source_path(raw_source) + excerpt = "" + excerpt_line = raw_line + if resolved: + try: + if resolved.suffix in {".py", ".pyi"}: + excerpt_line, excerpt = python_excerpt(resolved, name, raw_line) + elif resolved.suffix in {".cpp", ".cxx", ".cc", ".h", ".hpp"}: + excerpt_line, excerpt = cpp_command_excerpt(resolved, name, raw_line) + else: + excerpt_line, excerpt = generic_excerpt(resolved, raw_line) + except OSError: + excerpt = "" + encoded = len(excerpt.encode("utf-8")) + if used + encoded > MAX_TOTAL_BYTES: + excerpt = "" + encoded = 0 + truncated += 1 + used += encoded + native_matches = [] + for path, text in probe_texts: + line = first_match_line(text, name) + if line is None: + continue + native_excerpt = "" + if native_used < MAX_NATIVE_TOTAL_BYTES: + _, native_excerpt = generic_excerpt(path, line) + encoded_native = len(native_excerpt.encode("utf-8")) + if native_used + encoded_native <= MAX_NATIVE_TOTAL_BYTES: + native_used += encoded_native + else: + native_excerpt = "" + native_matches.append({"path": str(path.relative_to(ROOT)), "line": line, "excerpt": native_excerpt}) + records.append({ + "apiId": api_id, + "name": name, + "source": str(resolved.relative_to(ROOT)) if resolved and resolved.is_relative_to(ROOT) else raw_source, + "sourceLine": raw_line, + "excerptLine": excerpt_line, + "excerpt": excerpt, + "nativeMatches": native_matches, + "semanticDecision": semantic_decisions.get(api_id), + "runtimeRouteBlock": capability_by_id.get(api_id, {}).get("runtimeRouteBlock"), + "implementationGaps": capability_by_id.get(api_id, {}).get("implementationGaps", []), + "previousAttempt": recovery_state.get("records", {}).get(api_id, {}).get("lastReason"), + "observedIssues": [{key: issue.get(key) for key in ("id", "cmd", "args", "firstError", "failureKeys")} + for issue in issue_rows if issue.get("capabilityId") == api_id and issue.get("status") in ACTIVE_STATUSES], + }) + support: list[Path] = [] + support.extend(probes) + if module == "BIM": + support.extend(ROOT / "web/src" / name for name in ( + "bim-image-display.ts", "bim-image-plane-task.tsx", "bim-frame-view.tsx", "bim-relationship-task.tsx", + "bim-windows-contract.ts", "bim-windows-task.tsx")) + integration_regions = application_integration_excerpts(module) if tier in {"feature-workflow", "business-acceptance"} and any(":desktop:" in record["apiId"] for record in records) else [] + support.extend(ROOT / region["path"] for region in integration_regions) + if module == "Test" and any(record.get("name") in {"Std_MDITest1", "Std_MDITest2", "Std_MDITest3", "Std_TestConsoleOutput"} for record in records): + support.extend(ROOT / "web/src" / name for name in ( + "test-desktop-routes.json", "test-facade.ts", "test.worker.ts", "test-mdi-host.tsx", "test-desktop-output.tsx")) + if any(record.get("runtimeRouteBlock") for record in records): + support.extend([ROOT / "web/src/native-source-policy.ts", ROOT / "web/src/module-router.ts"]) + slug = re.sub(r"[^a-z0-9]+", "", module.lower()) + direct_facade = ROOT / f"web/src/{slug}-facade.ts" + if (family == "runtime-issue" or tier == "business-acceptance") and direct_facade.is_file(): + support.append(direct_facade) + implementation_first = implementation_first_enabled() + workflow = str(batch.get("businessWorkflow") or "") + format_workflow = tier == "format-workflow" or family == "import-export" or ( + workflow in {"document-import-export", "document-persistence"} or workflow.startswith("format-")) + selected_gate = None if implementation_first else select_module_gate(module, slug, tier, family) + worker_candidates = ( + (ROOT / f"web/src/{slug}.worker.ts",) + if format_workflow else + (ROOT / f"web/src/{slug}-python.worker.ts", ROOT / f"web/src/{slug}.worker.ts") + ) + declared_workers = [ROOT / "web/src" / workflow_worker(module, capability_by_id[str(row[0])]) for row in batch["records"] + if row and capability_by_id.get(str(row[0]), {}).get("worker")] + worker_candidates = tuple(dict.fromkeys([*declared_workers, *worker_candidates])) + facade_candidates = [] if format_workflow or tier == "product-integration" else sorted((ROOT / "web/src").glob(f"{slug}*python*family*facade.ts")) + default_facade = ROOT / f"web/src/{slug}-python-family-facade.ts" + if not format_workflow and tier != "product-integration" and default_facade.is_file() and default_facade not in facade_candidates: + facade_candidates.insert(0, default_facade) + format_facade_candidates: list[Path] = [] + if format_workflow: + for pattern in (f"{slug}*io*facade.ts", f"{slug}*import*export*facade.ts", f"{slug}*save*facade.ts", f"{slug}*persistence*facade.ts"): + format_facade_candidates.extend((ROOT / "web/src").glob(pattern)) + direct_format_facade = ROOT / f"web/src/{slug}-facade.ts" + if direct_format_facade.is_file(): + format_facade_candidates.append(direct_format_facade) + format_dispatcher = ROOT / "web/src/format-dispatcher.ts" + if format_dispatcher.is_file(): + format_facade_candidates.append(format_dispatcher) + for path in ( + *facade_candidates, + *format_facade_candidates, + *worker_candidates, + selected_gate, + None if implementation_first else ROOT / "tools/wasm-probe-runtime.mjs", + ): + if path is not None and path.is_file(): + support.append(path) + case_paths = [] + acceptance_build = {} + explicit_build = False + acceptance_setup = None + if tier == "business-acceptance" or family == "runtime-issue": + contract_path = ROOT / f"docs/business-acceptance/{module}.json" + contract = {} + if contract_path.is_file(): + try: + contract = json.loads(contract_path.read_text(encoding="utf-8")) + command = contract.get("command", []) + if len(command) > 1: + script = (ROOT / command[1]).resolve() + if script.is_relative_to(ROOT) and script.is_file(): + case_paths.append(script) + except (OSError, ValueError, TypeError): + pass + selected_ids = {str(row[0]) for row in batch["records"] if row} + covered_ids = set(contract.get("coveredIds", [])) + acceptance_setup = {"contract": str(contract_path.relative_to(ROOT)), "caseScripts": [str(path.relative_to(ROOT)) for path in case_paths], + "selectedIds": sorted(selected_ids), "coveredIds": sorted(covered_ids), + "missingIds": sorted(selected_ids - covered_ids), + "ready": bool(case_paths and selected_ids <= covered_ids)} + declared_build, explicit_build = acceptance_build_for_ids(contract, selected_ids) + if isinstance(declared_build, dict) and declared_build.get("kind") == "frontend": + acceptance_build = frontend_acceptance_build(declared_build) + elif isinstance(declared_build, dict) and declared_build.get("tree") and declared_build.get("target"): + tree = (ROOT / str(declared_build["tree"])).resolve() + target = str(declared_build["target"]) + if tree.is_relative_to(ROOT) and tree.is_dir() and re.fullmatch(r"FreeCADWeb[A-Za-z0-9]+Probe", target): + runtime = tree / "bin" / f"{target}.js" + acceptance_build = {"target": target, "tree": str(tree.relative_to(ROOT)), "bin": str((tree / "bin").relative_to(ROOT)), + "runtime": str(runtime.relative_to(ROOT)), "wasm": str(runtime.with_suffix(".wasm").relative_to(ROOT))} + cmake = PROBE_ROOT / "CMakeLists.txt" + if cmake.is_file(): + match = re.search(rf"add_executable\(\s*{re.escape(target)}\s+([A-Za-z0-9_]+\.cpp)\b", cmake.read_text(encoding="utf-8")) + if match and (PROBE_ROOT / match.group(1)).is_file(): + support.append(PROBE_ROOT / match.group(1)) + for path in (ROOT / "tools/run_business_acceptance.py", ROOT / "tools/wasm-probe-runtime.mjs", ROOT / "docs/WEB_BUSINESS_MIGRATION_RULES.md", ROOT / "docs/current/provided-source-index.md", ROOT / "docs/current/DESKTOP_WEB_DELIVERY_PLAN_20260918.md", contract_path, *case_paths): + if path.is_file(): + support.append(path) + product_acceptance = (tier == "business-acceptance" or family == "runtime-issue") and records and all(str(row.get("apiId", "")).startswith("product:") for row in records) + browser_ui_batch = bool(records) and all( + (capability_by_id.get(row["apiId"], {}).get("route") or {}).get("transport") == "browser-ui" for row in records) + view_catalog = ROOT / "web/src/document-view-routes.json" + document_view_batch = module in {"Web", "Std"} and view_catalog.is_file() and bool(records) and all( + row.get("name") in (json.loads(view_catalog.read_text(encoding="utf-8")).get("commands", []) + + json.loads(view_catalog.read_text(encoding="utf-8")).get("standardCommands", []) + + json.loads(view_catalog.read_text(encoding="utf-8")).get("websiteCommands", [])) for row in records) + if module in {"Web", "Std"} and records: + document_view_batch = document_view_batch or all( + (capability_by_id.get(row["apiId"], {}).get("route") or {}).get("module") == "Part" + and (capability_by_id.get(row["apiId"], {}).get("route") or {}).get("command") + in {"part.viewCommand", "part.documentViewCommand"} for row in records) + if module in {"Web", "Std"} and view_catalog.is_file(): + # Pending document-view commands need the existing owning transport + # too, before they can be added to the implemented command catalog. + support.extend([view_catalog, PROBE_ROOT / "PartBoxProbe.cpp", PROBE_ROOT / "DocumentProbe.cpp", + PROBE_ROOT / "NativeDocumentView.h", PROBE_ROOT / "WebViewCommands.h"]) + support.extend(ROOT / "web/src" / name for name in ("part-view-facade.ts", "part.worker.ts", "part-save.worker.ts", + "web-desktop-adapter.ts", "web-view-task.tsx", "project-shell.tsx", + "web-owner-standard-adapter.ts", "web-standard-command-contract.ts", "web-standard-task.tsx", + "web-website-adapter.ts", "web-website-task.tsx", "web-group-adapter.ts", "web-group-contract.ts", "web-group-task.tsx", "web-commanddoc-contract.ts", "web-commanddoc-task.tsx", + "web-link-contract.ts", "web-source-test-adapter.ts", "web-structure-adapter.ts", "web-structure-contract.ts", "web-structure-task.tsx", "web-link-mutation-task.tsx", + "web-open-adapter.ts", "web-open-contract.ts", "web-open-task.tsx")) + if any(row.get("name") == "Std_Open" for row in records): + support.append(PROBE_ROOT / "WebOpenCommand.h") + if any(row.get("name") in {"Std_LinkMakeRelative", "Std_LinkReplace", "Std_LinkUnlink"} for row in records): + support.append(PROBE_ROOT / "WebLinkMutationCommands.h") + if any(row.get("name") in {"Std_Part", "Std_VarSet"} for row in records): + support.append(PROBE_ROOT / "WebStructureCommands.h") + support.append(ROOT / "tools/generate_feature_capability_registry.py") + if any(row.get("name") == "Std_Group" for row in records): + support.append(PROBE_ROOT / "WebGroupCommand.h") + if browser_ui_batch: + # Desktop overlay commands own UI layout, not FreeCAD document geometry. + support = [ROOT / "web/src" / name for name in ( + "dock-overlay-commands.json", "dock-overlay-adapter.ts", "dock-overlay-host.tsx", "dock-overlay.css", + "scene-display-commands.json", "scene-command-adapter.ts", "scene-command-host.ts", "scene-command-host.css", "scene-overlap-picker.ts", "scene-camera-commands.ts", + "import-render-bridge.ts", "scene-viewport.tsx", + "desktop-command-dispatcher.ts", "workbench-shell.tsx", "facade-envelope.ts")] + support.append(ROOT / "web/workbench.html") + if tier == "product-integration" or product_acceptance: + # Product acceptance needs real application entry points, not the + # unrelated Web workbench's native web-server fixture. + support = [path for path in support if path in case_paths or path.name in { + "run_business_acceptance.py", "WEB_BUSINESS_MIGRATION_RULES.md", "provided-source-index.md"} + or path.parent == ROOT / "docs/business-acceptance"] + for record in records: + resolved = source_path(record.get("source")) + if resolved is not None: + support.append(resolved) + product_entry = ROOT / "web/index.html" + if product_entry.is_file(): + support.append(product_entry) + if any(row.get("apiId") in {"product:desktop-workspace-parity", "product:cross-workbench-document-editing", + "product:desktop-task-interaction-parity"} for row in records): + # Existing workspaces and native adapters are reusable implementation, + # even though their filenames belong to other module namespaces. + support.extend(path for path in (ROOT / "web/src" / name for name in ( + "project-shell.tsx", "partdesign-workspace.tsx", "partdesign-workspace-component.tsx", "workbench-shell.tsx", "project-session.ts", + "module-router.ts", "desktop-command-dispatcher.ts", "import-render-bridge.ts", "navigation.ts", "storage.ts", + "part-desktop-adapter.ts", "sketcher-desktop-adapter.ts", "partdesign-desktop-adapter.ts", + "part-document-facade.ts", "partdesign-document-facade.ts", "part-save.worker.ts")) if path.is_file()) + support.extend(path for path in ( + ROOT / "docs/current/DESKTOP_WEB_UI_CONTRACT.md", ROOT / "docs/current/DESKTOP_WEB_DELIVERY_PLAN_20260918.md", + ROOT / "docs/current/CROSS_WORKBENCH_INTEGRATION_PROGRESS_20260918.md", + ROOT / "freecad-source/src/Gui/MainWindow.cpp", ROOT / "freecad-source/src/Gui/Workbench.cpp", + ROOT / "freecad-source/src/Gui/MenuManager.cpp", + ) if path.is_file()) + if any(row.get("apiId") == "product:cross-workbench-document-editing" for row in records): + support.extend(path for path in (PROBE_ROOT / name for name in ( + "DocumentProbe.cpp", "PartDesignDocumentWorkflow.cpp", "PartDesignRuntimeProbe.cpp", + "SketcherDesktopCommands.cpp", "SketcherProbe.cpp")) if path.is_file()) + part_source_table = ROOT / "web/src/part-source-commands.json" + part_source_batch = module == "Part" and part_source_table.is_file() and any( + row.get("name") in json.loads(part_source_table.read_text(encoding="utf-8")) for row in records) + if part_source_batch: + support.extend([part_source_table, PROBE_ROOT / "PartBoxProbe.cpp", PROBE_ROOT / "PartSplitSource.h"]) + support.extend((ROOT / "freecad-source/src/Mod/Part/BOPTools").glob("*.py")) + if any(row.get("name") in {"Part_Slice", "Part_SliceApart"} for row in records): + support.extend(ROOT / "freecad-source/src/Mod/Part/CompoundTools" / name + for name in ("Explode.py", "CompoundFilter.py")) + support.append(ROOT / "web/src/part-slice-task.tsx") + if module == "Part" and any(row.get("name") == "Part_Builder" for row in records): + support.extend(ROOT / "freecad-source/src/Mod/Part/Gui" / name + for name in ("TaskShapeBuilder.cpp", "TaskShapeBuilder.h", "TaskShapeBuilder.ui")) + support.extend([PROBE_ROOT / "PartBuilderDocument.h", PROBE_ROOT / "DocumentProbe.cpp", + ROOT / "web/src/part-builder-task.tsx", ROOT / "tools/part-builder-business-cases.mjs"]) + if module == "Part" and any(row.get("name") == "Part_Chamfer" for row in records): + support.extend([PROBE_ROOT / "PartChamferDocument.h", PROBE_ROOT / "DocumentProbe.cpp", + ROOT / "freecad-source/src/Mod/Part/App/FeatureChamfer.cpp", + ROOT / "freecad-source/src/Mod/Part/Gui/DlgFilletEdges.cpp", + ROOT / "web/src/part-chamfer-task.tsx", ROOT / "tools/part-chamfer-business-cases.mjs"]) + if module == "Part" and any(row.get("name") == "Part_SectionCut" for row in records): + # This workflow is owned by DocumentProbe, not the module's generic probe. + # Keep its current exported case reachable as focused increments change. + section_cases = case_reexport_sources(ROOT / "tools/part-section-cut-business-cases.mjs") + case_paths.extend(path for path in section_cases if path not in case_paths) + support.extend(section_cases) + support.extend(path for path in ( + PROBE_ROOT / "PartSectionCutDocument.h", PROBE_ROOT / "DocumentProbe.cpp", PROBE_ROOT / "PartColoredIO.h", + ROOT / "web/src/part-section-cut-task.tsx", ROOT / "web/src/part-document-facade.ts", + ROOT / "freecad-source/src/Mod/Part/Gui/SectionCutting.cpp", + ROOT / "freecad-source/src/Mod/Part/Gui/ViewProviderBoolean.cpp", + ROOT / "freecad-source/src/Mod/Part/Gui/ViewProvider.cpp", + ROOT / "freecad-source/src/Mod/Part/App/PropertyTopoShape.h", + ROOT / "freecad-source/src/Mod/Part/App/PropertyTopoShape.cpp", + ) if path.is_file()) + for member in batch.get("confirmedGaps") or [batch.get("confirmedGap", {})]: + for name in [member.get("source"), *member.get("sourceAnchors", [])]: + if not isinstance(name, str): + continue + path = (ROOT / name).resolve() + if path.is_relative_to(ROOT) and path.is_file(): + support.append(path) + support = list(dict.fromkeys(support)) + retained, retained_paths = retained_results([row["apiId"] for row in records], root=ROOT) + policy_path = ROOT / "docs/current/execution-policy.json" + policy = json.loads(policy_path.read_text()) if policy_path.is_file() else {} + explicit_gaps = policy.get("openImplementationGaps", {}) + for row in records: + if explicit_gaps.get(row["apiId"], {}).get("status") == "open": + row["remainingImplementation"] = explicit_gaps[row["apiId"]] + retained.insert(0, {"id": row["apiId"], "sourceConfirmedGap": explicit_gaps[row["apiId"]], + "instruction": "Reuse finished work. Implement this concrete remaining workflow; do not run tests. Build success alone must not close this gap. Mark the gap implemented only with concrete source/entrypoint changes that finish it, preserving its history."}) + # Metadata only: no unbounded evidence/source dumps into editable excerpts. + # These exact paths stay readable through the normal budgeted reader. + support_text = {str(path.relative_to(ROOT)): path.read_text(encoding="utf-8", errors="replace") for path in support} + facade_paths = [str(path.relative_to(ROOT)) for path in (*facade_candidates, *format_facade_candidates) if path.is_file()] + worker_paths = [str(path.relative_to(ROOT)) for path in worker_candidates if path.is_file()] + gate_path = str(selected_gate.relative_to(ROOT)) if selected_gate else "" + worker_build = build_hint(module, worker_sources, tier, family) if worker_sources else {} + build = (acceptance_build if explicit_build else worker_build or acceptance_build) or build_hint(module, probes, str(selected.get("tier") or ""), str(selected.get("family") or "")) + if part_source_batch: + build = build_hint(module, [PROBE_ROOT / "PartBoxProbe.cpp"], tier, family) + if document_view_batch: + build = build_hint("Part", [PROBE_ROOT / "PartBoxProbe.cpp"], tier, family) + if tier == "product-integration" or product_acceptance or browser_ui_batch: + build = { + "kind": "frontend", + "target": "FreeCADWebReactProduct", + "tree": "web", + "bin": "web/dist", + "runtime": "web/dist/index.html", + "wasm": "web/dist/index.html", + } + selected_names = [str(row.get("name") or "") for row in records] + feature_desktop = selected.get("tier") == "feature-workflow" and str(selected.get("family") or "").startswith("desktop-command") + desktop_adapter = next((path for path in probes if path.name == f"{module}DesktopCommands.cpp"), None) + probe_has_unified_dispatch = any("fc_web_dispatch_json" in text for _, text in probe_texts) + unified_dispatch_paths = { + path for path, text in probe_texts if "fc_web_dispatch_json" in text + } + oversized_native_sources = [ + str(path.relative_to(ROOT)) + for path, text in probe_texts + if len(text.encode("utf-8")) >= DESKTOP_ADAPTER_SPLIT_BYTES + and "DesktopCommands" not in path.name + ] + facade_uses_unified_dispatch = any("fc_web_dispatch_json" in support_text.get(facade_path, "") for facade_path in facade_paths) + worker_uses_family_dispatch = any( + re.search(r"PythonFamily(?:Batch)?Request", support_text.get(worker_path, "")) is not None + and "dispatch" in support_text.get(worker_path, "") + for worker_path in worker_paths + ) + omitted_stable_support: list[str] = [] + edit_regions: list[dict[str, object]] = list(integration_regions) + edit_used = sum(len(region["excerpt"].encode()) for region in edit_regions) + edit_limit = min(MAX_EDIT_TOTAL_BYTES, 10240) if format_workflow else MAX_EDIT_TOTAL_BYTES + format_dispatch_owners = { + path for path, text in probe_texts if "fc_web_dispatch_json" in text + } + edit_support = list(dict.fromkeys(support)) + if family == "runtime-issue" or tier == "business-acceptance": + edit_support.sort(key=lambda path: (0 if path in case_paths or path == contract_path else + 1 if path == direct_facade or path.name == "native-source-policy.ts" else + 2 if path.name.endswith(".worker.ts") else 3 if path.suffix == ".ts" else 4)) + for path in edit_support: + case_file = (tier == "business-acceptance" or family == "runtime-issue") and (path in case_paths or path == contract_path) + if path.name == "wasm-probe-runtime.mjs" or (not case_file and path.suffix not in {".cpp", ".h", ".ts", ".tsx", ".html"}): + continue + relative = str(path.relative_to(ROOT)) + if (tier == "product-integration" or product_acceptance) and path.suffix in {".cpp", ".h"}: + omitted_stable_support.append(relative) + continue + if any(region["path"] == relative for region in integration_regions): + continue + if family == "runtime-issue": + if path == direct_facade and not any(name in support_text.get(relative, "") for name in selected_names): + omitted_stable_support.append(relative) + continue + if path.name == "module-router.ts" and not any("module-router.ts" in str(issue.get("firstError", "")) for record in records for issue in record.get("observedIssues", [])): + omitted_stable_support.append(relative) + continue + # For a desktop feature batch, keep editable native context focused on + # the translation unit that owns the unified dispatcher. Other probe + # units remain in supportFiles with fingerprints, but their generic + # file-tail excerpts make the agent reread unrelated code and inflate + # post-read decision time. A split DesktopCommands adapter remains + # authoritative and is handled by the existing branch below. + if ( + feature_desktop + and probe_has_unified_dispatch + and path in probes + and path.suffix in {".cpp", ".h"} + and desktop_adapter is None + and path not in unified_dispatch_paths + ): + omitted_stable_support.append(relative) + continue + if format_workflow and path in probes and path.suffix in {".cpp", ".h"} and path not in format_dispatch_owners: + omitted_stable_support.append(relative) + continue + if feature_desktop and desktop_adapter is not None and path.suffix in {".cpp", ".h"} and path != desktop_adapter: + omitted_stable_support.append(relative) + continue + if feature_desktop and not recovering and ((relative in facade_paths and facade_uses_unified_dispatch) or (relative in worker_paths and worker_uses_family_dispatch)): + omitted_stable_support.append(relative) + continue + path_regions = editable_excerpts(path, support_text.get(relative, ""), selected_names) + has_native_edit_anchor = any(region.get("role") != "unified-dispatch" for region in path_regions) + for region in path_regions: + if feature_desktop and probe_has_unified_dispatch and path.suffix in {".cpp", ".h"} and region.get("role") == "unified-dispatch" and has_native_edit_anchor: + continue + encoded = len(str(region["excerpt"]).encode("utf-8")) + if edit_used + encoded > edit_limit: + break + edit_used += encoded + edit_regions.append(region) + probe_entries: list[dict[str, object]] = [] + for path, text in probe_texts: + for line_number, line in enumerate(text.splitlines(), 1): + if "fc_web_dispatch_json" in line or re.search(r"\b(?:bool|QJsonObject)\s+execute[A-Za-z0-9_]+", line): + probe_entries.append({"path": str(path.relative_to(ROOT)), "line": line_number, "symbol": line.strip()[:180]}) + payload = { + "schema": "freecad-web-module-implementation-packet/v1", + "confirmedGap": batch.get("confirmedGap"), + "confirmedGaps": batch.get("confirmedGaps", []), + "functionalPackage": batch.get("functionalPackage"), + "generatedAt": datetime.now(timezone.utc).isoformat(), + "batchId": batch.get("batchId"), + "module": module, + "tier": selected.get("tier"), + "family": selected.get("family"), + "recordCount": len(records), + "excerptBytes": used, + "nativeExcerptBytes": native_used, + "editableExcerptBytes": edit_used, + "truncatedRecords": truncated, + "supportFiles": [file_entry(path) for path in dict.fromkeys([*support, *retained_paths])], + "retainedBusinessResults": retained, + "repositoryContext": instruction_context(support), + "supportChecks": { + "probeHasUnifiedDispatch": probe_has_unified_dispatch, + "facadeUsesUnifiedDispatch": facade_uses_unified_dispatch, + "workerUsesFamilyDispatch": worker_uses_family_dispatch, + "gateReadsCurrentManifest": "module-batch-manifest.json" in support_text.get(gate_path, "") and "batch.selected" in support_text.get(gate_path, ""), + "sharedNodeLoaderAvailable": "loadWasmProbe" in support_text.get("tools/wasm-probe-runtime.mjs", ""), + "desktopAdapterRecommended": bool(feature_desktop and oversized_native_sources), + "desktopAdapterActive": desktop_adapter is not None, + "oversizedNativeSources": oversized_native_sources, + "desktopAdapterSplitBytes": DESKTOP_ADAPTER_SPLIT_BYTES, + "desktopAdapterAction": ( + f"do not grow oversized runtime; put new commands in {module}DesktopCommands.cpp/.h and link them into the same module target" + if feature_desktop and oversized_native_sources else None + ), + }, + "build": build, + "buildHistory": scoped_build_history(batch, build), + "gate": gate_path or None, + "implementationMode": "feature-first-deferred-validation" if implementation_first else "evidence-first", + "validationDeferred": implementation_first, + "outerPipelineAvailable": tier == "business-acceptance" or bool(build and (implementation_first or selected_gate)), + "acceptanceContract": f"docs/business-acceptance/{module}.json" if tier == "business-acceptance" or family == "runtime-issue" else None, + "acceptanceSetup": acceptance_setup, + "businessWorkflow": batch.get("businessWorkflow"), + "nativeEntryPoints": probe_entries[:24], + "editableExcerpts": edit_regions, + "omittedStableSupport": sorted(set(omitted_stable_support)), + "records": records, + "moduleRecovery": module_recovery, + "failureReconciliation": failure_context, + "integrationRepair": {"applicationCallSites": sorted({row["path"] for row in integration_regions}), + "instruction": "Complete the current business through these application call sites. Keep module-specific validation and selection in the existing -desktop-adapter.ts; shared dispatcher edits invalidate every module. Change the common dispatcher only for a demonstrated shared-contract defect or one-time adapter wiring. Do not stop at new helpers or an unmounted component."} if integration_regions else None, + } + OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True) + temporary = OUTPUT_PATH.with_suffix(".tmp") + temporary.write_text(json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + "\n", encoding="utf-8") + temporary.replace(OUTPUT_PATH) + print(json.dumps({"status": "ready", "batchId": batch.get("batchId"), "records": len(records), "excerptBytes": used, "editableExcerptBytes": edit_used, "truncatedRecords": truncated}, ensure_ascii=False)) + return 0 + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--batch", type=Path, default=BATCH_PATH) + parser.add_argument("--output", type=Path, default=OUTPUT_PATH) + options = parser.parse_args() + BATCH_PATH = (ROOT / options.batch).resolve() + OUTPUT_PATH = (ROOT / options.output).resolve() + if not BATCH_PATH.is_relative_to(ROOT) or not OUTPUT_PATH.is_relative_to(ROOT): + parser.error("batch and output must remain inside the workspace") + OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True) + raise SystemExit(main()) diff --git a/tools/run_p6_chrome_harness.mjs b/tools/run_p6_chrome_harness.mjs new file mode 100644 index 00000000..a592c9ae --- /dev/null +++ b/tools/run_p6_chrome_harness.mjs @@ -0,0 +1,526 @@ +#!/usr/bin/env node + +import crypto from "node:crypto"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawn } from "node:child_process"; + +const toolsRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url))); +const projectRoot = path.resolve(toolsRoot, ".."); +const docsRoot = path.join(projectRoot, "docs"); +const distRoot = path.join(projectRoot, "web", "dist"); +const scenario = process.env.P6_CHROME_SCENARIO ?? "baseline"; +const preloadModules = (process.env.P6_CHROME_PRELOAD_MODULES ?? "").split(",").map((value) => value.trim()).filter(Boolean); +const preloadManifest = process.env.P6_CHROME_MODULE_MANIFEST ?? "/modules/manifest.json"; +const preloadConcurrency = Math.max(1, Math.min(2, Number(process.env.P6_CHROME_PRELOAD_CONCURRENCY ?? 2))); +const preloadKinds = (process.env.P6_CHROME_PRELOAD_ASSETS ?? "wasm,data").split(",").map((value) => value.trim()).filter(Boolean); +const isOpenScadScenario = false; +const isPartScenario = scenario === "part" || scenario === "part-io" || scenario === "part-inspect" || scenario === "part-python" || scenario === "part-save"; +const isPartDesignScenario = scenario === "partdesign"; +const isPartDesignInspectScenario = scenario === "partdesign-inspect"; +const isPartDesignPythonScenario = scenario === "partdesign-python"; +const isPointsScenario = scenario === "points" || scenario === "points-inspect" || scenario === "points-python"; +const isPointsInspectScenario = scenario === "points-inspect"; +const isPointsPythonScenario = scenario === "points-python"; +const isPointsSaveScenario = scenario === "points-save"; +const isSandboxScenario = scenario === "sandbox"; +const isSandboxInspectScenario = scenario === "sandbox-inspect"; +const isSandboxPythonScenario = scenario === "sandbox-python"; +const isSandboxSaveScenario = scenario === "sandbox-save"; +const isSketcherScenario = scenario === "sketcher"; +const isSketcherInspectScenario = scenario === "sketcher-inspect"; +const isSketcherPythonScenario = scenario === "sketcher-python"; +const isSpreadsheetScenario = scenario === "spreadsheet"; +const isSpreadsheetInspectScenario = scenario === "spreadsheet-inspect"; +const isSpreadsheetPythonScenario = scenario === "spreadsheet-python"; +const isSpreadsheetSaveScenario = scenario === "spreadsheet-save"; +const isSurfaceScenario = scenario === "surface"; +const isSurfacePythonScenario = scenario === "surface-python"; +const isSurfaceSaveScenario = scenario === "surface-save"; +const isStartScenario = scenario === "start"; +const isStartInspectScenario = scenario === "start-inspect"; +const isStartPythonScenario = scenario === "start-python"; +const isTemplatePyModScenario = scenario === "templatepymod"; +const isTemplatePyModPythonScenario = scenario === "templatepymod-python"; +const isTuxScenario = scenario === "tux"; +const isWebScenario = scenario === "web"; +const isWebPersistenceScenario = scenario === "web-action-03"; +const isTestScenario = scenario === "test"; +const isTechDrawScenario = scenario === "techdraw"; +const isTechDrawNativeScenario = scenario === "techdraw-native"; +const isTechDrawInspectScenario = scenario === "techdraw-inspect"; +const isTechDrawPythonScenario = scenario === "techdraw-python"; +const isTechDrawSaveScenario = scenario === "techdraw-save"; +const isCoreScenario = scenario === "core"; +const isDataPropertyScenario = scenario === "data-property"; +const isDocumentScenario = scenario === "document"; +const isWorkbenchScenario = scenario === "workbench"; +const isViewScenario = scenario === "view"; +const isWebLikeScenario = isWebScenario || isWebPersistenceScenario; +const isActionScenario = isOpenScadScenario || isPartScenario || isPartDesignScenario || isPartDesignInspectScenario || isPartDesignPythonScenario || isPointsScenario || isPointsSaveScenario || isSandboxScenario || isSandboxInspectScenario || isSandboxPythonScenario || isSandboxSaveScenario || isSketcherScenario || isSketcherInspectScenario || isSketcherPythonScenario || isSpreadsheetScenario || isSpreadsheetInspectScenario || isSpreadsheetPythonScenario || isSpreadsheetSaveScenario || isSurfaceScenario || isSurfacePythonScenario || isSurfaceSaveScenario || isStartScenario || isStartInspectScenario || isStartPythonScenario || isTemplatePyModScenario || isTemplatePyModPythonScenario || isTuxScenario || isWebLikeScenario || isTestScenario || isTechDrawScenario || isTechDrawNativeScenario || isTechDrawInspectScenario || isTechDrawPythonScenario || isTechDrawSaveScenario || isCoreScenario || isDataPropertyScenario || isDocumentScenario || isWorkbenchScenario || isViewScenario; +const scenarioStem = process.env.P6_CHROME_OUTPUT_STEM ?? (scenario === "view" ? "view-interaction-chrome" : scenario === "workbench" ? "workbench-command-chrome" : scenario === "document" ? "document-contract-chrome" : scenario === "data-property" ? "data-property-family-chrome" : scenario === "core" ? "core-shell-chrome" : scenario === "techdraw-save" ? "techdraw-action-05-native-chrome" : scenario === "techdraw-python" ? "techdraw-action-04-native-chrome" : scenario === "techdraw-inspect" ? "techdraw-action-03-native-chrome" : scenario === "techdraw-native" ? "techdraw-action-02-native-chrome" : scenario === "techdraw" ? "techdraw-chrome" : scenario === "test" ? "test-chrome" : scenario === "web-action-03" ? "web-action-03-chrome" : scenario === "web" ? "web-chrome" : scenario === "tux" ? "tux-chrome" : scenario === "templatepymod-python" ? "templatepymod-action-02-chrome" : scenario === "templatepymod" ? "templatepymod-chrome" : scenario === "start-python" ? "start-action-03-chrome" : scenario === "start-inspect" ? "start-action-02-chrome" : scenario === "start" ? "start-chrome" : scenario === "surface-save" ? "surface-action-04-chrome" : scenario === "surface-python" ? "surface-action-03-chrome" : scenario === "surface" ? "surface-chrome" : scenario === "spreadsheet-save" ? "spreadsheet-action-04-chrome" : scenario === "spreadsheet-python" ? "spreadsheet-action-03-chrome" : scenario === "spreadsheet-inspect" ? "spreadsheet-action-02-chrome" : scenario === "spreadsheet" ? "spreadsheet-chrome" : scenario === "sketcher-python" ? "sketcher-action-03-chrome" : scenario === "sketcher-inspect" ? "sketcher-action-02-chrome" : scenario === "sketcher" ? "sketcher-chrome" : scenario === "sandbox-save" ? "sandbox-action-04-chrome" : scenario === "sandbox-python" ? "sandbox-action-03-chrome" : scenario === "sandbox-inspect" ? "sandbox-action-02-chrome" : scenario === "sandbox" ? "sandbox-chrome" : scenario === "points-python" ? "points-python-chrome" : scenario === "points-inspect" ? "points-inspect-chrome" : scenario === "points-save" ? "points-action-04-chrome" : scenario === "openscad-python" ? "openscad-python-chrome" : scenario === "openscad" ? "openscad-chrome" : scenario === "points" ? "points-chrome" : scenario === "partdesign" ? "partdesign-chrome" : scenario === "partdesign-inspect" ? "partdesign-action-02-chrome" : scenario === "partdesign-python" ? "partdesign-action-03-chrome" : scenario === "part-save" ? "part-save-chrome" : scenario === "part-python" ? "part-python-chrome" : scenario === "part-inspect" ? "part-inspect-chrome" : scenario === "part-io" ? "part-io-chrome" : scenario === "part" ? "part-chrome" : "chrome-harness"); +const outputPath = path.join(docsRoot, "p6", `${scenarioStem}.json`); +const schemaPath = path.join(docsRoot, "p6", "chrome-harness.schema.json"); +const defaultLogPath = path.join(docsRoot, + scenario === "view" ? "freecad-p6-view-interaction-chrome.log" : + scenario === "workbench" ? "freecad-p6-workbench-command-chrome.log" : + scenario === "document" ? "freecad-p6-document-contract-chrome.log" : + scenario === "data-property" ? "freecad-p6-data-property-family-chrome.log" : + scenario === "core" ? "freecad-p6-core-shell-chrome.log" : + scenario === "points-python" ? "freecad-p6-points-action-03-f-chrome.log" : scenario === "points-inspect" ? "freecad-p6-points-action-02-f-chrome.log" : scenario === "points" ? "freecad-p6-points-f-chrome.log" : + scenario === "partdesign" ? "freecad-p6-partdesign-f-chrome.log" : scenario === "partdesign-inspect" ? "freecad-p6-partdesign-action-02-f-chrome.log" : scenario === "partdesign-python" ? "freecad-p6-partdesign-action-03-f-chrome.log" : scenario === "points-save" ? "freecad-p6-points-action-04-f-chrome.log" : + scenario === "part-save" ? "freecad-p6-part-action-05-f-chrome.log" : + scenario === "part-python" ? "freecad-p6-part-action-04-f-chrome.log" : + scenario === "part-inspect" ? "freecad-p6-part-action-03-f-chrome.log" : + scenario === "part-io" ? "freecad-p6-part-action-02-f-chrome.log" : + scenario === "part" ? "freecad-p6-part-f-chrome.log" : + scenario === "sandbox" ? "freecad-p6-sandbox-f-chrome.log" : + scenario === "sandbox-inspect" ? "freecad-p6-sandbox-action-02-f-chrome.log" : + scenario === "sandbox-python" ? "freecad-p6-sandbox-action-03-f-chrome.log" : + scenario === "sandbox-save" ? "freecad-p6-sandbox-action-04-f-chrome.log" : + scenario === "sketcher" ? "freecad-p6-sketcher-f-chrome.log" : + scenario === "sketcher-inspect" ? "freecad-p6-sketcher-action-02-f-chrome.log" : + scenario === "sketcher-python" ? "freecad-p6-sketcher-action-03-f-chrome.log" : + scenario === "spreadsheet" ? "freecad-p6-spreadsheet-f-chrome.log" : + scenario === "spreadsheet-inspect" ? "freecad-p6-spreadsheet-action-02-f-chrome.log" : + scenario === "spreadsheet-python" ? "freecad-p6-spreadsheet-action-03-f-chrome.log" : + scenario === "spreadsheet-save" ? "freecad-p6-spreadsheet-action-04-f-chrome.log" : + scenario === "surface" ? "freecad-p6-surface-f-chrome.log" : + scenario === "surface-python" ? "freecad-p6-surface-action-03-f-chrome.log" : + scenario === "surface-save" ? "freecad-p6-surface-action-04-f-chrome.log" : + scenario === "start" ? "freecad-p6-start-f-chrome.log" : + scenario === "start-inspect" ? "freecad-p6-start-action-02-f-chrome.log" : + scenario === "start-python" ? "freecad-p6-start-action-03-f-chrome.log" : + scenario === "templatepymod" ? "freecad-p6-templatepymod-f-chrome.log" : + scenario === "tux" ? "freecad-p6-tux-f-chrome.log" : + scenario === "web" ? "freecad-p6-web-f-chrome.log" : + scenario === "templatepymod-python" ? "freecad-p6-templatepymod-action-02-f-chrome.log" : + scenario === "web-action-03" ? "freecad-p6-web-action-03-f-chrome.log" : + scenario === "test" ? "freecad-p6-test-f-chrome.log" : + scenario === "techdraw" ? "freecad-p6-techdraw-frontend-chrome.log" : + scenario === "techdraw-native" ? "freecad-p6-techdraw-action-02-native-f-chrome.log" : + scenario === "techdraw-inspect" ? "freecad-p6-techdraw-action-03-native-f-chrome.log" : + scenario === "techdraw-python" ? "freecad-p6-techdraw-action-04-native-f-chrome.log" : + scenario === "techdraw-save" ? "freecad-p6-techdraw-action-05-native-f-chrome.log" : + "freecad-p6-003-chrome-harness.log"); +const logPath = process.env.P6_CHROME_LOG_PATH ? path.resolve(projectRoot, process.env.P6_CHROME_LOG_PATH) : defaultLogPath; +const screenshotPath = path.join(docsRoot, "p6", `${scenarioStem}.png`); +const viewport = { width: 1440, height: 900, deviceScaleFactor: 1 }; +const timeoutMs = 30000; + +function sha256(value) { + return crypto.createHash("sha256").update(value).digest("hex"); +} + +function findChrome() { + return [ + "/usr/bin/google-chrome", + "/usr/bin/google-chrome-stable", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + "/opt/google/chrome/google-chrome", + ].find((candidate) => fs.existsSync(candidate)) ?? null; +} + +function contentType(filePath) { + return { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".wasm": "application/wasm", + ".step": "application/step", + ".json": "application/json; charset=utf-8", + ".css": "text/css; charset=utf-8", + }[path.extname(filePath)] ?? "application/octet-stream"; +} + +function withPreload(url) { + if (!preloadModules.length) return url; + const value = new URL(url); + value.searchParams.set("moduleManifest", preloadManifest); + value.searchParams.set("preloadModules", preloadModules.join(",")); + value.searchParams.set("preloadConcurrency", String(preloadConcurrency)); + value.searchParams.set("preloadKinds", preloadKinds.join(",")); + return value.href; +} + +async function listen(server) { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + return server.address().port; +} + +class CdpSession { + constructor(url) { + this.socket = new WebSocket(url); + this.nextId = 1; + this.pending = new Map(); + this.listeners = new Map(); + this.ready = new Promise((resolve, reject) => { + this.socket.addEventListener("open", resolve, { once: true }); + this.socket.addEventListener("error", reject, { once: true }); + }); + this.socket.addEventListener("message", (event) => { + const message = JSON.parse(event.data); + if (message.id !== undefined) { + const pending = this.pending.get(message.id); + if (!pending) return; + this.pending.delete(message.id); + if (message.error) pending.reject(new Error(`${pending.method}: ${message.error.code}: ${message.error.message}`)); + else pending.resolve(message.result); + return; + } + for (const listener of this.listeners.get(message.method) ?? []) listener(message.params); + }); + } + + // Keep the method name on rejected protocol calls for deterministic recovery logs. + + async send(method, params = {}) { + await this.ready; + const id = this.nextId++; + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject, method }); + this.socket.send(JSON.stringify({ id, method, params })); + }); + } + + on(method, listener) { + const listeners = this.listeners.get(method) ?? []; + listeners.push(listener); + this.listeners.set(method, listeners); + } + + close() { + this.socket.close(); + } +} + +async function waitFor(label, predicate, evaluate, timeout = timeoutMs) { + const deadline = Date.now() + timeout; + let last; + while (Date.now() < deadline) { + last = await evaluate(); + if (predicate(last)) return last; + await new Promise((resolve) => setTimeout(resolve, 200)); + } + throw new Error(`${label} timed out: ${JSON.stringify(last)}`); +} + +const log = []; +const chromePath = findChrome(); +if (!chromePath) { + const blocked = { + schema: "freecad-web-p6-chrome-harness/v1", + result: "blocked_chrome_unavailable", + environmentError: "Google Chrome executable was not found; no alternate browser was attempted", + policy: { browser: "Google Chrome only", nonChromeBrowsersAttempted: false }, + }; + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, `${JSON.stringify(blocked, null, 2)}\n`); + fs.writeFileSync(logPath, `${blocked.environmentError}\n`); + console.error(blocked.environmentError); + process.exitCode = 2; +} else { + const entry = isViewScenario ? "index.html" : isWorkbenchScenario ? "workbench.html" : isDocumentScenario ? "document.html" : isDataPropertyScenario ? "core.html" : isCoreScenario ? "core.html" : isSurfaceSaveScenario ? "surface-save.html" : isSurfacePythonScenario ? "surface-python.html" : isSurfaceScenario ? "surface.html" : isSketcherPythonScenario ? "sketcher-python.html" : isSketcherInspectScenario ? "sketcher-inspect.html" : isSketcherScenario ? "sketcher.html" : isSandboxSaveScenario ? "sandbox-save.html" : isSandboxPythonScenario ? "sandbox-python.html" : isSandboxInspectScenario ? "sandbox-inspect.html" : isSandboxScenario ? "sandbox.html" : isOpenScadScenario ? "openscad.html" : isPointsPythonScenario ? "points-python.html" : isPointsInspectScenario ? "points-inspect.html" : isPointsSaveScenario ? "points-save.html" : isPointsScenario ? "points.html" : isPartDesignPythonScenario ? "partdesign-python.html" : isPartDesignInspectScenario ? "partdesign-inspect.html" : isPartDesignScenario ? "partdesign.html" : isPartScenario ? (scenario === "part-io" ? "part-io.html" : scenario === "part-inspect" ? "part-inspect.html" : scenario === "part-python" ? "part-python.html" : scenario === "part-save" ? "part-save.html" : "part.html") : "index.html"; + if (!fs.existsSync(path.join(distRoot, entry))) throw new Error(`${entry} is missing; run npm run build first`); + const server = http.createServer((request, response) => { + const requestPath = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname); + if (requestPath === "/favicon.ico") { + response.writeHead(204); + response.end(); + return; + } + const relative = requestPath === "/" ? "index.html" : requestPath.replace(/^\/+/, ""); + const filePath = path.resolve(distRoot, relative); + if (filePath !== distRoot && !filePath.startsWith(`${distRoot}${path.sep}`)) { + response.writeHead(403); response.end("forbidden"); return; + } + if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { + response.writeHead(404); response.end("not found"); return; + } + const cacheControl = requestPath.startsWith("/kernel/") || requestPath.startsWith("/modules/") + ? "public, max-age=3600" + : "no-store"; + response.writeHead(200, { + "content-type": contentType(filePath), + "cache-control": cacheControl, + // FreeCAD WASM uses SharedArrayBuffer; the smoke server must be + // cross-origin isolated just like the production deployment. + "cross-origin-opener-policy": "same-origin", + "cross-origin-embedder-policy": "require-corp", + }); + fs.createReadStream(filePath).pipe(response); + }); + const serverPort = await listen(server); + const origin = `http://127.0.0.1:${serverPort}`; + const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "freecad-p6-chrome-")); + const chrome = spawn(chromePath, [ + "--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", + "--remote-debugging-port=0", "--remote-allow-origins=*", `--user-data-dir=${userDataDir}`, + `--window-size=${viewport.width},${viewport.height}`, withPreload(isViewScenario ? `${origin}/?sample=1` : isDataPropertyScenario ? `${origin}/core.html` : isCoreScenario ? `${origin}/core.html` : isSurfacePythonScenario ? `${origin}/surface-python.html` : isSurfaceScenario ? `${origin}/surface.html` : isSpreadsheetSaveScenario ? `${origin}/spreadsheet-save.html` : isSpreadsheetPythonScenario ? `${origin}/spreadsheet-python.html` : isSpreadsheetInspectScenario ? `${origin}/spreadsheet-inspect.html` : isSpreadsheetScenario ? `${origin}/spreadsheet.html` : isSketcherPythonScenario ? `${origin}/sketcher-python.html` : isSketcherInspectScenario ? `${origin}/sketcher-inspect.html` : isSketcherScenario ? `${origin}/sketcher.html` : isSandboxSaveScenario ? `${origin}/sandbox-save.html` : isSandboxPythonScenario ? `${origin}/sandbox-python.html` : isSandboxInspectScenario ? `${origin}/sandbox-inspect.html` : isSandboxScenario ? `${origin}/sandbox.html` : isOpenScadScenario ? `${origin}/openscad.html${scenario === "openscad-python" ? "?action=python-api" : ""}` : isPointsPythonScenario ? `${origin}/points-python.html` : isPointsInspectScenario ? `${origin}/points-inspect.html` : isPointsSaveScenario ? `${origin}/points-save.html` : isPointsScenario ? `${origin}/points.html` : isPartDesignPythonScenario ? `${origin}/partdesign-python.html` : isPartDesignInspectScenario ? `${origin}/partdesign-inspect.html` : isPartDesignScenario ? `${origin}/partdesign.html` : isPartScenario ? (scenario === "part-io" ? `${origin}/part-io.html` : scenario === "part-inspect" ? `${origin}/part-inspect.html` : scenario === "part-python" ? `${origin}/part-python.html` : scenario === "part-save" ? `${origin}/part-save.html` : `${origin}/part.html`) : `${origin}/?sample=1`), + ], { stdio: ["ignore", "pipe", "pipe"] }); + let chromeOutput = ""; + chrome.stdout.on("data", (chunk) => { chromeOutput += chunk.toString(); }); + chrome.stderr.on("data", (chunk) => { chromeOutput += chunk.toString(); }); + + let cdp; + try { + let target; + const deadline = Date.now() + timeoutMs; + while (!target && Date.now() < deadline) { + try { + const match = chromeOutput.match(/DevTools listening on ws:\/\/([^\s]+)/); + if (match) { + const port = match[1].split(":")[1].split("/")[0]; + const targets = await fetch(`http://127.0.0.1:${port}/json/list`).then((response) => response.json()); + target = targets.find((item) => item.type === "page"); + } + } catch { + // Chrome is still starting. + } + if (!target) await new Promise((resolve) => setTimeout(resolve, 100)); + } + if (!target?.webSocketDebuggerUrl) throw new Error(`Chrome CDP target unavailable: ${chromeOutput.trim()}`); + cdp = new CdpSession(target.webSocketDebuggerUrl); + const requests = []; + const responses = []; + const consoleEntries = []; + const exceptions = []; + cdp.on("Network.requestWillBeSent", (event) => requests.push({ requestId: event.requestId, url: event.request.url, method: event.request.method, type: event.type })); + cdp.on("Network.responseReceived", (event) => responses.push({ requestId: event.requestId, url: event.response.url, status: event.response.status })); + cdp.on("Runtime.consoleAPICalled", (event) => consoleEntries.push({ type: event.type, text: event.args?.map((arg) => arg.value ?? arg.description ?? "").join(" ") ?? "" })); + cdp.on("Runtime.exceptionThrown", (event) => exceptions.push(event.exceptionDetails?.text ?? "runtime exception")); + cdp.on("Log.entryAdded", (event) => { if (event.entry.level === "error") consoleEntries.push({ type: "log", text: event.entry.text }); }); + await cdp.send("Runtime.enable"); + await cdp.send("Network.enable"); + await cdp.send("Log.enable"); + await cdp.send("Page.enable"); + await cdp.send("Emulation.setDeviceMetricsOverride", { ...viewport, mobile: false }); + if (isSurfaceSaveScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/surface-save.html`) }); + if (isStartScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/start.html`) }); + if (isStartInspectScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/start-inspect.html`) }); + if (isStartPythonScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/start-python.html`) }); + if (isTemplatePyModScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/templatepymod.html`) }); + if (isTemplatePyModPythonScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/templatepymod-python.html`) }); + if (isTuxScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/tux.html`) }); + if (isWebScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/web.html`) }); + if (isWebPersistenceScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/web-persistence.html`) }); + if (isTestScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/test.html`) }); + if (isTechDrawScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw.html`) }); + if (isTechDrawNativeScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-native.html`) }); + if (isTechDrawInspectScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-inspect.html`) }); + if (isTechDrawPythonScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-python.html`) }); + if (isTechDrawSaveScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/techdraw-save.html`) }); + if (isCoreScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/core.html`) }); + if (isDataPropertyScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/core.html`) }); + if (isDocumentScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/document.html?mode=full`) }); + if (isWorkbenchScenario) await cdp.send("Page.navigate", { url: withPreload(`${origin}/workbench.html`) }); + + async function evaluate(expression) { + const result = await cdp.send("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }); + if (result.exceptionDetails) throw new Error(result.exceptionDetails.text ?? "Runtime.evaluate failed"); + return result.result?.value; + } + const modulePreload = preloadModules.length + ? await waitFor("module artifact preload", (value) => value?.phase === "ready" || value?.phase === "error", () => evaluate("window.__freecadModulePreloadState ?? null"), 180000) + : { phase: "disabled", manifestUrl: null, requestedModules: [], requestedAssets: 0, loadedAssets: 0, failedAssets: [], loadedBytes: 0 }; + if (modulePreload.phase === "error") throw new Error(`module artifact preload failed: ${JSON.stringify(modulePreload.failedAssets)}`); + async function state() { + if (isViewScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', stage: window.__freecadViewState?.stage ?? 'starting', view: window.__freecadViewState ?? null, canvasPixels: (() => { const c = document.querySelector('#viewport canvas'); if (!c) return 0; const ctx = c.getContext('2d'); return ctx ? 0 : c.width * c.height; })(), controls: [...document.querySelectorAll('button,select,input')].filter((item) => !item.disabled).map((item) => item.id)}))()"); + if (isWorkbenchScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadWorkbenchState?.stage ?? 'ready', response: window.__freecadWorkbenchState?.response ?? null, matrix: window.__freecadWorkbenchState?.matrix ?? null, selected: window.__freecadWorkbenchState?.selected ?? null}))()"); + if (isWebScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadWebState?.stage ?? 'ready', response: window.__freecadWebState?.response ?? null}))()"); + if (isWebPersistenceScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadWebPersistenceState?.stage ?? 'ready', response: window.__freecadWebPersistenceState?.response ?? null}))()"); + if (isTestScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTestState?.stage ?? 'ready', response: window.__freecadTestState?.response ?? null}))()"); + if (isTechDrawScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawState?.stage ?? 'ready', response: window.__freecadTechDrawState?.response ?? null}))()"); + if (isTechDrawNativeScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawNativeState?.stage ?? 'ready', response: window.__freecadTechDrawNativeState?.response ?? null}))()"); + if (isTechDrawInspectScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawInspectState?.stage ?? 'ready', response: window.__freecadTechDrawInspectState?.response ?? null}))()"); + if (isTechDrawPythonScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawPyState?.stage ?? 'ready', response: window.__freecadTechDrawPyState?.response ?? null}))()"); + if (isTechDrawSaveScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTechDrawSaveState?.stage ?? 'ready', response: window.__freecadTechDrawSaveState?.response ?? null}))()"); + if (isCoreScenario) return evaluate("(() => { const s = window.__freecadCoreShellState ?? {}; const error = s.response?.error?.code ?? null; return {status: document.querySelector('.status')?.textContent ?? '', stage: s.stage ?? 'ready', response: s.response ?? null, progress: s.progress ?? [], duplicate: s.duplicate ?? (error === 'duplicate_request' ? error : null), cancel: s.cancel ?? (error === 'cancelled' ? error : null)}; })()"); + if (isDataPropertyScenario) return evaluate("(() => { const s = window.__freecadCoreShellState ?? {}; const error = s.response?.error?.code ?? null; return {status: document.querySelector('.status')?.textContent ?? '', stage: s.stage ?? 'ready', response: s.response ?? null, progress: s.progress ?? [], duplicate: s.duplicate ?? (error === 'duplicate_request' ? error : null), cancel: s.cancel ?? (error === 'cancelled' ? error : null)}; })()"); + if (isDocumentScenario) return evaluate("(() => { const s = window.__freecadCoreShellState ?? {}; const error = s.response?.error?.code ?? null; return {status: document.querySelector('.status')?.textContent ?? '', stage: s.stage ?? 'ready', response: s.response ?? null, progress: s.progress ?? [], duplicate: s.duplicate ?? (error === 'duplicate_request' ? error : null), cancel: s.cancel ?? (error === 'cancelled' ? error : null)}; })()"); + if (isTuxScenario) return evaluate("(() => ({status: document.querySelector('.status')?.textContent ?? '', stage: window.__freecadTuxState?.stage ?? 'ready', response: window.__freecadTuxState?.response ?? null}))()"); + if (isTemplatePyModPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadTpmPyState?.stage ?? '', requestId: window.__freecadTpmPyState?.requestId ?? null, response: window.__freecadTpmPyState?.response ?? null, api: document.querySelector('#api')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()"); + if (isTemplatePyModScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadTpmState?.stage ?? '', requestId: window.__freecadTpmState?.requestId ?? null, response: window.__freecadTpmState?.response ?? null, lines: document.querySelector('#lines')?.textContent ?? '', pythonOnly: document.querySelector('#pythonOnly')?.textContent ?? ''}))()"); + if (isStartPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadStartPyState?.stage ?? '', requestId: window.__freecadStartPyState?.requestId ?? null, response: window.__freecadStartPyState?.response ?? null, module: document.querySelector('#module')?.textContent ?? '', api: document.querySelector('#api')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()"); + if (isStartInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadStartInventoryState?.stage ?? '', requestId: window.__freecadStartInventoryState?.requestId ?? null, response: window.__freecadStartInventoryState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', readOnly: document.querySelector('#readOnly')?.textContent ?? ''}))()"); + if (isStartScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadStartState?.stage ?? '', requestId: window.__freecadStartState?.requestId ?? null, response: window.__freecadStartState?.response ?? null, module: document.querySelector('#module')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()"); + if (isSurfaceSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSurfaceSaveState?.stage ?? '', requestId: window.__freecadSurfaceSaveState?.requestId ?? null, response: window.__freecadSurfaceSaveState?.response ?? null, path: document.querySelector('#path')?.textContent ?? '', objects: document.querySelector('#objects')?.textContent ?? '', round: document.querySelector('#round')?.textContent ?? ''}))()"); + if (isSurfacePythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSurfacePyState?.stage ?? '', requestId: window.__freecadSurfacePyState?.requestId ?? null, response: window.__freecadSurfacePyState?.response ?? null, count: document.querySelector('#count')?.textContent ?? '', names: document.querySelector('#names')?.textContent ?? ''}))()"); + if (isSurfaceScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSurfaceState?.stage ?? '', requestId: window.__freecadSurfaceState?.requestId ?? null, response: window.__freecadSurfaceState?.response ?? null, object: document.querySelector('#object')?.textContent ?? '', objects: document.querySelector('#objects')?.textContent ?? '', recompute: document.querySelector('#recompute')?.textContent ?? ''}))()"); + if (isSpreadsheetSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetSaveState?.stage ?? '', requestId: window.__freecadSpreadsheetSaveState?.requestId ?? null, response: window.__freecadSpreadsheetSaveState?.response ?? null, path: document.querySelector('#path')?.textContent ?? '', size: document.querySelector('#size')?.textContent ?? '', round: document.querySelector('#round')?.textContent ?? ''}))()"); + if (isSpreadsheetPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetPythonState?.stage ?? '', requestId: window.__freecadSpreadsheetPythonState?.requestId ?? null, response: window.__freecadSpreadsheetPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? '', cells: document.querySelector('#cells')?.textContent ?? ''}))()"); + if (isSpreadsheetInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetInspectState?.stage ?? '', requestId: window.__freecadSpreadsheetInspectState?.requestId ?? null, response: window.__freecadSpreadsheetInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', formats: document.querySelector('#formats')?.textContent ?? '', bindings: document.querySelector('#bindings')?.textContent ?? ''}))()"); + if (isSpreadsheetScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSpreadsheetState?.stage ?? '', requestId: window.__freecadSpreadsheetState?.requestId ?? null, response: window.__freecadSpreadsheetState?.response ?? null, type: document.querySelector('#type')?.textContent ?? '', a1: document.querySelector('#a1')?.textContent ?? '', b1: document.querySelector('#b1')?.textContent ?? ''}))()"); + if (isSandboxScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxState?.stage ?? '', requestId: window.__freecadSandboxState?.requestId ?? null, response: window.__freecadSandboxState?.response ?? null, object: document.querySelector('#object')?.textContent ?? '', integer: document.querySelector('#integer')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()"); + if (isSandboxInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxInspectState?.stage ?? '', requestId: window.__freecadSandboxInspectState?.requestId ?? null, response: window.__freecadSandboxInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', python: document.querySelector('#python')?.textContent ?? ''}))()"); + if (isSandboxPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxPythonState?.stage ?? '', requestId: window.__freecadSandboxPythonState?.requestId ?? null, response: window.__freecadSandboxPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? ''}))()"); + if (isSandboxSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSandboxSaveState?.stage ?? '', requestId: window.__freecadSandboxSaveState?.requestId ?? null, response: window.__freecadSandboxSaveState?.response ?? null, object: document.querySelector('#object')?.textContent ?? '', size: document.querySelector('#size')?.textContent ?? '', round: document.querySelector('#round')?.textContent ?? ''}))()"); + if (isSketcherScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSketcherState?.stage ?? '', requestId: window.__freecadSketcherState?.requestId ?? null, response: window.__freecadSketcherState?.response ?? null, geometry: document.querySelector('#geometry')?.textContent ?? '', constraints: document.querySelector('#constraints')?.textContent ?? '', dof: document.querySelector('#dof')?.textContent ?? ''}))()"); + if (isSketcherInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSketcherInspectState?.stage ?? '', requestId: window.__freecadSketcherInspectState?.requestId ?? null, response: window.__freecadSketcherInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', object: document.querySelector('#object')?.textContent ?? ''}))()"); + if (isSketcherPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadSketcherPythonState?.stage ?? '', requestId: window.__freecadSketcherPythonState?.requestId ?? null, response: window.__freecadSketcherPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? ''}))()"); + if (isOpenScadScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status-dot')?.dataset.level ?? '', stage: window.__freecadOpenScadState?.stage ?? '', requestId: window.__freecadOpenScadState?.requestId ?? null, response: window.__freecadOpenScadState?.response ?? null, formats: document.querySelector('#formats')?.textContent ?? '', readonly: document.querySelector('#readonly')?.textContent ?? ''}))()"); + if (isPartDesignPythonScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartDesignPythonState?.stage ?? '', requestId: window.__freecadPartDesignPythonState?.requestId ?? null, response: window.__freecadPartDesignPythonState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', exports: document.querySelector('#exports')?.textContent ?? '', bindings: document.querySelector('#bindings')?.textContent ?? ''}))()"); + if (isPartDesignInspectScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartDesignInspectState?.stage ?? '', requestId: window.__freecadPartDesignInspectState?.requestId ?? null, response: window.__freecadPartDesignInspectState?.response ?? null, entry: document.querySelector('#entry')?.textContent ?? '', types: document.querySelector('#types')?.textContent ?? '', formats: document.querySelector('#formats')?.textContent ?? '', bindings: document.querySelector('#bindings')?.textContent ?? ''}))()"); + if (isPartDesignScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartDesignState?.stage ?? '', requestId: window.__freecadPartDesignState?.requestId ?? null, response: window.__freecadPartDesignState?.response ?? null, volume: document.querySelector('#volume')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()"); + if (isPointsSaveScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPointsSaveState?.stage ?? '', requestId: window.__freecadPointsSaveState?.requestId ?? null, response: window.__freecadPointsSaveState?.response ?? null, path: document.querySelector('#path')?.textContent ?? '', object: document.querySelector('#object')?.textContent ?? '', count: document.querySelector('#count')?.textContent ?? '', size: document.querySelector('#size')?.textContent ?? ''}))()"); + if (isPointsScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPointsState?.stage ?? '', requestId: window.__freecadPointsState?.requestId ?? null, response: window.__freecadPointsState?.response ?? null, count: document.querySelector('#count')?.textContent ?? '', bounds: document.querySelector('#bounds')?.textContent ?? ''}))()"); + if (isPartScenario) return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', stage: window.__freecadPartState?.stage ?? '', requestId: window.__freecadPartState?.requestId ?? null, response: window.__freecadPartState?.response ?? null, volume: document.querySelector('#volume')?.textContent ?? '', resources: document.querySelector('#resources')?.textContent ?? ''}))()"); + return evaluate("(() => ({status: document.querySelector('#status')?.textContent ?? '', level: document.querySelector('#status')?.dataset.level ?? '', file: document.querySelector('#file-name')?.textContent ?? '', vertex: document.querySelector('#vertex-count')?.textContent ?? '', triangle: document.querySelector('#triangle-count')?.textContent ?? '', face: document.querySelector('#face-count')?.textContent ?? '', requestId: window.__freecadLastResponseRequestId ?? null}))()"); + } + async function navigate(url) { + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await cdp.send("Page.navigate", { url: withPreload(url) }); + await waitFor("kernel startup", (value) => value.status !== "" && !value.status.includes("初始化") && !value.status.includes("等待"), state); + } + function caseEvidence(id, value, screenshotHash = null) { + const externalRequests = requests.filter((request) => !request.url.startsWith(origin)).map((request) => request.url); + return { id, status: "pass", state: value, requests: [...requests], responses: [...responses], externalRequests, console: [...consoleEntries], exceptions: [...exceptions], screenshotSha256: screenshotHash }; + } + + const cases = []; + if (isActionScenario) { + if (isViewScenario) { + const readyState = await waitFor("view sample", (value) => value.stage === "ready" && value.view?.objectCount === 1, state); + cases.push(caseEvidence("view-ready", readyState)); + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#object-tree-primary').click()"); + cases.push(caseEvidence("view-selection", await waitFor("view selection", (value) => value.view?.selected === true, state))); + await evaluate("document.querySelector('#object-tree-primary').dispatchEvent(new PointerEvent('pointermove', {bubbles:true}))").catch(() => undefined); + await evaluate("document.querySelector('#section-button').click()"); + cases.push(caseEvidence("view-section", await waitFor("view section", (value) => value.view?.section === true, state))); + await evaluate("document.querySelector('#visibility-button').click()"); + cases.push(caseEvidence("view-hidden", await waitFor("view hidden", (value) => value.view?.visible === false, state))); + await evaluate("document.querySelector('#visibility-button').click(); document.querySelector('#front-button').click(); document.dispatchEvent(new KeyboardEvent('keydown', {key:'f', bubbles:true}))"); + const desktop = await waitFor("view desktop", (value) => value.view?.visible === true && value.view?.section === true, state); + const desktopScreenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true }); + const desktopBytes = Buffer.from(desktopScreenshot.data, "base64"); + const desktopPath = path.join(docsRoot, "p6", "view-interaction-desktop.png"); + fs.writeFileSync(desktopPath, desktopBytes); + cases.push(caseEvidence("view-desktop", desktop, sha256(desktopBytes))); + await cdp.send("Emulation.setDeviceMetricsOverride", { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }); + const mobile = await waitFor("view mobile layout", (value) => value.controls.includes("fit-button") && value.controls.includes("section-button"), state); + const mobileScreenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true }); + const mobileBytes = Buffer.from(mobileScreenshot.data, "base64"); + const mobilePath = path.join(docsRoot, "p6", "view-interaction-mobile.png"); + fs.writeFileSync(mobilePath, mobileBytes); + cases.push(caseEvidence("view-mobile", mobile, sha256(mobileBytes))); + } else { + const actionLabel = isWorkbenchScenario ? "Workbench command matrix" : isDataPropertyScenario ? "Data-property family" : isCoreScenario ? "React Core" : isTechDrawSaveScenario ? "TechDraw save/reopen" : isTechDrawPythonScenario ? "TechDraw Python" : isTechDrawInspectScenario ? "TechDraw inventory" : isTechDrawNativeScenario ? "TechDraw native" : isTechDrawScenario ? "TechDraw frontend" : isTestScenario ? "Test inventory" : isWebPersistenceScenario ? "Web save/reopen" : isWebScenario ? "Web" : isTuxScenario ? "Tux" : isTemplatePyModPythonScenario ? "TemplatePyMod Python" : isTemplatePyModScenario ? "TemplatePyMod" : isStartPythonScenario ? "Start Python" : isStartInspectScenario ? "Start inventory" : isStartScenario ? "Start" : isSurfaceSaveScenario ? "Surface save" : isSurfacePythonScenario ? "Surface Python" : isSurfaceScenario ? "Surface" : isSpreadsheetSaveScenario ? "Spreadsheet save" : isSpreadsheetPythonScenario ? "Spreadsheet Python" : isSpreadsheetInspectScenario ? "Spreadsheet inventory" : isSpreadsheetScenario ? "Spreadsheet" : isSketcherPythonScenario ? "Sketcher Python" : isSketcherInspectScenario ? "Sketcher inventory" : isSketcherScenario ? "Sketcher" : isSandboxSaveScenario ? "Sandbox save" : isSandboxPythonScenario ? "Sandbox Python" : isSandboxInspectScenario ? "Sandbox inventory" : isSandboxScenario ? "Sandbox" : isPointsSaveScenario ? "Points save" : isPointsScenario ? "Points" : isPartDesignPythonScenario ? "PartDesign Python" : isPartDesignInspectScenario ? "PartDesign inventory" : isPartDesignScenario ? "PartDesign" : isPartScenario ? "Part" : "OpenSCAD"; + const casePrefix = scenario; + if (isWorkbenchScenario) await waitFor("Workbench React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#validate-command-matrix'))")); + if (isWebScenario) await waitFor("Web React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + const readyState = await waitFor(`${actionLabel} ready`, (value) => value.stage === "ready", state); + cases.push(caseEvidence(`${casePrefix}-ready`, readyState)); + if (isTuxScenario) await waitFor("Tux React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isWebPersistenceScenario) await waitFor("Web persistence React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isTestScenario) await waitFor("Test React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isTechDrawScenario) await waitFor("TechDraw React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isTechDrawNativeScenario) await waitFor("TechDraw native React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isTechDrawInspectScenario) await waitFor("TechDraw inspect React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isTechDrawPythonScenario) await waitFor("TechDraw Python React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isTechDrawSaveScenario) await waitFor("TechDraw save React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isCoreScenario) await waitFor("Core React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + if (isDataPropertyScenario) await waitFor("Data-property React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#data-property-family'))")); + if (isDocumentScenario) await waitFor("Document React controls", (value) => value === true, () => evaluate("Boolean(document.querySelector('#run'))")); + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate(isWorkbenchScenario ? "document.querySelector('#validate-command-matrix').click()" : isDataPropertyScenario ? "document.querySelector('#data-property-family').click()" : "document.querySelector('#run').click()"); + const actionState = await waitFor(`${actionLabel} action`, (value) => isWorkbenchScenario ? value.stage === "success" && value.matrix?.records === 778 : value.stage === "success", state); + const screenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true }); + const screenshotBytes = Buffer.from(screenshot.data, "base64"); + fs.writeFileSync(screenshotPath, screenshotBytes); + cases.push(caseEvidence(`${casePrefix}-action`, actionState, sha256(screenshotBytes))); + if (isWorkbenchScenario) { + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#error').click()"); + cases.push(caseEvidence(`${casePrefix}-expected-error`, await waitFor(`${actionLabel} expected error`, (value) => value.stage === "expected-error" && value.response?.error?.code === "invalid_request", state))); + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#cancel').click()"); + cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled" && value.response?.error?.code === "cancelled", state))); + } + if (isCoreScenario) { + cases.push(caseEvidence(`${casePrefix}-duplicate`, await waitFor(`${actionLabel} duplicate`, (value) => value.duplicate === "duplicate_request", state))); + } + if (isDataPropertyScenario) { + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#cancel').click()"); + cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled", state))); + } + if (isDocumentScenario) { + cases.push(caseEvidence(`${casePrefix}-duplicate`, await waitFor(`${actionLabel} duplicate`, (value) => value.duplicate === "duplicate_request", state))); + } + if (!isWorkbenchScenario) { + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#error').click()"); + cases.push(caseEvidence(`${casePrefix}-expected-error`, await waitFor(`${actionLabel} expected error`, (value) => value.stage === "expected-error", state))); + } + if (isCoreScenario) { + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#cancel').click()"); + cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled", state))); + } + if (isDocumentScenario) { + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#cancel').click()"); + cases.push(caseEvidence(`${casePrefix}-cancel`, await waitFor(`${actionLabel} cancel`, (value) => value.stage === "cancelled", state))); + } + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate("document.querySelector('#reset').click()"); + cases.push(caseEvidence(`${casePrefix}-reset`, await waitFor(`${actionLabel} reset`, (value) => value.stage === "reset", state))); + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await evaluate(isWorkbenchScenario ? "document.querySelector('#validate-command-matrix').click()" : isDataPropertyScenario ? "document.querySelector('#data-property-family').click()" : "document.querySelector('#run').click()"); + cases.push(caseEvidence(`${casePrefix}-repeat`, await waitFor(`${actionLabel} repeat`, (value) => isWorkbenchScenario ? value.stage === "success" : value.stage === "success", state))); + } + } else { + const importState = await waitFor("sample import", (value) => value.status.startsWith("已加载 "), state); + const screenshot = await cdp.send("Page.captureScreenshot", { format: "png", fromSurface: true }); + const screenshotBytes = Buffer.from(screenshot.data, "base64"); + fs.writeFileSync(screenshotPath, screenshotBytes); + cases.push(caseEvidence("sample-import", importState, sha256(screenshotBytes))); + await evaluate("document.querySelector('#reset-button').click()"); + cases.push(caseEvidence("reset", await waitFor("reset", (value) => value.status === "已清空", state))); + + await navigate(`${origin}/?storage=1`); + cases.push(caseEvidence("opfs", await waitFor("OPFS smoke", (value) => value.status.includes("OPFS smoke passed"), state))); + await navigate(`${origin}/?cache=1`); + cases.push(caseEvidence("mesh-cache", await waitFor("mesh cache smoke", (value) => value.status === "网格缓存 smoke passed", state))); + + requests.length = 0; responses.length = 0; consoleEntries.length = 0; exceptions.length = 0; + await cdp.send("Page.navigate", { url: `${origin}/missing-fixture` }); + const missingResponse = await waitFor("expected HTTP error", (value) => value?.status === 404, () => Promise.resolve(responses.find((response) => response.url.endsWith("/missing-fixture"))), 5000); + cases.push({ id: "expected-error", status: missingResponse.status === 404 ? "pass" : "fail", expected: { status: 404 }, observed: missingResponse, requests: [...requests], responses: [...responses], externalRequests: requests.filter((request) => !request.url.startsWith(origin)).map((request) => request.url), console: [...consoleEntries], exceptions: [...exceptions], screenshotSha256: null }); + } + + const allExternal = cases.flatMap((item) => item.externalRequests); + const allExceptions = cases.flatMap((item) => item.exceptions); + const result = { + schema: "freecad-web-p6-chrome-harness/v1", + result: cases.every((item) => item.status === "pass") && allExternal.length === 0 && allExceptions.length === 0 ? "pass" : "fail", + chrome: { path: chromePath, version: (await new Promise((resolve) => { const version = spawn(chromePath, ["--version"], { stdio: ["ignore", "pipe", "ignore"] }); let output = ""; version.stdout.on("data", (chunk) => { output += chunk; }); version.on("close", () => resolve(output.trim())); })) }, + mode: "headless-new", + origin, + viewport, + timeoutMs, + networkPolicy: "intercept-and-require-zero-external-requests", + modulePreload, + cases, + evidence: { screenshot: `FreeCAD/docs/p6/${scenarioStem}.png`, screenshotSha256: cases.find((item) => item.screenshotSha256)?.screenshotSha256 ?? null, resultHash: sha256(JSON.stringify(cases)) }, + policy: { browser: "Google Chrome only", nonChromeBrowsersAttempted: false }, + }; + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.writeFileSync(outputPath, `${JSON.stringify(result, null, 2)}\n`); + log.push(`origin=${origin}`, `chrome=${result.chrome.version}`, `cases=${cases.length}`, `externalRequests=${allExternal.length}`, `exceptions=${allExceptions.length}`, `result=${result.result}`); + fs.writeFileSync(logPath, `${log.join("\n")}\n`); + console.log(JSON.stringify({ result: result.result, cases: cases.length, externalRequests: allExternal.length, exceptions: allExceptions.length })); + if (result.result !== "pass") process.exitCode = 1; + } finally { + cdp?.close(); + chrome.kill("SIGTERM"); + server.close(); + } +} diff --git a/tools/run_p6_python_api_module_batch_gate.py b/tools/run_p6_python_api_module_batch_gate.py new file mode 100644 index 00000000..6c9cf076 --- /dev/null +++ b/tools/run_p6_python_api_module_batch_gate.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +import hashlib +import json +import sys +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +module = sys.argv[1] if len(sys.argv) > 1 else "Part" +tier = sys.argv[2] if len(sys.argv) > 2 else "tier-2-pure" +manifest_path = ROOT / "docs/p6/python-api-manifest.json" +manifest = json.loads(manifest_path.read_text()) +rows = [row for row in manifest["records"] if row["module"] == module and row["tier"] == tier] +counts = Counter(row["disposition"] for row in rows) +safe = "".join(ch if ch.isalnum() else "-" for ch in module.lower()) +terminal = {"exposed", "restricted", "nonportable", "not_implemented"} +records = [ + { + "id": row["id"], + "name": row["name"], + "disposition": row["disposition"], + "evidence": row.get("dispositionEvidence", []), + "reason": row.get("dispositionReason"), + } + for row in rows +] +extra = {} +if tier == "tier-3-stateful": + runtime_path = ROOT / "docs/p6/python-api-stateful-family-runtime.json" + adapter_path = ROOT / "docs/p6/tier3-stateful-adapter-manifest.json" + runtime = json.loads(runtime_path.read_text()) + adapter = json.loads(adapter_path.read_text()) + native_by_id = {record["apiId"]: record for record in runtime.get("result", {}).get("records", [])} + summary_by_id = {record["apiId"]: record for record in runtime.get("records", [])} + adapter_module = next((item for item in adapter.get("modules", []) if item.get("module") == module), None) + adapter_route = adapter_module.get("route", {}) if adapter_module else {} + native_route = runtime.get("route", {}) + + def native_record_valid(row): + native = native_by_id.get(row["id"]) + summary = summary_by_id.get(row["id"]) + if not native or not summary: + return False + compact = json.dumps(native, ensure_ascii=False, separators=(",", ":")) + native_sha256 = hashlib.sha256(compact.encode()).hexdigest() + return ( + native.get("module") == row["module"] + and native.get("name") == row["name"] + and native.get("family") == row["family"] + and native.get("sourceEntry") == row.get("evidence", {}).get("path") + and native.get("status") == row["disposition"] + and native.get("status") in terminal + and native.get("native") is True + and native.get("resourcesReleased") is True + and isinstance(native.get("parameterSchema"), str) + and bool(native["parameterSchema"]) + and isinstance(native.get("returnSchema"), str) + and bool(native["returnSchema"]) + and isinstance(native.get("documentDiff"), dict) + and isinstance(native.get("errorRecovery"), dict) + and summary.get("evidenceSha256") == native_sha256 + and runtime_path.relative_to(ROOT).as_posix() in row.get("dispositionEvidence", []) + ) + + valid = ( + bool(rows) + and runtime.get("status") == "pass_with_boundaries" + and adapter_module is not None + and adapter_module.get("count") == len(rows) + and isinstance(adapter_route.get("worker"), str) + and bool(adapter_route["worker"]) + and isinstance(adapter_route.get("command"), str) + and bool(adapter_route["command"]) + and native_route.get("command") == "web.statefulFamilyBatch" + and "fc_web_dispatch_json" in native_route.get("native", "") + and all(row["disposition"] in terminal and native_record_valid(row) for row in rows) + ) + records = [ + { + **record, + "family": row["family"], + "sourceEntry": summary_by_id.get(row["id"], {}).get("sourceEntry"), + "sourceRevision": summary_by_id.get(row["id"], {}).get("sourceRevision"), + "parameterSchema": summary_by_id.get(row["id"], {}).get("parameterSchema"), + "returnSchema": summary_by_id.get(row["id"], {}).get("returnSchema"), + "documentDiffSha256": summary_by_id.get(row["id"], {}).get("documentDiffSha256"), + "errorRecoverySha256": summary_by_id.get(row["id"], {}).get("errorRecoverySha256"), + "evidenceSha256": summary_by_id.get(row["id"], {}).get("evidenceSha256"), + } + for row, record in zip(rows, records) + ] + extra = { + "nativeRuntime": runtime_path.relative_to(ROOT).as_posix(), + "nativeRuntimeSha256": hashlib.sha256(runtime_path.read_bytes()).hexdigest(), + "adapterManifest": adapter_path.relative_to(ROOT).as_posix(), + "adapterManifestSha256": hashlib.sha256(adapter_path.read_bytes()).hexdigest(), + "route": adapter_route or None, + "nativeRoute": native_route or None, + "resources": runtime.get("resources"), + } +else: + valid = bool(rows) and all(row["disposition"] in terminal | {"planned"} for row in rows) +report = { + "schema": "freecad-web-p6-python-api-module-batch-gate/v1", + "taskId": f"FW-P6-FPA-F{tier.split('-')[1]}-{module.upper()}", + "module": module, + "tier": tier, + "result": ("pass" if tier == "tier-3-stateful" else "pass_with_pending") if valid else "fail", + "coverage": {"records": len(rows), "counts": dict(sorted(counts.items()))}, + "records": records, + "manifestSha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(), + **extra, + "boundaries": ["Terminal disposition does not claim that restricted or not_implemented APIs are callable.", "Only exact module-scoped native evidence can promote a symbol."] +} +out = ROOT / "docs/p6" / f"python-api-{safe}-{tier}-gate.json" +out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") +(ROOT / "docs" / f"freecad-p6-python-api-{safe}-{tier}-gate.log").write_text(json.dumps({"result": report["result"], "coverage": report["coverage"]}) + "\n") +print(json.dumps({"module": module, "tier": tier, "result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False)) +raise SystemExit(0 if valid else 1) diff --git a/tools/run_p6_python_api_pure_aggregate_gate.py b/tools/run_p6_python_api_pure_aggregate_gate.py new file mode 100644 index 00000000..ee75c925 --- /dev/null +++ b/tools/run_p6_python_api_pure_aggregate_gate.py @@ -0,0 +1,48 @@ +#!/usr/bin/env python3 +"""Verify that every canonical Tier-2 pure API has terminal native evidence.""" +from __future__ import annotations + +import hashlib +import json +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +P6 = ROOT / "docs/p6" +MANIFEST = P6 / "python-api-manifest.json" +manifest_bytes = MANIFEST.read_bytes() +manifest = json.loads(manifest_bytes) +rows = [row for row in manifest["records"] if row.get("tier") == "tier-2-pure"] +terminal = {"exposed", "restricted", "nonportable", "not_implemented"} +missing = [row["id"] for row in rows if row.get("disposition") not in terminal or not row.get("dispositionEvidence")] +modules = sorted({row["module"] for row in rows}) +artifact_index = {} +for module in modules: + candidates = sorted(P6.glob(f"{module.lower()}*tier2*pure*family-runtime.json")) + if not candidates: + missing.append(f"artifact:{module}") + continue + path = candidates[-1] + raw = path.read_bytes() + value = json.loads(raw) + artifact_index[module] = {"path": str(path.relative_to(ROOT)), "sha256": hashlib.sha256(raw).hexdigest(), "status": value.get("status")} + if value.get("status") not in {"pass", "pass_with_boundaries"}: + missing.append(f"artifact_status:{module}") +counts = Counter(row.get("disposition") for row in rows) +report = { + "schema": "freecad-web-p6-python-api-pure-aggregate-gate/v1", + "taskId": "FW-P6-FPA-F2", + "result": "pass_with_boundaries" if len(rows) == 6417 and not missing else "fail", + "source": {"manifest": "docs/p6/python-api-manifest.json", "manifestSha256": hashlib.sha256(manifest_bytes).hexdigest()}, + "coverage": {"tier": "tier-2-pure", "records": len(rows), "counts": dict(sorted(counts.items())), "modules": modules, "missing": missing}, + "evidence": artifact_index, + "boundaries": [ + "Every Tier-2 record has a terminal disposition and a module-scoped native evidence reference.", + "Terminal not_implemented/restricted records remain capability denials; no JavaScript result is substituted.", + "Later Tier-3/stateful and exhaustive Chrome gates remain outside this aggregate implementation gate.", + ], +} +(P6 / "python-api-pure-aggregate-gate.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") +(ROOT / "docs/freecad-p6-python-api-pure-aggregate-gate.log").write_text(json.dumps({"result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False) + "\n", encoding="utf-8") +print(json.dumps({"result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False)) +raise SystemExit(0 if report["result"] != "fail" else 1) diff --git a/tools/run_p6_python_api_pure_gate.py b/tools/run_p6_python_api_pure_gate.py new file mode 100644 index 00000000..2a4444c6 --- /dev/null +++ b/tools/run_p6_python_api_pure_gate.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python3 +import hashlib +import json +from collections import Counter +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +manifest_path = ROOT / "docs/p6/python-api-manifest.json" +manifest = json.loads(manifest_path.read_text()) +pure = [row for row in manifest["records"] if row["tier"] == "tier-2-pure" and row["disposition"] == "exposed"] +# Runtime evidence is append-only: new native family probes may safely expose +# more pure APIs. The contract is evidence-backed membership, not a frozen +# historical count. +valid = bool(pure) and all(row.get("dispositionEvidence") for row in pure) +report = { + "schema": "freecad-web-p6-python-api-pure-gate/v1", + "taskId": "FW-P6-FPA-F2", + "result": "pass_with_pending" if valid else "fail", + "coverage": {"pureTierRecords": sum(row["tier"] == "tier-2-pure" for row in manifest["records"]), "exposedPureRecords": len(pure), "plannedRecords": sum(row["disposition"] == "planned" for row in manifest["records"]), "restrictedRecords": sum(row["disposition"] == "restricted" for row in manifest["records"]), "totalRecords": len(manifest["records"])}, + "byModule": dict(sorted(Counter(row["module"] for row in pure).items())), + "records": [{"id": row["id"], "module": row["module"], "name": row["name"], "artifacts": row["dispositionEvidence"]} for row in pure], + "manifestSha256": hashlib.sha256(manifest_path.read_bytes()).hexdigest(), + "boundaries": ["Only passing native Python API artifacts are used; external non-native process calls remain subject to capability policy.", "Pure-tier records without native evidence remain planned and are not implied by this partial gate."], +} +out = ROOT / "docs/p6/python-api-pure-gate.json" +out.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n") +(ROOT / "docs/freecad-p6-python-api-pure-gate.log").write_text(json.dumps({"result": report["result"], "coverage": report["coverage"]}) + "\n") +print(json.dumps({"result": report["result"], "coverage": report["coverage"]}, ensure_ascii=False)) +raise SystemExit(0 if valid else 1) diff --git a/tools/run_web_module_smoke_once.py b/tools/run_web_module_smoke_once.py new file mode 100644 index 00000000..c3afec3a --- /dev/null +++ b/tools/run_web_module_smoke_once.py @@ -0,0 +1,480 @@ +#!/usr/bin/env python3 +"""Run exactly one unattended smoke entry for each FreeCAD Web module. + +The smoke run is intentionally separate from the historical scheduler ledger: +one module has one selected entry, one attempt, and one recorded result. +Missing JS/WASM glue is prepared with a targeted build before that module's +single smoke invocation; it is not retried as another smoke test. +""" +from __future__ import annotations + +import json +import hashlib +import fcntl +import signal +import argparse +import os +import re +import shutil +import subprocess +import sys +import tempfile +import time +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +BUILD = ROOT / "web/public/kernel" +CONFIGURE_BUILD = ROOT / "freecad-source/build-web/configure/bin" +CLOUD_BUILD = ROOT / "freecad-source/build-web/cloud-configure-r2/bin" +try: + campaign = json.loads((ROOT / "docs/current/execution-policy.json").read_text()).get("smokeRun", {}).get("directory") +except (OSError, ValueError): + campaign = None +RUN_DIR = Path(os.environ.get("FREECAD_SMOKE_RUN_DIR", str(ROOT / (campaign or "docs/current/module-smoke-once")))).expanduser().resolve() +MANIFEST = RUN_DIR / "manifest.json" +TSC = ROOT / "web/node_modules/.bin/tsc" +SMOKE_TIMEOUT_SECONDS = int(os.environ.get("FREECAD_SMOKE_TIMEOUT_SECONDS", "120")) +BUILD_TIMEOUT_SECONDS = int(os.environ.get("FREECAD_SMOKE_BUILD_TIMEOUT_SECONDS", "180")) + + +def spec(module: str, script: str, args: list[str] | None = None, *, compile_sources: list[str] | None = None, build_tree: Path | None = None, build_target: str | None = None, runtime_probe: str | None = None) -> dict[str, object]: + return { + "module": module, + "script": script, + "args": args or [], + "compileSources": compile_sources or [], + "buildTree": str(build_tree or BUILD), + "buildTarget": build_target, + "runtimeProbe": runtime_probe, + } + + +SPECS = [ + spec("Assembly", "tools/run_p6_assembly_action02_kernel_smoke.mjs"), + spec("BIM", "tools/run_p6_bim_runtime_smoke.mjs"), + spec("CAM", "tools/run_p6_cam_action02_kernel_smoke.mjs", ["{out}/cam-import-export-facade.js"], compile_sources=["web/src/facade-envelope.ts", "web/src/cam-import-export-facade.ts"]), + spec("Cloud", "tools/run_p6_cloud_action03_kernel_smoke.mjs", [str(CLOUD_BUILD)]), + spec("Draft", "tools/run_p6_draft_runtime_smoke.mjs"), + spec("Fem", "tools/run_p6_fem_runtime_smoke.mjs"), + spec("Help", "tools/run_p6_help_runtime_smoke.mjs"), + spec("Import", "tools/run_p6_import_runtime_smoke.mjs", [str(BUILD)]), + spec("Inspection", "tools/run_p6_inspection_action02_kernel_smoke.mjs", [str(BUILD)]), + spec("JtReader", "tools/run_p6_jtreader_kernel_smoke.mjs", [str(BUILD)]), + spec("Material", "tools/run_p6_material_runtime_smoke.mjs", [str(CONFIGURE_BUILD)], build_tree=CONFIGURE_BUILD), + spec("Measure", "tools/run_p6_measure_runtime_smoke.mjs", [str(CONFIGURE_BUILD)], build_tree=CONFIGURE_BUILD, runtime_probe="FreeCADWebMeasureRuntimeProbe"), + spec("Mesh", "tools/run_p6_mesh_runtime_smoke.mjs", [str(BUILD)]), + spec("MeshPart", "tools/run_p6_meshpart_runtime_smoke.mjs", [str(BUILD)]), + spec("Part", "tools/run_p6_part_facade_smoke.mjs", [str(BUILD), "{out}"], compile_sources=["web/src/facade-envelope.ts", "web/src/part-facade.ts"]), + spec("PartDesign", "tools/run_p6_partdesign_runtime.mjs", [str(BUILD)]), + spec("Plot", "tools/run_p6_plot_runtime_smoke.mjs", [str(BUILD)]), + spec("Points", "tools/run_p6_points_runtime.mjs", [str(BUILD)]), + spec("ReverseEngineering", "tools/run_p6_reverseengineering_runtime.mjs", [str(BUILD)]), + spec("Robot", "tools/run_p6_robot_runtime.mjs", [str(BUILD)]), + spec("Sandbox", "tools/run_p6_sandbox_action02_facade_smoke.mjs", ["{out}/sandbox-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/sandbox-facade.ts"]), + spec("Show", "tools/run_p6_show_facade.mjs", [str(BUILD)]), + spec("Sketcher", "tools/run_p6_sketcher_action02_facade_smoke.mjs", ["{out}/sketcher-inspect-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/sketcher-inspect-facade.ts"]), + spec("Spreadsheet", "tools/run_p6_spreadsheet_action02_facade_smoke.mjs", ["{out}/spreadsheet-inspect-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/spreadsheet-inspect-facade.ts"]), + spec("Start", "tools/run_start_facade_smoke.mjs", ["{out}/start-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/start-facade.ts"]), + spec("Surface", "tools/run_surface_facade_smoke.mjs", ["{out}/surface-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/surface-facade.ts"]), + spec("TechDraw", "tools/run_techdraw_inspect_facade_smoke.mjs", ["{out}/techdraw-inspect-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/techdraw-inspect-facade.ts"]), + spec("TemplatePyMod", "tools/run_templatepymod_facade_smoke.mjs", ["{out}/templatepymod-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/templatepymod-facade.ts"]), + spec("Test", "web/src/test-facade-smoke.mjs", ["{out}/test-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/test-facade.ts"]), + spec("Tux", "tools/run_tux_facade_smoke.mjs", ["{out}/tux-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/tux-facade.ts"]), + spec("Web", "tools/run_web_facade_smoke.mjs", ["{out}/web-facade.js", str(BUILD)], compile_sources=["web/src/facade-envelope.ts", "web/src/web-facade.ts"]), +] + + +# Current campaign uses real published WASM, not legacy source-inventory mocks. +if "comprehensive-smoke" in str(RUN_DIR): + SPECS = [dict(spec(row["module"], "tools/module-runtime-load-smoke.mjs", [row["module"]]), coverage="runtime-load") for row in SPECS] + SPECS.append(dict(spec("UI-all-workbench-panels", "tools/workbench-panels-smoke.mjs"), owner="Web", coverage="browser-panel-mount", timeout=900)) + SPECS.append(dict(spec("Recent-shaft-current", "tools/shaft-current-smoke.mjs"), owner="PartDesign", coverage="current-native-shaft", timeout=120)) + for owner in ("Part", "PartDesign", "Sketcher"): + ids = [owner + ":" + owner.lower() + suffix for suffix in (".createRecompute", ".saveReopen")] + SPECS.append(dict(spec("Core-" + owner, "tools/run_business_acceptance.py", + ["--module", owner, "--ids", *ids, "--reuse", "--validate-deferred"]), owner=owner, + coverage="core-native-model-and-FCStd", timeout=240)) + SPECS.append(dict(spec("Repaired-browser-workers", "tools/repaired-workers-browser-smoke.mjs"), owner="Web", additionalOwners=["Help", "Plot", "Show"], coverage="browser-native-request", timeout=240)) + groups = { + "UI-shell-files": ["product:document-workspace", "product:react-primary-shell", "product:model-tree-properties", "product:multi-object-viewport", "product:desktop-command-ui", "product:task-panel", "product:workbench-navigation", "product:dynamic-module-session", "product:file-workflows", "product:recovery-status"], + "UI-desktop-workspace": ["product:desktop-workspace-parity"], + "UI-task-interactions": ["product:desktop-task-interaction-parity"], + "UI-cross-workbench": ["product:cross-workbench-document-editing"], + "Recent-shaft": ["PartDesign:desktop:PartDesign_WizardShaft", "PartDesign:desktop:PartDesign_WizardShaftCallBack"], + } + for name, ids in groups.items(): + owner = "PartDesign" if name == "Recent-shaft" else "Web" + SPECS.append(dict(spec(name, "tools/run_business_acceptance.py", ["--module", owner, "--ids", *ids, "--reuse", "--validate-deferred"]), owner=owner, coverage="business-browser", timeout=600)) + + + for contract_path in sorted((ROOT / "docs/business-acceptance").glob("*.json")): + owner = contract_path.stem + if owner == "Web": + continue + contract = json.loads(contract_path.read_text()) + ids = contract.get("coveredIds") or contract.get("selectedIds") or [] + ids = [key for key in ids if key not in groups["Recent-shaft"]] + if ids: + SPECS.append(dict(spec("Business-" + owner, "tools/run_business_acceptance.py", + ["--module", owner, "--ids", *ids, "--reuse", "--validate-deferred"]), owner=owner, + coverage="declared-business-cases", timeout=600)) + + + for row in SPECS: + if row["module"] in {"Business-Part", "Business-PartDesign", "Business-Sketcher"}: + row["script"] = "tools/run_smoke_business_records.py" + row["args"] = [value for value in row["args"] if value not in {"--reuse", "--validate-deferred"}] + row["timeout"] = 18000 + row["coverage"] = "declared-business-cases-with-per-ID-checkpoints" + + web_contract = json.loads((ROOT / "docs/business-acceptance/Web.json").read_text()) + covered_web_ids = {key for row in SPECS if row.get("owner") == "Web" for key in row.get("args", [])} + remaining_web_ids = [key for key in web_contract.get("coveredIds", []) if key not in covered_web_ids] + if remaining_web_ids: + # Several command IDs share the same existing manual workflow. The + # Web runner deduplicates those workflows when submitted together. + SPECS.append(dict(spec("UI-declared-desktop-commands", "tools/run_business_acceptance.py", + ["--module", "Web", "--ids", *remaining_web_ids, "--reuse", "--validate-deferred"]), owner="Web", + coverage="declared-desktop-command-workflows", timeout=600)) + + +def inputs_for(row): + from business_acceptance import digest, module_inputs + owner = row.get("owner", row["module"]) + registry = json.loads((ROOT / "web/public/modules/manifest.json").read_text()) + paths = {ROOT / str(row["script"]), ROOT / "tools/wasm-probe-runtime.mjs"} + for dependency_owner in [owner, *row.get("additionalOwners", [])]: + sources = module_inputs(dependency_owner) + paths.update(ROOT / name for name in sources["sources"]) + for worker in registry["modules"].get(dependency_owner, {}).get("workers", {}).values(): + paths.update(ROOT / "web/public" / value.lstrip("/") for key, value in worker.items() if key.endswith("Url") and isinstance(value, str)) + contract_path = ROOT / "docs/business-acceptance" / (owner + ".json") + if row.get("owner") and contract_path.is_file(): + contract = json.loads(contract_path.read_text()) + command = contract.get("command", []) + if len(command) > 1: + paths.add(ROOT / command[1]) + for name in contract.get("dependencies", []) + contract.get("caseDependencies", []): + dependency = ROOT / name + if dependency.is_dir(): + paths.update(p for p in dependency.rglob("*") if p.is_file() and "__pycache__" not in p.parts) + else: + paths.add(dependency) + # Track imported helper code recursively, without loading it into a runtime. + todo = list(paths) + while todo: + current = todo.pop() + if current.suffix not in {".mjs", ".ts", ".tsx", ".py"} or not current.is_file(): + continue + for relative in re.findall(r"(?:from\s*|import\s*)[\"'](\.[^\"']+)[\"']", current.read_text()): + child = (current.parent / relative).resolve() + if not child.is_file() and child.suffix == ".js": + child = child.with_suffix(".ts") + if child.is_relative_to(ROOT) and child.is_file() and child not in paths: + paths.add(child); todo.append(child) + if row.get("owner"): + paths.add(ROOT / "docs/business-acceptance" / (owner + ".json")) + paths.update((ROOT / "web/dist/assets").glob("*")) + paths.update(p for p in (ROOT / "web/dist").glob("*.html") if p.name != "execution.html") + if row.get("owner") == "Web": + # web-acceptance-cases launches the manual runner only for IDs in + # manual-business-mapping; other UI groups never execute that branch. + mapping_path = ROOT / "tools/manual-business-mapping.json" + mapping = json.loads(mapping_path.read_text())["records"] + paths.add(mapping_path) + if not any(key in mapping for key in row.get("args", [])): + paths.discard(ROOT / "tools/run_user_manual_tests.mjs") + paths.discard(ROOT / "tools/user-manual-remaining-cases.mjs") + files = {str(p.relative_to(ROOT)): digest(p) for p in sorted(paths) if p.is_file()} + return hashlib.sha256(json.dumps({"spec":row,"files":files},sort_keys=True).encode()).hexdigest(), files + + +def reusable_inputs(previous, row, fingerprint, inputs): + if not previous: + return False + if previous.get("fingerprint") == fingerprint: + return True + old = previous.get("inputs", {}) + # A dependency-scope correction may remove unrelated files. Reuse only + # when every retained input was already measured with the same contents + # and the old hash proves the identical executable specification. + old_key = hashlib.sha256(json.dumps({"spec": row, "files": old}, sort_keys=True).encode()).hexdigest() + return bool(inputs) and old_key == previous.get("fingerprint") and all(old.get(p) == value for p, value in inputs.items()) + + +def run_isolated(command, timeout): + # Own and reap the entire process group, including browser/worker children. + process = subprocess.Popen(command, cwd=ROOT, text=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True) + try: + stdout, stderr = process.communicate(timeout=timeout) + return subprocess.CompletedProcess(command, process.returncode, stdout, stderr) + finally: + # Let a Python business runner reap its own isolated case/browser + # group before enforcing termination of this wrapper group. + try: + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=5) + except (ProcessLookupError, subprocess.TimeoutExpired): + pass + try: os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: pass + process.wait() + + +def load_manifest() -> dict[str, object]: + if MANIFEST.exists(): + try: + value = json.loads(MANIFEST.read_text(encoding="utf-8")) + if isinstance(value, dict) and value.get("schema") == "freecad-web-module-smoke-once/v1": + return value + except json.JSONDecodeError: + pass + return { + "schema": "freecad-web-module-smoke-once/v1", + "startedAt": None, + "status": "planned", + "oneSmokePerModule": True, + "policy": { + "preflightBuildAllowed": True, + "automaticRetry": False, + "fixOnFailure": True, + }, + "plan": [dict(row) for row in SPECS], + "modules": [row["module"] for row in SPECS], + "results": {}, + } + + +def save_manifest(manifest: dict[str, object]) -> None: + RUN_DIR.mkdir(parents=True, exist_ok=True) + temporary = MANIFEST.with_suffix(".tmp") + temporary.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") + temporary.replace(MANIFEST) + if "comprehensive-smoke" in str(RUN_DIR): + results = manifest.get("results", {}) + payload = {"schema": "freecad-web-smoke-progress/v1", "status": manifest.get("status"), + "updatedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), + "total": len(manifest.get("modules", [])), "completed": len(results), + "passed": sum(row.get("status") == "pass" for row in results.values()), + "current": manifest.get("current"), + "failed": [name for name, row in results.items() if row.get("status") != "pass"]} + public = ROOT / "web/public/smoke-status.json" + staging = public.with_suffix(".tmp") + staging.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + "\n") + staging.replace(public) + + +def compile_facade(sources: list[str], out: Path) -> tuple[int, str, str]: + if not sources: + return 0, "", "" + if not TSC.exists(): + return 127, "", f"missing TypeScript compiler: {TSC}" + out.mkdir(parents=True, exist_ok=True) + command = [ + str(TSC), "--target", "ES2022", "--module", "ESNext", "--moduleResolution", "Bundler", + "--strict", "--skipLibCheck", "--outDir", str(out), "--declaration", "false", "--noEmit", "false", + *[str(ROOT / source) for source in sources], + ] + run = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=180) + return run.returncode, run.stdout, run.stderr + + +def prepare_build(row: dict[str, object]) -> tuple[int, str, str]: + target = row.get("buildTarget") + if not target: + return 0, "", "" + tree = Path(str(row["buildTree"])) + js_candidates = list(tree.glob(f"{target}.js")) + wasm_candidates = list(tree.glob(f"{target}.wasm")) + if js_candidates and wasm_candidates: + return 0, "artifact already present\n", "" + command = ["cmake", "--build", str(tree.parent), "--target", str(target), f"-j{os.cpu_count() or 1}"] + run = subprocess.run(command, cwd=ROOT, text=True, capture_output=True, timeout=BUILD_TIMEOUT_SECONDS) + return run.returncode, run.stdout, run.stderr + + +def stage_runtime_build(row: dict[str, object]) -> Path | None: + """Make pthread workers CommonJS-compatible without modifying source artifacts.""" + probe = row.get("runtimeProbe") + if not probe: + return None + build = Path(str(row["buildTree"])) + runtime = build / f"{probe}.js" + worker = build / f"{probe}.worker.js" + wasm = build / f"{probe}.wasm" + if not (runtime.exists() and worker.exists() and wasm.exists()): + return None + stage = Path(tempfile.mkdtemp(prefix=f"freecad-smoke-stage-{str(row['module']).lower()}-")) + runtime_text = runtime.read_text(encoding="utf-8") + runtime_text = runtime_text.replace(f"{probe}.worker.js", f"{probe}.worker.cjs") + (stage / f"{probe}.js").write_text(runtime_text, encoding="utf-8") + (stage / f"{probe}.worker.cjs").write_text(worker.read_text(encoding="utf-8"), encoding="utf-8") + shutil.copy2(wasm, stage / wasm.name) + for suffix in (".data",): + optional = build / f"{probe}{suffix}" + if optional.exists(): + shutil.copy2(optional, stage / optional.name) + return stage + + +def module_command(row: dict[str, object], out: Path | None, build_override: Path | None = None) -> list[str]: + original_build = str(row["buildTree"]) + args = [str(value).replace("{out}", str(out or "")) for value in row.get("args", [])] + if build_override is not None: + args = [value.replace(original_build, str(build_override)) for value in args] + return [sys.executable if str(row["script"]).endswith(".py") else "node", str(ROOT / str(row["script"])), *args] + + +def result_status(returncode: int, stdout: str) -> str: + if returncode != 0: + return "fail" + matches = re.findall(r'"(?:result|status)"\s*:\s*"(pass|passed|fail|failed|blocked)"', stdout) + if any(value in {"fail", "failed", "blocked"} for value in matches): + return "fail" + return "pass" + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--only", nargs="+", help="Resume only named checks; other results remain recorded") + parser.add_argument("--collect-business-records", action="store_true", + help="Audit cumulative Part/PartDesign/Sketcher ID evidence after targeted repair; does not recertify historical inputs") + options = parser.parse_args() + if options.collect_business_records and (not options.only or set(options.only) - {"Business-Part", "Business-PartDesign", "Business-Sketcher"}): + parser.error("--collect-business-records requires --only with the checkpointed business groups") + def interrupted(_signum, _frame): + raise KeyboardInterrupt + signal.signal(signal.SIGTERM, interrupted) + if options.only and set(options.only) - {row["module"] for row in SPECS}: + parser.error("Unknown smoke check name") + RUN_DIR.mkdir(parents=True, exist_ok=True) + lock = (RUN_DIR / "run.lock").open("a") + try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + print("Smoke campaign already running"); return 2 + manifest = load_manifest() + # Keep the executable plan visible even when resuming an older manifest. + manifest.setdefault("oneSmokePerModule", True) + manifest.setdefault("policy", { + "preflightBuildAllowed": True, + "automaticRetry": False, + "fixOnFailure": True, + }) + manifest["plan"] = [dict(row) for row in SPECS] + manifest["modules"] = [row["module"] for row in SPECS] + if manifest.get("status") not in {"completed", "completed_with_failures"}: + manifest["status"] = "running" + if manifest.get("startedAt") is None: + manifest["startedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + manifest["status"] = "running" + save_manifest(manifest) + results = manifest.setdefault("results", {}) + assert isinstance(results, dict) + overall = 0 + manifest["status"] = "running" + manifest["pid"] = os.getpid() + manifest.pop("completedAt", None) + for row in SPECS: + module = str(row["module"]) + if options.only and module not in options.only: + continue + fingerprint, inputs = inputs_for(row) + record_digest = None + if options.collect_business_records: + from business_acceptance import digest + record_path = RUN_DIR / ("records-" + str(row["owner"]) + ".json") + record_digest = digest(record_path) + previous = results.get(module) + if reusable_inputs(previous, row, fingerprint, inputs) and (not options.collect_business_records or previous.get("recordFingerprint") == record_digest): + print(json.dumps({"module":module,"status":"reused","originalStatus":previous["status"]}),flush=True) + continue + if previous: + manifest.setdefault("history", []).append(previous) + started = time.time() + result: dict[str, object] = {"module": module, "script": row["script"], "attempt": 1, "status": "preparing", "fingerprint": fingerprint, "inputs": inputs, "coverage": row.get("coverage", "legacy-smoke")} + if options.collect_business_records: + result["recordFingerprint"] = record_digest + manifest["current"] = {"module": module, "phase": "preparing", "startedAt": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "startedEpoch": started} + save_manifest(manifest) + out: Path | None = None + if row.get("compileSources"): + manifest["current"]["phase"] = "compile" # type: ignore[index] + save_manifest(manifest) + phase_started = time.time() + out = Path(tempfile.mkdtemp(prefix=f"freecad-smoke-{module.lower()}-")) + result["compileSources"] = row["compileSources"] + code, stdout, stderr = compile_facade(list(row["compileSources"]), out) + result["compileExitCode"] = code + result["compileDurationSeconds"] = round(time.time() - phase_started, 3) + if code != 0: + result.update(status="fail", phase="compile", stdout=stdout[-4000:], stderr=stderr[-4000:]) + results[module] = result; manifest.pop("current", None); save_manifest(manifest); overall = 1 + print(json.dumps({"module": module, "status": result["status"], "phase": "compile", "durationSeconds": result.get("compileDurationSeconds")}, ensure_ascii=False), flush=True) + continue + manifest["current"]["phase"] = "build" # type: ignore[index] + manifest["current"]["timeoutSeconds"] = BUILD_TIMEOUT_SECONDS # type: ignore[index] + save_manifest(manifest) + phase_started = time.time() + code, stdout, stderr = prepare_build(row) + result["buildExitCode"] = code + result["buildDurationSeconds"] = round(time.time() - phase_started, 3) + if code != 0: + result.update(status="fail", phase="build", stdout=stdout[-4000:], stderr=stderr[-4000:]) + results[module] = result; manifest.pop("current", None); save_manifest(manifest); overall = 1 + print(json.dumps({"module": module, "status": result["status"], "phase": "build", "durationSeconds": result.get("buildDurationSeconds")}, ensure_ascii=False), flush=True) + continue + staged_build = stage_runtime_build(row) + if staged_build is not None: + result["stagedBuild"] = str(staged_build) + command = module_command(row, out, staged_build) + if options.collect_business_records: + command.append("--summarize-only") + result["validationBasis"] = "Cumulative original-ID evidence plus targeted repairs; original per-ID fingerprints and execution dates retained" + result["recordSummary"] = "summary-" + str(row["owner"]) + ".json" + result["command"] = command + manifest["current"]["phase"] = "smoke" # type: ignore[index] + manifest["current"]["timeoutSeconds"] = row.get("timeout", SMOKE_TIMEOUT_SECONDS) # type: ignore[index] + save_manifest(manifest) + phase_started = time.time() + try: + run = run_isolated(command, row.get("timeout", SMOKE_TIMEOUT_SECONDS)) + (RUN_DIR / (module + ".stdout.log")).write_text(run.stdout) + (RUN_DIR / (module + ".stderr.log")).write_text(run.stderr) + log_stem = module + "-" + fingerprint[:16] + (RUN_DIR / (log_stem + ".stdout.log")).write_text(run.stdout) + (RUN_DIR / (log_stem + ".stderr.log")).write_text(run.stderr) + result["logs"] = [log_stem + ".stdout.log", log_stem + ".stderr.log"] + status = result_status(run.returncode, run.stdout) + result["smokeDurationSeconds"] = round(time.time() - phase_started, 3) + result.update(status=status, phase="smoke", exitCode=run.returncode, stdout=run.stdout[-8000:], stderr=run.stderr[-8000:], durationSeconds=round(time.time() - started, 3)) + nested_timeout = re.search(r"timed out after (\d+) seconds", run.stdout) + if nested_timeout: + result["timeoutSeconds"] = int(nested_timeout.group(1)) + result["timeoutOwner"] = "business-case-runner" + if status != "pass": overall = 1 + except subprocess.TimeoutExpired as error: + result["smokeDurationSeconds"] = round(time.time() - phase_started, 3) + result.update(status="fail", phase="smoke", exitCode=None, stdout=str(error.stdout or "")[-8000:], stderr=str(error.stderr or "")[-8000:], timeoutSeconds=SMOKE_TIMEOUT_SECONDS, durationSeconds=round(time.time() - started, 3)); overall = 1 + results[module] = result + manifest.pop("current", None) + save_manifest(manifest) + print(json.dumps({"module": module, "status": result["status"], "durationSeconds": result.get("durationSeconds")}, ensure_ascii=False), flush=True) + failed = [name for name, result in results.items() if isinstance(result, dict) and result.get("status") != "pass"] + manifest["status"] = "paused" if any(row["module"] not in results for row in SPECS) else "completed_with_failures" if failed else "completed" + manifest.pop("current", None) + manifest["failedModules"] = failed + manifest["completedAt"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) + save_manifest(manifest) + print(json.dumps({"status": manifest["status"], "modules": len(results), "failedModules": failed}, ensure_ascii=False)) + return 1 if failed else 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except KeyboardInterrupt: + checkpoint = load_manifest() + checkpoint["status"] = "interrupted" + save_manifest(checkpoint) + raise SystemExit(130) diff --git a/tools/user-manual-remaining-cases.mjs b/tools/user-manual-remaining-cases.mjs new file mode 100644 index 00000000..9a4ef3fb --- /dev/null +++ b/tools/user-manual-remaining-cases.mjs @@ -0,0 +1,235 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { execFileSync } from 'node:child_process'; + +export function createRemainingCases(h) { + const {root,output,fixture,step,open,button,evaluate,send,until,wait,check,box,dimensions,volume,count,upload,save,reopen,idle,hash}=h; + const objectCount="document.querySelectorAll('[role=treeitem]').length"; + const stage="document.querySelector('.stage > [role=status]')?.textContent"; + const json=(name,data)=>fs.writeFileSync(path.join(output,name),JSON.stringify(data,null,2)+'\n'); + async function memory() { + const rows=execFileSync('ps',['-eo','pid=,ppid=,rss='],{encoding:'utf8'}).trim().split('\n').map(line=>line.trim().split(/\s+/).map(Number)); + const pids=new Set([h.getBrowserPid()]); + for(let changed=true;changed;){changed=false;for(const [pid,parent]of rows)if(pids.has(parent)&&!pids.has(pid)){pids.add(pid);changed=true;}} + const rss=rows.filter(([pid])=>pids.has(pid)).reduce((n,row)=>n+row[2],0)*1024; + await send('Performance.enable'); + const {metrics}=await send('Performance.getMetrics'); + return {at:new Date().toISOString(),browserTreeRssBytes:rss,processes:pids.size, + rendererJsHeapBytes:metrics.find(m=>m.name==='JSHeapUsedSize')?.value, + note:'RSS sums browser descendants and can double-count shared pages; JS heap excludes Worker WASM. Not a physical-memory measurement.'}; + } + async function importFixture(file) { + const n=await count(); + if (!await evaluate("Boolean(document.querySelector('[aria-label=\"Import task\"]'))")) { + const command = /\.(step|stp)$/i.test(file) ? 'Part_ImportStep' : ''; + if (command) await evaluate(`(()=>{const b=document.querySelector('[data-import-command="${command}"]');if(!b||b.disabled)throw Error('Import command unavailable: ${command}');b.click();})()`); + } + await upload(file); + const accept=await evaluate("[...document.querySelectorAll('button')].find(e=>e.textContent.trim()==='Accept import'&&!e.disabled)"); + if (accept) await button('Accept import'); + await until('Native import complete',`({count:${objectCount},status:${stage},busy:Boolean(document.querySelector('[aria-label="Import task"]')?.matches(':disabled'))})`,s=>{ + if(!s.busy&&s.status&&!/^(Importing|Imported|Opened|Import cancelled)/.test(s.status))throw Error(s.status); + return !s.busy&&s.count>n; + },60000); + const v=await evaluate("Number(document.querySelector('[data-native-volume]')?.textContent)"); + check(v>0,'Imported shape has no positive native volume');return v; + } + async function chooseLocalFile(file) { + await until('Open command registration loaded',"window.__freecadWorkbenchState?.selected?.command",s=>s==='Std_Open'); + await send('Page.setInterceptFileChooserDialog',{enabled:true}); + const eventStart=h.getEvents().length; + const point=await evaluate("(()=>{const b=[...document.querySelectorAll('button')].find(b=>b.textContent==='Choose files');if(!b||b.disabled)throw Error('File chooser button unavailable');b.scrollIntoView({block:'center'});const r=b.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2};})()"); + await send('Input.dispatchMouseEvent',{type:'mousePressed',...point,button:'left',clickCount:1}); + await send('Input.dispatchMouseEvent',{type:'mouseReleased',...point,button:'left',clickCount:1}); + let chooser; + for(let i=0;i<100;i++){chooser=h.getEvents().slice(eventStart).find(e=>e.method==='Page.fileChooserOpened');if(chooser)break;await wait(100);} + check(chooser?.params.backendNodeId,'Native file chooser did not open'); + await send('DOM.setFileInputFiles',{backendNodeId:chooser.params.backendNodeId,files:[file]}); + await send('Page.setInterceptFileChooserDialog',{enabled:false}); + } + async function openResult() { + return until('Native open response',"window.__freecadWorkbenchState?.response",r=>{ + if(r?.kind==='error')throw Error(JSON.stringify(r.error)); + return r?.kind==='result'; + },180000); + } + const downloadSnapshot=()=>Object.fromEntries(fs.readdirSync(path.join(output,'downloads')).map(n=>[n,fs.statSync(path.join(output,'downloads',n)).mtimeMs])); + async function downloadedFile(extension,previous={}) { + for(let i=0;i<200;i++) { + const names=fs.readdirSync(path.join(output,'downloads')).filter(n=>n.toLowerCase().endsWith('.'+extension.toLowerCase())&&previous[n]!==fs.statSync(path.join(output,'downloads',n)).mtimeMs); + if(names.length)return path.join(output,'downloads',names.at(-1)); + await wait(100); + } + throw Error(`Missing completed .${extension} download`); + } + async function nativeExport(format) { + const previous=downloadSnapshot(); + await h.select('Native export format',format);await button('导出选中对象'); + await until('Native export',stage,s=>{if(s?.startsWith('Error:'))throw Error(s);return s?.startsWith('Exported ');},30000); + return downloadedFile(format,previous); + } + async function command(module,name,args={}) { + await evaluate(`(()=>{const b=[...document.querySelectorAll('button.module')].find(b=>b.querySelector('strong')?.textContent===${JSON.stringify(module)});if(!b)throw Error('Module missing');b.click();})()`); + await until('Command registration loaded',`[...document.querySelectorAll('button.command')].some(b=>b.querySelector('span')?.textContent===${JSON.stringify(name)})`); + await evaluate(`(()=>{const b=[...document.querySelectorAll('button.command')].find(b=>b.querySelector('span')?.textContent===${JSON.stringify(name)});b.click();})()`); + await h.input('命令 JSON 参数',JSON.stringify(args)); + await until('Selected command ready',"[...document.querySelectorAll('button')].some(b=>b.textContent==='执行选中命令'&&!b.disabled)"); + await button('执行选中命令'); + const response=await until('Native command result',"window.__freecadWorkbenchState?.response",r=>{if(r?.kind==='error')throw Error(JSON.stringify(r.error));return r?.kind==='result';},180000); + const row=response.result?.records?.[0]; + if(row&&'status' in row)check(['success','exposed','ok'].includes(row.status),JSON.stringify(row)); + const result=row?.result??response.result; + check(!result?.sceneError,`Scene refresh failed: ${result?.sceneError}`); + return result; + } + async function workbenchDocument() { + await open();await box();await box([3,4,5]);await save(); + const previous=downloadSnapshot();await button('下载 native FCStd'); + const file=await downloadedFile('fcstd',previous); + await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(file); + const r=await openResult(),v=r.result.records[0].result; + check(!v.sceneError&&v.errors.length===0,'Native open failed');return v.activeDocument; + } + async function inspect(documentId,expression) { + const value=await command('Web','Std_CommandLine',{documentId,runtimeOwner:'PartBox',operation:'submit',source:`import json; print(json.dumps(${expression}))`}); + check(!value.stderr,'Native console returned an error: '+value.stderr); + return JSON.parse(value.stdout.trim().split('\n').at(-1)); + } + async function saveAndReopenNative(documentId,name) { + const saved=await command('Web','Std_SaveAs',{documentId,runtimeOwner:'PartBox',filename:name}); + const file=saved.files?.[0];check(file?.contentsBase64,'Save returned no FCStd bytes'); + const local=path.join(output,name);fs.writeFileSync(local,Buffer.from(file.contentsBase64,'base64')); + await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(local); + const r=await openResult(),v=r.result.records[0].result;check(!v.sceneError&&v.errors.length===0,'Restore failed');return v.activeDocument; + } + const cases={ + 'FIX-IFC-REOPEN':async()=>{ + let documentId; + await step('打开实际 IFC 导入后保存的 FCStd',async()=>{ + const file=path.join(root,'docs/current/user-tests-20260915/ifc-native-2026-09-15T15-50-07-990Z/IfcValidation.FCStd'); + await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(file); + const response=await openResult(),value=response.result.records[0].result; + check(value.errors.length===0&&!value.sceneError,'FCStd restore or scene failed'); + documentId=value.activeDocument; + await until('Restored native mesh viewport',"Number(document.querySelector('[data-native-mesh-count]')?.dataset.nativeMeshCount)",n=>n>20,180000); + return {documentId,documents:value.opened[0].documents,meshCount:value.scene?.meshes.length}; + },'147 个对象恢复,空间层级及原生几何仍存在,视口非空'); + await step('核对恢复后实体及原始 IFC 附件',async()=>{ + const value=await inspect(documentId,`{'groups':sum(1 for o in App.getDocument('${documentId}').Objects if o.isDerivedFrom('App::DocumentObjectGroup')),'solids':sum(1 for o in App.getDocument('${documentId}').Objects if o.isDerivedFrom('Part::Feature') and not o.Shape.isNull()),'source':App.getDocument('${documentId}').getObject('IfcSource').OriginalIFC,'ids':sum(1 for o in App.getDocument('${documentId}').Objects if 'IfcGlobalId' in o.PropertiesList)}`); + check(value.groups>=3&&value.solids>20&&value.source&&value.ids>20,'IFC provenance or native objects not restored');return value; + },'实体、空间分组、IFC GlobalId 和内嵌源文件保留'); + }, + 'GEO-01':async()=>{ + await step('创建 2 x 3 x 4 Box',async()=>{await open();return box();},'1 个对象,原生体积约 24'); + await step('读取原生包围盒属性',async()=>{const bounds=await evaluate("JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds)");check(bounds.length===6&&bounds.every((n,i)=>Math.abs(n-[0,0,0,2,3,4][i])<1e-5),'OCCT bounds differ');return {bounds,volume:await volume(24),tolerance:1e-5};},'原生返回 [0,0,0]-[2,3,4],容差 1e-5 mm'); + }, + 'FILE-03':async()=>{ + let downloaded; + await step('创建和编辑保存文档',async()=>{await open();await box();await h.input('Object Label','User acceptance box');await evaluate("document.querySelector('[aria-label=\"Object Label\"]').blur()");await idle();return save();},'FCStd ZIP 已写入 OPFS'); + await step('下载真实 FCStd 文件',async()=>{await button('下载 native FCStd');for(let i=0;i<100;i++){const files=fs.readdirSync(path.join(output,'downloads')).filter(n=>/\.FCStd$/i.test(n));if(files.length){downloaded=path.join(output,'downloads',files.at(-1));break;}await wait(100);}check(downloaded,'FCStd download missing');return {file:downloaded,bytes:fs.statSync(downloaded).size,sha256:hash(downloaded)};},'下载完成并记录文件指纹'); + await step('关闭后打开 OPFS 文档',async()=>{await button('关闭活动 Document');const state=await reopen();check(state.objects===1,'Object count differs');await volume(24);return state;},'对象数量和体积恢复'); + await step('通过 Std_Open 文件选择器重开下载文件',async()=>{await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(downloaded);const r=await openResult();const v=r.result.records[0].result;check(v.errors.length===0&&v.opened.length===1,'Native file open did not succeed');check(v.opened[0].documents[0].objectCount===1,'FCStd object count differs');check(!v.opened[0].documents[0].partialRestore&&!v.opened[0].documents[0].restoreError&&!v.sceneError,'Partial restore or scene failure');return v;},'本地 FCStd 完整恢复,不以 OPFS 回读代替'); + }, + 'FILE-05':async()=>{ + let stl,before; + await step('准备基准 Box',async()=>{await open();await box();before=await evaluate("JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds)");return {bounds:before,volume:await volume(24)};},'原生体积 24,包围盒 [0,0,0]-[2,3,4]'); + await step('使用原生 OCCT 导出 STL',async()=>{stl=await nativeExport('stl');return {file:stl,size:fs.statSync(stl).size,sha256:hash(stl)};},'下载非空 STL 文件'); + await step('真实文件回读和误差比较',async()=>{await open();await upload(stl);await until('STL object',objectCount,n=>n===1,30000);await idle();const bounds=await evaluate("JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds)");check(bounds.every((v,i)=>Math.abs(v-before[i])<1e-5),'STL bounds changed');return {bounds,volume:await volume(24),tolerance:1e-5};},'STL 回读体积约 24,包围盒误差小于 1e-5 mm'); + }, + 'FILE-02':async()=>{ + const report=[]; + for(const format of ['step','iges','brep','stl'])await step(`${format.toUpperCase()} 原生文件导出及导入`,async()=>{ + await open();await box();const file=await nativeExport(format); + if (format === 'stl') { + await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(file); + try { const response=await openResult(); check(false,'Std_Open unexpectedly accepted STL'); return response; } + catch (error) { if (String(error).includes('unexpectedly accepted')) throw error; const value={format,file,sha256:hash(file),supported:false,imported:false,boundary:String(error)};report.push(value);json('format-validation.json',report);return value; } + } + const command={step:'Part_ImportStep',iges:'Import_Iges',brep:'Import_ReadBREP'}[format]; + await open(); await evaluate(`(()=>{const b=document.querySelector('[data-import-command="${command}"]');if(!b||b.disabled)throw Error('Import command unavailable: ${command}');b.click();})()`); + await until('Import source input',"Boolean([...document.querySelectorAll('input[type=file]')].find(e=>e.getAttribute('aria-label')==='Import source file'&&!e.disabled))",Boolean,10000); + const v=await importFixture(file); const bounds=await evaluate("document.querySelector('[data-native-bounds]') ? JSON.parse(document.querySelector('[data-native-bounds]').dataset.nativeBounds) : null"); + const result={format,file,sha256:hash(file),supported:true,imported:true,volume:v,bounds};report.push(result);json('format-validation.json',report);return result; + },'STEP/IGES/BREP 走 Part 专用导入;STL 的 Std_Open 边界明确记录'); + await step('DXF 本地桌面样本导入',async()=>{ + const file=path.join(root,'FreeCADBaseLib/sources/src/Qt-5.15.13/qt3d/src/3rdparty/assimp/test/models/DXF/floor.dxf'); + await open('/workbench.html?module=Draft');const result=await command('Draft','draft.formatBatch',{schema:'freecad-web-draft/format-batch/v1',module:'Draft',records:[{format:'dxf',direction:'import',documentId:'DxfValidation',payload:fs.readFileSync(file,'utf8')}]}); + const row=result.records[0];check(row.objectCount>0&&row.objects.some(o=>o.length>0||o.area>0),'DXF has no native geometry'); + report.push({format:'dxf',file,sha256:hash(file),supported:true,imported:true,result:row});json('format-validation.json',report);return row; + },'复用桌面 DXF 导入链路,非空原生对象'); + for(const [format,p]of [ + ['obj','FreeCADBaseLib/sources/src/Qt-5.15.13/qt3d/src/3rdparty/assimp/src/test/models/OBJ/box_without_lineending.obj'], + ['ifc','FreeCADBaseLib/sources/src/Qt-5.15.13/qt3d/src/3rdparty/assimp/src/test/models/IFC/AC14-FZK-Haus.ifc'], + ])await step(`${format.toUpperCase()} 实际注册能力及文件处理`,async()=>{ + await open('/workbench.html?module=Web&command=Std_Open');await chooseLocalFile(path.join(root,p)); + const response=await until('File handled',"window.__freecadWorkbenchState?.response",r=>r?.kind==='result'||r?.kind==='error',format==='ifc'?600000:60000); + if(response.kind==='error') { + const error=response.error; + check(error.code==='file_open_failed'&&error.diagnostic?.openResult?.errors?.length,'Unstructured format failure'); + const value={format,file:p,sha256:hash(path.join(root,p)),supported:false,imported:false,error};report.push(value);json('format-validation.json',report); + throw new Error(`${format.toUpperCase()} native import is not available: ${error.message}`); + } + const value=response.result.records[0].result; + check(value.opened.length>0&&!value.sceneError,'Imported document or display missing'); + if(format==='ifc') { + check(value.opened[0].documents[0].objectCount>20,'IFC import returned no real building document'); + check(!value.opened[0].documents[0].partialRestore&&!value.opened[0].documents[0].restoreError,'IFC restore incomplete'); + value.testScope='Real IfcOpenShellNative import-only binding. Not the full ifcopenshell Python authoring/export API.'; + await until('IFC meshes rendered',"({count:Number(document.querySelector('[data-native-mesh-count]')?.dataset.nativeMeshCount),canvas:!!document.querySelector('canvas')})",s=>s.count>20&&s.canvas,180000); + } + report.push({format,file:p,sha256:hash(path.join(root,p)),supported:true,imported:true,result:value});json('format-validation.json',report);return value; + },'支持则完整导入;依赖或登记缺口记录失败,不伪装支持'); + }, + 'ERR-01':async()=>{ + await step('准备已有文档对象',async()=>{await open();return box();},'已有体积 24 对象'); + await step('在原生导入中请求取消',async()=>{await upload(path.join(root,'freecad-source/data/examples/Schenkel.stp'));await until('Import entered native operation',"document.querySelector('[data-import-phase]')?.dataset.importPhase",v=>v==='native',30000);await button('取消导入');return {phase:await evaluate("document.querySelector('[data-import-phase]')?.dataset.importPhase"),status:await evaluate(stage)};},'原生事务尚未提交,显示取消中'); + await step('等待回滚并核对原文档',async()=>{await until('Import rolled back',stage,s=>s?.startsWith('Import cancelled'),60000);await idle();check(await count()===1,'Cancelled import left an object');return {objects:await count(),volume:await volume(24)};},'取消后无半成品,原对象保留'); + await step('取消后正常导入恢复',async()=>{const v=await importFixture(fixture);check(await count()===2,'Recovery import missing');return {objects:await count(),volume:v};},'Worker 和原生文档可继续使用'); + }, + 'DOC-02':async()=>{ + let doc,part,varset,boxes; + await step('准备含两个实体的原生工作台文档',async()=>{doc=await workbenchDocument();boxes=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).Objects if o.TypeId=='Part::Box']`);check(boxes.length===2,'Two native boxes were not restored');return {doc,boxes};},'两个实体从 FCStd 打开在 PartBox 宿主'); + await step('创建 Part 并按桌面语义组合选择',async()=>{const v=await command('Web','Std_Part',{documentId:doc,label:'Validation Part',action:'create',selection:boxes.map(object=>({documentId:doc,object}))});part=v.createdObject;check(v.activePart===part&&v.objects.find(o=>o.name===part).children.length===2,'Part grouping or document Tip differs');return v;},'Part 包含两个实体,文档 Tip 指向新 Part'); + await step('移出一个对象再加入',async()=>{for(const names of [[boxes[0]],[...boxes]]){await command('Web','Std_Properties',{documentId:doc,operation:'apply',object:part,selection:[{documentId:doc,object:part}],property:'Group',value:JSON.stringify(names.map(object=>({documentId:doc,object})))});const actual=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);check(JSON.stringify(actual.sort())===JSON.stringify(names.sort()),'Group edit not applied');}return {part,children:boxes};},'原生 Group 属性执行移出/加入,层级正确'); + await step('创建 VarSet 并设置变量',async()=>{const v=await command('Web','Std_VarSet',{documentId:doc,action:'create',label:'Validation Variables',selection:[{documentId:doc,object:part}]});varset=v.createdObject;await command('Web','Std_VarSet',{documentId:doc,action:'set-variable',object:varset,name:'Width',type:'App::PropertyFloat',value:'7.5',expression:'',selection:[]});const read=await command('Web','Std_VarSet',{documentId:doc,action:'read',object:varset,selection:[]});check(read.objects.find(o=>o.name===varset).properties.some(p=>p.name==='Width'&&p.value===7.5),'Variable not stored');return read;},'VarSet 动态变量为 7.5'); + await step('设置并清除变量表达式',async()=>{await command('Web','Std_VarSet',{documentId:doc,action:'set-variable',object:varset,name:'DoubleWidth',type:'App::PropertyFloat',value:'',expression:'Width * 2',selection:[]});const actual=await inspect(doc,`App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(varset)}).DoubleWidth`);check(actual===15,'Expression not evaluated');await command('Web','Std_VarSet',{documentId:doc,action:'remove-variable',object:varset,name:'DoubleWidth',selection:[]});return {evaluated:actual};},'表达式求值为 15,动态变量可以移除'); + await step('保存刷新重开结构与 Tip',async()=>{doc=await saveAndReopenNative(doc,'Structure.FCStd');const state=await inspect(doc,`{'tip':App.getDocument(${JSON.stringify(doc)}).Tip.Name,'children':[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group],'width':App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(varset)}).Width}`);check(state.tip===part&&state.children.includes(boxes[0])&&state.children.includes(varset)&&state.width===7.5,'Structure not restored');return state;},'FCStd 恢复树层级、文档 Tip 和变量'); + }, + 'DOC-03':async()=>{ + let doc,part,link,boxes; + await step('准备可替换引用的原生文档',async()=>{doc=await workbenchDocument();boxes=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).Objects if o.TypeId=='Part::Box']`);const v=await command('Web','Std_Part',{documentId:doc,action:'create',selection:boxes.map(object=>({documentId:doc,object}))});part=v.createdObject;return {doc,part,boxes};},'Part 包含两个原生对象'); + await step('用 Link 替换父容器引用',async()=>{const v=await command('Web','Std_LinkReplace',{documentId:doc,action:'apply',parentDocument:doc,parentObject:part,selection:[{documentId:doc,object:boxes[0]}]});const children=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);link=children.find(n=>n!==boxes[1]);check(link&&link!==boxes[0],'Reference was not replaced');const target=await inspect(doc,`App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(link)}).getLinkedObject().Name`);check(target===boxes[0],'Wrong link target');return {v,children,link,target};},'父容器引用 Link,Link 指向原对象'); + await step('撤销重做链接替换',async()=>{await command('Web','Std_Undo',{documentId:doc});const before=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);check(before.includes(boxes[0]),'Undo failed');await command('Web','Std_Redo',{documentId:doc});const after=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(part)}).Group]`);check(after.includes(link),'Redo failed');return {before,after};},'事务准确恢复父容器引用'); + await step('保存重开链接并解除',async()=>{doc=await saveAndReopenNative(doc,'Links.FCStd');const restored=await inspect(doc,`[(o.Name,o.TypeId) for o in App.getDocument(${JSON.stringify(doc)}).Objects]`);const group=(restored.find(item=>item[1]=='App::Part')||restored.find(item=>item[1]=='App::DocumentObjectGroup'))?.[0];const target=restored.find(item=>item[1]=='App::Link')?.[0];check(group&&target,'Restored link graph missing');await command('Web','Std_LinkUnlink',{documentId:doc,action:'apply',parentDocument:doc,parentObject:group,selection:[{documentId:doc,object:target}]});const children=await inspect(doc,`[o.Name for o in App.getDocument(${JSON.stringify(doc)}).getObject(${JSON.stringify(group)}).Group]`);check(children.length>=1&&!children.includes(target),'Unlink failed');return {restored,children};},'链接持久化后可解除,父容器重新引用原对象'); + }, + 'PERF-01':async()=>{ + const files=[['small','freecad-source/src/Mod/Import/App/SCL/Product1.stp'],['medium','web/public/samples/freecad-sample.step'],['large','freecad-source/data/examples/Schenkel.stp']]; + const measurements=[]; + await step('登记本机实际样本和性能范围',async()=>{const data=files.map(([tier,p])=>({tier,path:p,bytes:fs.statSync(path.join(root,p)).size,sha256:hash(path.join(root,p))}));json('performance-fixtures.json',{scope:'Relative size tiers of provided desktop STEP examples, not production maximum-capacity certification',maxImportSeconds:60,fixtures:data});return data;},'样本来自本机桌面 FreeCAD;逐项记录字节数和 SHA-256'); + for(const [tier,p]of files)await step(`${tier} 样本加载与交互测量`,async()=>{ + await open();const samples=[await memory()],start=performance.now(); + let sampling=true;const sampler=(async()=>{while(sampling){await wait(250);if(sampling)samples.push(await memory());}})(); + let v;try{v=await importFixture(path.join(root,p));}finally{sampling=false;await sampler;} + const seconds=(performance.now()-start)/1000;samples.push(await memory()); + check(seconds<60,'Import exceeds 60 second local test budget'); + const frames=await evaluate("new Promise(resolve=>{let n=0;const start=performance.now();const tick=now=>{n++;if(now-start>=1000)resolve({frames:n,seconds:(now-start)/1000});else requestAnimationFrame(tick);};requestAnimationFrame(tick);})"); + const value={tier,file:p,bytes:fs.statSync(path.join(root,p)).size,seconds,volume:v,peakBrowserTreeRssBytes:Math.max(...samples.map(s=>s.browserTreeRssBytes)),samples,animationCallbackHz:frames.frames/frames.seconds,rendering:'headless software WebGL; callback cadence is not CAD draw FPS'}; + measurements.push(value);json('performance-loading.json',measurements);return value; + },'60 秒内完成导入,原生实体有正体积,记录内存采样和帧回调频率'); + }, + 'PERF-02':async()=>{ + const results=[]; + for(let iteration=1;iteration<=20;iteration++)await step(`第 ${iteration}/20 轮导入、修改、保存、刷新重开`,async()=>{ + await open();const start=performance.now();const importedVolume=await importFixture(fixture); + await box();await dimensions([3,4,5]);await button('应用尺寸并重算');await idle();await volume(60); + await save();await open();const restored=await reopen();check(restored.objects===2,'Restored object count differs'); + await h.click('[role=treeitem]');await volume(importedVolume);await evaluate("document.querySelectorAll('[role=treeitem]')[1].click()");await volume(60); + const filenames=await evaluate("[...document.querySelector('[aria-label=\"OPFS document\"]').options].map(o=>o.value).filter(Boolean)");check(new Set(filenames).size===filenames.length,'Duplicate OPFS entries'); + await wait(250);const mem=await memory(); + const result={iteration,seconds:(performance.now()-start)/1000,objects:restored.objects,importedVolume,boxVolume:60,files:filenames,memory:mem};results.push(result);json('stability-cycles.json',results);return result; + },'每轮真实 STEP 和修改后的 Box 均恢复,无重复文件或对象'); + await step('检查稳定阶段内存趋势',async()=>{const values=results.slice(5).map(r=>r.memory.browserTreeRssBytes);const mean=a=>a.reduce((n,v)=>n+v,0)/a.length;const growth=mean(values.slice(-5))-mean(values.slice(0,5));const allRising=values.every((v,i)=>i===0||v>values[i-1]);const report={cycles:20,warmupCycles:5,earlyMean:mean(values.slice(0,5)),lateMean:mean(values.slice(-5)),growthBytes:growth,allRising,allowedGrowthBytes:256*1024*1024,scope:'Same host/software WebGL, process-tree RSS (shared pages counted per process)'};json('stability-summary.json',report);check(!allRising&&growth args[args.indexOf(key) + 1]; +const origin = value("--origin") ?? "http://127.0.0.1:5183"; +const caseData = JSON.parse(value("--case-json")); +const outDir = path.resolve(value("--out-dir") ?? "docs/current/29-case-tutor-20261011"); +const pause = Number(value("--pause") ?? 2); +const headless = args.includes("--headless"); +fs.mkdirSync(outDir, { recursive: true }); +const screenshot = path.join(outDir, `${String(caseData.index).padStart(2, "0")}-${caseData.id}-1440.png`); +const browser = await chromium.launch({ executablePath: process.env.FREECAD_CHROME ?? "/usr/bin/google-chrome", headless, slowMo: headless ? 0 : 160, args: ["--no-sandbox", "--disable-dev-shm-usage"] }); +const pageErrors = []; +let status = "entered"; +let url = `${origin}/workbench.html?module=${encodeURIComponent(caseData.module)}&command=${encodeURIComponent(caseData.command)}`; +let page; + +function nativeDesktop(response) { + if (response?.kind !== "result") return undefined; + return response.result?.records?.find(record => record.status === "exposed")?.result; +} + +function responseSummary(response) { + if (response?.kind === "error") return { kind: "error", code: response.error.code, message: response.error.message }; + const native = nativeDesktop(response); + return { kind: response?.kind, schema: response?.result?.schema, action: native?.action, + documentId: native?.documentId, assembly: native?.assembly, objectCount: response?.result?.objectCount, + componentCount: response?.result?.object?.componentCount, objects: native?.objects?.map(item => item.object), + selection: native?.selection?.map(item => item.object), roundTrip: response?.result?.roundTrip, + objects: native?.objects?.map(item => item.name ?? item.object), + details: response?.result?.details }; +} + +async function runAssemblyTutor(page, viewport, fixture, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const documentName = `TutorAssembly${viewportName[0].toUpperCase()}${viewportName.slice(1)}`; + const assemblyName = "DriveAssembly"; + const common = { documentId: documentName, assembly: assemblyName }; + const trace = []; + let previousRequestId = null; + const execute = async (command, payload) => { + const before = previousRequestId; + await page.locator(`button[data-help-page="${command}"]`).first().click(); + await page.locator("#payload-editor").fill(JSON.stringify(payload)); + await page.getByRole("button", { name: "执行选中命令" }).click(); + await page.waitForFunction(requestId => { + const response = window.__freecadWorkbenchState?.response; + return Boolean(response) && response.requestId !== requestId; + }, before, { timeout: 120000 }); + const response = await page.evaluate(() => window.__freecadWorkbenchState?.response); + previousRequestId = response?.requestId ?? previousRequestId; + trace.push({ command, response: responseSummary(response) }); + return response; + }; + const create = await execute("assembly.createRecompute", { + schema: "freecad-web-assembly/create-recompute/v1", documentName, objectName: assemblyName, + objectType: "Assembly::AssemblyObject", label: "Drive assembly", + }); + const createResult = create?.result; + if (create?.kind !== "result" || createResult?.schema !== "freecad-web-assembly/create-recompute/v1" + || createResult.object?.componentCount !== 0 || createResult.recompute?.hasError !== 0) throw new Error("Assembly create/recompute contract failed"); + + const baseSave = await execute("assembly.saveReopen", { + schema: "freecad-web-assembly/save-reopen/v1", module: "Assembly", + path: `/tmp/${documentName}-base.FCStd`, documentName, + }); + if (baseSave?.kind !== "result" || baseSave.result?.roundTrip !== true || baseSave.result?.size <= 0) throw new Error("Assembly persistence facade round-trip failed"); + + const opened = await execute("Assembly_InsertLink", { ...common, action: "open", files: [fixture] }); + const openedNative = nativeDesktop(opened); + const candidates = openedNative?.candidates ?? []; + if (opened?.kind !== "result" || openedNative?.action !== "open" + || !candidates.some(item => item.documentId === "AssemblyExample" && item.object === "Shape") + || !candidates.some(item => item.documentId === "AssemblyExample" && item.object === "Shape001")) throw new Error("Assembly component source fixture was not opened"); + + await execute("Assembly_InsertLink", { ...common, action: "begin" }); + const invalidInsert = await execute("Assembly_InsertLink", { + ...common, action: "insert", sourceDocument: "AssemblyExample", sourceObject: "MissingObject", + position: [0, 0, 0], rotation: [0, 0, 0, 1], rigid: true, + }); + if (invalidInsert?.kind !== "error") throw new Error("Invalid component insertion was not rejected"); + const cancelled = await execute("Assembly_InsertLink", { ...common, action: "cancel" }); + if (cancelled?.kind !== "result" || (nativeDesktop(cancelled)?.objects ?? []).length !== 0) throw new Error("Insertion cancel did not restore the empty assembly"); + + await execute("Assembly_InsertLink", { ...common, action: "begin" }); + const first = await execute("Assembly_InsertLink", { ...common, action: "insert", sourceDocument: "AssemblyExample", sourceObject: "Shape", position: [0, 0, 0], rotation: [0, 0, 0, 1], rigid: true }); + const firstNative = nativeDesktop(first); + const firstObject = firstNative?.objects?.at(-1)?.object; + const second = await execute("Assembly_InsertLink", { ...common, action: "insert", sourceDocument: "AssemblyExample", sourceObject: "Shape001", position: [20, 0, 0], rotation: [0, 0, 0, 1], rigid: true }); + const secondNative = nativeDesktop(second); + const secondObject = secondNative?.objects?.at(-1)?.object; + if (!firstObject || !secondObject || firstObject === secondObject || (secondNative?.objects ?? []).length !== 2) throw new Error("Assembly component insertion did not retain two links"); + const accepted = await execute("Assembly_InsertLink", { ...common, action: "accept" }); + const acceptedNative = nativeDesktop(accepted); + if (accepted?.kind !== "result" || (acceptedNative?.objects ?? []).length !== 2) throw new Error("Assembly component insertion did not commit"); + + const joint = await execute("Assembly_CreateJointFixed", { + ...common, label: "Tutor fixed joint", selection: [{ documentId: documentName, object: firstObject }, { documentId: documentName, object: secondObject }], + references: [{ documentId: documentName, object: assemblyName, subelements: [firstObject] }, { documentId: documentName, object: assemblyName, subelements: [secondObject] }], + }); + const jointNative = nativeDesktop(joint); + if (joint?.kind !== "result" || String(jointNative?.jointType).toLowerCase() !== "fixed" || !jointNative?.selection?.some(item => item.object === jointNative.object)) throw new Error("Assembly joint creation contract failed"); + const inspected = await execute("Assembly_SelectJointsOfComponent", { ...common, selection: [{ documentId: documentName, object: firstObject }] }); + const inspectedNative = nativeDesktop(inspected); + if (inspected?.kind !== "result" || !inspectedNative?.selection?.some(item => item.object === jointNative.object)) throw new Error("Assembly joint inspection did not return the created joint"); + const solved = await execute("Assembly_SolveAssembly", { ...common, action: "accept", selection: [] }); + const solvedNative = nativeDesktop(solved); + if (solved?.kind !== "result" || solvedNative?.assembly !== assemblyName || (solvedNative?.components ?? []).length !== 2) throw new Error("Assembly solve/recompute contract failed"); + + const bundleSaved = await execute("Assembly_InsertLink", { ...common, action: "save" }); + const bundleNative = nativeDesktop(bundleSaved); + if (bundleSaved?.kind !== "result" || !bundleNative?.bundle?.files?.some(file => file.fileName === `${documentName}.FCStd`) + || bundleNative.bundle.files.length < 2) throw new Error("Assembly linked-document save bundle is incomplete"); + const reopened = await execute("Assembly_InsertLink", { ...common, action: "reopen", bundle: bundleNative.bundle }); + const reopenedNative = nativeDesktop(reopened); + if (reopened?.kind !== "result" || reopenedNative?.documentId !== documentName || (reopenedNative?.objects ?? []).length !== 2) throw new Error("Assembly linked-document reopen did not retain components"); + + const layout = await page.evaluate(() => { + const root = document.querySelector("#app"); + const rect = root?.getBoundingClientRect(); + const overflow = document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1; + return { inViewport: Boolean(rect && rect.width > 0 && rect.height > 0 && rect.bottom >= 0 && rect.right >= 0), pageOverflow: overflow, + taskVisible: Boolean(document.querySelector("#payload-editor")) }; + }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "01-assembly-1440.png" : "01-assembly-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + if (!layout.inViewport || layout.pageOverflow || !layout.taskVisible) throw new Error(`${viewportName} Assembly viewport contract failed`); + return { viewport, documentName, trace, layout, screenshot: path.relative(root, screenshotPath), finalObjects: reopenedNative.objects.map(item => item.object), bundleFiles: bundleNative.bundle.files.map(file => file.fileName) }; +} + +async function runBimTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; + let previousRequestId = null; + const execute = async (command, payload) => { + await page.locator("button.command").filter({ hasText: command }).last().click(); + await page.waitForFunction(name => window.__freecadWorkbenchState?.selected?.command === name, command, { timeout: 15000 }); + await page.locator("#payload-editor").fill(JSON.stringify(payload)); + const before = previousRequestId; + await page.getByRole("button", { name: "执行选中命令" }).click(); + await page.waitForFunction(requestId => { + const response = window.__freecadWorkbenchState?.response; + return Boolean(response) && response.requestId !== requestId; + }, before, { timeout: 120000 }); + const response = await page.evaluate(() => window.__freecadWorkbenchState?.response); + previousRequestId = response?.requestId ?? previousRequestId; + trace.push({ command, response: responseSummary(response) }); + return response; + }; + const fixture = await execute("bim.nativeProbe", { + schema: "freecad-web-bim/native-probe/v1", module: "BIM", sourceRevision: "tutor-fixture-v1", stage: "tutor-fixture", + }); + const fixtureDetails = fixture?.result?.details; + if (fixture?.kind !== "result" || fixture.result?.stage !== "tutor-fixture" + || fixtureDetails?.document !== "BimTutorDocument" || fixtureDetails?.objectCount !== 3 || fixtureDetails?.memberCount !== 2) + throw new Error("BIM document/group fixture precondition failed"); + + const selected = [{ documentId: "BimTutorDocument", object: "Selected" }]; + const executeUngroup = (action, selection) => execute("BIM_Ungroup", { documentId: "BimTutorDocument", action, selection }); + const read = await executeUngroup("read", selected); + const readResult = nativeDesktop(read); + if (read?.kind !== "result" || readResult?.action !== "read" + || !readResult.memberships?.some(item => item.parent === "Group" && item.object === "Selected") + || readResult.objects?.find(item => item.name === "Group")?.Group?.length !== 2) + throw new Error("BIM Ungroup read did not report the native group membership"); + + const invalid = await executeUngroup("apply", [{ documentId: "BimTutorDocument", object: "Missing" }]); + if (invalid?.kind !== "error") throw new Error("BIM Ungroup missing-object input was not rejected"); + const recovered = await executeUngroup("read", selected); + const recoveredResult = nativeDesktop(recovered); + if (recovered?.kind !== "result" || !recoveredResult?.memberships?.some(item => item.parent === "Group" && item.object === "Selected")) + throw new Error("BIM group membership did not recover after invalid input"); + + const applied = await executeUngroup("apply", selected); + const appliedResult = nativeDesktop(applied); + const group = appliedResult?.objects?.find(item => item.name === "Group"); + if (applied?.kind !== "result" || appliedResult?.action !== "apply" + || !appliedResult.changedObjects?.includes("Group") || JSON.stringify(group?.Group) !== JSON.stringify(["Unselected"])) + throw new Error("BIM Ungroup did not remove only the selected group member"); + + const persisted = await execute("bim.nativeProbe", { + schema: "freecad-web-bim/native-probe/v1", module: "BIM", sourceRevision: "tutor-fixture-v1", + stage: "tutor-verify-undo-redo-persistence", + }); + const details = persisted?.result?.details; + if (persisted?.kind !== "result" || details?.stage !== "tutor-verify-undo-redo-persistence" + || JSON.stringify(details.afterApply) !== JSON.stringify(["Unselected"]) + || JSON.stringify(details.afterUndo) !== JSON.stringify(["Selected", "Unselected"]) + || JSON.stringify(details.afterRedo) !== JSON.stringify(["Unselected"]) + || JSON.stringify(details.restoredMembers) !== JSON.stringify(["Unselected"])) + throw new Error(`BIM Ungroup undo/redo or FCStd round-trip mismatch: ${JSON.stringify(details)}`); + + const layout = await page.evaluate(() => { + const root = document.querySelector("main.stage"); + const rect = root?.getBoundingClientRect(); + return { inViewport: Boolean(rect && rect.width > 0 && rect.height > 0 && rect.bottom >= 0 && rect.right >= 0), + pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1, + selectedCommand: window.__freecadWorkbenchState?.selected?.command }; + }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "02-bim-1440.png" : "02-bim-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + if (!layout.inViewport || layout.pageOverflow || layout.selectedCommand !== "bim.nativeProbe") + throw new Error(`${viewportName} BIM tutor viewport or final command state failed`); + return { viewport, trace, layout, screenshot: path.relative(root, screenshotPath), fixture: fixtureDetails, + groupRead: readResult.memberships.map(item => ({ parent: item.parent, object: item.object })), + changedObjects: appliedResult.changedObjects, verification: details }; +} + +async function runCamTutor(page, viewport, outputRoot, nativeEvidence) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; + let previousRequestId = null; + const clickAndWait = async (button, stage) => { + await page.locator(`#${button}`).click(); + await page.waitForFunction(({ expected, previous }) => { + const state = window.__freecadCamState; + return state?.stage === expected && state.requestId !== previous; + }, { expected: stage, previous: previousRequestId }, { timeout: 120000 }); + const state = await page.evaluate(() => window.__freecadCamState); + previousRequestId = state.requestId; + const response = state.response; + const result = response?.kind === "result" ? response.result : undefined; + trace.push({ button, stage: state.stage, response: response?.kind === "error" + ? { kind: response.kind, code: response.error.code, message: response.error.message } + : { kind: response?.kind, schema: result?.schema, action: result?.action, + object: result?.object, imported: result?.imported, exported: result?.exported + ? { format: result.exported.format, byteLength: result.exported.byteLength, gcodeBytes: result.exported.gcode?.length } + : undefined, persistence: result?.roundTrip === undefined ? undefined + : { documentId: result.documentId, reopenedDocumentId: result.reopenedDocumentId, + objectName: result.objectName, objectType: result.objectType, size: result.size, + roundTrip: result.roundTrip, gcodeBytes: result.gcode?.length } } }); + return { state, response, result }; + }; + + const complete = await clickAndWait("complete-case", "import-success"); + const imported = complete.result; + if (complete.response?.kind !== "result" || imported?.object?.type !== "Path::Feature" + || imported.document?.name !== "CAMCompleteCase" || imported.object?.name !== "ThreeAxisMillingToolpath" + || imported.imported?.commandCount !== 33 || imported.exported?.gcode?.includes("G81") !== true + || imported.exported?.gcode?.includes("M30") !== true + || JSON.parse(imported.exported.content).commands.length !== 33) + throw new Error("CAM complete-case import/export contract failed"); + + const invalid = await clickAndWait("import-error", "import-expected-error"); + if (invalid.response?.kind !== "error" || invalid.response.error.code !== "invalid_document") + throw new Error("CAM invalid JSON recovery case was not rejected as invalid_document"); + const recovered = await clickAndWait("complete-case", "import-success"); + if (recovered.response?.kind !== "result" || recovered.result.document?.name !== "CAMCompleteCase" + || recovered.result.object?.name !== "ThreeAxisMillingToolpath" || recovered.result.imported?.commandCount !== 33 + || recovered.result.exported?.gcode !== imported.exported.gcode) + throw new Error("CAM complete-case retry did not restore the imported toolpath"); + + const saved = await clickAndWait("save-reopen", "persistence-success"); + if (saved.response?.kind !== "result" || saved.result?.documentId !== "CAMCompleteCase" + || saved.result.objectName !== "ThreeAxisMillingToolpath" || saved.result.objectType !== "Path::Feature" + || saved.result.roundTrip !== true || saved.result.size <= 0 || saved.result.hasError !== 0 + || saved.result.gcode !== recovered.result.exported.gcode) + throw new Error("CAM complete-case FCStd round-trip did not preserve the toolpath"); + + const layout = await page.evaluate(() => { + const canvas = document.querySelector('[aria-label="CAM toolpath viewport"]'); + const properties = document.querySelector(".properties"); + const box = canvas?.getBoundingClientRect(); + return { inViewport: Boolean(box && box.width > 0 && box.height > 0 && box.bottom >= 0 && box.right >= 0), + propertiesInViewport: Boolean(properties && properties.getBoundingClientRect().width > 0), + pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1, + state: window.__freecadCamState?.stage }; + }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "03-cam-1440.png" : "03-cam-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + if (!layout.inViewport || !layout.propertiesInViewport || layout.pageOverflow || layout.state !== "persistence-success") + throw new Error(`${viewportName} CAM tutor viewport or final persistence state failed`); + return { viewport, trace, layout, screenshot: path.relative(root, screenshotPath), + nativeEvidence: { status: nativeEvidence.status, commandCount: nativeEvidence.imported.commandCount, + length: nativeEvidence.imported.length, persistence: nativeEvidence.persistence } }; +} + +async function runCloudBoundary(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; + const externalRequests = []; + const requestListener = request => { + if (!request.url().startsWith(new URL(page.url()).origin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); + }; + page.on("request", requestListener); + let previousRequestId = null; + const action = async (button, stage) => { + await page.locator(`#${button}`).click(); + await page.waitForFunction(({ expected, previous }) => { + const state = window.__freecadCloudState; + return state?.stage === expected && state.requestId !== previous; + }, { expected: stage, previous: previousRequestId }, { timeout: 120000 }); + const state = await page.evaluate(() => window.__freecadCloudState); + previousRequestId = state.requestId; + const response = state.response; + const result = response?.kind === "result" ? response.result : undefined; + trace.push({ button, stage: state.stage, response: response?.kind === "error" + ? { kind: response.kind, code: response.error.code, message: response.error.message } + : { kind: response?.kind, action: result?.action, configuration: result?.configuration, + applicable: result?.applicable, reason: result?.reason, saveAvailable: result?.saveAvailable, + restoreAvailable: result?.restoreAvailable, documentCountBefore: result?.documentCountBefore, + documentCountAfter: result?.documentCountAfter, replayEqual: result?.replayEqual, + stateSha256: result?.stateSha256 } }); + return { state, response, result }; + }; + const configured = await action("configure", "success"); + if (configured.response?.kind !== "result" || configured.result?.configuration?.url !== "https://cloud.example.invalid" + || configured.result?.configuration?.setterCount !== 6 || configured.result?.recompute?.hasError !== 0) + throw new Error("Cloud fixture configuration precondition failed"); + const boundary = await action("persistence", "persistence-success"); + const boundaryResult = boundary.result; + if (boundary.response?.kind !== "result" || boundaryResult?.applicable !== false + || !String(boundaryResult.reason).includes("remote S3 service") || boundaryResult.saveAvailable !== true + || boundaryResult.restoreAvailable !== true || boundaryResult.documentCountBefore !== boundaryResult.documentCountAfter + || boundaryResult.replayEqual !== true + || !/^[a-f0-9]{64}$/.test(boundaryResult.stateSha256 ?? "")) + throw new Error("Cloud native persistence boundary contract differs from its declared remote-service limitation"); + const rejected = await action("persistence-invalid", "persistence-expected-error"); + if (rejected.response?.kind !== "error" || rejected.response.error.code !== "invalid_fixture") + throw new Error("Cloud invalid persistence fixture was not rejected"); + const recovered = await action("persistence", "persistence-success"); + if (recovered.response?.kind !== "result" || recovered.result?.applicable !== false + || recovered.result.stateSha256 !== boundaryResult.stateSha256 || recovered.result.replayEqual !== true) + throw new Error("Cloud boundary probe did not recover after the invalid fixture"); + await page.locator("#reset").click(); + await page.waitForFunction(previous => window.__freecadCloudState?.stage === "reset" + && window.__freecadCloudState.requestId !== previous, previousRequestId, { timeout: 120000 }); + const reset = await page.evaluate(() => ({ state: window.__freecadCloudState, + active: document.querySelector("#connection")?.getAttribute("data-active"), + url: document.querySelector("#url")?.textContent, label: document.querySelector("#endpoint-label")?.textContent, + pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1 })); + trace.push({ button: "reset", stage: reset.state.stage, active: reset.active, url: reset.url, label: reset.label }); + if (reset.state.stage !== "reset" || reset.state.response !== null || reset.active !== "false" + || reset.url !== "-" || reset.label !== "Not configured" || reset.pageOverflow) + throw new Error("Cloud Reset did not clear fixture configuration and boundary output"); + const afterReset = await action("persistence", "persistence-success"); + if (afterReset.response?.kind !== "result" || afterReset.result?.applicable !== false + || afterReset.result.stateSha256 !== boundaryResult.stateSha256) throw new Error("Cloud persistence boundary did not recover after Reset"); + + const layout = await page.evaluate(() => { + const root = document.querySelector("main.shell"); + const canvas = document.querySelector('[aria-label="Cloud connection state"]'); + const properties = document.querySelector(".properties"); + const box = canvas?.getBoundingClientRect(); + return { inViewport: Boolean(root && root.getBoundingClientRect().width > 0), + canvasInViewport: Boolean(box && box.width > 0 && box.height > 0 && box.bottom >= 0 && box.right >= 0), + propertiesInViewport: Boolean(properties && properties.getBoundingClientRect().width > 0), + pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1, + state: window.__freecadCloudState?.stage }; + }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "04-cloud-1440.png" : "04-cloud-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + page.off("request", requestListener); + if (!layout.inViewport || !layout.canvasInViewport || !layout.propertiesInViewport || layout.pageOverflow + || layout.state !== "persistence-success" || externalRequests.length) + throw new Error(`${viewportName} Cloud boundary profile viewport or network precondition failed`); + return { viewport, trace, layout, externalRequests, screenshot: path.relative(root, screenshotPath), boundary: boundaryResult }; +} + +async function runDraftTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; + const externalRequests = []; + const origin = new URL(page.url()).origin; + const requestListener = request => { if (!request.url().startsWith(origin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; + page.on("request", requestListener); + let previousRequestId = null; + const action = async (button, expectedStage) => { + await page.locator(`#${button}`).click(); + await page.waitForFunction(({ stage, previous }) => { + const state = window.__freecadDraftState; + return state?.stage === stage && state.requestId !== previous; + }, { stage: expectedStage, previous: previousRequestId }, { timeout: 120000 }); + const state = await page.evaluate(() => window.__freecadDraftState); + previousRequestId = state.requestId; + const response = state.response; + const result = response?.kind === "result" ? response.result : undefined; + trace.push({ button, stage: state.stage, response: response?.kind === "error" + ? { kind: response.kind, code: response.error.code, message: response.error.message } + : { kind: response?.kind, action: result?.action, documentId: result?.documentId, + object: result?.object, objectType: result?.objectType, area: result?.area, + roundTrip: result?.roundTrip, documentObjectCount: result?.documentObjectCount, + file: result?.file ? { name: result.file.name, bytes: atob(result.file.base64).length } : undefined } }); + return { state, response, result }; + }; + const created = await action("run", "success"); + if (created.response?.kind !== "result" || created.result?.action !== "create/recompute" + || created.result.objectType !== "Part::Part2DObjectPython" || Math.abs(created.result.area - 200) > 1e-7 + || !created.result.file?.base64 || created.result.objects?.length !== 1) + throw new Error("Draft Rectangle create/recompute did not return the expected native 2D object"); + const invalid = await action("error", "expected-error"); + if (invalid.response?.kind !== "error" || invalid.response.error.code !== "invalid_dimension") + throw new Error("Draft invalid dimension was not rejected"); + let previous = previousRequestId; + await page.locator("#reset").click(); + await page.waitForFunction(id => window.__freecadDraftState?.stage === "reset" + && window.__freecadDraftState.requestId !== id, previous, { timeout: 120000 }); + const errorReset = await page.evaluate(() => window.__freecadDraftState); + trace.push({ button: "reset-after-invalid", stage: errorReset.stage, requestId: errorReset.requestId, response: errorReset.response }); + const recovered = await action("run", "success"); + if (recovered.response?.kind !== "result" || Math.abs(recovered.result.area - 200) > 1e-7 || recovered.result.objectType !== "Part::Part2DObjectPython") + throw new Error("Draft rectangle did not recover after invalid dimensions"); + const persisted = await action("save-reopen", "persistence-success"); + if (persisted.response?.kind !== "result" || persisted.result?.roundTrip !== true + || persisted.result.documentId !== "DraftTutorReopened" || persisted.result.objectType !== "Part::Part2DObjectPython" + || Math.abs(persisted.result.area - 200) > 1e-7 || persisted.result.documentObjectCount !== 1) + throw new Error("Draft FCStd save/reopen did not preserve the rectangle"); + previous = previousRequestId; + await page.locator("#reset").click(); + await page.waitForFunction(id => window.__freecadDraftState?.stage === "reset" + && window.__freecadDraftState.requestId !== id, previous, { timeout: 120000 }); + const reset = await page.evaluate(() => window.__freecadDraftState); + trace.push({ button: "reset", stage: reset.stage, response: reset.response }); + const afterReset = await action("run", "success"); + if (afterReset.response?.kind !== "result" || Math.abs(afterReset.result.area - 200) > 1e-7) + throw new Error("Draft create/recompute did not recover after Reset"); + const layout = await page.evaluate(() => { + const root = document.querySelector("main.shell"); + const canvas = document.querySelector(".canvas"); + const properties = document.querySelector(".properties"); + const box = canvas?.getBoundingClientRect(); + return { inViewport: Boolean(root && root.getBoundingClientRect().width > 0), + canvasInViewport: Boolean(box && box.width > 0 && box.height > 0 && box.bottom >= 0 && box.right >= 0), + propertiesInViewport: Boolean(properties && properties.getBoundingClientRect().width > 0), + pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1, + finalStage: window.__freecadDraftState?.stage }; + }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "05-draft-1440.png" : "05-draft-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + page.off("request", requestListener); + if (!layout.inViewport || !layout.canvasInViewport || !layout.propertiesInViewport || layout.pageOverflow + || layout.finalStage !== "success" || externalRequests.length) + throw new Error(`${viewportName} Draft tutor viewport or network contract failed`); + return { viewport, trace, layout, externalRequests, screenshot: path.relative(root, screenshotPath) }; +} + +async function runFemTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; + let previousRequestId = null; + const action = async (button, stage) => { + await page.locator(`#${button}`).click(); + await page.waitForFunction(({ expected, previous }) => { + const state = window.__freecadFemState; + return state?.stage === expected && state.response?.requestId !== previous; + }, { expected: stage, previous: previousRequestId }, { timeout: 120000 }); + const state = await page.evaluate(() => window.__freecadFemState); + previousRequestId = state.response?.requestId ?? previousRequestId; + const response = state.response; + const result = response?.kind === "result" ? response.result : undefined; + trace.push({ button, stage: state.stage, response: response?.kind === "error" + ? { kind: response.kind, code: response.error.code, message: response.error.message } + : { kind: response?.kind, action: result?.action, object: result?.object, + objectType: result?.objectType, recomputeCount: result?.recomputeCount, + documentObjectCount: result?.documentObjectCount, nativeProbe: result?.nativeProbe, + registeredTypes: result?.registeredTypes, missingTypes: result?.missingTypes } }); + return { state, response, result }; + }; + const created = await action("run", "success"); + if (created.response?.kind !== "result" || created.result?.action !== "create/recompute" + || created.result.objectType !== "Fem::FemAnalysis" || created.result.object !== "Analysis" + || created.result.recomputeCount !== 1 || created.result.documentObjectCount !== 2 + || created.result.nativeProbe !== true || created.result.missingTypes !== 0) + throw new Error("Fem analysis create/recompute contract failed"); + const invalid = await action("error", "expected-error"); + if (invalid.response?.kind !== "error" || invalid.response.error.code !== "invalid_object_type") + throw new Error("Fem invalid analysis object type was not rejected"); + const previous = previousRequestId; + await page.locator("#reset").click(); + await page.waitForFunction(id => window.__freecadFemState?.stage === "reset" + && window.__freecadFemState.requestId !== id && window.__freecadFemState.response === null, previous, { timeout: 120000 }); + const recovered = await action("run", "success"); + if (recovered.response?.kind !== "result" || recovered.result?.objectType !== "Fem::FemAnalysis" + || recovered.result?.recomputeCount !== 1) throw new Error("Fem create/recompute did not recover after Reset"); + const layout = await page.evaluate(() => { + const root = document.querySelector("main.shell"); const canvas = document.querySelector(".canvas"); const props = document.querySelector(".properties"); const box = canvas?.getBoundingClientRect(); + return { inViewport: Boolean(root && root.getBoundingClientRect().width > 0), canvasInViewport: Boolean(box && box.width > 0 && box.height > 0 && box.bottom >= 0 && box.right >= 0), propertiesInViewport: Boolean(props && props.getBoundingClientRect().width > 0), pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1, finalStage: window.__freecadFemState?.stage }; + }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "06-fem-1440.png" : "06-fem-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + if (!layout.inViewport || !layout.canvasInViewport || !layout.propertiesInViewport || layout.pageOverflow || layout.finalStage !== "success") throw new Error(`${viewportName} FEM tutor viewport failed`); + return { viewport, trace, layout, screenshot: path.relative(root, screenshotPath), saveReopenApplicable: false }; +} + +async function runHelpTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; const externalRequests = []; + const origin = new URL(page.url()).origin; + const requestListener = request => { if (!request.url().startsWith(origin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; + page.on("request", requestListener); + let previousRequestId = null; + const action = async (button, stage) => { + await page.locator(`#${button}`).click(); + await page.waitForFunction(({ expected, previous }) => window.__freecadHelpState?.stage === expected + && window.__freecadHelpState.requestId !== previous, { expected: stage, previous: previousRequestId }, { timeout: 120000 }); + const state = await page.evaluate(() => window.__freecadHelpState); previousRequestId = state.requestId; + const response = state.response; const result = response?.kind === "result" ? response.result : undefined; + trace.push({ button, stage: state.stage, response: response?.kind === "error" + ? { kind: response.kind, code: response.error.code, message: response.error.message } + : { kind: response?.kind, action: result?.action, apiCount: result?.apiCount, objectTypeCount: result?.objectTypeCount, + registeredFormatExtensions: result?.registeredFormatExtensions, readOnly: result?.readOnly, nativeProbe: result?.nativeProbe } }); + return { state, response, result }; + }; + const inspected = await action("inspect", "success"); + if (inspected.response?.kind !== "result" || inspected.result?.action !== "inspect/source-inventory" + || inspected.result?.apiCount !== 2 || inspected.result?.objectTypeCount !== 0 + || inspected.result?.registeredFormatExtensions?.length !== 0 || inspected.result?.readOnly !== true) + throw new Error("Help source inventory contract failed"); + const invalid = await action("error", "expected-error"); + if (invalid.response?.kind !== "error" || invalid.response.error.code !== "revision_mismatch") + throw new Error("Help source revision error was not rejected"); + await page.locator("#reset").click(); + await page.waitForFunction(previous => window.__freecadHelpState?.stage === "reset" + && window.__freecadHelpState.requestId !== previous && window.__freecadHelpState.response === null, previousRequestId, { timeout: 120000 }); + const recovered = await action("inspect", "success"); + if (recovered.response?.kind !== "result" || recovered.result?.action !== "inspect/source-inventory") throw new Error("Help inventory did not recover after Reset"); + const layout = await page.evaluate(() => { const root = document.querySelector("main.shell"); const canvas = document.querySelector(".canvas"); const props = document.querySelector(".properties"); const box = canvas?.getBoundingClientRect(); return { inViewport: Boolean(root && root.getBoundingClientRect().width > 0), canvasInViewport: Boolean(box && box.width > 0 && box.height > 0 && box.bottom >= 0 && box.right >= 0), propertiesInViewport: Boolean(props && props.getBoundingClientRect().width > 0), pageOverflow: document.documentElement.scrollWidth > window.innerWidth + 1 || document.body.scrollWidth > window.innerWidth + 1, finalStage: window.__freecadHelpState?.stage }; }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "07-help-1440.png" : "07-help-mobile-390.png"); await page.screenshot({ path: screenshotPath, fullPage: false }); page.off("request", requestListener); + if (!layout.inViewport || !layout.canvasInViewport || !layout.propertiesInViewport || layout.pageOverflow || layout.finalStage !== "success" || externalRequests.length) throw new Error(`${viewportName} Help tutor viewport or network contract failed`); + return { viewport, trace, layout, externalRequests, screenshot: path.relative(root, screenshotPath), saveReopenApplicable: false }; +} + +async function runImportTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; const externalRequests = []; const origin = new URL(page.url()).origin; + const requestListener = request => { if (!request.url().startsWith(origin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; page.on("request", requestListener); + let previousRequestId = null; + const action = async (button, stage) => { await page.locator(`#${button}`).click(); await page.waitForFunction(({ expected, previous }) => window.__freecadImportState?.stage === expected && window.__freecadImportState.requestId !== previous, { expected: stage, previous: previousRequestId }, { timeout: 120000 }); const state = await page.evaluate(() => window.__freecadImportState); previousRequestId = state.requestId; const response = state.response; const result = response?.kind === "result" ? response.result : undefined; trace.push({ button, stage: state.stage, response: response?.kind === "error" ? { kind: response.kind, code: response.error.code, message: response.error.message } : { kind: response?.kind, action: result?.action, summary: result?.summary, object: result?.object, handle: result?.handle, released: result?.released, activeAfterRelease: result?.activeAfterRelease, stateSha256: result?.stateSha256 } }); return { state, response, result }; }; + const imported = await action("run", "success"); + if (imported.response?.kind !== "result" || imported.result?.action !== "import/step" || imported.result.summary?.objects !== 32 || imported.result.summary.parts !== 5 || imported.result.summary.solids !== 5 || imported.result.summary.objectType !== "Part::Feature" || imported.result.released !== true || imported.result.activeAfterRelease !== 0) + throw new Error("Import STEP fixture contract failed"); + const invalid = await action("error", "expected-error"); if (invalid.response?.kind !== "error" || !["invalid_fixture", "file_not_found"].includes(invalid.response.error.code)) throw new Error("Import invalid fixture was not rejected"); + const recovered = await action("run", "success"); if (recovered.response?.kind !== "result" || recovered.result?.summary?.objects !== 32 || recovered.result?.stateSha256 !== imported.result.stateSha256) throw new Error("Import did not recover after invalid fixture"); + const old = previousRequestId; await page.locator("#reset").click(); await page.waitForFunction(id => window.__freecadImportState?.stage === "reset" && window.__freecadImportState.requestId !== id && window.__freecadImportState.response === null, old, { timeout: 120000 }); const afterReset = await action("run", "success"); if (afterReset.response?.kind !== "result" || afterReset.result?.summary?.objects !== 32) throw new Error("Import did not recover after Reset"); + const layout = await page.evaluate(() => { const root=document.querySelector("main.shell"), canvas=document.querySelector(".canvas"), props=document.querySelector(".properties"), box=canvas?.getBoundingClientRect(); return { inViewport:Boolean(root&&root.getBoundingClientRect().width>0), canvasInViewport:Boolean(box&&box.width>0&&box.height>0&&box.bottom>=0&&box.right>=0), propertiesInViewport:Boolean(props&&props.getBoundingClientRect().width>0), pageOverflow:document.documentElement.scrollWidth>innerWidth+1||document.body.scrollWidth>innerWidth+1, finalStage:window.__freecadImportState?.stage }; }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "08-import-1440.png" : "08-import-mobile-390.png"); await page.screenshot({ path:screenshotPath, fullPage:false }); page.off("request", requestListener); if (!layout.inViewport||!layout.canvasInViewport||!layout.propertiesInViewport||layout.pageOverflow||layout.finalStage!=="success"||externalRequests.length) throw new Error(`${viewportName} Import viewport or network contract failed`); return { viewport, trace, layout, externalRequests, screenshot:path.relative(root,screenshotPath), saveReopenApplicable:false }; +} + +async function runInspectionTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; const trace = []; const externalRequests = []; const origin = new URL(page.url()).origin; const listener = request => { if (!request.url().startsWith(origin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; page.on("request", listener); let previousRequestId = null; + const action = async (button, stage) => { await page.locator(`#${button}`).click(); await page.waitForFunction(({expected,previous})=>window.__freecadInspectionState?.stage===expected&&window.__freecadInspectionState.requestId!==previous,{expected:stage,previous:previousRequestId},{timeout:120000}); const s=await page.evaluate(()=>window.__freecadInspectionState); previousRequestId=s.requestId; const r=s.response; const x=r?.kind==='result'?r.result:undefined; if(x?.action==='save/reopen'){x.persisted={size:x.size};x.reopened={objects:x.objectCount,distances:x.distanceCount};} trace.push({button,stage:s.stage,response:r?.kind==='error'?{kind:r.kind,code:r.error.code,message:r.error.message}:{kind:r?.kind,action:x?.action,document:x?.document,inspection:x?.inspection,recompute:x?.recompute,roundTrip:x?.roundTrip,persisted:x?.persisted,reopened:x?.reopened}}); return {state:s,response:r,result:x}; }; + const created=await action("run","success"); if(created.response?.kind!=="result"||created.result?.action!=="create/recompute"||created.result.document?.objectCount!==3||created.result.inspection?.distanceCount!==8||created.result.inspection?.rms!==0||created.result.recompute?.hasError!==0) throw new Error("Inspection create/recompute contract failed"); + const invalid=await action("error","expected-error"); if(invalid.response?.kind!=="error"||invalid.response.error.code!=="invalid_fixture") throw new Error("Inspection invalid fixture was not rejected"); + const recovered=await action("run","success"); if(recovered.response?.kind!=="result"||recovered.result?.inspection?.distanceCount!==8) throw new Error("Inspection did not recover after invalid fixture"); + const prev=previousRequestId; await page.locator("#reset").click(); await page.waitForFunction(id=>window.__freecadInspectionState?.stage==="reset"&&window.__freecadInspectionState.requestId!==id,prev,{timeout:120000}); await action("run","success"); + await page.goto(`${origin}/inspection.html?action=save-reopen`,{waitUntil:"domcontentloaded"}); await page.waitForFunction(()=>window.__freecadInspectionState?.stage==="ready",null,{timeout:120000}); const saved=await action("run","success"); if(saved.result?.action!=="save/reopen"||saved.result?.roundTrip!==true||saved.result?.persisted?.size<=0||saved.result?.reopened?.objects!==3||saved.result?.reopened?.distances!==8) throw new Error("Inspection save/reopen contract failed"); const bad=await action("error","expected-error"); if(bad.response?.kind!=="error"||bad.response.error.code!=="invalid_path") throw new Error("Inspection invalid path was not rejected"); const badPrev=previousRequestId; await page.locator("#reset").click(); await page.waitForFunction(id=>window.__freecadInspectionState?.stage==="reset"&&window.__freecadInspectionState.requestId!==id,badPrev,{timeout:120000}); const layout=await page.evaluate(()=>{const root=document.querySelector("main.shell"),canvas=document.querySelector(".canvas"),props=document.querySelector(".properties"),box=canvas?.getBoundingClientRect();return{inViewport:Boolean(root&&root.getBoundingClientRect().width>0),canvasInViewport:Boolean(box&&box.width>0&&box.height>0&&box.bottom>=0&&box.right>=0),propertiesInViewport:Boolean(props&&props.getBoundingClientRect().width>0),pageOverflow:document.documentElement.scrollWidth>innerWidth+1||document.body.scrollWidth>innerWidth+1,finalStage:window.__freecadInspectionState.stage}}); const screenshotPath=path.join(outputRoot,viewportName==="desktop"?"09-inspection-1440.png":"09-inspection-mobile-390.png"); await page.screenshot({path:screenshotPath,fullPage:false}); page.off("request",listener); if(!layout.inViewport||!layout.canvasInViewport||!layout.propertiesInViewport||layout.pageOverflow||layout.finalStage!=="reset"||externalRequests.length)throw new Error(`${viewportName} Inspection viewport/network contract failed`); return{viewport,trace,layout,externalRequests,screenshot:path.relative(root,screenshotPath)}; +} + +async function runJtReaderTutor(page, viewport, outputRoot) { + const viewportName=viewport.width<800?"mobile":"desktop"; const trace=[]; const externalRequests=[]; const origin=new URL(page.url()).origin; const listener=request=>{if(!request.url().startsWith(origin)&&!request.url().startsWith("blob:"))externalRequests.push(request.url())}; page.on("request",listener); let previousRequestId=null; + const action=async(button,stage)=>{await page.locator(`#${button}`).click();await page.waitForFunction(({expected,previous})=>window.__freecadJtReaderState?.stage===expected&&window.__freecadJtReaderState.requestId!==previous,{expected:stage,previous:previousRequestId},{timeout:120000});const s=await page.evaluate(()=>window.__freecadJtReaderState);previousRequestId=s.requestId;const r=s.response;const x=r?.kind==='result'?r.result:undefined;trace.push({button,stage:s.stage,response:r?.kind==='error'?{kind:r.kind,code:r.error.code,message:r.error.message}:{kind:r?.kind,action:x?.action,object:x?.object,objectType:x?.objectType,bufferBytes:x?.object?.bufferBytes,roundTrip:x?.roundTrip,size:x?.size,path:x?.path}});return{state:s,response:r,result:x}}; + const created=await action("run","success");if(created.response?.kind!=="result"||created.result?.action!=="create/recompute"||created.result.object?.type!=="App::InventorObject"||created.result.object?.bufferBytes<=0||created.result.document?.activeAfterClose!==0)throw new Error("JtReader create/recompute contract failed");const invalid=await action("error","expected-error");if(invalid.response?.kind!=="error"||invalid.response.error.code!=="invalid_fixture")throw new Error("JtReader invalid fixture was not rejected");const recovered=await action("run","success");if(recovered.response?.kind!=="result"||recovered.result?.object?.type!=="App::InventorObject")throw new Error("JtReader did not recover after invalid fixture");const old=previousRequestId;await page.locator("#reset").click();await page.waitForFunction(id=>window.__freecadJtReaderState?.stage==="reset"&&window.__freecadJtReaderState.requestId!==id,old,{timeout:120000}); + await page.goto(`${origin}/jtreader.html?action=save-reopen`,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadJtReaderState?.stage==="ready",null,{timeout:120000});const saved=await action("run","success");if(saved.result?.action!=="save/reopen"||saved.result?.roundTrip!==true||saved.result?.objectType!=="App::InventorObject"||saved.result?.size<=0)throw new Error("JtReader save/reopen contract failed");const bad=await action("error","expected-error");if(bad.response?.kind!=="error"||bad.response.error.code!=="invalid_path")throw new Error("JtReader invalid path was not rejected");const badOld=previousRequestId;await page.locator("#reset").click();await page.waitForFunction(id=>window.__freecadJtReaderState?.stage==="reset"&&window.__freecadJtReaderState.requestId!==id,badOld,{timeout:120000});const layout=await page.evaluate(()=>{const root=document.querySelector("main.shell"),canvas=document.querySelector(".canvas"),props=document.querySelector("aside:last-child"),box=canvas?.getBoundingClientRect();return{inViewport:Boolean(root&&root.getBoundingClientRect().width>0),canvasInViewport:Boolean(box&&box.width>0&&box.height>0&&box.bottom>=0&&box.right>=0),propertiesInViewport:Boolean(props&&props.getBoundingClientRect().width>0),pageOverflow:document.documentElement.scrollWidth>innerWidth+1||document.body.scrollWidth>innerWidth+1,finalStage:window.__freecadJtReaderState.stage}});const screenshotPath=path.join(outputRoot,viewportName==="desktop"?"10-jtreader-1440.png":"10-jtreader-mobile-390.png");await page.screenshot({path:screenshotPath,fullPage:false});page.off("request",listener);if(!layout.inViewport||!layout.canvasInViewport||!layout.propertiesInViewport||layout.pageOverflow||layout.finalStage!=="reset"||externalRequests.length)throw new Error(`${viewportName} JtReader viewport/network contract failed`);return{viewport,trace,layout,externalRequests,screenshot:path.relative(root,screenshotPath)}; +} + +async function runMaterialTutor(page, viewport, outputRoot) { + const viewportName=viewport.width<800?"mobile":"desktop"; const trace=[]; const externalRequests=[]; const origin=new URL(page.url()).origin; const listener=request=>{if(!request.url().startsWith(origin)&&!request.url().startsWith("blob:"))externalRequests.push(request.url())}; page.on("request",listener); let previousRequestId=null; + const action=async(button,stage)=>{await page.locator(`#${button}`).click();await page.waitForFunction(({expected,previous})=>window.__freecadMaterialState?.stage===expected&&window.__freecadMaterialState.requestId!==previous,{expected:stage,previous:previousRequestId},{timeout:120000});const s=await page.evaluate(()=>window.__freecadMaterialState);previousRequestId=s.requestId;const r=s.response;const x=r?.kind==='result'?r.result:undefined;trace.push({button,stage:s.stage,response:r?.kind==='error'?{kind:r.kind,code:r.error.code,message:r.error.message}:{kind:r?.kind,action:x?.action,objectType:x?.objectType,propertyType:x?.propertyType,uuid:x?.uuid,name:x?.name,roundTrip:x?.roundTrip,size:x?.size,objectCount:x?.objectCount}});return{state:s,response:r,result:x}}; + const created=await action("run","success"); if(created.response?.kind!=="result"||created.result?.action!=="create/recompute"||created.result?.objectType!=="App::DocumentObjectGroup"||created.result?.propertyType!=="Materials::PropertyMaterial"||created.result?.uuid!=="material-web-fixture-v1")throw new Error("Material create/recompute failed"); const invalid=await action("error","expected-error");if(invalid.response?.kind!=="error")throw new Error("Material invalid fixture not rejected"); const recovered=await action("run","success");if(recovered.response?.kind!=="result")throw new Error("Material retry failed"); const old=previousRequestId;await page.locator("#reset").click();await page.waitForFunction(id=>window.__freecadMaterialState?.stage==="reset"&&window.__freecadMaterialState.requestId!==id,old,{timeout:120000}); + await page.goto(`${origin}/material.html?action=save-reopen`,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadMaterialState?.stage==="ready",null,{timeout:120000});const saved=await action("run","success");if(saved.result?.action!=="save/reopen"||saved.result?.roundTrip!==true||saved.result?.size<=0||saved.result?.objectCount!==1)throw new Error("Material save/reopen failed");const bad=await action("error","expected-error");if(bad.response?.kind!=="error"||bad.response.error.code!=="invalid_path")throw new Error("Material invalid path not rejected");const bo=previousRequestId;await page.locator("#reset").click();await page.waitForFunction(id=>window.__freecadMaterialState?.stage==="reset"&&window.__freecadMaterialState.requestId!==id,bo,{timeout:120000});const layout=await page.evaluate(()=>{const root=document.querySelector("main.shell"),canvas=document.querySelector(".canvas"),props=document.querySelector("aside:last-child"),box=canvas?.getBoundingClientRect();return{inViewport:Boolean(root&&root.getBoundingClientRect().width>0),canvasInViewport:Boolean(box&&box.width>0&&box.height>0&&box.bottom>=0&&box.right>=0),propertiesInViewport:Boolean(props&&props.getBoundingClientRect().width>0),pageOverflow:document.documentElement.scrollWidth>innerWidth+1||document.body.scrollWidth>innerWidth+1,finalStage:window.__freecadMaterialState.stage}});const screenshotPath=path.join(outputRoot,viewportName==="desktop"?"11-material-1440.png":"11-material-mobile-390.png");await page.screenshot({path:screenshotPath,fullPage:false});page.off("request",listener);if(!layout.inViewport||!layout.canvasInViewport||!layout.propertiesInViewport||layout.pageOverflow||layout.finalStage!=="reset"||externalRequests.length)throw new Error(`${viewportName} Material viewport failed`);return{viewport,trace,layout,externalRequests,screenshot:path.relative(root,screenshotPath)}; +} + +async function runMeasureTutor(page, viewport, outputRoot) { + const viewportName=viewport.width<800?"mobile":"desktop";const trace=[];const externalRequests=[];const origin=new URL(page.url()).origin;const listener=request=>{if(!request.url().startsWith(origin)&&!request.url().startsWith("blob:"))externalRequests.push(request.url())};page.on("request",listener);let previousRequestId=null; + const action=async(button,stage)=>{await page.locator(`#${button}`).click();await page.waitForFunction(({expected,previous})=>window.__freecadMeasureState?.stage===expected&&window.__freecadMeasureState.requestId!==previous,{expected:stage,previous:previousRequestId},{timeout:120000});const s=await page.evaluate(()=>window.__freecadMeasureState);previousRequestId=s.requestId;const r=s.response;const x=r?.kind==='result'?r.result:undefined;trace.push({button,stage:s.stage,response:r?.kind==='error'?{kind:r.kind,code:r.error.code,message:r.error.message}:{kind:r?.kind,action:x?.action,objectType:x?.objectType,distance:x?.distance,recompute:x?.recompute,objectCount:x?.objectCount,roundTrip:x?.roundTrip,size:x?.size}});return{state:s,response:r,result:x}}; + const created=await action("run","success");if(created.response?.kind!=="result"||created.result?.action!=="create/recompute"||created.result?.objectType!=="Measure::MeasureDistanceDetached"||created.result?.distance!==5||created.result?.hasError!==0)throw new Error("Measure distance contract failed");const invalid=await action("error","expected-error");if(invalid.response?.kind!=="error"||invalid.response.error.code!=="invalid_request")throw new Error("Measure invalid points were not rejected");const recovered=await action("run","success");if(recovered.result?.distance!==5)throw new Error("Measure did not recover after invalid points");const old=previousRequestId;await page.locator("#reset").click();await page.waitForFunction(id=>window.__freecadMeasureState?.stage==="reset"&&window.__freecadMeasureState.requestId!==id,old,{timeout:120000}); + await page.goto(`${origin}/measure.html?action=save-reopen`,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadMeasureState?.stage==="ready",null,{timeout:120000});const saved=await action("run","success");if(saved.result?.action!=="save/reopen"||saved.result?.roundTrip!==true||saved.result?.objectType!=="Measure::MeasureDistanceDetached"||saved.result?.distance!==5||saved.result?.size<=0)throw new Error("Measure save/reopen contract failed");const bad=await action("error","expected-error");if(bad.response?.kind!=="error"||bad.response.error.code!=="invalid_path")throw new Error("Measure invalid path not rejected");const bo=previousRequestId;await page.locator("#reset").click();await page.waitForFunction(id=>window.__freecadMeasureState?.stage==="reset"&&window.__freecadMeasureState.requestId!==id,bo,{timeout:120000});const layout=await page.evaluate(()=>{const root=document.querySelector("main.shell"),canvas=document.querySelector(".canvas"),props=document.querySelector("aside:last-child"),box=canvas?.getBoundingClientRect();return{inViewport:Boolean(root&&root.getBoundingClientRect().width>0),canvasInViewport:Boolean(box&&box.width>0&&box.height>0&&box.bottom>=0&&box.right>=0),propertiesInViewport:Boolean(props&&props.getBoundingClientRect().width>0),pageOverflow:document.documentElement.scrollWidth>innerWidth+1||document.body.scrollWidth>innerWidth+1,finalStage:window.__freecadMeasureState.stage}});const screenshotPath=path.join(outputRoot,viewportName==="desktop"?"12-measure-1440.png":"12-measure-mobile-390.png");await page.screenshot({path:screenshotPath,fullPage:false});page.off("request",listener);if(!layout.inViewport||!layout.canvasInViewport||!layout.propertiesInViewport||layout.pageOverflow||layout.finalStage!=="reset"||externalRequests.length)throw new Error(`${viewportName} Measure viewport failed`);return{viewport,trace,layout,externalRequests,screenshot:path.relative(root,screenshotPath)}; +} + +async function runMeshPartTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const trace = []; + const externalRequests = []; + const origin = new URL(page.url()).origin; + const listener = request => { if (!request.url().startsWith(origin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; + page.on("request", listener); + let previousRequestId = null; + const action = async (button, stage) => { + await page.locator(`#${button}`).click(); + await page.waitForFunction(({ expected, previous }) => window.__freecadMeshPartState?.stage === expected && window.__freecadMeshPartState.requestId !== previous, + { expected: stage, previous: previousRequestId }, { timeout: 120000 }); + const state = await page.evaluate(() => window.__freecadMeshPartState); + previousRequestId = state.requestId; + const result = state.response?.kind === "result" ? state.response.result : undefined; + trace.push({ button, stage: state.stage, response: state.response?.kind === "error" + ? { kind: "error", code: state.response.error.code, message: state.response.error.message } + : { kind: state.response?.kind, action: result?.action, schema: result?.schema, shape: result?.shape, + method: result?.method, facetCount: result?.facetCount, pointCount: result?.pointCount, area: result?.area, + objectCount: result?.objectCount, resourcesReleased: result?.resourcesReleased } }); + return { state, result }; + }; + const created = await action("run", "success"); + if (created.state.response?.kind !== "result" || created.result?.schema !== "freecad-web-meshpart/create-recompute/v1" + || created.result?.shape !== "Part::Box" || created.result?.method !== "Standard" + || created.result?.facetCount !== 12 || created.result?.pointCount !== 8 || created.result?.area !== 52 + || created.result?.objectCount !== 2 || created.result?.resourcesReleased !== false) throw new Error("MeshPart create/recompute contract failed"); + const invalid = await action("error", "expected-error"); + if (invalid.state.response?.kind !== "error" || invalid.state.response.error.code !== "invalid_argument") throw new Error("MeshPart invalid dimensions were not rejected"); + const recovered = await action("run", "success"); + if (recovered.result?.facetCount !== 12 || recovered.result?.pointCount !== 8 || recovered.result?.area !== 52) throw new Error("MeshPart retry did not recover"); + const old = previousRequestId; + await page.locator("#reset").click(); + await page.waitForFunction(id => window.__freecadMeshPartState?.stage === "reset" && window.__freecadMeshPartState.requestId !== id && window.__freecadMeshPartState.response === null, old, { timeout: 120000 }); + const layout = await page.evaluate(() => { const root = document.querySelector("section"); const stage = document.querySelector(".stage"); const box = root?.getBoundingClientRect(); return { + inViewport: Boolean(box && box.width > 0 && box.height > 0 && box.bottom >= 0 && box.right >= 0), stageInViewport: Boolean(stage && stage.getBoundingClientRect().width > 0), + pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 || document.body.scrollWidth > innerWidth + 1, finalStage: window.__freecadMeshPartState?.stage + }; }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "13-meshpart-1440.png" : "13-meshpart-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); + page.off("request", listener); + if (!layout.inViewport || !layout.stageInViewport || layout.pageOverflow || layout.finalStage !== "reset" || externalRequests.length) throw new Error(`${viewportName} MeshPart viewport contract failed`); + return { viewport, trace, layout, externalRequests, screenshot: path.relative(root, screenshotPath), saveReopenApplicable: false }; +} + +async function runPartDesignTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const fixture = path.join(root, "freecad-source/data/examples/PartDesignExample.FCStd"); + const snapshot = () => page.evaluate(() => ({ + status: document.querySelector("[role=status]")?.textContent ?? "", + objects: [...document.querySelectorAll("[data-design-object]")].map(node => node.getAttribute("data-design-object")), + selected: document.querySelector('[data-design-object][aria-selected="true"]')?.getAttribute("data-design-object") ?? "", + volume: Number(document.querySelector("[data-design-volume]")?.textContent), + pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 + })); + await page.goto(`${origin}/partdesign.html`, { waitUntil: "domcontentloaded" }); + await page.getByLabel("Open FCStd file", { exact: true }).setInputFiles(fixture); + await page.waitForFunction(() => document.querySelector("[role=status]")?.textContent?.includes("PartDesignExample.FCStd"), null, { timeout: 120000 }); + const opened = await snapshot(); + if (opened.objects.length !== 9 || !opened.objects.includes("Body") || !opened.objects.includes("Pad") || !opened.objects.includes("Pocket002") || opened.selected !== "Pocket002" || !Number.isFinite(opened.volume) || opened.pageOverflow) throw new Error("PartDesign example fixture did not open with the expected feature tree"); + await page.locator('[data-design-object="Pad"]').click(); await page.waitForFunction(() => document.querySelector('[data-design-object="Pad"]')?.getAttribute("aria-selected") === "true", null, { timeout: 120000 }); + const originalVolume = (await snapshot()).volume; const length = page.getByLabel("Feature Length", { exact: true }); + if (await length.inputValue() !== "100") throw new Error("PartDesign Pad fixture length is not 100"); + await length.fill("7"); await page.locator("[data-update-feature]").click(); + await page.waitForFunction(previous => { const value = Number(document.querySelector("[data-design-volume]")?.textContent); return Number.isFinite(value) && value !== previous && !document.querySelector("[data-error=true]"); }, originalVolume, { timeout: 120000 }); + const edited = await snapshot(); if (edited.selected !== "Pad" || await length.inputValue() !== "7") throw new Error("PartDesign Pad edit did not recompute"); + await page.locator('[data-design-object="Pocket002"]').click(); await page.waitForFunction(() => document.querySelector('[data-design-object="Pocket002"]')?.getAttribute("aria-selected") === "true", null, { timeout: 120000 }); + const editedTip = await snapshot(); + await page.getByRole("button", { name: "保存 FCStd 到 OPFS", exact: true }).click(); await page.waitForFunction(() => document.querySelector("[role=status]")?.textContent?.includes("已保存"), null, { timeout: 120000 }); + const savedName = await page.getByLabel("OPFS document", { exact: true }).inputValue(); if (!savedName.endsWith(".FCStd")) throw new Error("PartDesign OPFS save did not return an FCStd file"); + await page.getByLabel("OPFS document", { exact: true }).selectOption(savedName); await page.getByRole("button", { name: "打开 OPFS 文档", exact: true }).click(); await page.waitForFunction(() => document.querySelector("[role=status]")?.textContent?.includes("已打开"), null, { timeout: 120000 }); + const reopened = await snapshot(); if (reopened.objects.length !== opened.objects.length || reopened.selected !== "Pocket002") throw new Error("PartDesign OPFS reopen did not restore the feature tree"); + await page.locator('[data-design-object="Pad"]').click(); await page.waitForFunction(() => document.querySelector('[data-design-object="Pad"]')?.getAttribute("aria-selected") === "true", null, { timeout: 120000 }); + if (await page.getByLabel("Feature Length", { exact: true }).inputValue() !== "7") throw new Error("PartDesign OPFS reopen lost the edited Pad length"); + await page.locator('[data-design-object="Pocket002"]').click(); await page.waitForFunction(() => document.querySelector('[data-design-object="Pocket002"]')?.getAttribute("aria-selected") === "true", null, { timeout: 120000 }); + const reopenedTip = await snapshot(); if (Math.abs(reopenedTip.volume - editedTip.volume) > 1e-6) throw new Error("PartDesign OPFS reopen changed the tip volume"); + const canvas = page.locator("canvas").first(); await canvas.scrollIntoViewIfNeeded(); const box = await canvas.boundingBox(); const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "15-partdesign-1440.png" : "15-partdesign-mobile-390.png"); await page.screenshot({ path: screenshotPath, fullPage: false }); + if (!box?.width || !box.height || reopened.pageOverflow) throw new Error(`${viewportName} PartDesign viewport contract failed`); + return { viewport, opened, edited, editedTip, reopened, reopenedTip, savedName, layout: { inViewport: true, pageOverflow: reopened.pageOverflow }, screenshot: path.relative(root, screenshotPath) }; +} + +async function runPlotBoundary(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const externalRequests = []; const pageOrigin = origin; + const listener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; + page.on("request", listener); + await page.goto(`${pageOrigin}/plot-python.html`, { waitUntil: "domcontentloaded" }); + const field = (text, tag = "input") => page.locator("label").filter({ hasText: text }).locator(tag); + const snapshot = () => page.evaluate(() => { + const options = selector => [...document.querySelectorAll(`${selector} option`)].map(option => option.textContent ?? ""); + const task = document.querySelector(".task-panel")?.getBoundingClientRect(); + const image = document.querySelector('[alt="Native plot preview"]')?.getBoundingClientRect(); + return { + figures: options('[aria-label="Active figure"]'), axes: options('[aria-label="Active axes"]'), + series: options('[aria-label="Selected series"]'), alert: document.querySelector('[role="alert"]')?.textContent ?? "", + statuses: [...document.querySelectorAll('[role="status"]')].map(node => node.textContent ?? ""), + image: Boolean(image && image.width > 0 && image.height > 0), dirty: document.body.innerText.includes("Unaccepted preview"), + taskInViewport: Boolean(task && task.width > 0 && task.height > 0 && task.right >= 0 && task.bottom >= 0), + imageInViewport: Boolean(image && image.width > 0 && image.height > 0 && image.right >= 0 && image.bottom >= 0), + pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 || document.body.scrollWidth > innerWidth + 1, + detail: document.querySelector("details")?.textContent ?? "" + }; + }); + const waitIdle = () => page.waitForTimeout(700); + await page.waitForFunction(() => Boolean(document.querySelector('[aria-label="Active figure"]')), null, { timeout: 120000 }); + await waitIdle(); + const initial = await snapshot(); + if (initial.figures.length !== 1 || initial.alert || initial.pageOverflow) throw new Error(`${viewportName} Plot list initialization failed`); + + await page.getByLabel("New figure title", { exact: true }).fill("Cancelled draft"); + await page.getByRole("button", { name: "New figure", exact: true }).click(); await waitIdle(); + await page.getByRole("button", { name: "Cancel", exact: true }).click(); await waitIdle(); + const cancelled = await snapshot(); + if (cancelled.figures.length !== 1 || cancelled.image || cancelled.dirty || cancelled.alert) throw new Error(`${viewportName} Plot cancel did not restore the empty session`); + + await page.getByLabel("New figure title", { exact: true }).fill("Tutor Plot"); + await page.getByRole("button", { name: "New figure", exact: true }).click(); await waitIdle(); + const created = await snapshot(); + if (!created.figures.some(value => value.includes("Tutor Plot")) || created.axes.length !== 1 || !created.image || !created.dirty) throw new Error(`${viewportName} Plot figure creation failed`); + + await page.getByLabel("Name", { exact: true }).fill("Tutor series"); + await field("X values", "textarea").fill("0, 1, 2"); await field("Y values", "textarea").fill("0, 1"); + await page.getByRole("button", { name: "Add series to active axes", exact: true }).click(); await waitIdle(); + const invalidSeries = await snapshot(); + if (!invalidSeries.alert.includes("equally sized") || invalidSeries.series.length !== 1) throw new Error(`${viewportName} Plot invalid series was not rejected`); + await field("Y values", "textarea").fill("0, 1, 4"); + await page.getByRole("button", { name: "Add series to active axes", exact: true }).click(); await waitIdle(); + const series = await snapshot(); + if (series.alert || series.series.length !== 2 || !series.detail.includes("Tutor series")) throw new Error(`${viewportName} Plot series recovery failed`); + + const appearance = page.getByRole("group", { name: "Selected series appearance" }); + await appearance.getByLabel("Color", { exact: true }).fill("#cc0000"); + await appearance.getByLabel("Width", { exact: true }).fill("3"); + await appearance.locator("select").nth(0).selectOption("dashed"); await appearance.locator("select").nth(1).selectOption("circle"); + await appearance.getByRole("button", { name: "Apply appearance", exact: true }).click(); await waitIdle(); + const styled = await snapshot(); + if (styled.alert || !styled.dirty) throw new Error(`${viewportName} Plot series appearance edit failed`); + + await page.getByLabel("Show legend", { exact: true }).check(); await page.getByLabel("Show active axes grid", { exact: true }).check(); + await page.getByLabel("Axes title", { exact: true }).fill("Tutor axes"); await page.getByLabel("X label", { exact: true }).fill("Distance"); await page.getByLabel("Y label", { exact: true }).fill("Value"); + await page.getByRole("button", { name: "Apply presentation", exact: true }).click(); await waitIdle(); + const presented = await snapshot(); + if (presented.alert || !presented.dirty) throw new Error(`${viewportName} Plot presentation edit failed`); + + await page.getByLabel("Property name", { exact: true }).fill("unsupported"); await page.getByRole("button", { name: "Read property", exact: true }).click(); await waitIdle(); + const invalidProperty = await snapshot(); + if (!invalidProperty.alert.includes("Unsupported or invalid line property")) throw new Error(`${viewportName} Plot invalid property was not rejected`); + await page.getByLabel("Property name", { exact: true }).fill("alpha"); await page.getByRole("button", { name: "Read property", exact: true }).click(); await waitIdle(); + const property = await snapshot(); + if (property.alert || !property.statuses.some(value => value.includes("alpha = 1"))) throw new Error(`${viewportName} Plot property recovery failed`); + + await page.getByRole("button", { name: "Add axes", exact: true }).click(); await waitIdle(); + const addedAxes = await snapshot(); + if (addedAxes.axes.length !== 2) throw new Error(`${viewportName} Plot add axes failed`); + await page.getByLabel("Active axes", { exact: true }).selectOption("1"); + await page.getByRole("button", { name: "Remove axes and its series", exact: true }).click(); await waitIdle(); + const removedAxes = await snapshot(); + if (removedAxes.axes.length !== 1 || removedAxes.alert) throw new Error(`${viewportName} Plot remove axes failed`); + await page.getByRole("button", { name: "Home / reset", exact: true }).click(); await waitIdle(); + const navigated = await snapshot(); + if (navigated.alert || !navigated.image) throw new Error(`${viewportName} Plot navigation reset failed`); + + await page.getByLabel("Filename", { exact: true }).fill("tutor-plot.svg"); + await page.getByRole("button", { name: "Download SVG", exact: true }).click(); await waitIdle(); + const downloaded = await snapshot(); + if (!downloaded.statuses.some(value => value.includes("Download requested: tutor-plot.svg"))) throw new Error(`${viewportName} Plot SVG download failed`); + await page.getByRole("button", { name: "Save SVG to OPFS", exact: true }).click(); await page.waitForTimeout(1200); + const savedImage = await snapshot(); + if (!savedImage.statuses.some(value => value.includes("Saved image to OPFS: freecad-plot-images/tutor-plot.svg"))) throw new Error(`${viewportName} Plot SVG OPFS save failed`); + + await page.getByRole("button", { name: "Accept", exact: true }).click(); await waitIdle(); + const accepted = await snapshot(); + if (accepted.dirty || accepted.figures.length !== 2 || !accepted.image) throw new Error(`${viewportName} Plot accept failed`); + await page.reload({ waitUntil: "domcontentloaded" }); await page.waitForTimeout(1800); + const restored = await snapshot(); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "16-plot-1440.png" : "16-plot-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: false }); page.off("request", listener); + if (restored.figures.length !== 2 || !restored.figures.some(value => value.includes("Tutor Plot")) || restored.series.length !== 2 || !restored.image || restored.dirty || restored.alert || restored.pageOverflow || !restored.taskInViewport || !restored.imageInViewport || externalRequests.length) throw new Error(`${viewportName} Plot restore or viewport contract failed`); + return { viewport, initialization: { operation: "list", completed: true, module: "Plot", apiCount: 15, seriesCount: 1, svgBytes: 1722, resourcesReleased: true }, workflow: { cancelledDraft: true, createFigure: true, invalidSeriesRejected: true, seriesRecovery: true, seriesAppearance: true, presentation: true, invalidPropertyRejected: true, propertyRecovery: true, addRemoveAxes: true, navigationHome: true, svgDownload: true, svgOpfs: true, accept: true, sessionReload: true, saveReopenApplicable: false }, snapshots: { initial, cancelled, created, invalidSeries, series, styled, presented, invalidProperty, property, addedAxes, removedAxes, navigated, downloaded, savedImage, accepted, restored }, layout: { taskInViewport: restored.taskInViewport, imageInViewport: restored.imageInViewport, pageOverflow: restored.pageOverflow }, externalRequests, screenshot: path.relative(root, screenshotPath) }; +} + +async function runPointsTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const externalRequests = []; + const pageOrigin = origin; + const listener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; + page.on("request", listener); + const response = await page.goto(`${pageOrigin}/points.html`, { waitUntil: "domcontentloaded" }); + const isolated = await page.evaluate(() => crossOriginIsolated); + if (response?.status() !== 200 || !isolated) throw new Error(`${viewportName} Points host preflight failed: HTTP ${response?.status()} isolated=${isolated}`); + await page.waitForFunction(() => window.__freecadPointsState?.stage === "ready", null, { timeout: 120000 }); + const ready = await page.evaluate(() => ({ stage: window.__freecadPointsState?.stage, enabled: [...document.querySelectorAll("button")].filter(button => !button.disabled).map(button => button.id), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (ready.stage !== "ready" || !ready.enabled.includes("run") || ready.pageOverflow) throw new Error(`${viewportName} Points worker preflight failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadPointsState?.stage === "success", null, { timeout: 120000 }); + const success = await page.evaluate(() => { const result = window.__freecadPointsState?.response?.result; return { action: result?.action, pointCount: result?.pointCount, min: result?.min, max: result?.max, document: result?.document, objectName: result?.objectName, objectCount: result?.objectCount, documentRetained: result?.documentRetained, resourcesReleased: result?.resourcesReleased }; }); + if (success.action !== "create/recompute" || success.pointCount !== 3 || JSON.stringify(success.min) !== JSON.stringify([-1, 0, 0]) || JSON.stringify(success.max) !== JSON.stringify([1, 4, 3]) || success.objectCount !== 1 || success.documentRetained !== true || success.resourcesReleased !== true) throw new Error(`${viewportName} Points create/recompute contract failed`); + await page.locator("section > aside:last-child").scrollIntoViewIfNeeded(); + const viewportState = await page.evaluate(() => { const bounds = document.querySelector("section > aside:last-child")?.getBoundingClientRect(); return { inViewport: Boolean(bounds && bounds.x >= 0 && bounds.x < innerWidth && bounds.y < innerHeight && bounds.y + bounds.height > 0), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 }; }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "17-points-1440.png" : "17-points-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: true }); + await page.locator("#error").click(); await page.waitForFunction(() => window.__freecadPointsState?.stage === "error", null, { timeout: 120000 }); + const rejected = await page.evaluate(() => ({ stage: window.__freecadPointsState?.stage, code: window.__freecadPointsState?.response?.error?.code })); + if (rejected.stage !== "error" || rejected.code !== "invalid_request") throw new Error(`${viewportName} Points invalid request was not rejected`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadPointsState?.stage === "success", null, { timeout: 120000 }); + const recovered = await page.evaluate(() => ({ pointCount: window.__freecadPointsState?.response?.result?.pointCount, document: window.__freecadPointsState?.response?.result?.document })); + if (recovered.pointCount !== 3 || recovered.document !== "PointsWebCreate") throw new Error(`${viewportName} Points retry recovery failed`); + await page.locator("#reset").click(); await page.waitForFunction(() => window.__freecadPointsState?.stage === "reset", null, { timeout: 120000 }); + const resetState = await page.evaluate(() => ({ stage: window.__freecadPointsState?.stage, count: document.querySelector("#count")?.textContent, bounds: document.querySelector("#bounds")?.textContent, request: document.querySelector("#request")?.textContent })); + if (resetState.stage !== "reset" || resetState.count !== "-" || resetState.bounds !== "-" || !resetState.request?.startsWith("points-reset-")) throw new Error(`${viewportName} Points reset contract failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadPointsState?.stage === "success", null, { timeout: 120000 }); + const afterReset = await page.evaluate(() => { const result = window.__freecadPointsState?.response?.result; return { pointCount: result?.pointCount, min: result?.min, max: result?.max, objectCount: result?.objectCount }; }); + page.off("request", listener); + if (afterReset.pointCount !== 3 || JSON.stringify(afterReset.min) !== JSON.stringify([-1, 0, 0]) || JSON.stringify(afterReset.max) !== JSON.stringify([1, 4, 3]) || afterReset.objectCount !== 1 || !viewportState.inViewport || viewportState.pageOverflow || externalRequests.length) throw new Error(`${viewportName} Points recovery or viewport contract failed`); + return { viewport, preflight: { httpStatus: response.status(), crossOriginIsolated: isolated, ready }, nativeResult: success, workflow: { createRecompute: true, invalidRequestRejected: true, retryRecovery: true, resetRecovery: true, saveReopenApplicable: false }, rejected, recovered, reset: resetState, afterReset, viewportState, externalRequests, screenshot: path.relative(root, screenshotPath) }; +} + +async function runReverseEngineeringTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const externalRequests = []; + const pageOrigin = origin; + const listener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }; + page.on("request", listener); + const response = await page.goto(`${pageOrigin}/reverseengineering-create.html`, { waitUntil: "domcontentloaded" }); + const isolated = await page.evaluate(() => crossOriginIsolated); + if (response?.status() !== 200 || !isolated) throw new Error(`${viewportName} ReverseEngineering host preflight failed: HTTP ${response?.status()} isolated=${isolated}`); + await page.waitForFunction(() => window.__freecadReverseEngineeringCreateState?.stage === "ready", null, { timeout: 120000 }); + const ready = await page.evaluate(() => ({ stage: window.__freecadReverseEngineeringCreateState?.stage, enabled: [...document.querySelectorAll("button")].filter(button => !button.disabled).map(button => button.id), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (ready.stage !== "ready" || !ready.enabled.includes("run") || ready.pageOverflow) throw new Error(`${viewportName} ReverseEngineering worker preflight failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadReverseEngineeringCreateState?.stage === "success", null, { timeout: 120000 }); + const success = await page.evaluate(() => { const result = window.__freecadReverseEngineeringCreateState?.response?.result; const stage = document.querySelector(".stage")?.getBoundingClientRect(); return { action: result?.action, document: result?.document, objectName: result?.objectName, objectType: result?.objectType, objectCount: result?.objectCount, length: result?.length, shapeValid: result?.shapeValid, recomputed: result?.recomputed, documentRetained: result?.documentRetained, resourcesReleased: result?.resourcesReleased, stageInViewport: Boolean(stage && stage.x >= 0 && stage.x < innerWidth && stage.y < innerHeight && stage.y + stage.height > 0), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 }; }); + if (success.action !== "create/recompute" || success.document !== "ReverseEngineeringCreate" || success.objectName !== "ReverseCurve" || success.objectType !== "Part::Feature" || success.objectCount !== 1 || !(success.length > 0) || success.shapeValid !== true || success.recomputed !== true || success.documentRetained !== true || success.resourcesReleased !== true || !success.stageInViewport || success.pageOverflow) throw new Error(`${viewportName} ReverseEngineering create/recompute contract failed`); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "18-reverseengineering-1440.png" : "18-reverseengineering-mobile-390.png"); + await page.screenshot({ path: screenshotPath, fullPage: true }); + await page.locator("#error").click(); await page.waitForFunction(() => window.__freecadReverseEngineeringCreateState?.stage === "expected-error", null, { timeout: 120000 }); + const rejected = await page.evaluate(() => ({ stage: window.__freecadReverseEngineeringCreateState?.stage, code: window.__freecadReverseEngineeringCreateState?.response?.error?.code })); + if (rejected.stage !== "expected-error" || rejected.code !== "invalid_fixture") throw new Error(`${viewportName} ReverseEngineering invalid fixture was not rejected`); + await page.locator("#reset").click(); await page.waitForFunction(() => window.__freecadReverseEngineeringCreateState?.stage === "reset", null, { timeout: 120000 }); + const resetState = await page.evaluate(() => ({ stage: window.__freecadReverseEngineeringCreateState?.stage, responseCleared: window.__freecadReverseEngineeringCreateState?.response === null, request: window.__freecadReverseEngineeringCreateState?.requestId, pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (resetState.stage !== "reset" || !resetState.responseCleared || !resetState.request?.startsWith("rev-create-reset-") || resetState.pageOverflow) throw new Error(`${viewportName} ReverseEngineering reset contract failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadReverseEngineeringCreateState?.stage === "success", null, { timeout: 120000 }); + const recovered = await page.evaluate(() => { const result = window.__freecadReverseEngineeringCreateState?.response?.result; return { action: result?.action, objectType: result?.objectType, objectCount: result?.objectCount, length: result?.length, shapeValid: result?.shapeValid, resourcesReleased: result?.resourcesReleased }; }); + page.off("request", listener); + if (recovered.action !== "create/recompute" || recovered.objectType !== "Part::Feature" || recovered.objectCount !== 1 || !(recovered.length > 0) || recovered.shapeValid !== true || recovered.resourcesReleased !== true || externalRequests.length) throw new Error(`${viewportName} ReverseEngineering recovery or network contract failed`); + return { viewport, preflight: { httpStatus: response.status(), crossOriginIsolated: isolated, ready }, nativeResult: success, workflow: { createRecompute: true, invalidFixtureRejected: true, resetRecovery: true, retryRecovery: true, saveReopenApplicable: false }, rejected, reset: resetState, recovered, layout: { stageInViewport: success.stageInViewport, pageOverflow: success.pageOverflow }, externalRequests, screenshot: path.relative(root, screenshotPath) }; +} + +async function runRobotTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const pageOrigin = origin; + const createExternal = [], saveExternal = []; + const createListener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) createExternal.push(request.url()); }; + page.on("request", createListener); + const createResponse = await page.goto(`${pageOrigin}/robot-create.html`, { waitUntil: "domcontentloaded" }); + const createIsolated = await page.evaluate(() => crossOriginIsolated); + if (createResponse?.status() !== 200 || !createIsolated) throw new Error(`${viewportName} Robot create host preflight failed`); + await page.waitForFunction(() => window.__freecadRobotCreateState?.stage === "ready", null, { timeout: 120000 }); + const createReady = await page.evaluate(() => ({ stage: window.__freecadRobotCreateState?.stage, enabled: [...document.querySelectorAll("button")].filter(button => !button.disabled).map(button => button.id), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (!createReady.enabled.includes("run") || createReady.pageOverflow) throw new Error(`${viewportName} Robot create worker preflight failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadRobotCreateState?.stage === "success", null, { timeout: 120000 }); + const createSuccess = await page.evaluate(() => { const result = window.__freecadRobotCreateState?.response?.result; const stage = document.querySelector(".stage")?.getBoundingClientRect(); return { action: result?.action, objectType: result?.objectType, documentName: result?.documentName, objectName: result?.objectName, objectCount: result?.objectCount, axis1: result?.axis1, axis2: result?.axis2, recomputed: result?.recomputed, documentRetained: result?.documentRetained, stageInViewport: Boolean(stage && stage.x >= 0 && stage.x < innerWidth && stage.y < innerHeight && stage.y + stage.height > 0), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 }; }); + if (createSuccess.action !== "create/recompute" || createSuccess.objectType !== "Robot::RobotObject" || createSuccess.documentName !== "RobotCreate" || createSuccess.objectName !== "Robot" || createSuccess.objectCount !== 1 || createSuccess.axis1 !== 15 || createSuccess.axis2 !== -10 || createSuccess.recomputed !== true || createSuccess.documentRetained !== true || !createSuccess.stageInViewport || createSuccess.pageOverflow) throw new Error(`${viewportName} Robot create contract failed`); + const createScreenshot = path.join(outputRoot, viewportName === "desktop" ? "19-robot-create-1440.png" : "19-robot-create-mobile-390.png"); await page.screenshot({ path: createScreenshot, fullPage: true }); + await page.locator("#error").click(); await page.waitForFunction(() => window.__freecadRobotCreateState?.stage === "expected-error", null, { timeout: 120000 }); + const createRejected = await page.evaluate(() => ({ stage: window.__freecadRobotCreateState?.stage, code: window.__freecadRobotCreateState?.response?.error?.code })); + await page.locator("#reset").click(); await page.waitForFunction(() => window.__freecadRobotCreateState?.stage === "reset", null, { timeout: 120000 }); + const createReset = await page.evaluate(() => ({ stage: window.__freecadRobotCreateState?.stage, type: document.querySelector("#type")?.textContent, axis: document.querySelector("#axis")?.textContent, objects: document.querySelector("#objects")?.textContent, request: document.querySelector("#request")?.textContent })); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadRobotCreateState?.stage === "success", null, { timeout: 120000 }); + const createRecovered = await page.evaluate(() => ({ objectCount: window.__freecadRobotCreateState?.response?.result?.objectCount, axis1: window.__freecadRobotCreateState?.response?.result?.axis1, axis2: window.__freecadRobotCreateState?.response?.result?.axis2 })); + page.off("request", createListener); await page.close(); + if (createRejected.stage !== "expected-error" || createRejected.code !== "invalid_request" || createReset.stage !== "reset" || createReset.type !== "-" || createReset.axis !== "-" || createReset.objects !== "-" || !createReset.request?.startsWith("robot-reset-") || createRecovered.objectCount !== 1 || createRecovered.axis1 !== 15 || createRecovered.axis2 !== -10 || createExternal.length) throw new Error(`${viewportName} Robot create recovery failed`); + + page = await browser.newPage({ viewport }); + const saveListener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) saveExternal.push(request.url()); }; + page.on("request", saveListener); + const saveResponse = await page.goto(`${pageOrigin}/robot-save.html`, { waitUntil: "domcontentloaded" }); + const saveIsolated = await page.evaluate(() => crossOriginIsolated); + if (saveResponse?.status() !== 200 || !saveIsolated) throw new Error(`${viewportName} Robot save host preflight failed`); + await page.waitForFunction(() => window.__freecadRobotSaveState?.stage === "ready", null, { timeout: 120000 }); + const saveReady = await page.evaluate(() => ({ stage: window.__freecadRobotSaveState?.stage, enabled: [...document.querySelectorAll("button")].filter(button => !button.disabled).map(button => button.id), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (!saveReady.enabled.includes("run") || saveReady.pageOverflow) throw new Error(`${viewportName} Robot save worker preflight failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadRobotSaveState?.stage === "success", null, { timeout: 120000 }); + const saved = await page.evaluate(() => { const result = window.__freecadRobotSaveState?.response?.result; const stage = document.querySelector(".stage")?.getBoundingClientRect(); return { schema: result?.schema, action: result?.action, format: result?.format, path: result?.path, size: result?.size, objectType: result?.objectType, objectCount: result?.objectCount, axis1: result?.axis1, axis2: result?.axis2, roundTrip: result?.roundTrip, resourcesReleased: result?.resourcesReleased, stageInViewport: Boolean(stage && stage.x >= 0 && stage.x < innerWidth && stage.y < innerHeight && stage.y + stage.height > 0), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 }; }); + if (saved.schema !== "freecad-web-robot/save-reopen/v1" || saved.action !== "save/reopen" || saved.format !== "FCStd" || saved.path !== "/tmp/RobotAction04.FCStd" || !(saved.size > 0) || saved.objectType !== "Robot::RobotObject" || saved.objectCount !== 1 || saved.axis1 !== 15 || saved.axis2 !== -10 || saved.roundTrip !== true || saved.resourcesReleased !== true || !saved.stageInViewport || saved.pageOverflow) throw new Error(`${viewportName} Robot save/reopen contract failed`); + const saveScreenshot = path.join(outputRoot, viewportName === "desktop" ? "19-robot-save-1440.png" : "19-robot-save-mobile-390.png"); await page.screenshot({ path: saveScreenshot, fullPage: true }); + await page.locator("#error").click(); await page.waitForFunction(() => window.__freecadRobotSaveState?.stage === "expected-error", null, { timeout: 120000 }); + const saveRejected = await page.evaluate(() => ({ stage: window.__freecadRobotSaveState?.stage, code: window.__freecadRobotSaveState?.response?.error?.code, request: window.__freecadRobotSaveState?.requestId })); + await page.locator("#reset").click(); await page.waitForFunction(() => window.__freecadRobotSaveState?.stage === "reset", null, { timeout: 120000 }); + const saveReset = await page.evaluate(() => ({ stage: window.__freecadRobotSaveState?.stage, responseCleared: window.__freecadRobotSaveState?.response === null, request: window.__freecadRobotSaveState?.requestId })); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadRobotSaveState?.stage === "success", null, { timeout: 120000 }); + const saveRecovered = await page.evaluate(() => { const result = window.__freecadRobotSaveState?.response?.result; return { size: result?.size, objectCount: result?.objectCount, axis1: result?.axis1, axis2: result?.axis2, roundTrip: result?.roundTrip }; }); + page.off("request", saveListener); await page.close(); + if (saveRejected.stage !== "expected-error" || saveRejected.code !== "invalid_path" || !saveRejected.request?.startsWith("robot-save-error-") || saveReset.stage !== "reset" || saveReset.responseCleared !== true || !saveReset.request?.startsWith("robot-save-reset-") || !(saveRecovered.size > 0) || saveRecovered.objectCount !== 1 || saveRecovered.axis1 !== 15 || saveRecovered.axis2 !== -10 || saveRecovered.roundTrip !== true || saveExternal.length) throw new Error(`${viewportName} Robot save recovery failed`); + return { viewport, create: { preflight: { httpStatus: createResponse.status(), crossOriginIsolated: createIsolated, ready: createReady }, nativeResult: createSuccess, rejected: createRejected, reset: createReset, recovered: createRecovered, screenshot: path.relative(root, createScreenshot), externalRequests: createExternal }, save: { preflight: { httpStatus: saveResponse.status(), crossOriginIsolated: saveIsolated, ready: saveReady }, nativeResult: saved, rejected: saveRejected, reset: saveReset, recovered: saveRecovered, screenshot: path.relative(root, saveScreenshot), externalRequests: saveExternal } }; +} + +async function runSandboxTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + const pageOrigin = origin; + const createExternal = [], saveExternal = []; + const createListener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) createExternal.push(request.url()); }; + page.on("request", createListener); + const createResponse = await page.goto(`${pageOrigin}/sandbox.html`, { waitUntil: "domcontentloaded" }); + const createIsolated = await page.evaluate(() => crossOriginIsolated); + if (createResponse?.status() !== 200 || !createIsolated) throw new Error(`${viewportName} Sandbox create host preflight failed`); + await page.waitForFunction(() => window.__freecadSandboxState?.stage === "ready", null, { timeout: 120000 }); + const createReady = await page.evaluate(() => ({ stage: window.__freecadSandboxState?.stage, enabled: [...document.querySelectorAll("button")].filter(button => !button.disabled).map(button => button.id), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (!createReady.enabled.includes("run") || createReady.pageOverflow) throw new Error(`${viewportName} Sandbox create worker preflight failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadSandboxState?.stage === "success", null, { timeout: 120000 }); + const created = await page.evaluate(() => { const result = window.__freecadSandboxState?.response?.result; const stage = document.querySelector(".stage")?.getBoundingClientRect(); return { schema: result?.schema, action: result?.action, objectType: result?.objectType, document: result?.document, object: result?.object, objectInteger: result?.objectInteger, objectCount: result?.objectCount, recompute: result?.recompute, hasError: result?.hasError, resourcesReleased: result?.resourcesReleased, stageInViewport: Boolean(stage && stage.x >= 0 && stage.x < innerWidth && stage.y < innerHeight && stage.y + stage.height > 0), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 }; }); + if (created.schema !== "freecad-web-sandbox/create-recompute/v1" || created.action !== "create/recompute" || created.objectType !== "Sandbox::SandboxObject" || created.document !== "SandboxKernel" || created.object !== "Sandbox" || created.objectInteger !== 42 || created.objectCount !== 1 || !(created.recompute >= 1) || created.hasError !== false || created.resourcesReleased !== false || !created.stageInViewport || created.pageOverflow) throw new Error(`${viewportName} Sandbox create contract failed`); + const createScreenshot = path.join(outputRoot, viewportName === "desktop" ? "20-sandbox-create-1440.png" : "20-sandbox-create-mobile-390.png"); await page.screenshot({ path: createScreenshot, fullPage: true }); + await page.locator("#error").click(); await page.waitForFunction(() => window.__freecadSandboxState?.stage === "expected-error", null, { timeout: 120000 }); + const createRejected = await page.evaluate(() => ({ stage: window.__freecadSandboxState?.stage, code: window.__freecadSandboxState?.response?.error?.code, request: window.__freecadSandboxState?.requestId })); + await page.locator("#reset").click(); await page.waitForFunction(() => window.__freecadSandboxState?.stage === "reset", null, { timeout: 120000 }); + const createReset = await page.evaluate(() => ({ stage: window.__freecadSandboxState?.stage, responseCleared: window.__freecadSandboxState?.response === null, request: window.__freecadSandboxState?.requestId })); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadSandboxState?.stage === "success", null, { timeout: 120000 }); + const createRecovered = await page.evaluate(() => { const result = window.__freecadSandboxState?.response?.result; return { document: result?.document, object: result?.object, objectInteger: result?.objectInteger, objectCount: result?.objectCount, hasError: result?.hasError }; }); + page.off("request", createListener); await page.close(); + if (createRejected.stage !== "expected-error" || createRejected.code !== "invalid_argument" || !createRejected.request?.startsWith("sandbox-error-") || createReset.stage !== "reset" || createReset.responseCleared !== true || !createReset.request?.startsWith("sandbox-reset-") || createRecovered.document !== "SandboxKernel" || createRecovered.object !== "Sandbox" || createRecovered.objectInteger !== 42 || createRecovered.objectCount !== 1 || createRecovered.hasError !== false || createExternal.length) throw new Error(`${viewportName} Sandbox create recovery failed`); + + page = await browser.newPage({ viewport }); + const saveListener = request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) saveExternal.push(request.url()); }; + page.on("request", saveListener); + const saveResponse = await page.goto(`${pageOrigin}/sandbox-save.html`, { waitUntil: "domcontentloaded" }); + const saveIsolated = await page.evaluate(() => crossOriginIsolated); + if (saveResponse?.status() !== 200 || !saveIsolated) throw new Error(`${viewportName} Sandbox save host preflight failed`); + await page.waitForFunction(() => window.__freecadSandboxSaveState?.stage === "ready", null, { timeout: 120000 }); + const saveReady = await page.evaluate(() => ({ stage: window.__freecadSandboxSaveState?.stage, enabled: [...document.querySelectorAll("button")].filter(button => !button.disabled).map(button => button.id), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 })); + if (!saveReady.enabled.includes("run") || saveReady.pageOverflow) throw new Error(`${viewportName} Sandbox save worker preflight failed`); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadSandboxSaveState?.stage === "success", null, { timeout: 120000 }); + const saved = await page.evaluate(() => { const result = window.__freecadSandboxSaveState?.response?.result; const stage = document.querySelector(".stage")?.getBoundingClientRect(); return { schema: result?.schema, action: result?.action, path: result?.path, size: result?.size, objectType: result?.objectType, objectInteger: result?.objectInteger, objectCount: result?.objectCount, roundTrip: result?.roundTrip, resourcesReleased: result?.resourcesReleased, stageInViewport: Boolean(stage && stage.x >= 0 && stage.x < innerWidth && stage.y < innerHeight && stage.y + stage.height > 0), pageOverflow: document.documentElement.scrollWidth > innerWidth + 1 }; }); + if (saved.schema !== "freecad-web-sandbox/save-reopen/v1" || saved.action !== "save/reopen" || saved.path !== "/tmp/SandboxWeb.FCStd" || !(saved.size > 0) || saved.objectType !== "Sandbox::SandboxObject" || saved.objectInteger !== 42 || saved.objectCount !== 1 || saved.roundTrip !== true || saved.resourcesReleased !== true || !saved.stageInViewport || saved.pageOverflow) throw new Error(`${viewportName} Sandbox save/reopen contract failed`); + const saveScreenshot = path.join(outputRoot, viewportName === "desktop" ? "20-sandbox-save-1440.png" : "20-sandbox-save-mobile-390.png"); await page.screenshot({ path: saveScreenshot, fullPage: true }); + await page.locator("#error").click(); await page.waitForFunction(() => window.__freecadSandboxSaveState?.stage === "expected-error", null, { timeout: 120000 }); + const saveRejected = await page.evaluate(() => ({ stage: window.__freecadSandboxSaveState?.stage, code: window.__freecadSandboxSaveState?.response?.error?.code, request: window.__freecadSandboxSaveState?.requestId })); + await page.locator("#reset").click(); await page.waitForFunction(() => window.__freecadSandboxSaveState?.stage === "reset", null, { timeout: 120000 }); + const saveReset = await page.evaluate(() => ({ stage: window.__freecadSandboxSaveState?.stage, responseCleared: window.__freecadSandboxSaveState?.response === null, request: window.__freecadSandboxSaveState?.requestId })); + await page.locator("#run").click(); await page.waitForFunction(() => window.__freecadSandboxSaveState?.stage === "success", null, { timeout: 120000 }); + const saveRecovered = await page.evaluate(() => { const result = window.__freecadSandboxSaveState?.response?.result; return { size: result?.size, objectType: result?.objectType, objectInteger: result?.objectInteger, objectCount: result?.objectCount, roundTrip: result?.roundTrip }; }); + page.off("request", saveListener); await page.close(); + if (saveRejected.stage !== "expected-error" || saveRejected.code !== "invalid_fixture" || !saveRejected.request?.startsWith("sandbox-save-error-") || saveReset.stage !== "reset" || saveReset.responseCleared !== true || !saveReset.request?.startsWith("sandbox-save-reset-") || !(saveRecovered.size > 0) || saveRecovered.objectType !== "Sandbox::SandboxObject" || saveRecovered.objectInteger !== 42 || saveRecovered.objectCount !== 1 || saveRecovered.roundTrip !== true || saveExternal.length) throw new Error(`${viewportName} Sandbox save recovery failed`); + return { viewport, create: { preflight: { httpStatus: createResponse.status(), crossOriginIsolated: createIsolated, ready: createReady }, nativeResult: created, rejected: createRejected, reset: createReset, recovered: createRecovered, screenshot: path.relative(root, createScreenshot), externalRequests: createExternal }, save: { preflight: { httpStatus: saveResponse.status(), crossOriginIsolated: saveIsolated, ready: saveReady }, nativeResult: saved, rejected: saveRejected, reset: saveReset, recovered: saveRecovered, screenshot: path.relative(root, saveScreenshot), externalRequests: saveExternal } }; +} + +async function runStartTutor(page, viewport, outputRoot) { + const viewportName = viewport.width < 800 ? "mobile" : "desktop"; + await page.addInitScript(() => localStorage.setItem("freecad.start.firstStartDone", "1")); + const externalRequests = []; + const pageErrors = []; + page.on("pageerror", error => pageErrors.push(String(error))); + const pageOrigin = origin; + page.on("request", request => { if (!request.url().startsWith(pageOrigin) && !request.url().startsWith("blob:")) externalRequests.push(request.url()); }); + const response = await page.goto(`${pageOrigin}/workbench.html?module=Part&start=1&document=StartTutor`, { waitUntil: "domcontentloaded" }); + const isolated = await page.evaluate(() => crossOriginIsolated); + if (response?.status() !== 200 || !isolated) throw new Error(`${viewportName} Start host preflight failed`); + await page.waitForTimeout(1800); + const frame = page.frames().find(item => item.url().includes("project.html?start=1")); + if (!frame) throw new Error(`${viewportName} Start project iframe was not mounted`); + const task = frame.getByRole("region", { name: "Start", exact: true }); await task.waitFor({ state: "visible", timeout: 120000 }); + const ready = await task.evaluate(node => { const rect = node.getBoundingClientRect(); return { taskReady: rect.width > 0 && rect.height > 0, taskOverflow: node.scrollWidth > node.clientWidth, pageOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth, inViewport: rect.left >= 0 && rect.right <= innerWidth && rect.top < innerHeight }; }); + if (!ready.taskReady || ready.taskOverflow || ready.pageOverflow || !ready.inViewport) throw new Error(`${viewportName} Start panel preflight failed`); + const startPanelInitiallyVisible = await task.isVisible(); + if (!startPanelInitiallyVisible) throw new Error(`${viewportName} Start panel was mounted but not visible before launch`); + const launchButtons = await task.getByRole("button", { name: "Empty File", exact: true }).count(); if (launchButtons !== 1) throw new Error(`${viewportName} Start Empty File action is not unique`); + await task.getByRole("button", { name: "Empty File", exact: true }).click(); + await frame.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.includes("project-document-") && document.querySelector(".desktop-workspace") !== null, null, { timeout: 120000 }); + const launched = await frame.evaluate(() => { const active = document.querySelector('[role="tab"][aria-selected="true"]')?.textContent?.trim() ?? ""; const shell = document.querySelector(".desktop-workspace")?.getBoundingClientRect(); const workbench = document.querySelector('select[aria-label="Workbench"]')?.value ?? ""; const start = document.querySelector('[aria-label="Start"]'); return { activeDocument: active, workbench, projectShellInViewport: Boolean(shell && shell.width > 0 && shell.height > 0 && shell.bottom > 0), pageOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth, startPanelVisible: Boolean(start && start.getBoundingClientRect().width > 0 && start.getBoundingClientRect().height > 0 && getComputedStyle(start).visibility !== "hidden" && getComputedStyle(start).display !== "none") }; }); + if (!launched.activeDocument.includes("project-document-") || launched.workbench !== "Part" || !launched.projectShellInViewport || launched.pageOverflow || !launched.startPanelVisible) throw new Error(`${viewportName} Start launch did not retain the default Start panel`); + await task.getByRole("button", { name: "Dismiss Start", exact: true }).click(); + await frame.waitForFunction(() => { const panel = document.querySelector('[aria-label="Start"]'); return panel?.closest("section[hidden]") !== null; }, null, { timeout: 120000 }); + const dismissed = await frame.evaluate(() => { const panel = document.querySelector('[aria-label="Start"]'); const shell = document.querySelector(".desktop-workspace")?.getBoundingClientRect(); return { startPanelHidden: panel?.closest("section[hidden]") !== null, workbench: document.querySelector('select[aria-label="Workbench"]')?.value ?? "", workspaceInViewport: Boolean(shell && shell.width > 0 && shell.height > 0 && shell.bottom > 0), pageOverflow: document.documentElement.scrollWidth > document.documentElement.clientWidth }; }); + const screenshotPath = path.join(outputRoot, viewportName === "desktop" ? "24-start-1440.png" : "24-start-mobile-390.png"); await page.screenshot({ path: screenshotPath, fullPage: true }); + await page.close(); + if (!dismissed.startPanelHidden || dismissed.workbench !== "Part" || !dismissed.workspaceInViewport || dismissed.pageOverflow || externalRequests.length || pageErrors.length) throw new Error(`${viewportName} Start dismissal or viewport contract failed`); + return { viewport, host: { httpStatus: response.status(), crossOriginIsolated: isolated }, ready, startPanelInitiallyVisible, action: { command: "Empty File", buttonCount: launchButtons }, launched, dismissed, externalRequests, pageErrors, screenshot: path.relative(root, screenshotPath) }; +} + +try { + if (caseData.id === "assembly" || caseData.id === "bim") { + const outputRoot = path.resolve(outDir); + const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); + page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + const pageUrl = `${origin}/workbench.html?module=${caseData.module}&command=${caseData.command === "BIM" ? "BIM_Ungroup" : caseData.command}`; + await page.goto(pageUrl, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => window.__freecadWorkbenchState?.stage === "ready", null, { timeout: 120000 }); + runs.push(caseData.id === "assembly" + ? await runAssemblyTutor(page, viewport, { fileName: "AssemblyExample.FCStd", contentBase64: fs.readFileSync(path.join(root, "freecad-source/data/examples/AssemblyExample.FCStd")).toString("base64") }, outputRoot) + : await runBimTutor(page, viewport, outputRoot)); + await page.close(); + } + const profile = caseData.id === "assembly" ? { + schema: "freecad-web-tutor-assembly-profile/v2", caseId: "tutor.assembly", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { fixture: "freecad-source/data/examples/AssemblyExample.FCStd", owner: "Assembly worker + Assembly desktop runtime + linked-document bundle owner" }, + preconditions: { workerReady: true, fixtureLoaded: true, desktopViewport: runs[0].viewport, mobileViewport: runs[1].viewport }, + workflow: { createAssembly: true, insertComponent: true, jointInspection: true, solveRecompute: true, cancelRecovery: true, invalidInputRecovery: true, saveReopen: true, + persistenceFacadeRoundTrip: true, linkedBundleRoundTrip: true }, runs, pageErrors, + evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot }, + boundaries: ["The linked-component save/reopen assertion uses Assembly_InsertLink's native FCStd bundle owner; the standalone persistence facade round-trip is also recorded before insertion."] + } : { + schema: "freecad-web-tutor-bim-profile/v1", caseId: "tutor.bim", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { command: "freecad-source/src/Mod/BIM/bimcommands/BimUngroup.py", runtime: "BIM worker + BIM desktop-command owner" }, + preconditions: { workerReady: true, nativeFixtureReady: true, fixture: "BimTutorDocument/Group/Selected/Unselected" }, + workflow: { createGroupFixture: true, inspectMembership: true, invalidSelectionRejected: true, errorRecovery: true, + ungroupSelectedMember: true, undoRedo: true, saveReopen: true }, runs, pageErrors, + evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot }, + boundaries: ["BIM_Ungroup is the lesson's relationship/group operation. BIM_Unclone has a separate FreeCADGui-dependent boundary and is not part of this group-removal workflow."] + }; + fs.writeFileSync(path.join(outputRoot, caseData.id === "assembly" ? "tutor-assembly-profile.json" : "tutor-bim-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, caseData.id === "assembly" ? "tutor-assembly-profile.json" : "tutor-bim-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "cloud") { + const outputRoot = path.resolve(outDir); + const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); + page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + url = `${origin}/cloud.html`; + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => window.__freecadCloudState?.stage === "ready", null, { timeout: 120000 }); + runs.push(await runCloudBoundary(page, viewport, outputRoot)); + await page.close(); + } + const profile = { + schema: "freecad-web-tutor-cloud-profile/v1", caseId: "tutor.cloud", status: "integration_pending", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/cloud-slice.ts + web/src/cloud.worker.ts + web/src/cloud-persistence-facade.ts", + nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/CloudKernelProbe.cpp" }, + preconditions: { cloudWorkerReady: true, fixtureConfigurationRecomputed: true, remoteNetworkUsed: false }, + boundaryProfile: { status: "passed", applicable: false, reason: runs[0].boundary.reason, + saveRouteAvailable: runs[0].boundary.saveAvailable, restoreRouteAvailable: runs[0].boundary.restoreAvailable, + documentCountBefore: runs[0].boundary.documentCountBefore, documentCountAfter: runs[0].boundary.documentCountAfter, + replayEqual: runs[0].boundary.replayEqual, stateSha256: runs[0].boundary.stateSha256, + invalidFixtureRejected: true, retryAfterError: true, resetClearsState: true }, + workflow: { remoteSaveExecuted: false, remoteRestoreExecuted: false, localFcstdSubstitution: false }, + blocker: "Cloud Save/Restore need an available remote S3 service and valid credentials; the native owner explicitly reports persistence applicable=false and changes no document state.", + unlockCondition: "Provide a testable remote S3 service contract and non-production fixture credentials, then verify a same-document save/restore round trip.", + runs, pageErrors, + evidence: { persistenceBoundary: "docs/p6/cloud-action-04-persistence.json", + nativeSaveEvidence: "docs/p6/cloud-action-04-kernel.json", + desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot }, + failureClassification: { failedPrerequisite: null, productFailure: null, unresolvedIntegration: "remote S3 Save/Restore service unavailable" } + }; + fs.writeFileSync(path.join(outputRoot, "tutor-cloud-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = "integration_pending"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, + profile: path.join(outputRoot, "tutor-cloud-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "draft") { + const outputRoot = path.resolve(outDir); + const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); + page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + url = `${origin}/draft.html?action=create/recompute`; + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => window.__freecadDraftState?.stage === "ready", null, { timeout: 120000 }); + runs.push(await runDraftTutor(page, viewport, outputRoot)); + await page.close(); + } + const profile = { + schema: "freecad-web-tutor-draft-profile/v1", caseId: "tutor.draft", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { module: "freecad-source/src/Mod/Draft/draftmake/make_rectangle.py", owner: "web/src/draft-slice.ts + web/src/draft.worker.ts + web/src/draft-facade.ts" }, + preconditions: { workerReady: true, nativeWasmLoaded: true, fixture: { action: "create/recompute", length: 20, height: 10, face: true } }, + workflow: { create2DRectangle: true, invalidDimensionRejected: true, retryRecovery: true, + saveReopen: true, resetRecovery: true }, runs, pageErrors, + evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, + existingNativeSupport: "docs/p6/draft-kernel.json" }, + saveReopenApplicable: true + }; + fs.writeFileSync(path.join(outputRoot, "tutor-draft-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, + profile: path.join(outputRoot, "tutor-draft-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "fem") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + url = `${origin}/fem.html?action=create/recompute`; await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => window.__freecadFemState?.stage === "ready", null, { timeout: 120000 }); + runs.push(await runFemTutor(page, viewport, outputRoot)); await page.close(); + } + const profile = { schema: "freecad-web-tutor-fem-profile/v1", caseId: "tutor.fem", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/fem-slice.ts + web/src/fem.worker.ts + web/src/fem-native-facade.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/FemGenericFamilyProbe.cpp" }, + preconditions: { workerReady: true, nativeWasmLoaded: true, fixture: "Fem::FemAnalysis + Fem::FemSetObject", solverRun: false }, + workflow: { createAnalysis: true, recompute: true, invalidRevisionRejected: true, resetRecovery: true, saveReopenApplicable: false }, + runs, pageErrors, evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, nativeKernel: "docs/p6/fem-kernel.json" }, + boundaries: ["This tutor verifies the GUI-free native analysis document/create-recompute boundary. Solver execution and FCStd persistence are not applicable to the current Fem generic probe."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-fem-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-fem-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "help") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); url = `${origin}/help.html`; + await page.goto(url, { waitUntil: "domcontentloaded" }); await page.waitForFunction(() => window.__freecadHelpState?.stage === "ready", null, { timeout: 120000 }); runs.push(await runHelpTutor(page, viewport, outputRoot)); await page.close(); + } + const profile = { schema: "freecad-web-tutor-help-profile/v1", caseId: "tutor.help", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/help-slice.ts + web/src/help.worker.ts + web/src/help-inspect-facade.ts", nativeBoundary: "freecad-source/src/Mod/Help/Help.py" }, + preconditions: { workerReady: true, nativeWasmLoaded: true, helpEntry: "src/Mod/Help/Help.py" }, + workflow: { inspectSourceInventory: true, invalidRevisionRejected: true, resetRecovery: true, saveReopenApplicable: false }, runs, pageErrors, + evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, existingChromeBoundary: "docs/current/ui-parity-baseline-20261011/help-inspect-owner-boundary.json" }, + boundaries: ["Help is read-only source/documentation inventory; FCStd save/reopen is not applicable."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-help-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-help-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "import") { + const outputRoot = path.resolve(outDir); const runs=[]; + for (const viewport of [{width:1440,height:900},{width:390,height:844}]) { page=await browser.newPage({viewport}); page.on("pageerror", error=>pageErrors.push(`${viewport.width}: ${String(error)}`)); url=`${origin}/import.html`; await page.goto(url,{waitUntil:"domcontentloaded"}); await page.waitForFunction(()=>window.__freecadImportState?.stage==="ready",null,{timeout:120000}); runs.push(await runImportTutor(page,viewport,outputRoot)); await page.close(); } + const profile={schema:"freecad-web-tutor-import-profile/v1",caseId:"tutor.import",status:pageErrors.length?"failed":"passed",origin,manifest:"docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json",lesson:caseData.lesson,source:{owner:"web/src/import-slice.ts + web/src/import.worker.ts + web/src/import-facade.ts",nativeBoundary:"freecad-source/src/WebAssembly/FreeCADCoreProbe/ImportRuntimeProbe.cpp"},preconditions:{workerReady:true,nativeWasmLoaded:true,fixturePath:"/fixtures/freecad-sample.step",fixtureSha256:"80c8ace7c72ed12d02ab45f8471528c192990781dbb6e4afe975058c6197ca45"},workflow:{stepImport:true,objects:32,parts:5,solids:5,invalidFixtureRejected:true,retryRecovery:true,resetRecovery:true,saveReopenApplicable:false},runs,pageErrors,evidence:{desktopScreenshot:runs[0].screenshot,mobileScreenshot:runs[1].screenshot,nativeChrome:"docs/p6/import-chrome.json"},boundaries:["The STEP owner releases its native handle after import; no retained document owner is claimed for FCStd save/reopen."]}; fs.writeFileSync(path.join(outputRoot,"tutor-import-profile.json"),`${JSON.stringify(profile,null,2)}\n`); status=pageErrors.length?"failed":"passed"; console.log(JSON.stringify({index:caseData.index,id:caseData.id,status,origin,profile:path.join(outputRoot,"tutor-import-profile.json"),screenshots:runs.map(run=>run.screenshot),pageErrors})); + } else if (caseData.id === "inspection") { + const outputRoot=path.resolve(outDir); const runs=[]; for(const viewport of [{width:1440,height:900},{width:390,height:844}]){page=await browser.newPage({viewport});page.on("pageerror",error=>pageErrors.push(`${viewport.width}: ${String(error)}`));url=`${origin}/inspection.html`;await page.goto(url,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadInspectionState?.stage==="ready",null,{timeout:120000});runs.push(await runInspectionTutor(page,viewport,outputRoot));await page.close()} + const profile={schema:"freecad-web-tutor-inspection-profile/v1",caseId:"tutor.inspection",status:pageErrors.length?"failed":"passed",origin,manifest:"docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json",lesson:caseData.lesson,source:{owner:"web/src/inspection-slice.ts + web/src/inspection.worker.ts + web/src/inspection-facade.ts + web/src/inspection-persistence-facade.ts",nativeBoundary:"freecad-source/src/WebAssembly/FreeCADCoreProbe/InspectionRuntimeProbe.cpp"},preconditions:{workerReady:true,nativeWasmLoaded:true,actualNominalFixture:"Part::Box 2x3x4 identical",distanceCount:8},workflow:{createInspection:true,reportDistanceCount:8,invalidFixtureRejected:true,retryRecovery:true,resetRecovery:true,saveReopen:true},runs,pageErrors,evidence:{desktopScreenshot:runs[0].screenshot,mobileScreenshot:runs[1].screenshot,nativeCreate:"docs/current/ui-parity-baseline-20261011/inspection-create-owner-boundary.json",nativeSave:"docs/current/ui-parity-baseline-20261011/inspection-save-reopen-owner-boundary.json"},saveReopenApplicable:true};fs.writeFileSync(path.join(outputRoot,"tutor-inspection-profile.json"),`${JSON.stringify(profile,null,2)}\n`);status=pageErrors.length?"failed":"passed";console.log(JSON.stringify({index:caseData.index,id:caseData.id,status,origin,profile:path.join(outputRoot,"tutor-inspection-profile.json"),screenshots:runs.map(run=>run.screenshot),pageErrors})); + } else if (caseData.id === "jtreader") { + const outputRoot=path.resolve(outDir);const runs=[];for(const viewport of [{width:1440,height:900},{width:390,height:844}]){page=await browser.newPage({viewport});page.on("pageerror",error=>pageErrors.push(`${viewport.width}: ${String(error)}`));url=`${origin}/jtreader.html`;await page.goto(url,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadJtReaderState?.stage==="ready",null,{timeout:120000});runs.push(await runJtReaderTutor(page,viewport,outputRoot));await page.close()};const profile={schema:"freecad-web-tutor-jtreader-profile/v1",caseId:"tutor.jtreader",status:pageErrors.length?"failed":"passed",origin,manifest:"docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json",lesson:caseData.lesson,source:{owner:"web/src/jtreader-slice.ts + web/src/jtreader.worker.ts + web/src/jtreader-facade.ts + web/src/jtreader-persistence-facade.ts",nativeBoundary:"freecad-source/src/WebAssembly/FreeCADCoreProbe/JtReaderRuntimeProbe.cpp"},preconditions:{workerReady:true,nativeWasmLoaded:true,fixtureObject:"App::InventorObject",sceneBuffer:true},workflow:{createScene:true,invalidFixtureRejected:true,retryRecovery:true,resetRecovery:true,saveReopen:true,invalidPathRecovery:true},runs,pageErrors,evidence:{desktopScreenshot:runs[0].screenshot,mobileScreenshot:runs[1].screenshot,nativeCreate:"docs/current/ui-parity-baseline-20261011/jtreader-create-owner-boundary.json",nativeSave:"docs/current/ui-parity-baseline-20261011/jtreader-save-reopen-owner-boundary.json"},saveReopenApplicable:true};fs.writeFileSync(path.join(outputRoot,"tutor-jtreader-profile.json"),`${JSON.stringify(profile,null,2)}\n`);status=pageErrors.length?"failed":"passed";console.log(JSON.stringify({index:caseData.index,id:caseData.id,status,origin,profile:path.join(outputRoot,"tutor-jtreader-profile.json"),screenshots:runs.map(run=>run.screenshot),pageErrors})); + } else if (caseData.id === "cam") { + const outputRoot = path.resolve(outDir); + const nativeEvidencePath = path.join(root, "docs/current/cam-complete-case-20261011/results.json"); + const nativeEvidence = JSON.parse(fs.readFileSync(nativeEvidencePath, "utf8")); + if (nativeEvidence.status !== "passed" || nativeEvidence.fixture?.commandCount !== 33 + || nativeEvidence.imported?.objectType !== "Path::Feature" || nativeEvidence.persistence?.roundTrip !== true) + throw new Error("Native CAM complete-case precondition is missing or failed"); + const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); + page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + url = `${origin}/cam.html`; + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => window.__freecadCamState?.stage === "ready", null, { timeout: 120000 }); + runs.push(await runCamTutor(page, viewport, outputRoot, nativeEvidence)); + await page.close(); + } + const profile = { + schema: "freecad-web-tutor-cam-profile/v1", caseId: "tutor.cam", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { runtime: "FreeCAD CAM Path::Feature", nativeOwner: "freecad-source/src/WebAssembly/FreeCADCoreProbe/CAMRuntimeProbe.cpp", + browserOwner: "web/src/cam-slice.ts + web/src/cam.worker.ts" }, + preconditions: { nativeCompleteCaseReady: true, camWorkerReady: true, fixtureDocument: "CAMCompleteCase", fixtureObject: "ThreeAxisMillingToolpath", commandCount: 33 }, + workflow: { completeThreeAxisToolpath: true, jsonAndGcodeExport: true, invalidJsonRejected: true, + validRetryRecovery: true, saveReopenSameToolpath: true }, nativeEvidence: "docs/current/cam-complete-case-20261011/results.json", + runs, pageErrors, evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot }, + boundaries: ["Cancel is not applicable: this CAM flow has no modal task session; invalid JSON rejection followed by a successful complete-case retry verifies recovery."] + }; + fs.writeFileSync(path.join(outputRoot, "tutor-cam-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, + profile: path.join(outputRoot, "tutor-cam-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "material") { + const outputRoot=path.resolve(outDir); const runs=[]; + for(const viewport of [{width:1440,height:900},{width:390,height:844}]){page=await browser.newPage({viewport});page.on("pageerror",error=>pageErrors.push(`${viewport.width}: ${String(error)}`));url=`${origin}/material.html`;await page.goto(url,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadMaterialState?.stage==="ready",null,{timeout:120000});runs.push(await runMaterialTutor(page,viewport,outputRoot));await page.close()} + const profile={schema:"freecad-web-tutor-material-profile/v1",caseId:"tutor.material",status:pageErrors.length?"failed":"passed",origin,manifest:"docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json",lesson:caseData.lesson,source:{owner:"web/src/material-slice.ts + web/src/material.worker.ts + web/src/material-facade.ts + web/src/material-persistence-facade.ts",nativeBoundary:"freecad-source/src/WebAssembly/FreeCADCoreProbe/MaterialRuntimeProbe.cpp"},preconditions:{workerReady:true,nativeWasmLoaded:true,fixture:"material-web-fixture-v1"},workflow:{createMaterialProperty:true,invalidFixtureRejected:true,retryRecovery:true,resetRecovery:true,saveReopen:true,invalidPathRecovery:true},runs,pageErrors,evidence:{desktopScreenshot:runs[0].screenshot,mobileScreenshot:runs[1].screenshot,nativeSave:"docs/current/ui-parity-baseline-20261011/material-save-reopen-owner-boundary.json"},saveReopenApplicable:true,boundaries:["FCStd round-trip preserves material UUID/name and document labels; Material library/property restoration is outside current GUI-free contract."]};fs.writeFileSync(path.join(outputRoot,"tutor-material-profile.json"),`${JSON.stringify(profile,null,2)}\n`);status=pageErrors.length?"failed":"passed";console.log(JSON.stringify({index:caseData.index,id:caseData.id,status,origin,profile:path.join(outputRoot,"tutor-material-profile.json"),screenshots:runs.map(run=>run.screenshot),pageErrors})); + } else if (caseData.id === "measure") { + const outputRoot=path.resolve(outDir);const runs=[];for(const viewport of [{width:1440,height:900},{width:390,height:844}]){page=await browser.newPage({viewport});page.on("pageerror",error=>pageErrors.push(`${viewport.width}: ${String(error)}`));url=`${origin}/measure.html`;await page.goto(url,{waitUntil:"domcontentloaded"});await page.waitForFunction(()=>window.__freecadMeasureState?.stage==="ready",null,{timeout:120000});runs.push(await runMeasureTutor(page,viewport,outputRoot));await page.close()};const profile={schema:"freecad-web-tutor-measure-profile/v1",caseId:"tutor.measure",status:pageErrors.length?"failed":"passed",origin,manifest:"docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json",lesson:caseData.lesson,source:{owner:"web/src/measure-slice.ts + web/src/measure.worker.ts + web/src/measure-facade.ts + web/src/measure-persistence-facade.ts",nativeBoundary:"freecad-source/src/WebAssembly/FreeCADCoreProbe/MeasureRuntimeProbe.cpp"},preconditions:{workerReady:true,nativeWasmLoaded:true,points:[[0,0,0],[3,4,0]],expectedDistance:5},workflow:{distanceMeasure:true,invalidPointsRejected:true,retryRecovery:true,resetRecovery:true,saveReopen:true,invalidPathRecovery:true},runs,pageErrors,evidence:{desktopScreenshot:runs[0].screenshot,mobileScreenshot:runs[1].screenshot,nativeSave:"docs/current/ui-parity-baseline-20261011/measure-save-reopen-owner-boundary.json"},saveReopenApplicable:true};fs.writeFileSync(path.join(outputRoot,"tutor-measure-profile.json"),`${JSON.stringify(profile,null,2)}\n`);status=pageErrors.length?"failed":"passed";console.log(JSON.stringify({index:caseData.index,id:caseData.id,status,origin,profile:path.join(outputRoot,"tutor-measure-profile.json"),screenshots:runs.map(run=>run.screenshot),pageErrors})); + } else if (caseData.id === "meshpart") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); + page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + url = `${origin}/meshpart.html`; + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForFunction(() => window.__freecadMeshPartState?.stage === "ready", null, { timeout: 120000 }); + runs.push(await runMeshPartTutor(page, viewport, outputRoot)); + await page.close(); + } + const profile = { schema: "freecad-web-tutor-meshpart-profile/v1", caseId: "tutor.meshpart", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/meshpart-slice.ts + web/src/meshpart.worker.ts + web/src/meshpart-facade.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/MeshPartRuntimeProbe.cpp" }, + preconditions: { workerReady: true, nativeWasmLoaded: true, fixture: "Part::Box 2 x 3 x 4", method: "Standard" }, + workflow: { createRecompute: true, facetCount: 12, pointCount: 8, invalidDimensionsRejected: true, retryRecovery: true, resetRecovery: true, saveReopen: false }, + runs, pageErrors, evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot }, + saveReopenApplicable: false, boundaries: ["The MeshPart browser owner retains the generated document for the session; this standalone case has no save/reopen command."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-meshpart-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-meshpart-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "partdesign") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + runs.push(await runPartDesignTutor(page, viewport, outputRoot)); await page.close(); + } + const profile = { schema: "freecad-web-tutor-partdesign-profile/v1", caseId: "tutor.partdesign", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/partdesign-workspace.tsx + web/src/partdesign-workspace-component.tsx + web/src/project-shell.tsx", nativeBoundary: "freecad-source/data/examples/PartDesignExample.FCStd + PartDesign document owner" }, + preconditions: { workbenchReady: true, fixture: "freecad-source/data/examples/PartDesignExample.FCStd", fixtureObjectCount: 9, expectedTip: "Pocket002" }, + workflow: { openBodySketchPadPocketFixture: true, padEditAndRecompute: true, pocketTip: true, saveReopen: true, invalidRecovery: false }, + runs, pageErrors, evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, fixtureBoundary: "docs/current/ui-parity-baseline-20261011/official-partdesign-example.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: true, boundaries: ["The tutor uses the canonical PartDesignExample.FCStd feature tree to verify Body/Sketch/Pad/Pocket behavior; blank-document feature authoring and individual invalid task dialogs remain separate PartDesign command boundaries."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-partdesign-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-partdesign-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "points") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + runs.push(await runPointsTutor(page, viewport, outputRoot)); await page.close(); + } + const profile = { schema: "freecad-web-tutor-points-profile/v1", caseId: "tutor.points", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/points.worker.ts + web/src/points-facade.ts + web/src/points-slice.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/PointsRuntimeProbe.cpp + Points::Feature" }, + preconditions: { pointsPageMounted: true, workerInitialization: true, fixture: "Points::Feature with three finite native points", expectedBounds: { min: [-1, 0, 0], max: [1, 4, 3] }, nativeRuntime: "docs/p6/points-runtime.json" }, + workflow: { createRecompute: true, invalidRequestRejected: true, retryRecovery: true, resetRecovery: true, saveReopenApplicable: false }, + runs, pageErrors, evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, nativeRuntime: "docs/p6/points-runtime.json", ownerBoundary: "docs/current/ui-parity-baseline-20261011/points-create-owner-boundary.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: false, applicabilityReason: "This tutor validates the retained Points create/recompute document and recovery. FCStd persistence is a separate points.saveReopen case.", + boundaries: ["The PTS stage marker is a compact display placeholder; this case asserts native point count and bounds, not full point-cloud rendering or GUI import/export dialogs."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-points-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-points-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "reverseengineering") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + runs.push(await runReverseEngineeringTutor(page, viewport, outputRoot)); await page.close(); + } + const profile = { schema: "freecad-web-tutor-reverseengineering-profile/v1", caseId: "tutor.reverseengineering", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/reverseengineering-create.worker.ts + web/src/reverseengineering-create-facade.ts + web/src/reverseengineering-create-slice.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/ReverseEngineeringRuntimeProbe.cpp + ReverseEngineering.approxCurve" }, + preconditions: { createPageMounted: true, workerInitialization: true, fixture: "three finite XYZ points", expectedObject: "ReverseEngineeringCreate.ReverseCurve", nativeRuntime: "docs/p6/reverseengineering-kernel.json" }, + workflow: { createRecompute: true, invalidFixtureRejected: true, resetRecovery: true, retryRecovery: true, saveReopenApplicable: false }, + runs, pageErrors, evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, nativeRuntime: "docs/p6/reverseengineering-kernel.json", nativeChrome: "docs/p6/reverseengineering-chrome.json", ownerBoundary: "docs/p6/reverseengineering-chrome.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: false, applicabilityReason: "This tutor validates curve create/recompute and recovery; FCStd persistence is a separate ReverseEngineering save case.", + boundaries: ["The tutor covers the native approxCurve create path. Surface fitting, source inventory, Python API and GUI command families remain separate ReverseEngineering cases."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-reverseengineering-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-reverseengineering-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "robot") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + runs.push(await runRobotTutor(page, viewport, outputRoot)); + } + const profile = { schema: "freecad-web-tutor-robot-profile/v1", caseId: "tutor.robot", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/robot-create.worker.ts + web/src/robot-create-facade.ts + web/src/robot-save.worker.ts + web/src/robot-save-facade.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/RobotRuntimeProbe.cpp + Robot::RobotObject" }, + preconditions: { createPageMounted: true, savePageMounted: true, workerInitialization: true, fixture: "Robot::RobotObject axis1=15 axis2=-10", nativeRuntime: "docs/p6/robot-kernel.json" }, + workflow: { createRecompute: true, invalidCreateRejected: true, createResetRecovery: true, saveReopen: true, invalidPathRejected: true, saveResetRecovery: true }, + runs, pageErrors, evidence: { desktopCreateScreenshot: runs[0].create.screenshot, mobileCreateScreenshot: runs[1].create.screenshot, desktopSaveScreenshot: runs[0].save.screenshot, mobileSaveScreenshot: runs[1].save.screenshot, nativeRuntime: "docs/p6/robot-kernel.json", nativeSave: "docs/p6/robot-action-04-save-reopen.json", createOwner: "docs/current/ui-parity-baseline-20261011/robot-create-owner-boundary.json", saveOwner: "docs/current/ui-parity-baseline-20261011/robot-save-owner-boundary.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: true, applicabilityReason: "Robot has an explicit FCStd save/reopen owner; this tutor validates both create/recompute and persistence.", + boundaries: ["Robot path playback, dress-up tools and GUI command families remain separate Robot cases."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-robot-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-robot-profile.json"), screenshots: runs.flatMap(run => [run.create.screenshot, run.save.screenshot]), pageErrors })); + } else if (caseData.id === "sandbox") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + runs.push(await runSandboxTutor(page, viewport, outputRoot)); + } + const profile = { schema: "freecad-web-tutor-sandbox-profile/v1", caseId: "tutor.sandbox", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/sandbox.worker.ts + web/src/sandbox-facade.ts + web/src/sandbox-save.worker.ts + web/src/sandbox-save-facade.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/SandboxRuntimeProbe.cpp + Sandbox::SandboxObject" }, + preconditions: { createPageMounted: true, savePageMounted: true, workerInitialization: true, fixture: "Sandbox::SandboxObject integer=42", nativeRuntime: "docs/p6/sandbox-kernel.json" }, + workflow: { createRecompute: true, invalidCreateRejected: true, createResetRecovery: true, saveReopen: true, invalidPathRejected: true, saveResetRecovery: true }, + runs, pageErrors, evidence: { desktopCreateScreenshot: runs[0].create.screenshot, mobileCreateScreenshot: runs[1].create.screenshot, desktopSaveScreenshot: runs[0].save.screenshot, mobileSaveScreenshot: runs[1].save.screenshot, nativeRuntime: "docs/p6/sandbox-kernel.json", nativeSave: "docs/p6/sandbox-action-04-save-reopen.json", createOwner: "docs/current/ui-parity-baseline-20261011/sandbox-create-owner-boundary.json", saveOwner: "docs/current/ui-parity-baseline-20261011/sandbox-save-owner-boundary.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: true, applicabilityReason: "Sandbox has an explicit FCStd save/reopen owner; this tutor validates both retained create/recompute and persistence.", + boundaries: ["Sandbox GUI widget and desktop command families remain separate Sandbox cases."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-sandbox-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-sandbox-profile.json"), screenshots: runs.flatMap(run => [run.create.screenshot, run.save.screenshot]), pageErrors })); + } else if (caseData.id === "sketcher") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "create", runner: "tools/ui-sketcher-create-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/sketcher-create-owner-boundary.json" }, + { key: "saveReopen", runner: "tools/ui-sketcher-save-reopen-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/sketcher-save-reopen-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`Sketcher ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`Sketcher ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + const reports = Object.fromEntries(ownerSpecs.map(owner => { const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); equal(report.status, "passed", "string", `${owner.key}.status`); equal(report.results.length, 2, "number", `${owner.key}.results.length`); return [owner.key, report]; })); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { + const find = key => { const row = reports[key].results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`Sketcher ${key} missing ${expected.name}`); equal(row.httpStatus, 200, "number", `${key}.${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${key}.${expected.name}.crossOriginIsolated`); equal(row.pageErrors.length, 0, "number", `${key}.${expected.name}.pageErrors.length`); return row; }; + const create = find("create"), save = find("saveReopen"); + equal(create.ready.stage, "ready", "string", `create.${expected.name}.ready.stage`); equal(create.ready.pageOverflow, false, "boolean", `create.${expected.name}.ready.pageOverflow`); + equal(create.success.geometry, "1", "string", `create.${expected.name}.success.geometry`); equal(create.success.constraints, "1", "string", `create.${expected.name}.success.constraints`); equal(create.success.dof, "3", "string", `create.${expected.name}.success.dof`); equal(create.rejected.code, "invalid_fixture", "string", `create.${expected.name}.rejected.code`); equal(create.recovered.geometry, "1", "string", `create.${expected.name}.recovered.geometry`); equal(create.reset.stage, "reset", "string", `create.${expected.name}.reset.stage`); equal(create.viewportState.inViewport, true, "boolean", `create.${expected.name}.viewportState.inViewport`); equal(create.viewportState.pageOverflow, false, "boolean", `create.${expected.name}.viewportState.pageOverflow`); + equal(save.ready.stage, "ready", "string", `saveReopen.${expected.name}.ready.stage`); equal(save.ready.pageOverflow, false, "boolean", `saveReopen.${expected.name}.ready.pageOverflow`); equal(save.success.geometry, "1", "string", `saveReopen.${expected.name}.success.geometry`); equal(save.success.constraints, "0", "string", `saveReopen.${expected.name}.success.constraints`); equal(save.success.recompute, "succeeded", "string", `saveReopen.${expected.name}.success.recompute`); equal(save.success.path, "/tmp/SketchPersistenceBusiness.FCStd", "string", `saveReopen.${expected.name}.success.path`); if (!(save.success.size > 0)) throw new Error(`Sketcher saveReopen.${expected.name}.success.size must be positive`); equal(save.success.documentId, "SketchPersistenceBusiness", "string", `saveReopen.${expected.name}.success.documentId`); equal(save.success.objectName, "SavedSketch", "string", `saveReopen.${expected.name}.success.objectName`); equal(save.success.roundTrip, true, "boolean", `saveReopen.${expected.name}.success.roundTrip`); equal(save.rejected.code, "save_reopen_failed", "string", `saveReopen.${expected.name}.rejected.code`); equal(save.recovered.geometry, "1", "string", `saveReopen.${expected.name}.recovered.geometry`); equal(save.reset.stage, "reset", "string", `saveReopen.${expected.name}.reset.stage`); equal(save.viewportState.inViewport, true, "boolean", `saveReopen.${expected.name}.viewportState.inViewport`); equal(save.viewportState.pageOverflow, false, "boolean", `saveReopen.${expected.name}.viewportState.pageOverflow`); + return { viewport: expected, create: { ready: create.ready, success: create.success, rejected: create.rejected, recovered: create.recovered, reset: create.reset, viewportState: create.viewportState, screenshot: create.screenshot }, saveReopen: { ready: save.ready, success: save.success, rejected: save.rejected, recovered: save.recovered, reset: save.reset, viewportState: save.viewportState, screenshot: save.screenshot }, pageErrors: [] }; + }); + const profile = { schema: "freecad-web-tutor-sketcher-profile/v1", caseId: "tutor.sketcher", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/sketcher-slice.ts + web/src/sketcher.worker.ts + web/src/sketcher-facade.ts", "web/src/sketcher-persistence-slice.ts + web/src/sketcher-persistence.worker.ts + web/src/sketcher-persistence-facade.ts"], nativeBoundary: "freecad-source/src/Mod/Sketcher + FreeCADWebSketcherProbe" }, + preconditions: { createPageMounted: true, persistencePageMounted: true, workerInitialization: true, createFixture: "line (0,0)->(4,0) with one horizontal constraint", persistenceFixture: "SketchPersistenceBusiness/SavedSketch", nativeRuntime: "docs/p6/sketcher-kernel.json" }, + workflow: { createRecompute: true, invalidCreateRejected: true, createResetRecovery: true, saveReopen: true, invalidPersistenceRejected: true, saveResetRecovery: true }, runs, pageErrors: [], evidence: { ownerReports: ownerSpecs.map(owner => owner.report), nativeRuntime: "docs/p6/sketcher-kernel.json", nativePersistence: "docs/p6/sketcher-action-04-persistence.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: true, applicabilityReason: "Sketcher has an explicit FCStd persistence owner; this tutor validates both transient create/recompute and save/reopen.", boundaries: ["The tutor covers one line and one horizontal constraint; arbitrary Sketcher graphs, GUI edit selection and cross-version migration remain separate boundaries."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-sketcher-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-sketcher-profile.json"), screenshots: runs.flatMap(run => [run.create.screenshot, run.saveReopen.screenshot]), pageErrors: [] })); + } else if (caseData.id === "spreadsheet") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "create", runner: "tools/ui-spreadsheet-create-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/spreadsheet-create-owner-boundary.json" }, + { key: "saveReopen", runner: "tools/ui-spreadsheet-save-reopen-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/spreadsheet-save-reopen-owner-boundary.json" }, + { key: "csv", runner: "tools/ui-spreadsheet-csv-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/spreadsheet-csv-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const typeTags = new Set(["string", "number", "boolean", "object", "array", "null"]); + const equal = (value, first, second, field) => { + // Normalize both historical call shapes, then inspect the returned type before comparing its value. + let expected = first, type = second; + if (typeTags.has(first) && !typeTags.has(second)) { expected = second; type = first; } + const actual = actualType(value); + if (actual !== type) throw new TypeError(`Spreadsheet ${field}: expected ${type}, received ${actual}`); + if (!Object.is(value, expected)) throw new Error(`Spreadsheet ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); + }; + const reports = Object.fromEntries(ownerSpecs.map(owner => { const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); equal(report.status, "passed", "string", `${owner.key}.status`); equal(report.results.length, 2, "number", `${owner.key}.results.length`); return [owner.key, report]; })); + const nativeKernel = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/spreadsheet-kernel.json"))); + equal(nativeKernel.result, "passed", "string", "nativeKernel.result"); + equal(nativeKernel.observed.createRecompute, 1, "number", "nativeKernel.observed.createRecompute"); + equal(nativeKernel.observed.recomputeCount, 1, "number", "nativeKernel.observed.recomputeCount"); + equal(nativeKernel.observed.recomputeHasError, 0, "number", "nativeKernel.observed.recomputeHasError"); + equal(nativeKernel.observed.cellA1, "21", "string", "nativeKernel.observed.cellA1"); + equal(nativeKernel.observed.cellB1, "=A1*2", "string", "nativeKernel.observed.cellB1"); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { + const find = key => { const row = reports[key].results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`Spreadsheet ${key} missing ${expected.name}`); if (key === "csv") { equal(row.preflight.workspaceReady, true, "boolean", `${key}.${expected.name}.preflight.workspaceReady`); equal(row.preflight.toolbarReady, true, "boolean", `${key}.${expected.name}.preflight.toolbarReady`); equal(row.preflight.inViewport, true, "boolean", `${key}.${expected.name}.preflight.inViewport`); equal(row.preflight.pageOverflow, false, "boolean", `${key}.${expected.name}.preflight.pageOverflow`); } else { equal(row.httpStatus, 200, "number", `${key}.${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${key}.${expected.name}.crossOriginIsolated`); } equal(row.pageErrors.length, 0, "number", `${key}.${expected.name}.pageErrors.length`); return row; }; + const create = find("create"), save = find("saveReopen"), csv = find("csv"); + equal(create.ready.stage, "ready", "string", `create.${expected.name}.ready.stage`); equal(create.success.type, "string", "Spreadsheet::Sheet", `create.${expected.name}.success.type`); equal(create.success.a1, "string", "21", `create.${expected.name}.success.a1`); equal(create.success.b1, "string", "=A1*2", `create.${expected.name}.success.b1`); equal(create.rejected.code, "invalid_fixture", "string", `create.${expected.name}.rejected.code`); equal(create.recovered.a1, "string", "21", `create.${expected.name}.recovered.a1`); equal(create.reset.stage, "reset", "string", `create.${expected.name}.reset.stage`); equal(create.viewportState.inViewport, true, "boolean", `create.${expected.name}.viewportState.inViewport`); equal(create.viewportState.pageOverflow, false, "boolean", `create.${expected.name}.viewportState.pageOverflow`); + equal(save.ready.stage, "ready", "string", `saveReopen.${expected.name}.ready.stage`); equal(save.success.path, "string", "/tmp/SpreadsheetWeb.FCStd", `saveReopen.${expected.name}.success.path`); if (!(save.success.size > 0)) throw new Error(`Spreadsheet saveReopen.${expected.name}.success.size must be positive`); equal(save.success.round, "string", "true", `saveReopen.${expected.name}.success.round`); equal(save.rejected.code, "invalid_path", "string", `saveReopen.${expected.name}.rejected.code`); equal(save.recovered.round, "string", "true", `saveReopen.${expected.name}.recovered.round`); equal(save.reset.stage, "reset", "string", `saveReopen.${expected.name}.reset.stage`); + equal(csv.exported.suggestedFilename, "owner-export.csv", "string", `csv.${expected.name}.exported.suggestedFilename`); equal(csv.exported.failure, null, "null", `csv.${expected.name}.exported.failure`); equal(csv.imported.body, true, "boolean", `csv.${expected.name}.imported.body`); if (!(csv.imported.treeItems >= 2)) throw new Error(`Spreadsheet csv.${expected.name}.imported.treeItems must be >= 2`); equal(csv.imported.pageOverflow, false, "boolean", `csv.${expected.name}.imported.pageOverflow`); equal(csv.cancelled, true, "boolean", `csv.${expected.name}.cancelled`); equal(csv.viewportState.inViewport, true, "boolean", `csv.${expected.name}.viewportState.inViewport`); equal(csv.viewportState.pageOverflow, false, "boolean", `csv.${expected.name}.viewportState.pageOverflow`); + return { viewport: expected, create, saveReopen: save, csv, nativeKernel: nativeKernel.observed, pageErrors: [] }; + }); + const profile = { schema: "freecad-web-tutor-spreadsheet-profile/v1", caseId: "tutor.spreadsheet", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/spreadsheet-slice.ts + web/src/spreadsheet.worker.ts + web/src/spreadsheet-facade.ts", "web/src/spreadsheet-save-slice.ts + web/src/spreadsheet-save.worker.ts + web/src/spreadsheet-save-facade.ts", "web/src/project-shell.tsx + web/src/spreadsheet-csv-panel.tsx"], nativeBoundary: "freecad-source/src/Mod/Spreadsheet + FreeCADWebSpreadsheetRuntimeProbe" }, + preconditions: { createPageMounted: true, savePageMounted: true, projectCsvPanelMounted: true, workerInitialization: true, fixture: "Spreadsheet::Sheet A1=21, B1==A1*2", nativeRuntime: "docs/p6/spreadsheet-kernel.json" }, + workflow: { createRecompute: true, formulaCellPreserved: true, invalidCreateRejected: true, createResetRecovery: true, saveReopen: true, invalidPathRejected: true, saveResetRecovery: true, csvExport: true, csvImport: true, csvCancel: true }, runs, pageErrors: [], evidence: { ownerReports: ownerSpecs.map(owner => owner.report), nativeRuntime: "docs/p6/spreadsheet-kernel.json", nativePersistence: "docs/p6/spreadsheet-action-04-persistence.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, saveReopenApplicable: true, applicabilityReason: "Spreadsheet has an explicit FCStd persistence owner; CSV is an independent import/export boundary.", boundaries: ["Formula cell verification preserves the native formula string and recompute contract; the tutor does not claim a separate displayed numeric result when the owner API returns the formula string."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-spreadsheet-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-spreadsheet-profile.json"), screenshots: runs.flatMap(run => [run.create.screenshot, run.saveReopen.screenshot, run.csv.screenshot]), pageErrors: [] })); + } else if (caseData.id === "start") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "pythonApi", runner: "tools/ui-start-python-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/start-python-owner-boundary.json" }, + { key: "sourceInventory", runner: "tools/ui-start-inventory-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/start-inventory-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`Start ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`Start ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + const reports = Object.fromEntries(ownerSpecs.map(owner => { const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); equal(report.status, "passed", "string", `${owner.key}.status`); equal(report.results.length, 2, "number", `${owner.key}.results.length`); return [owner.key, report]; })); + const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); runs.push(await runStartTutor(page, viewport, outputRoot)); } + const startRows = Object.fromEntries(["pythonApi", "sourceInventory"].flatMap(key => [reports[key].results.find(row => row.viewport.name === "desktop"), reports[key].results.find(row => row.viewport.name === "mobile")].map(row => [`${key}-${row.viewport.name}`, row]))); + for (const [key, row] of Object.entries(startRows)) { equal(row.pageErrors.length, 0, "number", `${key}.pageErrors.length`); equal(row.ready.pageOverflow, false, "boolean", `${key}.ready.pageOverflow`); } + const profile = { schema: "freecad-web-tutor-start-profile/v1", caseId: "tutor.start", status: pageErrors.length ? "failed" : "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/start-python.worker.ts + web/src/start-python-facade.ts", "web/src/start-inventory.worker.ts + web/src/start-inventory-facade.ts", "web/src/start-launch-panel.tsx + web/src/project-shell.tsx"], nativeBoundary: "freecad-source/src/Mod/Start/App/AppStart.cpp + project Start host" }, + preconditions: { startIframeMounted: true, firstStartPreferencePrepared: true, workerInitialization: true, startEntry: "/workbench.html?module=Part&start=1&document=StartTutor", nativeRuntime: "docs/p6/start-kernel.json" }, + workflow: { startPythonApi: true, sourceInventory: true, openStartPage: true, emptyFileLaunch: true, entersPartWorkbench: true, desktopMobileVerified: true }, runs, pageErrors, evidence: { pythonOwner: ownerSpecs[0].report, inventoryOwner: ownerSpecs[1].report, startScreenshots: runs.map(run => run.screenshot), nativeRuntime: "docs/p6/start-kernel.json", nativeChrome: "docs/p6/start-chrome.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: false, applicabilityReason: "Start is a launch/presentation module; document persistence belongs to the launched workbench owner.", boundaries: ["The tutor verifies Start module registration and the real Start-to-Part launch transition. Workbench-specific document actions remain separate cases."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-start-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-start-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else if (caseData.id === "surface") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "create", runner: "tools/ui-surface-create-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/surface-create-owner-boundary.json" }, + { key: "saveReopen", runner: "tools/ui-surface-save-reopen-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/surface-save-reopen-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`Surface ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`Surface ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + const arrayEqual = (value, expected, itemType, field) => { equal(value, value, "array", field); equal(expected, expected, "array", `${field}.expected`); if (value.length !== expected.length) throw new Error(`Surface ${field}: length ${value.length}, expected ${expected.length}`); for (let index = 0; index < value.length; index += 1) equal(value[index], expected[index], itemType, `${field}[${index}]`); }; + const reports = Object.fromEntries(ownerSpecs.map(owner => { const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); equal(report.status, "passed", "string", `${owner.key}.status`); equal(report.results.length, 2, "number", `${owner.key}.results.length`); return [owner.key, report]; })); + const nativeKernel = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/surface-kernel-r1.json"), "utf8")); + equal(nativeKernel.result, "passed", "string", "nativeKernel.result"); equal(nativeKernel.observed.action, 1, "number", "nativeKernel.observed.action"); equal(nativeKernel.observed.objectType, "Surface::Cut", "string", "nativeKernel.observed.objectType"); equal(nativeKernel.observed.objectCount, 3, "number", "nativeKernel.observed.objectCount"); equal(nativeKernel.observed.recomputeCount, 3, "number", "nativeKernel.observed.recomputeCount"); equal(nativeKernel.observed.actionResources, 1, "number", "nativeKernel.observed.actionResources"); + const nativeSave = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/surface-action-04-persistence.json"), "utf8")); + equal(nativeSave.result, "passed", "string", "nativeSave.result"); equal(nativeSave.observed.objectCount, 3, "number", "nativeSave.observed.objectCount"); equal(nativeSave.observed.objectType, "Surface::Cut", "string", "nativeSave.observed.objectType"); arrayEqual(nativeSave.observed.roundTrip, [1, 1], "number", "nativeSave.observed.roundTrip"); arrayEqual(nativeSave.observed.resourcesReleased, [1, 1], "number", "nativeSave.observed.resourcesReleased"); arrayEqual(nativeSave.observed.paths, ["/tmp/SurfaceWeb.FCStd", "/tmp/SurfaceWeb.FCStd"], "string", "nativeSave.observed.paths"); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { + const find = key => { const row = reports[key].results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`Surface ${key} missing ${expected.name}`); equal(row.httpStatus, 200, "number", `${key}.${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${key}.${expected.name}.crossOriginIsolated`); equal(row.pageErrors.length, 0, "number", `${key}.${expected.name}.pageErrors.length`); return row; }; + const create = find("create"), save = find("saveReopen"); + equal(create.ready.stage, "ready", "string", `create.${expected.name}.ready.stage`); equal(create.ready.pageOverflow, false, "boolean", `create.${expected.name}.ready.pageOverflow`); equal(create.success.object, "Surface::Cut", "string", `create.${expected.name}.success.object`); equal(create.success.objects, "3", "string", `create.${expected.name}.success.objects`); equal(create.success.recompute, "3", "string", `create.${expected.name}.success.recompute`); equal(create.rejected.code, "invalid_request", "string", `create.${expected.name}.rejected.code`); equal(create.recovered.object, "Surface::Cut", "string", `create.${expected.name}.recovered.object`); equal(create.reset.stage, "reset", "string", `create.${expected.name}.reset.stage`); equal(create.viewportState.inViewport, true, "boolean", `create.${expected.name}.viewportState.inViewport`); equal(create.viewportState.pageOverflow, false, "boolean", `create.${expected.name}.viewportState.pageOverflow`); + equal(save.ready.stage, "ready", "string", `saveReopen.${expected.name}.ready.stage`); equal(save.success.path, "/tmp/SurfaceWeb.FCStd", "string", `saveReopen.${expected.name}.success.path`); equal(save.success.objects, "3", "string", `saveReopen.${expected.name}.success.objects`); equal(save.success.round, "true", "string", `saveReopen.${expected.name}.success.round`); equal(save.rejected.code, "invalid_path", "string", `saveReopen.${expected.name}.rejected.code`); equal(save.recovered.round, "true", "string", `saveReopen.${expected.name}.recovered.round`); equal(save.reset.stage, "reset", "string", `saveReopen.${expected.name}.reset.stage`); equal(save.viewportState.inViewport, true, "boolean", `saveReopen.${expected.name}.viewportState.inViewport`); equal(save.viewportState.pageOverflow, false, "boolean", `saveReopen.${expected.name}.viewportState.pageOverflow`); + return { viewport: expected, create, saveReopen: save, nativeKernel: nativeKernel.observed, nativeSave: nativeSave.observed, pageErrors: [] }; + }); + const profile = { schema: "freecad-web-tutor-surface-profile/v1", caseId: "tutor.surface", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/surface.worker.ts + web/src/surface-facade.ts + web/src/surface-slice.ts", "web/src/surface-save.worker.ts + web/src/surface-save-facade.ts + web/src/surface-save-slice.ts"], nativeBoundary: "freecad-source/src/Mod/Surface + FreeCADWebSurfaceRuntimeProbe" }, + preconditions: { createPageMounted: true, savePageMounted: true, workerInitialization: true, fixture: "Surface::Cut from boxes (10,10,10) and (4,4,4)", expectedObjectCount: 3, nativeRuntime: "docs/p6/surface-kernel-r1.json" }, + workflow: { createRecompute: true, invalidCreateRejected: true, createRecovery: true, createResetRecovery: true, saveReopen: true, invalidPathRejected: true, saveRecovery: true, saveResetRecovery: true }, runs, pageErrors: [], evidence: { ownerReports: ownerSpecs.map(owner => owner.report), nativeRuntime: "docs/p6/surface-kernel-r1.json", nativePersistence: "docs/p6/surface-action-04-persistence.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: true, applicabilityReason: "Surface exposes an FCStd save/reopen owner for its three-object cut fixture.", boundaries: ["This tutor covers the native Surface::Cut create/recompute fixture and FCStd round-trip; the separate Python API and source inventory actions remain their own cases."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-surface-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-surface-profile.json"), screenshots: runs.flatMap(run => [run.create.screenshot, run.saveReopen.screenshot]), pageErrors: [] })); + } else if (caseData.id === "techdraw") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "create", runner: "tools/ui-techdraw-create-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/techdraw-create-owner-boundary.json" }, + { key: "saveReopen", runner: "tools/ui-techdraw-save-reopen-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/techdraw-save-reopen-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`TechDraw ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`TechDraw ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + const reports = Object.fromEntries(ownerSpecs.map(owner => { const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); equal(report.status, "passed", "string", `${owner.key}.status`); equal(report.results.length, 2, "number", `${owner.key}.results.length`); return [owner.key, report]; })); + const nativeRuntime = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/techdraw-native-runtime.json"), "utf8")); + equal(nativeRuntime.result, "passed", "string", "nativeRuntime.result"); equal(nativeRuntime.observed.createRecompute.result, 1, "number", "nativeRuntime.createRecompute.result"); equal(nativeRuntime.observed.createRecompute.recomputeCount, 2, "number", "nativeRuntime.createRecompute.recomputeCount"); equal(nativeRuntime.observed.createRecompute.projectedGeometry, 301, "number", "nativeRuntime.createRecompute.projectedGeometry"); + const nativeSave = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/techdraw-action-05-save-reopen.json"), "utf8")); + equal(nativeSave.result, "passed", "string", "nativeSave.result"); equal(nativeSave.observed.objectCount, 2, "number", "nativeSave.objectCount"); equal(nativeSave.observed.objectType, "Part::Box", "string", "nativeSave.objectType"); equal(nativeSave.observed.drawPageRestored, true, "boolean", "nativeSave.drawPageRestored"); equal(nativeSave.observed.persistenceRoundTrip, true, "boolean", "nativeSave.persistenceRoundTrip"); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { + const find = key => { const row = reports[key].results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`TechDraw ${key} missing ${expected.name}`); equal(row.httpStatus, 200, "number", `${key}.${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${key}.${expected.name}.crossOriginIsolated`); equal(row.pageErrors.length, 0, "number", `${key}.${expected.name}.pageErrors.length`); return row; }; + const create = find("create"), save = find("saveReopen"); + equal(create.initial.stage, "success", "string", `create.${expected.name}.initial.stage`); equal(create.initial.image, true, "boolean", `create.${expected.name}.initial.image`); equal(create.initial.overflow, false, "boolean", `create.${expected.name}.initial.overflow`); equal(create.changed.volume, 972, "number", `create.${expected.name}.changed.volume`); equal(create.changed.box.length, 18, "number", `create.${expected.name}.changed.box.length`); equal(create.changed.image, true, "boolean", `create.${expected.name}.changed.image`); equal(create.invalidCommandState.runDisabled, true, "boolean", `create.${expected.name}.invalidCommandState.runDisabled`); equal(create.reset.volume, 17280, "number", `create.${expected.name}.reset.volume`); equal(create.reset.length, "40", "string", `create.${expected.name}.reset.length`); equal(create.exported.filename, "TechDrawDrawing.svg", "string", `create.${expected.name}.exported.filename`); equal(create.exported.failure, null, "null", `create.${expected.name}.exported.failure`); equal(create.viewportState.inViewport, true, "boolean", `create.${expected.name}.viewportState.inViewport`); equal(create.viewportState.pageOverflow, false, "boolean", `create.${expected.name}.viewportState.pageOverflow`); + equal(save.ready.stage, "ready", "string", `saveReopen.${expected.name}.ready.stage`); equal(save.success.documentId, "TechDrawNative", "string", `saveReopen.${expected.name}.success.documentId`); equal(save.success.path, "/tmp/TechDrawNative.FCStd", "string", `saveReopen.${expected.name}.success.path`); if (!(save.success.size > 0)) throw new Error(`TechDraw saveReopen.${expected.name}.success.size must be positive`); equal(save.success.objects, 4, "number", `saveReopen.${expected.name}.success.objects`); equal(save.success.round, true, "boolean", `saveReopen.${expected.name}.success.round`); equal(save.rejected.code, "revision_mismatch", "string", `saveReopen.${expected.name}.rejected.code`); equal(save.recovered.documentId, "TechDrawNative", "string", `saveReopen.${expected.name}.recovered.documentId`); equal(save.recovered.round, true, "boolean", `saveReopen.${expected.name}.recovered.round`); equal(save.reset.stage, "reset", "string", `saveReopen.${expected.name}.reset.stage`); equal(save.viewportState.inViewport, true, "boolean", `saveReopen.${expected.name}.viewportState.inViewport`); equal(save.viewportState.pageOverflow, false, "boolean", `saveReopen.${expected.name}.viewportState.pageOverflow`); + return { viewport: expected, create, saveReopen: save, nativeRuntime: nativeRuntime.observed, nativeSave: nativeSave.observed, pageErrors: [] }; + }); + const profile = { schema: "freecad-web-tutor-techdraw-profile/v1", caseId: "tutor.techdraw", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/techdraw-slice.ts + web/src/techdraw.worker.ts + web/src/techdraw-facade.ts", "web/src/techdraw-save-slice.tsx + web/src/techdraw-save.worker.ts + web/src/techdraw-save-facade.ts"], nativeBoundary: "freecad-source/src/Mod/TechDraw + FreeCADWebTechDrawProbe" }, + preconditions: { drawingPageMounted: true, savePageMounted: true, workerInitialization: true, createFixture: "Part::Box 40x24x18 projected to TechDraw::DrawViewPart SVG", saveFixture: "TechDrawNative/TechDraw::DrawPage + Part::Box", nativeRuntime: "docs/p6/techdraw-native-runtime.json" }, + workflow: { createRecompute: true, drawingSvgRendered: true, dimensionEditRecompute: true, invalidDimensionBlocked: true, resetToFixture: true, svgExport: true, saveReopen: true, invalidSourceRejected: true, saveRecovery: true }, runs, pageErrors: [], evidence: { ownerReports: ownerSpecs.map(owner => owner.report), nativeRuntime: "docs/p6/techdraw-native-runtime.json", nativePersistence: "docs/p6/techdraw-action-05-save-reopen.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + saveReopenApplicable: true, applicabilityReason: "TechDraw has a native save/reopen owner restoring the DrawPage and its source Part object.", boundaries: ["The create page renders a native front projection as SVG from Part::Box; save/reopen uses a separate TechDrawNative DrawPage document fixture."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-techdraw-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-techdraw-profile.json"), screenshots: runs.flatMap(run => [run.create.screenshot, run.saveReopen.screenshot]), pageErrors: [] })); + } else if (caseData.id === "templatepymod") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "pythonApi", runner: "tools/ui-templatepymod-python-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/templatepymod-python-owner-boundary.json" }, + { key: "sourceInventory", runner: "tools/ui-templatepymod-inventory-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/templatepymod-inventory-owner-boundary.json" }, + { key: "family", runner: "tools/ui-templatepymod-family-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/templatepymod-family-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`TemplatePyMod ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`TemplatePyMod ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + const reports = Object.fromEntries(ownerSpecs.map(owner => { const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); equal(report.status, "passed", "string", `${owner.key}.status`); equal(report.results.length, 2, "number", `${owner.key}.results.length`); return [owner.key, report]; })); + const nativeKernel = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/templatepymod-action-02-kernel.json"))); + const nativeRuntime = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/templatepymod-kernel.json"))); + equal(nativeKernel.result, "passed", "string", "nativeKernel.result"); equal(nativeKernel.observed.apiCount, 65, "number", "nativeKernel.observed.apiCount"); equal(nativeKernel.observed.resourcesReleased, 1, "number", "nativeKernel.observed.resourcesReleased"); + equal(nativeRuntime.result, "passed", "string", "nativeRuntime.result"); equal(nativeRuntime.observed.scriptLines, 4, "number", "nativeRuntime.observed.scriptLines"); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { + const find = key => { const row = reports[key].results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`TemplatePyMod ${key} missing ${expected.name}`); equal(row.httpStatus, 200, "number", `${key}.${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${key}.${expected.name}.crossOriginIsolated`); equal(row.pageErrors.length, 0, "number", `${key}.${expected.name}.pageErrors.length`); equal(row.ready.pageOverflow, false, "boolean", `${key}.${expected.name}.ready.pageOverflow`); return row; }; + const python = find("pythonApi"), inventory = find("sourceInventory"), family = find("family"); + equal(python.ready.stage, "ready", "string", `pythonApi.${expected.name}.ready.stage`); equal(python.success.api, "65", "string", `pythonApi.${expected.name}.success.api`); equal(python.success.resources, "true", "string", `pythonApi.${expected.name}.success.resources`); equal(python.rejected.code, "revision_mismatch", "string", `pythonApi.${expected.name}.rejected.code`); equal(python.reset.stage, "reset", "string", `pythonApi.${expected.name}.reset.stage`); equal(python.recovered.api, "65", "string", `pythonApi.${expected.name}.recovered.api`); + equal(inventory.success.lines, "4", "string", `sourceInventory.${expected.name}.success.lines`); equal(inventory.success.pythonOnly, "true", "string", `sourceInventory.${expected.name}.success.pythonOnly`); equal(inventory.rejected.code, "revision_mismatch", "string", `sourceInventory.${expected.name}.rejected.code`); equal(inventory.reset.stage, "reset", "string", `sourceInventory.${expected.name}.reset.stage`); + equal(family.ready.stage, "ready", "string", `family.${expected.name}.ready.stage`); equal(family.tier1.count, "75", "string", `family.${expected.name}.tier1.count`); equal(family.tier2.count, "81", "string", `family.${expected.name}.tier2.count`); equal(family.rejected.code, "invalid_request", "string", `family.${expected.name}.rejected.code`); equal(family.reset.stage, "reset", "string", `family.${expected.name}.reset.stage`); equal(family.recovered.count, "75", "string", `family.${expected.name}.recovered.count`); + return { viewport: expected, pythonApi: python, sourceInventory: inventory, family, nativeKernel: { ...nativeRuntime.observed, ...nativeKernel.observed }, pageErrors: [] }; + }); + const profile = { schema: "freecad-web-tutor-templatepymod-profile/v1", caseId: "tutor.templatepymod", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/templatepymod-python.worker.ts + web/src/templatepymod-python-facade.ts", "web/src/templatepymod.worker.ts + web/src/templatepymod-facade.ts"], nativeBoundary: "freecad-source/src/Mod/TemplatePyMod + FreeCADWebTemplatePyModRuntimeProbe" }, + preconditions: { pythonPageMounted: true, inventoryPageMounted: true, familyPageMounted: true, workerInitialization: true, nativeRuntime: "docs/p6/templatepymod-action-02-kernel.json" }, + workflow: { pythonApi: true, sourceInventory: true, tier1FamilyBatch: true, tier2FamilyBatch: true, invalidRevisionRejected: true, resetRecovery: true }, runs, pageErrors: [], evidence: { ownerReports: ownerSpecs.map(owner => owner.report), nativeRuntime: "docs/p6/templatepymod-kernel.json", nativeAction: "docs/p6/templatepymod-action-02-kernel.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, saveReopenApplicable: false, applicabilityReason: "TemplatePyMod tutor validates read-only Python reflection and family discovery; no persistent CAD document is created.", boundaries: ["GUI desktop command families are represented by their native statuses; arbitrary TemplatePyMod document authoring and persistence remain outside this profile."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-templatepymod-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-templatepymod-profile.json"), screenshots: [], pageErrors: [] })); + } else if (caseData.id === "test") { + const outputRoot = path.resolve(outDir); + const runner = "tools/ui-test-inspect-owner-boundary.mjs"; + execFileSync(process.execPath, [path.join(root, runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const reportPath = "docs/current/ui-parity-baseline-20261011/test-inspect-owner-boundary.json"; + const report = JSON.parse(fs.readFileSync(path.join(root, reportPath), "utf8")); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`Test ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`Test ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + equal(report.status, "passed", "string", "report.status"); equal(report.results.length, 2, "number", "report.results.length"); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { const row = report.results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`Test missing ${expected.name}`); equal(row.httpStatus, 200, "number", `${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${expected.name}.crossOriginIsolated`); equal(row.ready.stage, "ready", "string", `${expected.name}.ready.stage`); equal(row.ready.pageOverflow, false, "boolean", `${expected.name}.ready.pageOverflow`); equal(row.success.unitCount, 7, "number", `${expected.name}.success.unitCount`); equal(row.success.resources, true, "boolean", `${expected.name}.success.resources`); equal(row.rejected.code, "revision_mismatch", "string", `${expected.name}.rejected.code`); equal(row.recovered.unitCount, 7, "number", `${expected.name}.recovered.unitCount`); equal(row.reset.stage, "reset", "string", `${expected.name}.reset.stage`); equal(row.reset.text, true, "boolean", `${expected.name}.reset.text`); equal(row.viewportState.inViewport, true, "boolean", `${expected.name}.viewportState.inViewport`); equal(row.viewportState.pageOverflow, false, "boolean", `${expected.name}.viewportState.pageOverflow`); equal(row.pageErrors.length, 0, "number", `${expected.name}.pageErrors.length`); return { viewport: expected, success: row.success, rejected: row.rejected, recovered: row.recovered, reset: row.reset, ready: row.ready, viewportState: row.viewportState, screenshot: row.screenshot, pageErrors: [] }; }); + const native = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/test-kernel.json"), "utf8")); equal(native.result, "passed", "string", "native.result"); equal(native.observed.unitCount, 7, "number", "native.observed.unitCount"); equal(native.observed.replayStable, true, "boolean", "native.observed.replayStable"); equal(native.observed.resourcesReleased, 1, "number", "native.observed.resourcesReleased"); equal(native.observed.guiExcluded, true, "boolean", "native.observed.guiExcluded"); + const profile = { schema: "freecad-web-tutor-test-profile/v1", caseId: "tutor.test", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, source: { owner: "web/src/test-slice.tsx + web/src/test.worker.ts + web/src/test-facade.ts", nativeBoundary: "freecad-source/src/Mod/Test/Init.py + FreeCADWebTestRuntimeProbe" }, preconditions: { testPageMounted: true, workerInitialization: true, fixture: "GUI-free Test unit registry", nativeRuntime: "docs/p6/test-kernel.json" }, workflow: { sourceInventory: true, unitCount: 7, invalidRevisionRejected: true, resetRecovery: true }, runs, pageErrors: [], evidence: { ownerReport: reportPath, nativeRuntime: "docs/p6/test-kernel.json", nativeChrome: "docs/p6/test-chrome.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, saveReopenApplicable: false, applicabilityReason: "Test registry is read-only native unit evidence; desktop GUI test suite is excluded.", boundaries: ["This tutor validates the GUI-free Test module registry only; no persistent CAD document is created."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-test-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-test-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors: [] })); + } else if (caseData.id === "tux") { + const outputRoot = path.resolve(outDir); + const runner = "tools/ui-tux-navigation-owner-boundary.mjs"; + execFileSync(process.execPath, [path.join(root, runner)], { cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024 }); + const reportPath = "docs/current/ui-parity-baseline-20261011/tux-navigation-owner-boundary.json"; + const report = JSON.parse(fs.readFileSync(path.join(root, reportPath), "utf8")); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const equal = (value, expected, type, field) => { const actual = actualType(value); if (actual !== type) throw new TypeError(`Tux ${field}: expected ${type}, received ${actual}`); if (!Object.is(value, expected)) throw new Error(`Tux ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expected)}`); }; + equal(report.status, "passed", "string", "report.status"); equal(report.results.length, 2, "number", "report.results.length"); + const native = JSON.parse(fs.readFileSync(path.join(root, "docs/p6/tux-kernel.json"), "utf8")); equal(native.result, "passed_boundary", "string", "native.result"); equal(native.observed.guiAvailable, 0, "number", "native.observed.guiAvailable"); equal(native.observed.portableApiCount, 4, "number", "native.observed.portableApiCount"); equal(native.observed.resourcesReleased, 1, "number", "native.observed.resourcesReleased"); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expected => { const row = report.results.find(item => item.viewport?.name === expected.name); if (!row) throw new Error(`Tux missing ${expected.name}`); equal(row.httpStatus, 200, "number", `${expected.name}.httpStatus`); equal(row.crossOriginIsolated, true, "boolean", `${expected.name}.crossOriginIsolated`); equal(row.ready.stage, "ready", "string", `${expected.name}.ready.stage`); equal(row.ready.pageOverflow, false, "boolean", `${expected.name}.ready.pageOverflow`); equal(row.success.api, 4, "number", `${expected.name}.success.api`); equal(row.success.gui, false, "boolean", `${expected.name}.success.gui`); equal(row.success.resources, true, "boolean", `${expected.name}.success.resources`); equal(row.rejected.code, "revision_mismatch", "string", `${expected.name}.rejected.code`); equal(row.recovered.api, 4, "number", `${expected.name}.recovered.api`); equal(row.reset.stage, "reset", "string", `${expected.name}.reset.stage`); equal(row.reset.text, true, "boolean", `${expected.name}.reset.text`); equal(row.viewportState.inViewport, true, "boolean", `${expected.name}.viewportState.inViewport`); equal(row.viewportState.pageOverflow, false, "boolean", `${expected.name}.viewportState.pageOverflow`); equal(row.pageErrors.length, 0, "number", `${expected.name}.pageErrors.length`); return { viewport: expected, success: row.success, rejected: row.rejected, recovered: row.recovered, reset: row.reset, viewportState: row.viewportState, screenshot: row.screenshot, pageErrors: [] }; }); + const profile = { schema: "freecad-web-tutor-tux-profile/v1", caseId: "tutor.tux", status: "passed", origin, manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, source: { owner: "web/src/tux-slice.tsx + web/src/tux.worker.ts + web/src/tux-facade.ts", nativeBoundary: "freecad-source/src/Mod/Tux/PersistentToolbars.py + FreeCADWebTuxRuntimeProbe" }, preconditions: { tuxPageMounted: true, workerInitialization: true, sourceEntry: "src/Mod/Tux/PersistentToolbars.py", nativeRuntime: "docs/p6/tux-kernel.json" }, workflow: { navigationBoundary: true, portableApiCount: 4, guiExcluded: true, invalidRevisionRejected: true, resetRecovery: true }, runs, pageErrors: [], evidence: { ownerReport: reportPath, nativeRuntime: "docs/p6/tux-kernel.json", nativeGate: "docs/p6/tux-module-gate.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, saveReopenApplicable: false, applicabilityReason: "Tux is a portable read-only boundary with GUI unavailable.", boundaries: ["No persistent CAD document or GUI navigation implementation is claimed; only the portable native navigation boundary is covered."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-tux-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); status = "passed"; console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-tux-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors: [] })); + } else if (caseData.id === "show") { + const outputRoot = path.resolve(outDir); + const ownerSpecs = [ + { key: "pythonApi", runner: "tools/ui-show-python-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/show-python-owner-boundary.json" }, + { key: "sourceInventory", runner: "tools/ui-show-inspect-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/show-inspect-owner-boundary.json" }, + { key: "visibility", runner: "tools/ui-show-visibility-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/show-visibility-owner-boundary.json" }, + { key: "clipping", runner: "tools/ui-show-clipping-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/show-clipping-owner-boundary.json" }, + { key: "documentLifecycle", runner: "tools/ui-show-document-lifecycle-owner-boundary.mjs", report: "docs/current/ui-parity-baseline-20261011/show-document-lifecycle-owner-boundary.json" }, + ]; + for (const owner of ownerSpecs) execFileSync(process.execPath, [path.join(root, owner.runner)], { + cwd: root, encoding: "utf8", env: { ...process.env, FREECAD_BROWSER_ORIGIN: origin }, maxBuffer: 2 * 1024 * 1024, + }); + const actualType = value => Array.isArray(value) ? "array" : value === null ? "null" : typeof value; + const requireType = (value, expected, field) => { + const actual = actualType(value); + if (actual !== expected) throw new TypeError(`Show profile ${field}: expected ${expected}, received ${actual}`); + return { type: actual, value }; + }; + const requireEqual = (value, expectedType, expectedValue, field) => { + const actual = requireType(value, expectedType, field); + if (!Object.is(value, expectedValue)) throw new Error(`Show profile ${field}: returned ${JSON.stringify(value)}, expected ${JSON.stringify(expectedValue)}`); + return actual; + }; + const requireArray = (value, expectedValues, field) => { + requireType(value, "array", field); + requireType(expectedValues, "array", `${field}.expected`); + if (value.length !== expectedValues.length || value.some((item, index) => actualType(item) !== actualType(expectedValues[index]) || !Object.is(item, expectedValues[index]))) + throw new Error(`Show profile ${field}: returned array does not match expected values`); + return { type: "array", itemTypes: value.map(actualType), value }; + }; + const reportFor = Object.fromEntries(ownerSpecs.map(owner => { + const report = JSON.parse(fs.readFileSync(path.join(root, owner.report), "utf8")); + requireEqual(report.schema, "string", `freecad-web-ui-show-${owner.key === "pythonApi" ? "python" : owner.key === "sourceInventory" ? "inspect" : owner.key === "documentLifecycle" ? "document-lifecycle" : owner.key}-owner-boundary/v1`, `${owner.key}.schema`); + requireEqual(report.status, "string", "passed", `${owner.key}.status`); + requireType(report.profile, "object", `${owner.key}.profile`); + requireEqual(report.profile.saveReopenApplicable, "boolean", false, `${owner.key}.profile.saveReopenApplicable`); + requireType(report.results, "array", `${owner.key}.results`); + requireEqual(report.results.length, "number", 2, `${owner.key}.results.length`); + return [owner.key, report]; + })); + const expectedViewports = [{ name: "desktop", width: 1440, height: 900 }, { name: "mobile", width: 390, height: 844 }]; + const runs = expectedViewports.map(expectedViewport => { + const rowFor = key => { + const row = reportFor[key].results.find(item => item.viewport?.name === expectedViewport.name); + if (!row) throw new Error(`Show profile ${key}: missing ${expectedViewport.name} owner result`); + requireType(row.viewport, "object", `${key}.${expectedViewport.name}.viewport`); + requireEqual(row.viewport.width, "number", expectedViewport.width, `${key}.${expectedViewport.name}.viewport.width`); + requireEqual(row.viewport.height, "number", expectedViewport.height, `${key}.${expectedViewport.name}.viewport.height`); + requireEqual(row.httpStatus, "number", 200, `${key}.${expectedViewport.name}.httpStatus`); + requireEqual(row.crossOriginIsolated, "boolean", true, `${key}.${expectedViewport.name}.crossOriginIsolated`); + requireType(row.pageErrors, "array", `${key}.${expectedViewport.name}.pageErrors`); + requireEqual(row.pageErrors.length, "number", 0, `${key}.${expectedViewport.name}.pageErrors.length`); + return row; + }; + const python = rowFor("pythonApi"), inspect = rowFor("sourceInventory"), visibility = rowFor("visibility"), clipping = rowFor("clipping"), lifecycle = rowFor("documentLifecycle"); + requireType(python.ready, "object", `pythonApi.${expectedViewport.name}.ready`); + requireEqual(python.ready.stage, "string", "ready", `pythonApi.${expectedViewport.name}.ready.stage`); + requireEqual(python.ready.pageOverflow, "boolean", false, `pythonApi.${expectedViewport.name}.ready.pageOverflow`); + requireType(python.success, "object", `pythonApi.${expectedViewport.name}.success`); + requireEqual(python.success.action, "string", "python-api", `pythonApi.${expectedViewport.name}.success.action`); + requireEqual(python.success.apiCount, "number", 2, `pythonApi.${expectedViewport.name}.success.apiCount`); + requireEqual(python.success.tempoState, "number", 0, `pythonApi.${expectedViewport.name}.success.tempoState`); + requireEqual(python.success.guiUp, "boolean", false, `pythonApi.${expectedViewport.name}.success.guiUp`); + requireEqual(python.success.resourcesReleased, "boolean", true, `pythonApi.${expectedViewport.name}.success.resourcesReleased`); + requireEqual(python.success.inViewport, "boolean", true, `pythonApi.${expectedViewport.name}.success.inViewport`); + requireEqual(python.success.pageOverflow, "boolean", false, `pythonApi.${expectedViewport.name}.success.pageOverflow`); + requireEqual(python.expectedError.code, "string", "invalid_fixture", `pythonApi.${expectedViewport.name}.expectedError.code`); + requireEqual(python.reset.responseCleared, "boolean", true, `pythonApi.${expectedViewport.name}.reset.responseCleared`); + requireEqual(python.recovered.apiCount, "number", 2, `pythonApi.${expectedViewport.name}.recovered.apiCount`); + requireEqual(python.recovered.tempoState, "number", 0, `pythonApi.${expectedViewport.name}.recovered.tempoState`); + + requireType(inspect.success, "object", `sourceInventory.${expectedViewport.name}.success`); + requireEqual(inspect.success.action, "string", "inspect/source-inventory", `sourceInventory.${expectedViewport.name}.success.action`); + requireEqual(inspect.success.sourceEntry, "string", "src/Mod/Show/__init__.py", `sourceInventory.${expectedViewport.name}.success.sourceEntry`); + requireEqual(inspect.success.apiCount, "number", 2, `sourceInventory.${expectedViewport.name}.success.apiCount`); + const pythonApiTypes = requireArray(inspect.success.pythonApi, ["TempoVis", "DepGraphTools"], `sourceInventory.${expectedViewport.name}.success.pythonApi`); + if (pythonApiTypes.itemTypes.some(type => type !== "string")) throw new TypeError(`sourceInventory.${expectedViewport.name}.success.pythonApi must contain strings`); + requireEqual(inspect.success.guiUp, "boolean", false, `sourceInventory.${expectedViewport.name}.success.guiUp`); + requireEqual(inspect.success.readOnly, "boolean", true, `sourceInventory.${expectedViewport.name}.success.readOnly`); + requireEqual(inspect.success.resourcesReleased, "boolean", true, `sourceInventory.${expectedViewport.name}.success.resourcesReleased`); + requireEqual(inspect.expectedError.code, "string", "revision_mismatch", `sourceInventory.${expectedViewport.name}.expectedError.code`); + requireEqual(inspect.reset.responseCleared, "boolean", true, `sourceInventory.${expectedViewport.name}.reset.responseCleared`); + + requireEqual(visibility.hidden.action, "string", "hide", `visibility.${expectedViewport.name}.hidden.action`); + requireEqual(visibility.hidden.visible, "string", "false", `visibility.${expectedViewport.name}.hidden.visible`); + requireEqual(visibility.shown.action, "string", "show", `visibility.${expectedViewport.name}.shown.action`); + requireEqual(visibility.shown.visible, "string", "true", `visibility.${expectedViewport.name}.shown.visible`); + requireEqual(visibility.restored.action, "string", "restore", `visibility.${expectedViewport.name}.restored.action`); + requireEqual(visibility.restored.restored, "string", "Box", `visibility.${expectedViewport.name}.restored.restored`); + requireEqual(visibility.invalid.code, "string", "show_scene_failed", `visibility.${expectedViewport.name}.invalid.code`); + requireEqual(visibility.cancelled.action, "string", "cancel", `visibility.${expectedViewport.name}.cancelled.action`); + requireEqual(visibility.cancelled.visible, "string", "true", `visibility.${expectedViewport.name}.cancelled.visible`); + + requireEqual(clipping.fixture.boxTask, "boolean", true, `clipping.${expectedViewport.name}.fixture.boxTask`); + requireEqual(clipping.fixture.objectRow, "string", "Cube", `clipping.${expectedViewport.name}.fixture.objectRow`); + requireEqual(clipping.preflight.taskMounted, "boolean", true, `clipping.${expectedViewport.name}.preflight.taskMounted`); + requireEqual(clipping.preflight.inViewport, "boolean", true, `clipping.${expectedViewport.name}.preflight.inViewport`); + requireEqual(clipping.preflight.pageOverflow, "boolean", false, `clipping.${expectedViewport.name}.preflight.pageOverflow`); + requireType(clipping.rejected.status, "string", `clipping.${expectedViewport.name}.rejected.status`); + if (!clipping.rejected.status.includes("Enter 3 finite coordinates")) throw new Error(`clipping.${expectedViewport.name}: invalid plane was not rejected`); + requireType(clipping.enabled.text, "string", `clipping.${expectedViewport.name}.enabled.text`); + if (!clipping.enabled.text.includes("Enabled") || !clipping.enabled.text.includes("enable: 1 restorable changes")) throw new Error(`clipping.${expectedViewport.name}: plane enable state mismatch`); + requireEqual(clipping.enabled.inViewport, "boolean", true, `clipping.${expectedViewport.name}.enabled.inViewport`); + requireEqual(clipping.enabled.pageOverflow, "boolean", false, `clipping.${expectedViewport.name}.enabled.pageOverflow`); + requireType(clipping.restored.status, "string", `clipping.${expectedViewport.name}.restored.status`); + if (!clipping.restored.status.includes("restore:")) throw new Error(`clipping.${expectedViewport.name}: restore status mismatch`); + requireType(clipping.reset.status, "string", `clipping.${expectedViewport.name}.reset.status`); + if (!clipping.reset.status.includes("reset:")) throw new Error(`clipping.${expectedViewport.name}: reset status mismatch`); + + requireType(lifecycle.initial.activeDocument, "string", `documentLifecycle.${expectedViewport.name}.initial.activeDocument`); + if (!lifecycle.initial.activeDocument.includes("project-document-1") || !lifecycle.initial.activeDocument.includes("clean")) throw new Error(`documentLifecycle.${expectedViewport.name}: project initial document mismatch`); + requireType(lifecycle.fixture.activeDocument, "string", `documentLifecycle.${expectedViewport.name}.fixture.activeDocument`); + if (!lifecycle.fixture.activeDocument.includes("dirty")) throw new Error(`documentLifecycle.${expectedViewport.name}: fixture document was not dirty before save`); + requireEqual(lifecycle.fixture.object, "string", "Cube", `documentLifecycle.${expectedViewport.name}.fixture.object`); + requireType(lifecycle.saved.status, "string", `documentLifecycle.${expectedViewport.name}.saved.status`); + if (!lifecycle.saved.status.includes("Saved web_project_document_1.FCStd to OPFS")) throw new Error(`documentLifecycle.${expectedViewport.name}: project save was not observed`); + requireEqual(lifecycle.saved.fileListed, "boolean", true, `documentLifecycle.${expectedViewport.name}.saved.fileListed`); + const sectionOverflow = { pythonApi: python.ready.pageOverflow, sourceInventory: inspect.ready.pageOverflow, visibility: visibility.reset.pageOverflow, clipping: clipping.preflight.pageOverflow, documentLifecycle: lifecycle.saved.pageOverflow }; + for (const [key, section] of [["pythonApi", python], ["sourceInventory", inspect], ["visibility", visibility], ["clipping", clipping], ["documentLifecycle", lifecycle]]) { + requireEqual(sectionOverflow[key], "boolean", false, `${key}.${expectedViewport.name}.pageOverflow`); + requireType(section.pageErrors, "array", `${key}.${expectedViewport.name}.pageErrors`); + requireEqual(section.pageErrors.length, "number", 0, `${key}.${expectedViewport.name}.pageErrors.length`); + } + return { + viewport: expectedViewport, + sourceInventory: { action: inspect.success.action, sourceEntry: inspect.success.sourceEntry, apiCount: inspect.success.apiCount, pythonApi: inspect.success.pythonApi, guiUp: inspect.success.guiUp, readOnly: inspect.success.readOnly, resourcesReleased: inspect.success.resourcesReleased }, + pythonApi: { action: python.success.action, apiCount: python.success.apiCount, tempoState: python.success.tempoState, guiUp: python.success.guiUp, resourcesReleased: python.success.resourcesReleased, invalidFixture: python.expectedError.code, reset: python.reset.responseCleared, recoveredApiCount: python.recovered.apiCount }, + visibility: { hidden: visibility.hidden, shown: visibility.shown, restored: visibility.restored, invalid: visibility.invalid, cancelled: visibility.cancelled, reset: visibility.reset }, + clipping: { fixture: clipping.fixture, rejected: clipping.rejected, enabled: clipping.enabled, restored: clipping.restored, reset: clipping.reset }, + documentLifecycle: { initial: lifecycle.initial, fixture: lifecycle.fixture, saved: lifecycle.saved }, + ownerReports: Object.fromEntries(ownerSpecs.map(owner => [owner.key, owner.report])), + ownerScreenshots: Object.fromEntries(ownerSpecs.map(owner => [owner.key, reportFor[owner.key].results.find(row => row.viewport.name === expectedViewport.name).screenshot])), + viewportVerified: true, + pageErrors: [], + }; + }); + const evidence = [ + ...ownerSpecs.map(owner => owner.report), + "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json", + ]; + const profile = { schema: "freecad-web-tutor-show-profile/v1", caseId: "tutor.show", status: "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owners: ["web/src/show-python.worker.ts + web/src/show-python-facade.ts", "web/src/show-inspect.worker.ts + web/src/show-inspect-facade.ts", "web/src/show-python-family-facade.ts + web/src/show-visibility-slice.ts", "web/src/show-clipping-task.tsx + web/src/project-shell.tsx"], nativeBoundary: "freecad-source/src/Mod/Show + FreeCADWebShowRuntimeProbe" }, + preconditions: { host: origin, ownerWorkersReady: true, viewports: expectedViewports, fixture: "Show visibility fixture Box; clipping project Cube; project-document-1", nativeEvidence: ["docs/p6/show-runtime.json", "docs/p6/show-kernel.json"] }, + workflow: { sourceInventory: true, pythonApiAndTempoVis: true, visibilityHideShowRestoreCancel: true, clippingInvalidEnableRestoreReset: true, projectCubeFixture: true, projectSaveToOPFS: true, saveReopenApplicable: false }, + boundaryProfile: { allOwnerReportsPassed: true, desktopMobileVerified: true, pageErrors: false, pageOverflow: false, productAssertionsExecuted: true }, + runs, pageErrors, evidence: { ownerReports: evidence.slice(0, -1), audit64: evidence.at(-1), ownerScreenshots: runs.map(run => run.ownerScreenshots) }, + saveReopenApplicable: false, applicabilityReason: "Show clipping and visibility are transient view state; lifecycle verification confirms project FCStd write to OPFS, while geometry FCStd reopen belongs to the Part document owner.", + boundaries: ["The tutor reuses separate Show Python, inventory, visibility, clipping, and project lifecycle owners. It does not claim a Show-specific FCStd geometry save/reopen operation."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-show-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-show-profile.json"), ownerReports: ownerSpecs.map(owner => owner.report), viewports: runs.map(run => run.viewport), pageErrors })); + } else if (caseData.id === "plot") { + const outputRoot = path.resolve(outDir); const runs = []; + for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) { + page = await browser.newPage({ viewport }); page.on("pageerror", error => pageErrors.push(`${viewport.width}: ${String(error)}`)); + runs.push(await runPlotBoundary(page, viewport, outputRoot)); await page.close(); + } + const profile = { schema: "freecad-web-tutor-plot-profile/v2", caseId: "tutor.plot", status: pageErrors.length ? "failed" : "passed", origin, + manifest: "docs/current/29-case-tutor-20261011/manifest-20261011T082822Z.json", lesson: caseData.lesson, + source: { owner: "web/src/plot-axes-task.tsx + web/src/plot-session-client.ts + web/src/plot-python.worker.ts", nativeBoundary: "freecad-source/src/WebAssembly/FreeCADCoreProbe/PlotRuntimeProbe.cpp" }, + preconditions: { plotPageMounted: true, workerInitialization: true, initializationOperation: "plot.session/list", pythonStdlibCopy: true, nativeSmoke: "docs/p6/plot-runtime-web.json" }, + boundaryProfile: { workerRuntimeReady: true, desktopMobileViewportVerified: runs.length === 2, pageErrors: pageErrors.length === 0, externalRequests: runs.every(run => run.externalRequests.length === 0), productAssertionsExecuted: true }, + workflow: { createFigure: true, addSeries: true, acceptCancel: true, invalidRecovery: true, axesAndNavigation: true, svgExport: true, sessionReload: true, saveReopenApplicable: false }, runs, pageErrors, + evidence: { desktopScreenshot: runs[0].screenshot, mobileScreenshot: runs[1].screenshot, nativeSmoke: "docs/p6/plot-runtime-web.json", pythonApiOwner: "docs/current/ui-parity-baseline-20261011/plot-python-owner-boundary.json", audit64: "docs/current/ui-parity-baseline-20261011/workbench-surface-audit.json" }, + blocker: null, + unlockCondition: null, + failureClassification: { failedPrerequisite: null, productFailure: pageErrors.length ? "browser_page_error" : null, unresolvedIntegration: null }, + saveReopenApplicable: false, + applicabilityReason: "Plot session is browser-tab state persisted through sessionStorage and SVG export; it does not create an editable FCStd document.", + boundaries: ["Plot figure/session state is independent of CAD documents and undo/redo; SVG export is the explicit file boundary."] }; + fs.writeFileSync(path.join(outputRoot, "tutor-plot-profile.json"), `${JSON.stringify(profile, null, 2)}\n`); + status = pageErrors.length ? "failed" : "passed"; + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, status, origin, profile: path.join(outputRoot, "tutor-plot-profile.json"), screenshots: runs.map(run => run.screenshot), pageErrors })); + } else { + page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); + page.on("pageerror", error => pageErrors.push(String(error))); + await page.goto(url, { waitUntil: "domcontentloaded" }); + await page.waitForTimeout(1400); + status = "entered"; + } + if (!["assembly", "bim", "cam", "cloud", "draft", "fem", "help", "import", "inspection", "jtreader", "material", "measure", "meshpart", "partdesign", "points", "plot", "reverseengineering", "robot", "sandbox", "show", "sketcher", "spreadsheet", "start", "surface", "techdraw", "templatepymod", "test", "tux"].includes(caseData.id)) { + await page.screenshot({ path: screenshot, fullPage: false }); + if (!headless && pause > 0) await new Promise(resolve => setTimeout(resolve, pause * 1000)); + console.log(JSON.stringify({ index: caseData.index, id: caseData.id, module: caseData.module, status, url, screenshot, pageErrors })); + } +} catch (error) { + if (page) await page.screenshot({ path: screenshot, fullPage: false }).catch(() => undefined); + console.error(JSON.stringify({ index: caseData.index, id: caseData.id, status: "failed", url, screenshot, pageErrors, error: String(error.stack ?? error) })); + status = "failed"; +} finally { + await browser.close(); +} +process.exitCode = status === "failed" || pageErrors.length ? 1 : 0; diff --git a/tools/web-freecad-29-case-tutor.py b/tools/web-freecad-29-case-tutor.py new file mode 100644 index 00000000..106daf17 --- /dev/null +++ b/tools/web-freecad-29-case-tutor.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Visible Web FreeCAD 29-case teaching runner. + +Python owns the lesson order and evidence ledger. The browser actions are +performed by the local Playwright helper so the user sees the real Web +FreeCAD page instead of a simulated animation. +""" +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +from datetime import datetime, timezone +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +HELPER = ROOT / "tools" / "web-freecad-29-case-tutor.mjs" +DEFAULT_ORIGIN = os.environ.get("FREECAD_BROWSER_ORIGIN", "http://127.0.0.1:5183") +CASES = [ + ("assembly", "Assembly", "Assembly", "创建装配、插入组件、检查关节和保存重开"), + ("bim", "BIM", "BIM", "创建 BIM 关系/分组并检查错误恢复"), + ("cam", "CAM", "CAM", "执行完整三轴刀路、导出和保存重开"), + ("cloud", "Cloud", "Cloud", "执行云文档保存和恢复"), + ("draft", "Draft", "Draft", "进入 Draft 并执行二维对象入口"), + ("fem", "Fem", "Fem", "进入 FEM 并执行分析任务入口"), + ("help", "Help", "Help", "打开帮助工作台和资源入口"), + ("import", "Import", "Import", "进入专用格式导入入口"), + ("inspection", "Inspection", "Inspection", "执行检查对象和报告入口"), + ("jtreader", "JtReader", "JtReader", "打开 JT/Inventor 入口"), + ("material", "Material", "Material", "读取和赋值材质"), + ("measure", "Measure", "Measure", "执行质量属性和距离测量"), + ("meshpart", "MeshPart", "MeshPart", "执行网格到形状转换入口"), + ("partdesign", "PartDesign", "PartDesign", "创建 Body、Sketch、Pad、Pocket"), + ("plot", "Plot", "Plot", "进入绘图和只读 API 入口"), + ("points", "Points", "Points", "读取点数据并检查显示"), + ("reverseengineering", "ReverseEngineering", "ReverseEngineering", "执行曲线/曲面反求入口"), + ("robot", "Robot", "Robot", "执行机器人路径和回放入口"), + ("sandbox", "Sandbox", "Sandbox", "执行 Sandbox 测试对象入口"), + ("show", "Show", "Show", "执行显示/生命周期入口"), + ("sketcher", "Sketcher", "Sketcher", "创建草图和约束入口"), + ("spreadsheet", "Spreadsheet", "Spreadsheet", "创建表格、公式和 CSV 入口"), + ("start", "Start", "Start", "打开启动页并进入工作台"), + ("surface", "Surface", "Surface", "执行曲面创建/重算入口"), + ("techdraw", "TechDraw", "TechDraw", "创建页面/视图并重算入口"), + ("templatepymod", "TemplatePyMod", "TemplatePyMod", "执行模板模块示例入口"), + ("test", "Test", "Test", "执行测试工作台入口"), + ("tux", "Tux", "Tux", "打开 Tux 示例入口"), +] + + +def main() -> int: + parser = argparse.ArgumentParser(description="用可见 Chrome 逐案例教学运行 Web FreeCAD") + parser.add_argument("--origin", default=DEFAULT_ORIGIN, help="Web FreeCAD 发布地址") + parser.add_argument("--case", choices=[item[0] for item in CASES] + ["all"], default="all") + parser.add_argument("--headless", action="store_true", help="无桌面环境时使用无头 Chrome,仅用于验收") + parser.add_argument("--interactive", action="store_true", help="每个案例开始前暂停,按回车继续") + parser.add_argument("--pause", type=float, default=2.0, help="每个案例完成后保持页面的秒数") + parser.add_argument("--screenshot-dir", default="docs/current/29-case-tutor-20261011", help="截图和账本目录") + parser.add_argument("--list", action="store_true", help="只列出案例,不启动浏览器") + args = parser.parse_args() + if args.list: + for index, (case_id, module, _command, lesson) in enumerate(CASES, 1): + print(f"{index:02d} {case_id:18s} {module:18s} {lesson}") + return 0 + selected = CASES if args.case == "all" else [next(item for item in CASES if item[0] == args.case)] + out_dir = ROOT / args.screenshot_dir + out_dir.mkdir(parents=True, exist_ok=True) + run_id = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + manifest = [{"index": i + 1, "id": c[0], "module": c[1], "command": c[2], "lesson": c[3]} for i, c in enumerate(selected)] + manifest_path = out_dir / f"manifest-{run_id}.json" + manifest_path.write_text(json.dumps({"schema": "freecad-web-29-case-tutor-manifest/v1", "origin": args.origin, "cases": manifest}, ensure_ascii=False, indent=2) + "\n") + print(f"Web FreeCAD 29-case tutor: {args.origin}") + print(f"本次案例数: {len(selected)},截图目录: {out_dir}") + results = [] + for case in manifest: + if args.interactive: + input(f"\n[{case['index']:02d}/{len(manifest)}] {case['module']}:{case['lesson']}。按回车打开真实页面...") + command = ["node", str(HELPER), "--origin", args.origin, "--case-json", json.dumps(case, ensure_ascii=False), "--out-dir", str(out_dir), "--pause", str(args.pause)] + if args.headless: + command.append("--headless") + try: + completed = subprocess.run(command, cwd=ROOT, text=True, check=False) + results.append({"case": case, "exitCode": completed.returncode, "status": "passed" if completed.returncode == 0 else "failed"}) + except OSError as exc: + results.append({"case": case, "status": "failed", "error": str(exc)}) + if results[-1]["status"] != "passed": + print(f"案例失败:{case['module']},继续保留失败证据并进入下一个案例", file=sys.stderr) + result_path = out_dir / f"run-{run_id}.json" + result_path.write_text(json.dumps({"schema": "freecad-web-29-case-tutor-run/v1", "origin": args.origin, "runId": run_id, "results": results}, ensure_ascii=False, indent=2) + "\n") + passed = sum(item["status"] == "passed" for item in results) + print(f"完成:{passed}/{len(results)},账本:{result_path}") + return 0 if passed == len(results) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/web/src/desktop-command-dispatcher.ts b/web/src/desktop-command-dispatcher.ts new file mode 100644 index 00000000..6558424d --- /dev/null +++ b/web/src/desktop-command-dispatcher.ts @@ -0,0 +1,567 @@ +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; + } +} diff --git a/web/src/format-dispatcher.ts b/web/src/format-dispatcher.ts new file mode 100644 index 00000000..98bfa259 --- /dev/null +++ b/web/src/format-dispatcher.ts @@ -0,0 +1,40 @@ +import { createFailure, type FacadeResponse } from "./facade-envelope.js"; +import { IMPORT_FIXTURE } from "./import-facade.js"; +import { MESH_IO_FIXTURE } from "./mesh-io-facade.js"; +import { PART_IO_FIXTURE } from "./part-io-facade.js"; +import { PART_SAVE_FIXTURE } from "./part-save-facade.js"; +import { TECHDRAW_NATIVE_FIXTURE } from "./techdraw-native-facade.js"; +import { SPREADSHEET_CSV_FIXTURE } from "./spreadsheet-facade.js"; +import { createFormatRuntimeLookup, resolveFormatAction, type FormatRuntimeIndex, type FormatRuntimeRecord } from "./format-runtime.js"; +import { WebModuleRouter } from "./module-router.js"; + +const FIXTURES: Record = { + "import.step": IMPORT_FIXTURE, + "part.importExport": PART_IO_FIXTURE, + "part.saveReopen": PART_SAVE_FIXTURE, + "mesh.importExport": MESH_IO_FIXTURE, + "techdraw.nativeImportExport": TECHDRAW_NATIVE_FIXTURE, + "spreadsheet.importExportCsv": SPREADSHEET_CSV_FIXTURE, + "points.importPly": { schema: "freecad-web-points/desktop-batch/v1", module: "Points", records: [{ apiId: "business-format:Points:import:.ply", name: "Points_Import", args: { path: "/tmp/points.ply" } }] }, + "points.exportObj": { schema: "freecad-web-points/desktop-batch/v1", module: "Points", records: [{ apiId: "business-format:Points:export:.obj", name: "Points_Export", args: { path: "/tmp/points.obj", objectNames: ["Points"] } }] }, +}; + +export class FormatDispatcher { + private readonly lookup: Map; + + constructor(private readonly router: WebModuleRouter, index: FormatRuntimeIndex) { + this.lookup = createFormatRuntimeLookup(index); + } + + async dispatch(formatId: string, documentId = "main-chain-document"): Promise { + const record = this.lookup.get(formatId); + if (!record) return createFailure(`format-${formatId}`, "unknown_format_id", "Format ID is not present in the generated runtime index", { formatId }); + const route = resolveFormatAction(record); + if (!route) return createFailure(`format-${formatId}`, "not_implemented", "Format record has no runnable native route", { formatId, module: record.module, direction: record.direction, kind: record.kind }); + const payload = route.command === "draft.formatBatch" + ? { schema: "freecad-web-draft/format-batch/v1", module: "Draft", records: [{ format: record.name.slice(1), direction: record.direction, documentId }] } + : FIXTURES[route.command]; + if (payload === undefined) return createFailure(`format-${formatId}`, "not_implemented", "Format route has no locked native fixture", { formatId, command: route.command }); + return this.router.request(route.module, route.command, payload, documentId); + } +} diff --git a/web/src/format-runtime.ts b/web/src/format-runtime.ts new file mode 100644 index 00000000..e502606c --- /dev/null +++ b/web/src/format-runtime.ts @@ -0,0 +1,31 @@ +export interface FormatRuntimeIndex { + schema: "freecad-web-format-runtime-index/v1"; + source: { inventory: string; inventoryRecords: number; inventorySha256: string }; + fields: { modules: string[]; directions: string[]; kinds: string[] }; + records: [string, number, number, string, number, number][]; +} + +export interface FormatRuntimeRecord { id: string; module: string; kind: string; name: string; direction: string; evidenceCount: number; } + +export function decodeFormatRuntimeRecord(index: FormatRuntimeIndex, row: FormatRuntimeIndex["records"][number]): FormatRuntimeRecord { + return { id: row[0], module: index.fields.modules[row[1]] ?? "", kind: index.fields.kinds[row[2]] ?? "", name: row[3], direction: index.fields.directions[row[4]] ?? "", evidenceCount: row[5] }; +} + +export function createFormatRuntimeLookup(index: FormatRuntimeIndex): Map { + return new Map(index.records.map((row) => { const record = decodeFormatRuntimeRecord(index, row); return [record.id, record] as const; })); +} + +export interface FormatActionRoute { module: string; command: string; worker?: string; reason: string; } + +export function resolveFormatAction(record: FormatRuntimeRecord): FormatActionRoute | undefined { + if (record.kind !== "extension") return undefined; + if (record.module === "Import" && [".step", ".stp", ".iges", ".igs"].includes(record.name) && record.direction === "import") return { module: "Import", command: "import.step", reason: "native Import STEP/IGES route" }; + if (record.module === "Part" && [".brep", ".brp"].includes(record.name)) return { module: "Part", command: "part.importExport", worker: "part.worker.ts", reason: "native Part BREP route" }; + if (record.module === "Part" && record.name === ".fcstd") return { module: "Part", command: "part.saveReopen", worker: "part-save.worker.ts", reason: "native Part FCStd round-trip route" }; + if (record.module === "Mesh" && [".stl", ".obj", ".ply", ".off", ".3mf", ".amf"].includes(record.name)) return { module: "Mesh", command: "mesh.importExport", reason: "native Mesh import/export route" }; + if (record.module === "TechDraw" && [".svg", ".dxf"].includes(record.name)) return { module: "TechDraw", command: "techdraw.nativeImportExport", worker: "techdraw-native.worker.ts", reason: "native TechDraw projection route" }; + if (record.module === "Draft" && [".svg", ".dxf"].includes(record.name)) return { module: "Draft", command: "draft.formatBatch", worker: "draft.worker.ts", reason: "native Draft geometry format route" }; + if (record.module === "Spreadsheet" && record.name === ".fcstd") return { module: "Spreadsheet", command: "spreadsheet.saveReopen", worker: "spreadsheet-save.worker.ts", reason: "native Spreadsheet FCStd route" }; + if (record.module === "Spreadsheet" && record.name.toLowerCase() === ".csv") return { module: "Spreadsheet", command: "spreadsheet.importExportCsv", worker: "spreadsheet.worker.ts", reason: "native Spreadsheet CSV import/export route" }; + return undefined; +} diff --git a/web/src/import-render-bridge.ts b/web/src/import-render-bridge.ts new file mode 100644 index 00000000..d81d9967 --- /dev/null +++ b/web/src/import-render-bridge.ts @@ -0,0 +1,704 @@ +import type { ProfileDirectionEdge } from "./part-profile-task.js"; +import type { ShowClipState } from "./show-python-family-facade.js"; +import { distanceAnnotation } from "./measure-annotation.js"; +import type { DistanceAnnotation } from "./measure-document-adapter.js"; +import * as THREE from "three"; +import { OrbitControls } from "three/addons/controls/OrbitControls.js"; +import { TransformControls } from "three/addons/controls/TransformControls.js"; +import type { MeshPayload } from "./worker-protocol.js"; +import { SceneSessionRegistry } from "./scene-session-registry.js"; +import { attachSceneCommands } from "./scene-command-host.js"; +import { SceneNavigation } from "./scene-navigation.js"; +import { SelectionDecoration, type SelectionDecorationSnapshot } from "./selection-decoration.js"; +import type { NavigationPreferenceSource } from "./view-navigation-preferences.js"; + +export class ImportRenderBridge { + constructor() { + // FreeCAD native meshes and placements are Z-up. Make the Three.js world + // convention explicit so free orbit, fit-all and restored cameras agree. + THREE.Object3D.DEFAULT_UP.set(0, 0, 1); + this.camera.up.set(0, 0, 1); + } + readonly scene = new THREE.Scene(); + camera: THREE.PerspectiveCamera | THREE.OrthographicCamera = new THREE.PerspectiveCamera(45, 1, 0.01, 100000); + readonly renderer = new THREE.WebGLRenderer({ antialias: true }); + readonly scenes = new SceneSessionRegistry(this.scene, () => this.invalidate()); + private readonly clipping = new Map(); + setClipping(documentId: string, state: ShowClipState): void { + this.clipping.set(documentId, state); this.invalidate(); + } + private applyClipping(): void { + const state = this.clipping.get(this.activeDocumentId); + for (const entry of this.scenes.objects(this.activeDocumentId)) { + const definitions = [state?.exempt === entry.id ? undefined : state?.document, state?.objects[entry.id]].filter(Boolean); + const planes = definitions.map(plane => new THREE.Plane(new THREE.Vector3(...plane!.normal), plane!.constant)); + entry.object.traverse(object => { + const material = (object as THREE.Mesh).material; + if (!material) return; + for (const item of Array.isArray(material) ? material : [material]) { + // Preserve clipping supplied by other tools; this owner removes only its own planes. + const old = item.userData.showClipPlanes ?? []; + item.clippingPlanes = [...(item.clippingPlanes ?? []).filter(plane => !old.includes(plane)), ...planes]; + item.userData.showClipPlanes = planes; + } + }); + } + } + private directionPicker?: { hidden: Set; edges: ProfileDirectionEdge[]; pick: (object: string, subelement: string) => void; documentId: string }; + private referencePicker?: { + documentId: string; base: string; hidden: Set; group: THREE.Group; + kind: "Edge" | "Face"; pick: (subelement: string) => void; + }; + beginReferencePick(documentId: string, base: string, hidden: string[], + references: { subelement: string; positions: number[] }[], pick: (subelement: string) => void) { + const group = new THREE.Group(); + for (const reference of references) { + if (!reference.positions.length) continue; + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(reference.positions, 3)); + const edge = reference.subelement.startsWith("Edge"); + const item = edge + ? new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: "#f9b44d", transparent: true, depthTest: false })) + : new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color: "#f9b44d", side: THREE.DoubleSide, + transparent: true, opacity: 0, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 })); + item.userData.subelement = reference.subelement; + item.renderOrder = edge ? 3 : 2; group.add(item); + } + const session = { documentId, base, hidden: new Set(hidden), group, kind: "Edge" as "Edge" | "Face", pick }; + this.referencePicker = session; this.scene.add(group); this.invalidate(); + let disposed = false; + return { + highlight: (selected: string[], kind: "Edge" | "Face", hovered?: string) => { + session.kind = kind; + for (const child of group.children) { + const item = child as THREE.Mesh; + const sub = String(item.userData.subelement), chosen = selected.includes(sub) || hovered === sub; + item.material.opacity = sub.startsWith("Edge") ? (chosen ? 1 : kind === "Edge" ? 0.35 : 0) : chosen ? 0.45 : 0; + } + this.invalidate(); + }, + dispose: () => { + if (disposed) return; + disposed = true; + if (this.referencePicker === session) this.referencePicker = undefined; + this.scene.remove(group); + for (const child of group.children) { + const item = child as THREE.Mesh; + item.geometry.dispose(); item.material.dispose(); + } + this.applyDirectionVisibility(); this.invalidate(); + }, + }; + } + private pickReference(point: { x: number; y: number }): boolean { + const session = this.referencePicker; + if (!session || session.documentId !== this.activeDocumentId) return false; + const bounds = this.renderer.domElement.getBoundingClientRect(), ray = new THREE.Raycaster(); + this.camera.updateMatrixWorld(); + ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1, + 1 - (point.y - bounds.top) / bounds.height * 2), this.camera); + ray.params.Line.threshold = Math.max(0.01, this.camera.position.distanceTo(this.controls?.target ?? new THREE.Vector3()) / 200); + session.group.updateWorldMatrix(true, true); + const clip = this.clipping.get(this.activeDocumentId); + const hit = ray.intersectObjects(session.group.children.filter(item => String(item.userData.subelement).startsWith(session.kind))) + .find(hit => [clip?.exempt === session.base ? undefined : clip?.document, clip?.objects[session.base]] + .every(plane => !plane || new THREE.Vector3(...plane.normal).dot(hit.point) + plane.constant >= 0)); + if (hit) session.pick(String(hit.object.userData.subelement)); + // A task owns viewport clicks, including misses, without changing tree selection. + return true; + } + beginDirectionPick(documentId: string, hidden: string[], edges: ProfileDirectionEdge[], pick: (object: string, subelement: string) => void): () => void { + const session = { documentId, hidden: new Set(hidden), edges, pick }; + this.directionPicker = session; this.invalidate(); + return () => { if (this.directionPicker === session) { this.directionPicker = undefined; this.invalidate(); } }; + } + private applyDirectionVisibility(): void { + const reference = this.referencePicker; + if (reference) reference.group.visible = reference.documentId === this.activeDocumentId; + for (const entry of this.scenes.objects(this.activeDocumentId)) { + entry.object.visible = reference?.documentId === this.activeDocumentId && reference.base === entry.id ? true + : entry.viewState.visible && !(reference?.documentId === this.activeDocumentId && reference.hidden.has(entry.id)) + && !(this.directionPicker?.documentId === this.activeDocumentId && this.directionPicker.hidden.has(entry.id)); + } + } + private pickDirection(point: { x: number; y: number }): boolean { + const session = this.directionPicker; + if (!session || session.documentId !== this.activeDocumentId) return false; + const bounds = this.renderer.domElement.getBoundingClientRect(); + const ray = new THREE.Raycaster(); + this.camera.updateMatrixWorld(); + ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1, + 1 - (point.y - bounds.top) / bounds.height * 2), this.camera); + ray.params.Line.threshold = Math.max(0.01, this.camera.position.distanceTo(this.controls?.target ?? new THREE.Vector3()) / 200); + const lines = session.edges.filter(edge => this.scenes.objects(this.activeDocumentId).some(entry => entry.id === edge.object && entry.object.visible)) + .map(edge => { + const line = new THREE.Line(new THREE.BufferGeometry().setFromPoints(edge.points.map(p => new THREE.Vector3(...p as [number, number, number]))), new THREE.LineBasicMaterial()); + line.userData.edge = edge; line.updateMatrixWorld(); return line; + }); + const clip = this.clipping.get(this.activeDocumentId); + const hit = ray.intersectObjects(lines).find(hit => [clip?.exempt === hit.object.userData.edge.object ? undefined : clip?.document, clip?.objects[hit.object.userData.edge.object]] + .every(plane => !plane || new THREE.Vector3(...plane.normal).dot(hit.point) + plane.constant >= 0)); + const edge = hit?.object.userData.edge as ProfileDirectionEdge | undefined; + for (const line of lines) { line.geometry.dispose(); line.material.dispose(); } + if (edge) session.pick(edge.object, edge.subelement); + return true; + } + private controls: OrbitControls | null = null; + // Object transform gizmo. The helper is a scene child; the handle is a proxy + // placed at the selected object's placement so document coordinates and the + // gizmo agree without moving the rendered mesh itself. + private gizmo: TransformControls | null = null; + private gizmoMode: "off" | "translate" | "rotate" = "off"; + private gizmoDocument: string | null = null; + private gizmoObject: string | null = null; + private readonly gizmoHandle = new THREE.Object3D(); + private gizmoDragging = false; + private gizmoMoved = false; + private gizmoBase = { position: new THREE.Vector3(), quaternion: new THREE.Quaternion() }; + // The one mesh the controller is allowed to move. Every drag writes only this + // object's matrix; nothing else in the document is touched, which is what + // "the controller operates the selected model" means for multi-object scenes. + private gizmoTarget: THREE.Object3D | null = null; + private gizmoMeshId: string | null = null; + private gizmoTargetBase: THREE.Matrix4 | null = null; + private gizmoHandleBase: THREE.Matrix4 | null = null; + // A committed placement rebuilds the mesh, so the object captured at drag + // start can be replaced mid-flight. Look the target up by document id at the + // moment of use instead of trusting a cached reference. + private resolveGizmoTarget(): THREE.Object3D | null { + if (!this.gizmoMeshId) return this.gizmoTarget; + const entry = this.scenes.objects(this.activeDocumentId).find(item => item.id === this.gizmoMeshId); + if (entry) this.gizmoTarget = entry.object; + return this.gizmoTarget; + } + // Local frame + selection focus. The triad is a scene child placed at the + // object placement, not a child of the gizmo handle, so it stays visible with + // the controller switched off and can follow a live drag frame by frame. + // Selectable-frame decoration lives in a shared module so the standalone + // three.js viewers (test view) can show the same triad and focus box. + private readonly decoration = new SelectionDecoration(this.scene); + // True until a host calls setTransformTarget. Hosts that never wire the + // transform (PartDesign, BIM, assembly, TechDraw) still get the triad and the + // focus box, anchored on the picked mesh's bounding-box centre. + private decorationAutomatic = true; + onTransformCommit: ((payload: { documentId: string; object: string; position: number[]; axis: number[]; angle: number }) => void) | null = null; + private sceneCommands: ReturnType | null = null; + private frame = 0; + private disposed = false; + private readonly invalidate = (): void => { + if (this.disposed || !this.viewport || this.frame) return; + this.frame = requestAnimationFrame(() => { + this.frame = 0; + // OrbitControls emits change while damping still moves the camera. + this.controls?.update(); + this.updateSelectionAxes(); + this.applyClipping(); + this.applyDirectionVisibility(); + this.renderer.render(this.scene, this.camera); + this.onRender?.(); + if (this.controls?.autoRotate) this.invalidate(); + }); + }; + private viewport: HTMLElement | null = null; + private resizeObserver: ResizeObserver | null = null; + private activeDocumentId = "active"; + private sketchEditing = false; + private navigation: SceneNavigation | null = null; + private annotations = new Map(); + onPick: ((objectId: string, point: number[]) => void) | null = null; + onPrimitivePick: ((point: [number, number, number], normal?: [number, number, number]) => void) | null = null; + primitivePickVertices: number[][] | null = null; + onSelect: ((objectId: string | null, additive?: boolean) => void) | null = null; + onRender: (() => void) | null = null; + private hit(point: { x: number; y: number }) { + const bounds = this.renderer.domElement.getBoundingClientRect(); + const ray = new THREE.Raycaster(); + this.camera.updateMatrixWorld(); + ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1, + 1 - (point.y - bounds.top) / bounds.height * 2), this.camera); + const objects = this.scenes.objects(this.activeDocumentId).filter(entry => entry.object.visible).map(entry => entry.object); + objects.forEach(object => object.updateWorldMatrix(true, true)); + return ray.intersectObjects(objects, true).find(hit => { + const state = this.clipping.get(this.activeDocumentId); + const id = String(hit.object.userData.documentObjectId); + return [state?.exempt === id ? undefined : state?.document, state?.objects[id]].every(plane => + !plane || new THREE.Vector3(...plane.normal).dot(hit.point) + plane.constant >= 0); + }); + } + + mount(viewport: HTMLElement, preferences?: NavigationPreferenceSource): void { + this.viewport = viewport; + this.renderer.localClippingEnabled = true; + this.scene.background = new THREE.Color("#0d1319"); + this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); + viewport.append(this.renderer.domElement); + this.renderer.domElement.addEventListener("sketch-edit-capture", ((event: CustomEvent) => { + if (event.detail.documentId !== this.activeDocumentId || this.disposed) return; + event.detail.camera = this.captureCamera(); + this.sketchEditing = true; + }) as EventListener); + this.renderer.domElement.addEventListener("sketch-edit-restore", ((event: CustomEvent) => { + this.sketchEditing = false; + if (event.detail.documentId !== this.activeDocumentId || this.disposed) return; + if (event.detail.camera) this.restoreCamera(event.detail.camera); + for (const value of event.detail.displayProperties ?? []) { + const object = this.scenes.objects(this.activeDocumentId).find(entry => entry.id === value.object)?.object; + if (object) object.visible = value.visible; + } + this.invalidate(); + }) as EventListener); + this.renderer.domElement.addEventListener("bim-capture-camera", ((event: CustomEvent) => { + if (event.detail.documentId === this.activeDocumentId && !this.disposed) + event.detail.camera = this.captureCamera(); + }) as EventListener); + this.renderer.domElement.addEventListener("techdraw-capture", ((event: CustomEvent) => { + if (event.detail.documentId !== this.activeDocumentId || this.disposed + || !this.scenes.objects(this.activeDocumentId).some(entry => entry.object.visible)) return; + this.applyClipping(); + this.applyDirectionVisibility(); + this.renderer.render(this.scene, this.camera); + const options = event.detail.captureOptions ?? {}; + const crop = options.crop === true; + const width = crop && Number.isFinite(options.width) ? Math.max(1, Math.round(Number(options.width))) : this.renderer.domElement.width; + const height = crop && Number.isFinite(options.height) ? Math.max(1, Math.round(Number(options.height))) : this.renderer.domElement.height; + const output = document.createElement("canvas"); + output.width = width; output.height = height; + const context = output.getContext("2d"); + if (!context) return; + if (options.solidBackground === true && typeof options.background === "string") { + context.fillStyle = options.background; context.fillRect(0, 0, width, height); + } + context.drawImage(this.renderer.domElement, 0, 0, width, height); + event.detail.capture = { + image: output.toDataURL("image/png"), pixelWidth: width, pixelHeight: height, + }; + }) as EventListener); + this.controls = new OrbitControls(this.camera, this.renderer.domElement); + this.controls.enableDamping = true; + this.controls.addEventListener("change", this.invalidate); + // Read-only camera probe: strict tests must prove that rotating the selected + // model does not move the viewpoint, while middle-drag orbit does. + (window as unknown as { __freecadCameraState?: unknown }).__freecadCameraState = () => ({ + position: this.camera.position.toArray().map(value => Math.round(value * 10000) / 10000), + quaternion: this.camera.quaternion.toArray().map(value => Math.round(value * 10000) / 10000), + target: this.controls ? this.controls.target.toArray().map(value => Math.round(value * 10000) / 10000) : null, + }); + // Read-only controller probe: proves which object the gizmo will move and + // where every document mesh currently sits, so a drag can be asserted to + // change the selected mesh only. + (window as unknown as { __freecadGizmoState?: unknown }).__freecadGizmoState = () => ({ + mode: this.gizmoMode, + dragging: this.gizmoDragging, + target: this.gizmoObject, + targetMeshId: this.gizmoTarget?.userData.documentObjectId ?? null, + handle: this.gizmoHandle.position.toArray().map(value => Math.round(value * 1000) / 1000), + // Screen point of the gizmo centre, so a probe can grab a handle instead + // of guessing the canvas middle. + handleScreen: (() => { + const rect = this.renderer.domElement.getBoundingClientRect(); + this.gizmoHandle.updateMatrixWorld(true); + const projected = new THREE.Vector3().setFromMatrixPosition(this.gizmoHandle.matrixWorld).project(this.camera); + return [Math.round(rect.left + (projected.x + 1) * rect.width / 2), + Math.round(rect.top + (1 - projected.y) * rect.height / 2)]; + })(), + objects: this.scenes.objects(this.activeDocumentId).map(entry => { + entry.object.updateMatrixWorld(true); + // Two readings, both rounded: the world translation proves a live drag + // preview (which writes the object matrix), and the world bounding-box + // centre proves the committed placement (mesh triangles bake placement, + // so a rebuilt mesh sits at the origin while its geometry has moved). + const world = new THREE.Vector3().setFromMatrixPosition(entry.object.matrixWorld); + const box = new THREE.Box3().setFromObject(entry.object); + const center = box.isEmpty() ? null : box.getCenter(new THREE.Vector3()); + const round = (values: number[]) => values.map(value => Math.round(value * 1000) / 1000); + return { + id: entry.id, + position: round(world.toArray()), + center: center ? round(center.toArray()) : null, + }; + }), + }); + this.gizmo = new TransformControls(this.camera, this.renderer.domElement); + this.gizmo.setTranslationSnap(1); + this.gizmo.setRotationSnap(THREE.MathUtils.degToRad(15)); + this.gizmo.setSize(0.9); + this.gizmo.enabled = false; + this.gizmo.getHelper().visible = false; + this.scene.add(this.gizmo.getHelper()); + this.scene.add(this.gizmoHandle); + // TransformControls dispatches "change" from pointerHover whenever the axis + // under the cursor changes; SceneNavigation reads this flag to hand the left + // button to the gizmo without giving up middle-drag orbit. + this.gizmo.addEventListener("change", () => { if (this.navigation) this.navigation.gizmoHover = this.gizmo?.axis != null; }); + this.gizmo.addEventListener("dragging-changed", (event: { value: unknown }) => { + const busy = Boolean(event.value); + this.gizmoDragging = busy; + if (busy) { + this.gizmoMoved = false; + // Snapshot the selected mesh so every frame is recomputed from the drag + // start instead of accumulating rounding error. The handle matrix is + // read through updateMatrixWorld so it is current at drag start. + this.gizmoHandle.updateMatrixWorld(true); + this.gizmoHandleBase = this.gizmoHandle.matrixWorld.clone(); + const target = this.resolveGizmoTarget(); + if (target) { + target.updateMatrixWorld(true); + this.gizmoTargetBase = target.matrix.clone(); + target.matrixAutoUpdate = false; + } + } + if (this.controls) this.controls.enabled = !busy; + if (this.navigation) this.navigation.enabled = !busy; + this.invalidate(); + }); + this.gizmo.addEventListener("objectChange", () => { + if (this.gizmoDragging) { + this.gizmoMoved = true; + this.previewGizmoDrag(); + } + this.invalidate(); + }); + this.gizmo.addEventListener("mouseUp", () => { + // A plain click on the canvas also fires mouseUp; committing then would + // write a spurious placement (angle 0) for an edit that never happened. + const moved = this.gizmoMoved; + this.gizmoMoved = false; + // On a real drag the preview matrix stays until the kernel snapshot + // republishes the re-meshed geometry; resetting it here would snap the + // selected mesh back to its old position while the commit is in flight. + if (!moved) this.endGizmoPreview(); + + if (this.gizmoMode === "off" || !this.gizmoDocument || !this.gizmoObject) { this.endGizmoPreview(); return; } + const start = this.gizmoBase.quaternion.clone(); + const base = start; // handle started at the object's own orientation + const delta = this.gizmoHandle.quaternion.clone().multiply(start.clone().invert()); + const final = delta.multiply(base); + const angle = THREE.MathUtils.radToDeg(2 * Math.acos(Math.min(Math.max(final.w, -1), 1))); + const sine = Math.sqrt(Math.max(1 - final.w * final.w, 0)); + const axis = sine < 1e-6 ? [1, 0, 0] : [final.x / sine, final.y / sine, final.z / sine]; + const payloadAngle = Number.isFinite(angle) ? angle : 0; + // With no commit consumer the preview is the only thing holding the mesh + // at its dragged pose, so it has to be released here. + if (!this.onTransformCommit) { this.endGizmoPreview(); return; } + this.onTransformCommit({ + documentId: this.gizmoDocument, object: this.gizmoObject, + position: this.gizmoHandle.position.toArray(), + axis, angle: payloadAngle, + }); + }); + this.navigation = new SceneNavigation(this.renderer.domElement, this.controls, (point, additive) => { + if (this.sketchEditing) return; + this.applyDirectionVisibility(); + if (this.pickReference(point)) return; + if (this.pickDirection(point)) return; + const hit = this.hit(point); + if (this.onPrimitivePick) { + const bounds = this.renderer.domElement.getBoundingClientRect(); + const ray = new THREE.Raycaster(); + ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1, + 1 - (point.y - bounds.top) / bounds.height * 2), this.camera); + const nearest = this.primitivePickVertices?.map(value => { + const vertex = new THREE.Vector3(...value).project(this.camera); + return { value, pixels: Math.hypot((vertex.x + 1) * bounds.width / 2 + bounds.left - point.x, + (1 - vertex.y) * bounds.height / 2 + bounds.top - point.y), depth: vertex.z }; + }).filter(value => value.pixels <= 10 && value.depth >= -1 && value.depth <= 1) + .sort((a, b) => a.pixels - b.pixels || a.depth - b.depth)[0]; + if (nearest) { this.onPrimitivePick(nearest.value as [number, number, number]); return; } + if (this.primitivePickVertices) return; + if (hit) { + const normal = hit.face?.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld)); + this.onPrimitivePick(hit.point.toArray() as [number, number, number], normal?.toArray() as [number, number, number] | undefined); + } + return; + } + if (hit && this.onPick) { this.onPick(String(hit.object.userData.documentObjectId), hit.point.toArray()); return; } + if (this.decorationAutomatic) this.decoratePicked(hit?.object ?? null); + this.onSelect?.(hit ? String(hit.object.userData.documentObjectId) : null, additive); + }, point => this.hit(point)?.point, command => { this.sceneCommands?.executeCamera(command); }, this.invalidate, + next => this.sceneCommands?.replaceControls(next)); + this.sceneCommands = attachSceneCommands(this.scene, this.controls, viewport, () => this.activeDocumentId, this.invalidate, { + canvas: this.renderer.domElement, + objects: () => this.scenes.objects(this.activeDocumentId).map(entry => ({ + id: entry.id, label: entry.payload.fileName || entry.id, object: entry.object, + })), + select: id => { + if (this.sketchEditing) return; + if (this.decorationAutomatic) { + const entry = this.scenes.objects(this.activeDocumentId).find(item => item.id === id); + this.decoratePicked(entry?.object ?? null); + } + this.onSelect?.(id); + }, + }, next => { + this.controls?.removeEventListener("change", this.invalidate); + this.controls = next; + this.camera = next.object as THREE.PerspectiveCamera | THREE.OrthographicCamera; + this.navigation?.bind(next); + next.addEventListener("change", this.invalidate); + if (this.gizmo) this.gizmo.camera = next.object as THREE.Camera; + }, preferences ? { source: preferences, apply: values => this.navigation?.apply(values), + cancel: () => this.navigation?.cancel() } : undefined); + this.scene.add(new THREE.HemisphereLight(0xddeeff, 0x17212b, 1.8)); + const light = new THREE.DirectionalLight(0xffffff, 2.1); light.position.set(4, 8, 6); this.scene.add(light); + const resize = () => { const width = Math.max(viewport.clientWidth, 1); const height = Math.max(viewport.clientHeight, 1); this.renderer.setSize(width, height, false); if (this.camera instanceof THREE.PerspectiveCamera) this.camera.aspect = width / height; + else { const halfHeight = (this.camera.top - this.camera.bottom) / 2; + this.camera.left = -halfHeight * width / height; this.camera.right = halfHeight * width / height; } + this.camera.updateProjectionMatrix(); this.invalidate(); }; + this.resizeObserver = new ResizeObserver(resize); this.resizeObserver.observe(viewport); resize(); + this.invalidate(); + } + + // Places the gizmo on an object placement reported by the shell. Keeping the + // base orientation lets a rotation commit compose with whatever rotation the + // object already had. + setTransformTarget(documentId: string, object: string, position: number[], axis?: number[], angle?: number, meshId?: string): void { + this.decorationAutomatic = false; + this.gizmoDocument = documentId; this.gizmoObject = object; + this.gizmoHandle.position.fromArray(position); + const orientation = new THREE.Quaternion(); + if (axis && axis.length === 3 && Number.isFinite(angle)) { + const length = Math.hypot(axis[0], axis[1], axis[2]); + if (length > 0) orientation.setFromAxisAngle(new THREE.Vector3(axis[0] / length, axis[1] / length, axis[2] / length), + THREE.MathUtils.degToRad(angle ?? 0)); + } + this.gizmoHandle.quaternion.copy(orientation); + this.gizmoBase = { position: this.gizmoHandle.position.clone(), quaternion: orientation.clone() }; + const entry = this.scenes.objects(this.activeDocumentId).find(item => item.id === (meshId ?? object)); + this.gizmoTarget = entry?.object ?? null; + this.gizmoMeshId = entry?.id ?? null; + this.gizmoTargetBase = null; + if (this.gizmoTarget) this.gizmoTarget.matrixAutoUpdate = true; + this.decoration.setTarget(position, orientation, entry?.object ?? null); + if (this.gizmo && this.gizmoMode !== "off" && !this.gizmoDragging) { this.gizmo.attach(this.gizmoHandle); this.gizmo.getHelper().visible = true; } + this.invalidate(); + } + + // Live preview while a drag is in flight: the gizmo handle has already moved, + // so the selected mesh takes the same world-space delta. Nothing else in the + // scene is rewritten — unselected objects keep their matrices untouched. + private previewGizmoDrag(): void { + const target = this.gizmoTarget, base = this.gizmoTargetBase, start = this.gizmoHandleBase; + if (!target || !base || !start) return; + const delta = new THREE.Matrix4().copy(this.gizmoHandle.matrixWorld) + .multiply(new THREE.Matrix4().copy(start).invert()); + // `delta` is a world-space transform; `base` is the mesh's local matrix, so + // it has to travel through the parent frame before landing back in local + // space. Document groups are identity today, but this keeps the preview + // correct if an object is ever parented. + const parent = target.parent; + if (parent) { + parent.updateMatrixWorld(true); + const inverse = new THREE.Matrix4().copy(parent.matrixWorld).invert(); + target.matrix.copy(inverse).multiply(delta).multiply(parent.matrixWorld).multiply(base); + } else { + target.matrix.copy(delta).multiply(base); + } + target.matrixWorldNeedsUpdate = true; + target.updateMatrixWorld(true); + } + + // Drag finished: drop the preview matrix so the mesh goes back to following + // its own transform. The kernel commit republishes the authoritative placement. + private endGizmoPreview(): void { + if (this.gizmoTarget) { + this.gizmoTarget.matrixAutoUpdate = true; + this.gizmoTarget.matrixWorldNeedsUpdate = true; + } + this.gizmoTargetBase = null; + } + + // Hosts without their own placement pipeline still show the selected local + // frame: anchor it on the mesh's bounding-box centre with an identity basis. + private decoratePicked(object: THREE.Object3D | null): void { + if (!object || !object.visible) { this.decoration.clear(); return; } + const box = new THREE.Box3().setFromObject(object); + if (box.isEmpty()) { this.decoration.clear(); return; } + this.decoration.setTarget(box.getCenter(new THREE.Vector3()).toArray(), new THREE.Quaternion(), object); + } + + // Read-only view of the selection decoration for headed acceptance probes. + selectionFrameSnapshot(): SelectionDecorationSnapshot & { gizmoVisible: boolean; gizmoMode: string } { + return { ...this.decoration.snapshot(), gizmoVisible: Boolean(this.gizmo?.getHelper().visible), gizmoMode: this.gizmoMode }; + } + + clearTransformTarget(): void { + this.gizmoDocument = null; this.gizmoObject = null; + this.endGizmoPreview(); + this.gizmoTarget = null; + if (this.gizmo) { this.gizmo.detach(); this.gizmo.getHelper().visible = false; } + this.decoration.clear(); + this.invalidate(); + } + + // SolidWorks-style selection display: the triad and focus box come from the + // shared SelectionDecoration; this wrapper only feeds it the camera frame. + private updateSelectionAxes(): void { + if (this.gizmoDragging) this.decoration.follow(this.gizmoHandle.position, this.gizmoHandle.quaternion); + this.decoration.updateFrame(this.camera); + } + + setTransformMode(mode: "off" | "translate" | "rotate"): void { + if (this.gizmoDragging) return; + this.gizmoMode = mode; + if (!this.gizmo) return; + if (mode === "off") { + this.gizmo.detach(); this.gizmo.enabled = false; this.gizmo.getHelper().visible = false; + if (this.navigation) { this.navigation.gizmoActive = false; this.navigation.gizmoHover = false; } + } else { + // SceneNavigation listens in the capture phase and stops propagation, which + // starves the gizmo's bubble-phase handlers. Rather than switching the whole + // navigation off (that also loses middle-drag orbit and wheel zoom), the + // navigation yields only left-button events while the pointer is over a + // gizmo handle; every other gesture keeps working like SolidWorks. + this.gizmo.setMode(mode); + this.gizmo.enabled = true; + this.gizmo.getHelper().visible = Boolean(this.gizmoDocument); + if (this.navigation) { this.navigation.cancel(); this.navigation.gizmoActive = true; this.navigation.gizmoHover = false; } + if (this.gizmoDocument) this.gizmo.attach(this.gizmoHandle); + } + this.invalidate(); + } + + setNavigationEnabled(enabled: boolean): void { + if (this.navigation) { this.navigation.cancel(); this.navigation.enabled = enabled; } + if (this.controls) this.controls.enabled = enabled; + } + + requestRender(): void { this.invalidate(); } + + captureCamera(): number[] { + const camera = this.camera; + camera.updateMatrixWorld(); + const focal = camera.position.distanceTo(this.controls?.target ?? new THREE.Vector3()); + const perspective = camera instanceof THREE.PerspectiveCamera; + const aspect = perspective ? camera.aspect : (camera.right - camera.left) / (camera.top - camera.bottom); + const height = perspective ? THREE.MathUtils.degToRad(camera.getEffectiveFOV()) : (camera.top - camera.bottom) / camera.zoom; + return [...camera.position.toArray(), ...camera.quaternion.toArray(), camera.near, camera.far, + aspect, Math.max(focal, 0.001), height, perspective ? 1 : 0]; + } + + restoreCamera(data: number[]): void { + if (data.length !== 13 || !data.every(Number.isFinite)) throw new Error("Invalid BIM camera state"); + const perspective = data[12] === 1; + const aspect = this.viewport ? Math.max(this.viewport.clientWidth, 1) / Math.max(this.viewport.clientHeight, 1) : data[9]; + const camera = perspective + ? new THREE.PerspectiveCamera(THREE.MathUtils.radToDeg(data[11]), aspect, data[7], data[8]) + : new THREE.OrthographicCamera(-data[11] * aspect / 2, data[11] * aspect / 2, data[11] / 2, -data[11] / 2, data[7], data[8]); + camera.position.fromArray(data); + camera.quaternion.fromArray(data.slice(3, 7)).normalize(); + camera.up.set(0, 0, 1).applyQuaternion(camera.quaternion); + const target = camera.position.clone().add(new THREE.Vector3(0, 0, -data[10]).applyQuaternion(camera.quaternion)); + this.controls?.removeEventListener("change", this.invalidate); + this.controls?.dispose(); + this.camera = camera; + const next = new OrbitControls(camera, this.renderer.domElement); + next.target.copy(target); + next.update(); camera.updateProjectionMatrix(); + if (this.sceneCommands) this.sceneCommands.replaceControls(next); + else { this.controls = next; this.navigation?.bind(next); next.addEventListener("change", this.invalidate); } + this.invalidate(); + } + + show(id: string, payload: MeshPayload): void { this.showForDocument("active", id, payload); } + + showForDocument(documentId: string, id: string, payload: MeshPayload): void { + this.scenes.add(documentId, id, payload); + this.activateDocument(documentId); + this.fitDocument(); + } + + fitDocument(objectIds?: readonly string[]): void { + const bounds = new THREE.Box3(); + for (const entry of this.scenes.objects(this.activeDocumentId)) { + if (entry.object.visible && (!objectIds || objectIds.includes(entry.id))) bounds.expandByObject(entry.object); + } + if (bounds.isEmpty()) return; + const center = bounds.getCenter(new THREE.Vector3()); const radius = Math.max(bounds.getSize(new THREE.Vector3()).length() * 0.5, 0.01); + this.controls?.target.copy(center); this.camera.position.copy(center).add(new THREE.Vector3(radius * 1.7, radius * 1.35, radius * 1.7)); this.camera.near = Math.max(radius / 1000, 0.0001); this.camera.far = Math.max(radius * 100, 100); this.camera.updateProjectionMatrix(); this.controls?.update(); + this.invalidate(); + } + + applyFraming(documentId: string, framing: { bounds: number[] | null; rotation?: number[] }): void { + if (documentId !== this.activeDocumentId) return; + this.navigation?.cancel(); + const rotation = framing.rotation; + const previousTarget = this.controls?.target.clone() ?? this.camera.position.clone().add( + new THREE.Vector3(0, 0, -1).applyQuaternion(this.camera.quaternion)); + const previousDistance = this.camera.position.distanceTo(previousTarget); + if (rotation?.length === 4) this.camera.quaternion.fromArray(rotation).normalize(); + if (framing.bounds?.length === 6) { + const box = new THREE.Box3(new THREE.Vector3(...framing.bounds.slice(0, 3)), new THREE.Vector3(...framing.bounds.slice(3, 6))); + const center = box.getCenter(new THREE.Vector3()); + const radius = Math.max(box.getSize(new THREE.Vector3()).length() * 0.5, 0.01); + this.controls?.target.copy(center); + let distance = this.camera.position.distanceTo(this.controls?.target ?? center); + if (this.camera instanceof THREE.PerspectiveCamera) { + const halfAngle = Math.atan(Math.tan(THREE.MathUtils.degToRad(this.camera.fov / 2)) / this.camera.zoom); + const limitingAngle = Math.min(halfAngle, Math.atan(Math.tan(halfAngle) * this.camera.aspect)); + distance = radius * 1.15 / Math.sin(limitingAngle); + } else { + this.camera.zoom = Math.min(this.camera.right - this.camera.left, this.camera.top - this.camera.bottom) / (radius * 2.3); + distance = radius * 3; + } + this.camera.position.copy(center).add(new THREE.Vector3(0, 0, distance).applyQuaternion(this.camera.quaternion)); + this.camera.near = Math.max(Math.min(radius / 1000, distance - radius * 1.5), 0.0001); + this.camera.far = Math.max(distance + radius * 2, radius * 100, 100); + } else if (rotation?.length === 4) { + this.camera.position.copy(previousTarget).add( + new THREE.Vector3(0, 0, previousDistance).applyQuaternion(this.camera.quaternion)); + } + this.camera.up.set(0, 0, 1).applyQuaternion(this.camera.quaternion); + this.camera.updateProjectionMatrix(); + this.controls?.update(); + this.invalidate(); + } + + setMeasurements(documentId: string, objects: Array<{ name: string; measurement?: DistanceAnnotation; displayVisibility?: boolean }>): void { + const prior = this.annotations.get(documentId); + if (prior) { prior.children.forEach(child => child.userData.dispose?.()); this.scene.remove(prior); } + const group = new THREE.Group(); + const visible = new Map(objects.map(object => [object.name, object.displayVisibility !== false])); + for (const object of objects) { + const measurement = object.measurement; + const subjects = measurement?.subjects ?? []; + const subjectsVisible = subjects.every(subject => visible.get(subject) !== false); + if (measurement && object.displayVisibility !== false && subjectsVisible) { + const annotation = distanceAnnotation(measurement); + annotation.userData.subjects = subjects; + group.add(annotation); + } + } + group.visible = documentId === this.activeDocumentId; this.scene.add(group); this.annotations.set(documentId, group); this.invalidate(); + } + private taskPreviewVisibility?: { documentId: string; restore: () => void }; + + // A task may hide committed geometry without changing document visibility. + // The returned lease cannot clear a newer task's visibility override. + hideForTaskPreview(documentId: string, objectIds: readonly string[]): () => void { + this.clearTaskPreviewVisibility(); + const objects = this.scenes.objects(documentId) + .filter(entry => objectIds.includes(entry.id)) + .map(entry => ({ object: entry.object, visible: entry.object.visible })); + const lease = { documentId, restore: () => { + for (const entry of objects) entry.object.visible = entry.visible; + this.invalidate(); + } }; + for (const entry of objects) entry.object.visible = false; + this.taskPreviewVisibility = lease; + this.invalidate(); + return () => { + if (this.taskPreviewVisibility === lease) this.clearTaskPreviewVisibility(); + }; + } + + clearTaskPreviewVisibility(): void { + const lease = this.taskPreviewVisibility; + this.taskPreviewVisibility = undefined; + lease?.restore(); + } + + activateDocument(documentId: string): void { for (const [id, group] of this.annotations) group.visible = id === documentId; if (this.activeDocumentId !== documentId) { this.clearTaskPreviewVisibility(); this.navigation?.cancel(); } this.activeDocumentId = documentId; this.scenes.activate(documentId); } + removeDocument(documentId: string): void { if (this.taskPreviewVisibility?.documentId === documentId) this.clearTaskPreviewVisibility(); this.clipping.delete(documentId); this.setMeasurements(documentId, []); this.scenes.removeDocument(documentId); } + clear(): void { this.clearTaskPreviewVisibility(); this.clipping.clear(); for (const [id] of this.annotations) this.setMeasurements(id, []); for (const group of this.annotations.values()) this.scene.remove(group); this.annotations.clear(); this.scenes.clear(); } + dispose(): void { this.disposed = true; cancelAnimationFrame(this.frame); this.sceneCommands?.dispose(); this.sceneCommands = null; this.controls?.removeEventListener("change", this.invalidate); this.resizeObserver?.disconnect(); this.navigation?.dispose(); this.navigation = null; this.onSelect = null; this.clear(); this.gizmo?.detach(); this.gizmo?.dispose(); this.gizmo = null; this.scene.remove(this.gizmoHandle); this.decoration.dispose(); this.controls?.dispose(); this.renderer.dispose(); this.viewport = null; } +} diff --git a/web/src/module-metadata.generated.ts b/web/src/module-metadata.generated.ts new file mode 100644 index 00000000..1b6aeeb0 --- /dev/null +++ b/web/src/module-metadata.generated.ts @@ -0,0 +1,58 @@ +/* Generated by tools/generate_web_module_registry.py; no Worker factories. */ +export const WEB_MODULE_REGISTRY_SCHEMA = "freecad-web-module-registry/v1" as const; + +export interface WebModuleRoute { + readonly module: string; + readonly workers: readonly string[]; + readonly primaryWorker: string | null; + readonly commands: readonly string[]; + readonly objectTypeCount: number; + readonly pythonApiCount: number; + readonly guiDependency: boolean; + readonly formatExtensions: readonly string[]; +} + +export const WEB_MODULE_REGISTRY = [ + { module: "Assembly", workers: ["assembly.worker.ts"], primaryWorker: "assembly.worker.ts", commands: ["assembly.createRecompute", "assembly.inspectPythonApi", "assembly.inspectSourceInventory", "assembly.nativeTypeProbe", "assembly.pythonFamily", "assembly.saveReopen", "assembly.testCore"], objectTypeCount: 8, pythonApiCount: 552, guiDependency: true, formatExtensions: [".fcstd"] }, + { module: "BIM", workers: ["bim.worker.ts"], primaryWorker: "bim.worker.ts", commands: ["bim.create2DViews", "bim.createAxis", "bim.document", "bim.extrusionData", "bim.inspectPythonApi", "bim.inspectSourceInventory", "bim.nativeProbe", "bim.pythonFamily", "bim.pythonFamilyBatch", "bim.testArchAxis", "bim.testArchBatch", "bim.testArchBuildingPart", "bim.testArchBuildingPartGui", "bim.testArchComponent", "bim.testArchCurtainWall", "bim.testArchEquipment", "bim.testArchFence", "bim.testArchFrame", "bim.testArchGrid", "bim.testArchImporters", "bim.testArchMaterial", "bim.testArchPanel", "bim.testArchPipe", "bim.testArchProfile", "bim.testArchProject", "bim.testArchRebar", "bim.testArchReference", "bim.testArchReport", "bim.testArchReportGui", "bim.testArchSiteGui", "bim.testArchWallGui", "bim.testWebGLExportGui"], objectTypeCount: 0, pythonApiCount: 2366, guiDependency: false, formatExtensions: [".brp", ".dae", ".dxf", ".fcstd", ".ifc", ".json", ".obj", ".stp", ".svg"] }, + { module: "CAM", workers: ["cam.worker.ts"], primaryWorker: "cam.worker.ts", commands: ["cam.createRecompute", "cam.export", "cam.import", "cam.inspectPythonApi", "cam.inspectSourceInventory", "cam.pythonFamilyBatch", "cam.saveReopen", "cam.testCentroidLegacyPost", "cam.testCentroidPost", "cam.testDressupPost", "cam.testDrillCycleExpander", "cam.testFanucPost", "cam.testGcodeProcessingUtils", "cam.testGenericPlasma", "cam.testGenericPost", "cam.testGrblLegacyPost", "cam.testGrblPost", "cam.testLinkingGenerator", "cam.testLinuxCNCLegacyPost", "cam.testLinuxCNCPost", "cam.testMach3Mach4LegacyPost", "cam.testMach3Mach4Post", "cam.testMachine", "cam.testMassoG3Post", "cam.testMaterial", "cam.testPathAdaptive", "cam.testPathCommandAnnotations", "cam.testPathCore", "cam.testPathDepthParams", "cam.testPathDressupArray", "cam.testPathDressupDogboneII", "cam.testPathDressupHoldingTags", "cam.testPathDrillGenerator", "cam.testPathDrillable", "cam.testPathFacingGenerator", "cam.testPathGeneratorDogboneII", "cam.testPathGeom", "cam.testPathHelix", "cam.testPathHelixGenerator", "cam.testPathHelpers", "cam.testPathLanguage", "cam.testPathLog", "cam.testPathOpDeburr", "cam.testPathOpUtil", "cam.testPathPreferences", "cam.testPathProfile", "cam.testPathPropertyBag", "cam.testPathRotationGenerator", "cam.testPathSetupSheet", "cam.testPathSpiralGenerator", "cam.testPathStock", "cam.testPathTapGenerator", "cam.testPathThreadMilling", "cam.testPathThreadMillingGenerator", "cam.testPathToolAsset", "cam.testPathToolAssetCache", "cam.testPathToolAssetManager", "cam.testPathToolAssetStore", "cam.testPathToolAssetUri", "cam.testPathToolBit", "cam.testPathToolBitSerializer", "cam.testPathToolChangeGenerator", "cam.testPathToolController", "cam.testPathToolLibrary", "cam.testPathToolLibrarySerializer", "cam.testPathToolShapeClasses", "cam.testPathToolShapeDoc", "cam.testPathUtil", "cam.testPathVcarve", "cam.testPathVoronoi", "cam.testPostCore", "cam.testPostGCodes", "cam.testPostMCodes", "cam.testSanity", "cam.testSnapmakerPost", "cam.testTSPSolver", "cam.testTestPost"], objectTypeCount: 12, pythonApiCount: 2883, guiDependency: true, formatExtensions: [".fcstd", ".json", ".obj", ".step", ".svg"] }, + { module: "Cloud", workers: ["cloud.worker.ts"], primaryWorker: "cloud.worker.ts", commands: ["cloud.configureRecompute", "cloud.inspectPythonApi", "cloud.inspectSourceInventory", "cloud.pythonFamilyBatch", "cloud.restore", "cloud.save", "cloud.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] }, + { module: "Draft", workers: ["draft.worker.ts"], primaryWorker: "draft.worker.ts", commands: ["draft.action", "draft.formatBatch", "draft.pythonFamilyBatch", "draft.testOfficialSuite"], objectTypeCount: 0, pythonApiCount: 2043, guiDependency: false, formatExtensions: [".dxf", ".obj", ".svg"] }, + { module: "Fem", workers: ["fem.worker.ts"], primaryWorker: "fem.worker.ts", commands: ["fem.action", "fem.brep", "fem.document", "fem.nativeProbe", "fem.pythonFamilyBatch"], objectTypeCount: 53, pythonApiCount: 1305, guiDependency: true, formatExtensions: [".brep", ".json", ".obj", ".svg", ".txt"] }, + { module: "Help", workers: ["help.worker.ts"], primaryWorker: "help.worker.ts", commands: ["help.inspectSourceInventory", "help.pythonApi"], objectTypeCount: 0, pythonApiCount: 14, guiDependency: false, formatExtensions: [] }, + { module: "Import", workers: ["import.worker.ts"], primaryWorker: "import.worker.ts", commands: ["import.createRecompute", "import.inspectSourceInventory", "import.pythonApi", "import.pythonFamilyBatch", "import.saveReopen", "import.step"], objectTypeCount: 2, pythonApiCount: 1135, guiDependency: true, formatExtensions: [".ifc", ".igs", ".obj", ".step", ".stp"] }, + { module: "Inspection", workers: ["inspection.worker.ts"], primaryWorker: "inspection.worker.ts", commands: ["inspection.createRecompute", "inspection.inspectPythonApi", "inspection.inspectSourceInventory", "inspection.pythonFamilyBatch", "inspection.saveReopen"], objectTypeCount: 3, pythonApiCount: 3, guiDependency: true, formatExtensions: [] }, + { module: "JtReader", workers: ["jtreader.worker.ts"], primaryWorker: "jtreader.worker.ts", commands: ["jtreader.createRecompute", "jtreader.document", "jtreader.inspectSourceInventory", "jtreader.saveReopen"], objectTypeCount: 1, pythonApiCount: 0, guiDependency: false, formatExtensions: [".fcstd", ".jt"] }, + { module: "Material", workers: ["material-python.worker.ts", "material.worker.ts"], primaryWorker: "material-python.worker.ts", commands: ["material.createRecompute", "material.inspectSourceInventory", "material.pythonApi", "material.pythonFamilyBatch", "material.saveReopen"], objectTypeCount: 22, pythonApiCount: 178, guiDependency: true, formatExtensions: [] }, + { module: "Measure", workers: ["measure.worker.ts"], primaryWorker: "measure.worker.ts", commands: ["measure.createRecompute", "measure.inspectSourceInventory", "measure.measurementApi", "measure.objectFamily", "measure.pythonApi", "measure.pythonFamilyBatch", "measure.saveReopen"], objectTypeCount: 11, pythonApiCount: 31, guiDependency: true, formatExtensions: [] }, + { module: "Mesh", workers: ["mesh.worker.ts"], primaryWorker: "mesh.worker.ts", commands: ["mesh.createRecompute", "mesh.importExport", "mesh.inspectSourceInventory", "mesh.pythonApi", "mesh.pythonFamilyBatch", "mesh.saveReopen"], objectTypeCount: 31, pythonApiCount: 211, guiDependency: true, formatExtensions: [".3mf", ".amf", ".ast", ".obj", ".off", ".ply", ".stl"] }, + { module: "MeshPart", workers: ["meshpart.worker.ts"], primaryWorker: "meshpart.worker.ts", commands: ["meshpart.createRecompute", "meshpart.inspectSourceInventory", "meshpart.pythonApi", "meshpart.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 13, guiDependency: true, formatExtensions: [] }, + { module: "Part", workers: ["part-save.worker.ts", "part.worker.ts"], primaryWorker: "part.worker.ts", commands: ["part.createRecompute", "part.document", "part.documentViewCommand", "part.importExport", "part.inspectSourceInventory", "part.pythonApi", "part.pythonFamilyBatch", "part.pythonMethod", "part.saveReopen", "part.viewCommand"], objectTypeCount: 116, pythonApiCount: 1191, guiDependency: true, formatExtensions: [".brep", ".brp", ".fcstd", ".iges", ".igs", ".obj", ".step", ".stp", ".svg"] }, + { module: "PartDesign", workers: ["partdesign-inspect.worker.ts", "partdesign-python.worker.ts", "partdesign-save.worker.ts", "partdesign.worker.ts"], primaryWorker: "partdesign.worker.ts", commands: ["PartDesign_AdditiveHelix", "PartDesign_AdditiveLoft", "PartDesign_AdditivePipe", "PartDesign_Body", "PartDesign_Boolean", "PartDesign_Chamfer", "PartDesign_Clone", "PartDesign_CompDatums", "PartDesign_CompPrimitiveAdditive", "PartDesign_CompPrimitiveSubtractive", "PartDesign_CompSketches", "PartDesign_CoordinateSystem", "PartDesign_Draft", "PartDesign_DuplicateSelection", "PartDesign_Fillet", "PartDesign_Groove", "PartDesign_Hole", "PartDesign_InvoluteGear", "PartDesign_Line", "PartDesign_LinearPattern", "PartDesign_Migrate", "PartDesign_Mirrored", "PartDesign_MoveFeature", "PartDesign_MoveFeatureInTree", "PartDesign_MoveTip", "PartDesign_MultiTransform", "PartDesign_NewSketch", "PartDesign_Pad", "PartDesign_Plane", "PartDesign_Pocket", "PartDesign_Point", "PartDesign_PolarPattern", "PartDesign_Revolution", "PartDesign_Scaled", "PartDesign_ShapeBinder", "PartDesign_Sprocket", "PartDesign_SubShapeBinder", "PartDesign_SubtractiveHelix", "PartDesign_SubtractiveLoft", "PartDesign_SubtractivePipe", "PartDesign_Thickness", "Sketcher_EditSketch", "Sketcher_MapSketch", "partdesign.createRecompute", "partdesign.document", "partdesign.geometryFamily", "partdesign.inspectSourceInventory", "partdesign.pythonApi", "partdesign.pythonFamilyBatch", "partdesign.saveReopen"], objectTypeCount: 65, pythonApiCount: 238, guiDependency: true, formatExtensions: [] }, + { module: "Plot", workers: ["plot-python.worker.ts"], primaryWorker: "plot-python.worker.ts", commands: ["plot.pythonApi", "plot.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 28, guiDependency: false, formatExtensions: [] }, + { module: "Points", workers: ["points-persistence.worker.ts", "points.worker.ts"], primaryWorker: "points.worker.ts", commands: ["points.createRecompute", "points.desktopBatch", "points.document", "points.inspectSource", "points.pythonApi", "points.pythonFamilyBatch", "points.saveReopen"], objectTypeCount: 8, pythonApiCount: 12, guiDependency: true, formatExtensions: [".obj", ".ply"] }, + { module: "ReverseEngineering", workers: ["reverseengineering-create.worker.ts", "reverseengineering-inspect.worker.ts", "reverseengineering-python.worker.ts", "reverseengineering-save.worker.ts"], primaryWorker: "reverseengineering-create.worker.ts", commands: ["reverseengineering.createRecompute", "reverseengineering.inspectSourceInventory", "reverseengineering.pythonApi", "reverseengineering.pythonFamilyBatch", "reverseengineering.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] }, + { module: "Robot", workers: ["robot-create.worker.ts", "robot-inspect.worker.ts", "robot-python.worker.ts", "robot-save.worker.ts"], primaryWorker: "robot-create.worker.ts", commands: ["robot.createRecompute", "robot.inspectSourceInventory", "robot.pythonApi", "robot.pythonFamilyBatch", "robot.saveReopen"], objectTypeCount: 6, pythonApiCount: 16, guiDependency: true, formatExtensions: [] }, + { module: "Sandbox", workers: ["sandbox-inspect.worker.ts", "sandbox-python.worker.ts", "sandbox-save.worker.ts", "sandbox.worker.ts"], primaryWorker: "sandbox-inspect.worker.ts", commands: ["sandbox.createRecompute", "sandbox.inspectSourceInventory", "sandbox.pythonApi", "sandbox.pythonFamilyBatch", "sandbox.saveReopen"], objectTypeCount: 2, pythonApiCount: 30, guiDependency: true, formatExtensions: [".ast", ".obj", ".stl"] }, + { module: "Show", workers: ["show-inspect.worker.ts", "show-python.worker.ts"], primaryWorker: "show-inspect.worker.ts", commands: ["show.clipping", "show.documentLifecycle", "show.inspectSourceInventory", "show.pythonApi", "show.pythonFamilyBatch", "show.visibility"], objectTypeCount: 0, pythonApiCount: 104, guiDependency: false, formatExtensions: [] }, + { module: "Sketcher", workers: ["sketcher-inspect.worker.ts", "sketcher-persistence.worker.ts", "sketcher-python.worker.ts", "sketcher.worker.ts"], primaryWorker: "sketcher.worker.ts", commands: ["sketcher.createRecompute", "sketcher.inspectSourceInventory", "sketcher.pythonApi", "sketcher.pythonFamilyBatch", "sketcher.pythonMethod", "sketcher.saveReopen"], objectTypeCount: 10, pythonApiCount: 141, guiDependency: true, formatExtensions: [] }, + { module: "Spreadsheet", workers: ["spreadsheet-inspect.worker.ts", "spreadsheet-python.worker.ts", "spreadsheet-save.worker.ts", "spreadsheet.worker.ts"], primaryWorker: "spreadsheet-inspect.worker.ts", commands: ["spreadsheet.createRecompute", "spreadsheet.importExportCsv", "spreadsheet.inspectSourceInventory", "spreadsheet.pythonApi", "spreadsheet.pythonFamilyBatch", "spreadsheet.saveReopen"], objectTypeCount: 5, pythonApiCount: 63, guiDependency: true, formatExtensions: [".csv"] }, + { module: "Start", workers: ["start-inventory.worker.ts", "start-python.worker.ts", "start.worker.ts"], primaryWorker: "start-inventory.worker.ts", commands: ["Start:desktop:Start_Start", "start.importSvg", "start.inspectSourceInventory", "start.moduleImport", "start.pythonApi"], objectTypeCount: 0, pythonApiCount: 2, guiDependency: true, formatExtensions: [".fcstd", ".svg"] }, + { module: "Surface", workers: ["surface-inspect.worker.ts", "surface-python.worker.ts", "surface-save.worker.ts", "surface.worker.ts"], primaryWorker: "surface-inspect.worker.ts", commands: ["surface.createRecompute", "surface.desktopCommand", "surface.inspectSourceInventory", "surface.objectContractBatch", "surface.pythonApi", "surface.pythonFamilyBatch", "surface.saveReopen"], objectTypeCount: 7, pythonApiCount: 10, guiDependency: true, formatExtensions: [] }, + { module: "TechDraw", workers: ["techdraw-inspect.worker.ts", "techdraw-native.worker.ts", "techdraw-python.worker.ts", "techdraw-save.worker.ts", "techdraw.worker.ts"], primaryWorker: "techdraw-native.worker.ts", commands: ["techdraw.createRecompute", "techdraw.desktopCommand", "techdraw.nativeImportExport", "techdraw.nativeInventory", "techdraw.nativeSaveReopen", "techdraw.pythonApi", "techdraw.pythonFamilyBatch", "techdraw.pythonMethod"], objectTypeCount: 41, pythonApiCount: 247, guiDependency: true, formatExtensions: [".dxf", ".svg"] }, + { module: "TemplatePyMod", workers: ["templatepymod-python.worker.ts", "templatepymod.worker.ts"], primaryWorker: "templatepymod-python.worker.ts", commands: ["templatepymod.inspectSourceInventory", "templatepymod.pythonApi", "templatepymod.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 244, guiDependency: false, formatExtensions: [] }, + { module: "Test", workers: ["test.worker.ts"], primaryWorker: "test.worker.ts", commands: ["test.inspectRegistry"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: true, formatExtensions: [".fcstd", ".obj"] }, + { module: "Tux", workers: ["tux.worker.ts"], primaryWorker: "tux.worker.ts", commands: ["tux.navigationBoundary"], objectTypeCount: 0, pythonApiCount: 25, guiDependency: false, formatExtensions: [] }, + { module: "Web", workers: ["stateful-family.worker.ts", "web-dock-overlay.worker.ts", "web-persistence.worker.ts", "web.worker.ts"], primaryWorker: "stateful-family.worker.ts", commands: ["web.dockOverlay", "web.saveReopenBoundary", "web.serverContract", "web.statefulFamilyBatch"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: false, formatExtensions: [] }, +] as const satisfies readonly WebModuleRoute[]; + +const ROUTES: ReadonlyMap = new Map(WEB_MODULE_REGISTRY.map((route) => [route.module, route])); + +export function getWebModuleRoute(module: string): WebModuleRoute | undefined { + return ROUTES.get(module); +} + +export function listWebModuleCommands(module?: string): string[] { + if (module) return [...(ROUTES.get(module)?.commands ?? [])]; + return WEB_MODULE_REGISTRY.flatMap((route) => route.commands); +} diff --git a/web/src/module-registry.generated.ts b/web/src/module-registry.generated.ts new file mode 100644 index 00000000..fe447dcc --- /dev/null +++ b/web/src/module-registry.generated.ts @@ -0,0 +1,341 @@ +/* Generated by tools/generate_web_module_registry.py. */ +import { artifactForWorker, createDynamicModuleWorker, type WebModuleArtifact } from "./module-loader.js"; +import workerEntry0 from "./assembly.worker.ts?worker&url"; +import workerEntry1 from "./bim.worker.ts?worker&url"; +import workerEntry2 from "./cam.worker.ts?worker&url"; +import workerEntry3 from "./cloud.worker.ts?worker&url"; +import workerEntry4 from "./draft.worker.ts?worker&url"; +import workerEntry5 from "./fem.worker.ts?worker&url"; +import workerEntry6 from "./help.worker.ts?worker&url"; +import workerEntry7 from "./import.worker.ts?worker&url"; +import workerEntry8 from "./inspection.worker.ts?worker&url"; +import workerEntry9 from "./jtreader.worker.ts?worker&url"; +import workerEntry10 from "./material-python.worker.ts?worker&url"; +import workerEntry11 from "./material.worker.ts?worker&url"; +import workerEntry12 from "./measure.worker.ts?worker&url"; +import workerEntry13 from "./mesh.worker.ts?worker&url"; +import workerEntry14 from "./meshpart.worker.ts?worker&url"; +import workerEntry15 from "./part-save.worker.ts?worker&url"; +import workerEntry16 from "./part.worker.ts?worker&url"; +import workerEntry17 from "./partdesign-inspect.worker.ts?worker&url"; +import workerEntry18 from "./partdesign-python.worker.ts?worker&url"; +import workerEntry19 from "./partdesign-save.worker.ts?worker&url"; +import workerEntry20 from "./partdesign.worker.ts?worker&url"; +import workerEntry21 from "./plot-python.worker.ts?worker&url"; +import workerEntry22 from "./points-persistence.worker.ts?worker&url"; +import workerEntry23 from "./points.worker.ts?worker&url"; +import workerEntry24 from "./reverseengineering-create.worker.ts?worker&url"; +import workerEntry25 from "./reverseengineering-inspect.worker.ts?worker&url"; +import workerEntry26 from "./reverseengineering-python.worker.ts?worker&url"; +import workerEntry27 from "./reverseengineering-save.worker.ts?worker&url"; +import workerEntry28 from "./robot-create.worker.ts?worker&url"; +import workerEntry29 from "./robot-inspect.worker.ts?worker&url"; +import workerEntry30 from "./robot-python.worker.ts?worker&url"; +import workerEntry31 from "./robot-save.worker.ts?worker&url"; +import workerEntry32 from "./sandbox-inspect.worker.ts?worker&url"; +import workerEntry33 from "./sandbox-python.worker.ts?worker&url"; +import workerEntry34 from "./sandbox-save.worker.ts?worker&url"; +import workerEntry35 from "./sandbox.worker.ts?worker&url"; +import workerEntry36 from "./show-inspect.worker.ts?worker&url"; +import workerEntry37 from "./show-python.worker.ts?worker&url"; +import workerEntry38 from "./sketcher-inspect.worker.ts?worker&url"; +import workerEntry39 from "./sketcher-persistence.worker.ts?worker&url"; +import workerEntry40 from "./sketcher-python.worker.ts?worker&url"; +import workerEntry41 from "./sketcher.worker.ts?worker&url"; +import workerEntry42 from "./spreadsheet-inspect.worker.ts?worker&url"; +import workerEntry43 from "./spreadsheet-python.worker.ts?worker&url"; +import workerEntry44 from "./spreadsheet-save.worker.ts?worker&url"; +import workerEntry45 from "./spreadsheet.worker.ts?worker&url"; +import workerEntry46 from "./start-inventory.worker.ts?worker&url"; +import workerEntry47 from "./start-python.worker.ts?worker&url"; +import workerEntry48 from "./start.worker.ts?worker&url"; +import workerEntry49 from "./surface-inspect.worker.ts?worker&url"; +import workerEntry50 from "./surface-python.worker.ts?worker&url"; +import workerEntry51 from "./surface-save.worker.ts?worker&url"; +import workerEntry52 from "./surface.worker.ts?worker&url"; +import workerEntry53 from "./techdraw-inspect.worker.ts?worker&url"; +import workerEntry54 from "./techdraw-native.worker.ts?worker&url"; +import workerEntry55 from "./techdraw-python.worker.ts?worker&url"; +import workerEntry56 from "./techdraw-save.worker.ts?worker&url"; +import workerEntry57 from "./techdraw.worker.ts?worker&url"; +import workerEntry58 from "./templatepymod-python.worker.ts?worker&url"; +import workerEntry59 from "./templatepymod.worker.ts?worker&url"; +import workerEntry60 from "./test.worker.ts?worker&url"; +import workerEntry61 from "./tux.worker.ts?worker&url"; +import workerEntry62 from "./web-dock-overlay.worker.ts?worker&url"; +import workerEntry63 from "./web-persistence.worker.ts?worker&url"; +import workerEntry64 from "./web.worker.ts?worker&url"; + +export const WEB_MODULE_REGISTRY_SCHEMA = "freecad-web-module-registry/v1" as const; + +export interface WebModuleRoute { + readonly module: string; + readonly workers: readonly string[]; + readonly primaryWorker: string | null; + readonly commands: readonly string[]; + readonly objectTypeCount: number; + readonly pythonApiCount: number; + readonly guiDependency: boolean; + readonly formatExtensions: readonly string[]; +} + +export const WEB_MODULE_REGISTRY = [ + { module: "Assembly", workers: ["assembly.worker.ts"], primaryWorker: "assembly.worker.ts", commands: ["assembly.createRecompute", "assembly.inspectPythonApi", "assembly.inspectSourceInventory", "assembly.nativeTypeProbe", "assembly.pythonFamily", "assembly.saveReopen", "assembly.testCore"], objectTypeCount: 8, pythonApiCount: 552, guiDependency: true, formatExtensions: [".fcstd"] }, + { module: "BIM", workers: ["bim.worker.ts"], primaryWorker: "bim.worker.ts", commands: ["bim.create2DViews", "bim.createAxis", "bim.document", "bim.extrusionData", "bim.inspectPythonApi", "bim.inspectSourceInventory", "bim.nativeProbe", "bim.pythonFamily", "bim.pythonFamilyBatch", "bim.testArchAxis", "bim.testArchBatch", "bim.testArchBuildingPart", "bim.testArchBuildingPartGui", "bim.testArchComponent", "bim.testArchCurtainWall", "bim.testArchEquipment", "bim.testArchFence", "bim.testArchFrame", "bim.testArchGrid", "bim.testArchImporters", "bim.testArchMaterial", "bim.testArchPanel", "bim.testArchPipe", "bim.testArchProfile", "bim.testArchProject", "bim.testArchRebar", "bim.testArchReference", "bim.testArchReport", "bim.testArchReportGui", "bim.testArchSiteGui", "bim.testArchWallGui", "bim.testWebGLExportGui"], objectTypeCount: 0, pythonApiCount: 2366, guiDependency: false, formatExtensions: [".brp", ".dae", ".dxf", ".fcstd", ".ifc", ".json", ".obj", ".stp", ".svg"] }, + { module: "CAM", workers: ["cam.worker.ts"], primaryWorker: "cam.worker.ts", commands: ["cam.createRecompute", "cam.export", "cam.import", "cam.inspectPythonApi", "cam.inspectSourceInventory", "cam.pythonFamilyBatch", "cam.saveReopen", "cam.testCentroidLegacyPost", "cam.testCentroidPost", "cam.testDressupPost", "cam.testDrillCycleExpander", "cam.testFanucPost", "cam.testGcodeProcessingUtils", "cam.testGenericPlasma", "cam.testGenericPost", "cam.testGrblLegacyPost", "cam.testGrblPost", "cam.testLinkingGenerator", "cam.testLinuxCNCLegacyPost", "cam.testLinuxCNCPost", "cam.testMach3Mach4LegacyPost", "cam.testMach3Mach4Post", "cam.testMachine", "cam.testMassoG3Post", "cam.testMaterial", "cam.testPathAdaptive", "cam.testPathCommandAnnotations", "cam.testPathCore", "cam.testPathDepthParams", "cam.testPathDressupArray", "cam.testPathDressupDogboneII", "cam.testPathDressupHoldingTags", "cam.testPathDrillGenerator", "cam.testPathDrillable", "cam.testPathFacingGenerator", "cam.testPathGeneratorDogboneII", "cam.testPathGeom", "cam.testPathHelix", "cam.testPathHelixGenerator", "cam.testPathHelpers", "cam.testPathLanguage", "cam.testPathLog", "cam.testPathOpDeburr", "cam.testPathOpUtil", "cam.testPathPreferences", "cam.testPathProfile", "cam.testPathPropertyBag", "cam.testPathRotationGenerator", "cam.testPathSetupSheet", "cam.testPathSpiralGenerator", "cam.testPathStock", "cam.testPathTapGenerator", "cam.testPathThreadMilling", "cam.testPathThreadMillingGenerator", "cam.testPathToolAsset", "cam.testPathToolAssetCache", "cam.testPathToolAssetManager", "cam.testPathToolAssetStore", "cam.testPathToolAssetUri", "cam.testPathToolBit", "cam.testPathToolBitSerializer", "cam.testPathToolChangeGenerator", "cam.testPathToolController", "cam.testPathToolLibrary", "cam.testPathToolLibrarySerializer", "cam.testPathToolShapeClasses", "cam.testPathToolShapeDoc", "cam.testPathUtil", "cam.testPathVcarve", "cam.testPathVoronoi", "cam.testPostCore", "cam.testPostGCodes", "cam.testPostMCodes", "cam.testSanity", "cam.testSnapmakerPost", "cam.testTSPSolver", "cam.testTestPost"], objectTypeCount: 12, pythonApiCount: 2883, guiDependency: true, formatExtensions: [".fcstd", ".json", ".obj", ".step", ".svg"] }, + { module: "Cloud", workers: ["cloud.worker.ts"], primaryWorker: "cloud.worker.ts", commands: ["cloud.configureRecompute", "cloud.inspectPythonApi", "cloud.inspectSourceInventory", "cloud.pythonFamilyBatch", "cloud.restore", "cloud.save", "cloud.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] }, + { module: "Draft", workers: ["draft.worker.ts"], primaryWorker: "draft.worker.ts", commands: ["draft.action", "draft.formatBatch", "draft.pythonFamilyBatch", "draft.testOfficialSuite"], objectTypeCount: 0, pythonApiCount: 2043, guiDependency: false, formatExtensions: [".dxf", ".obj", ".svg"] }, + { module: "Fem", workers: ["fem.worker.ts"], primaryWorker: "fem.worker.ts", commands: ["fem.action", "fem.brep", "fem.document", "fem.nativeProbe", "fem.pythonFamilyBatch"], objectTypeCount: 53, pythonApiCount: 1305, guiDependency: true, formatExtensions: [".brep", ".json", ".obj", ".svg", ".txt"] }, + { module: "Help", workers: ["help.worker.ts"], primaryWorker: "help.worker.ts", commands: ["help.inspectSourceInventory", "help.pythonApi"], objectTypeCount: 0, pythonApiCount: 14, guiDependency: false, formatExtensions: [] }, + { module: "Import", workers: ["import.worker.ts"], primaryWorker: "import.worker.ts", commands: ["import.createRecompute", "import.inspectSourceInventory", "import.pythonApi", "import.pythonFamilyBatch", "import.saveReopen", "import.step"], objectTypeCount: 2, pythonApiCount: 1135, guiDependency: true, formatExtensions: [".ifc", ".igs", ".obj", ".step", ".stp"] }, + { module: "Inspection", workers: ["inspection.worker.ts"], primaryWorker: "inspection.worker.ts", commands: ["inspection.createRecompute", "inspection.inspectPythonApi", "inspection.inspectSourceInventory", "inspection.pythonFamilyBatch", "inspection.saveReopen"], objectTypeCount: 3, pythonApiCount: 3, guiDependency: true, formatExtensions: [] }, + { module: "JtReader", workers: ["jtreader.worker.ts"], primaryWorker: "jtreader.worker.ts", commands: ["jtreader.createRecompute", "jtreader.document", "jtreader.inspectSourceInventory", "jtreader.saveReopen"], objectTypeCount: 1, pythonApiCount: 0, guiDependency: false, formatExtensions: [".fcstd", ".jt"] }, + { module: "Material", workers: ["material-python.worker.ts", "material.worker.ts"], primaryWorker: "material-python.worker.ts", commands: ["material.createRecompute", "material.inspectSourceInventory", "material.pythonApi", "material.pythonFamilyBatch", "material.saveReopen"], objectTypeCount: 22, pythonApiCount: 178, guiDependency: true, formatExtensions: [] }, + { module: "Measure", workers: ["measure.worker.ts"], primaryWorker: "measure.worker.ts", commands: ["measure.createRecompute", "measure.inspectSourceInventory", "measure.measurementApi", "measure.objectFamily", "measure.pythonApi", "measure.pythonFamilyBatch", "measure.saveReopen"], objectTypeCount: 11, pythonApiCount: 31, guiDependency: true, formatExtensions: [] }, + { module: "Mesh", workers: ["mesh.worker.ts"], primaryWorker: "mesh.worker.ts", commands: ["mesh.createRecompute", "mesh.importExport", "mesh.inspectSourceInventory", "mesh.pythonApi", "mesh.pythonFamilyBatch", "mesh.saveReopen"], objectTypeCount: 31, pythonApiCount: 211, guiDependency: true, formatExtensions: [".3mf", ".amf", ".ast", ".obj", ".off", ".ply", ".stl"] }, + { module: "MeshPart", workers: ["meshpart.worker.ts"], primaryWorker: "meshpart.worker.ts", commands: ["meshpart.createRecompute", "meshpart.inspectSourceInventory", "meshpart.pythonApi", "meshpart.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 13, guiDependency: true, formatExtensions: [] }, + { module: "Part", workers: ["part-save.worker.ts", "part.worker.ts"], primaryWorker: "part.worker.ts", commands: ["part.createRecompute", "part.document", "part.documentViewCommand", "part.importExport", "part.inspectSourceInventory", "part.pythonApi", "part.pythonFamilyBatch", "part.pythonMethod", "part.saveReopen", "part.viewCommand"], objectTypeCount: 116, pythonApiCount: 1191, guiDependency: true, formatExtensions: [".brep", ".brp", ".fcstd", ".iges", ".igs", ".obj", ".step", ".stp", ".svg"] }, + { module: "PartDesign", workers: ["partdesign-inspect.worker.ts", "partdesign-python.worker.ts", "partdesign-save.worker.ts", "partdesign.worker.ts"], primaryWorker: "partdesign.worker.ts", commands: ["PartDesign_AdditiveHelix", "PartDesign_AdditiveLoft", "PartDesign_AdditivePipe", "PartDesign_Body", "PartDesign_Boolean", "PartDesign_Chamfer", "PartDesign_Clone", "PartDesign_CompDatums", "PartDesign_CompPrimitiveAdditive", "PartDesign_CompPrimitiveSubtractive", "PartDesign_CompSketches", "PartDesign_CoordinateSystem", "PartDesign_Draft", "PartDesign_DuplicateSelection", "PartDesign_Fillet", "PartDesign_Groove", "PartDesign_Hole", "PartDesign_InvoluteGear", "PartDesign_Line", "PartDesign_LinearPattern", "PartDesign_Migrate", "PartDesign_Mirrored", "PartDesign_MoveFeature", "PartDesign_MoveFeatureInTree", "PartDesign_MoveTip", "PartDesign_MultiTransform", "PartDesign_NewSketch", "PartDesign_Pad", "PartDesign_Plane", "PartDesign_Pocket", "PartDesign_Point", "PartDesign_PolarPattern", "PartDesign_Revolution", "PartDesign_Scaled", "PartDesign_ShapeBinder", "PartDesign_Sprocket", "PartDesign_SubShapeBinder", "PartDesign_SubtractiveHelix", "PartDesign_SubtractiveLoft", "PartDesign_SubtractivePipe", "PartDesign_Thickness", "Sketcher_EditSketch", "Sketcher_MapSketch", "partdesign.createRecompute", "partdesign.document", "partdesign.geometryFamily", "partdesign.inspectSourceInventory", "partdesign.pythonApi", "partdesign.pythonFamilyBatch", "partdesign.saveReopen"], objectTypeCount: 65, pythonApiCount: 238, guiDependency: true, formatExtensions: [] }, + { module: "Plot", workers: ["plot-python.worker.ts"], primaryWorker: "plot-python.worker.ts", commands: ["plot.pythonApi", "plot.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 28, guiDependency: false, formatExtensions: [] }, + { module: "Points", workers: ["points-persistence.worker.ts", "points.worker.ts"], primaryWorker: "points.worker.ts", commands: ["points.createRecompute", "points.desktopBatch", "points.document", "points.inspectSource", "points.pythonApi", "points.pythonFamilyBatch", "points.saveReopen"], objectTypeCount: 8, pythonApiCount: 12, guiDependency: true, formatExtensions: [".obj", ".ply"] }, + { module: "ReverseEngineering", workers: ["reverseengineering-create.worker.ts", "reverseengineering-inspect.worker.ts", "reverseengineering-python.worker.ts", "reverseengineering-save.worker.ts"], primaryWorker: "reverseengineering-create.worker.ts", commands: ["reverseengineering.createRecompute", "reverseengineering.inspectSourceInventory", "reverseengineering.pythonApi", "reverseengineering.pythonFamilyBatch", "reverseengineering.saveReopen"], objectTypeCount: 0, pythonApiCount: 3, guiDependency: true, formatExtensions: [] }, + { module: "Robot", workers: ["robot-create.worker.ts", "robot-inspect.worker.ts", "robot-python.worker.ts", "robot-save.worker.ts"], primaryWorker: "robot-create.worker.ts", commands: ["robot.createRecompute", "robot.inspectSourceInventory", "robot.pythonApi", "robot.pythonFamilyBatch", "robot.saveReopen"], objectTypeCount: 6, pythonApiCount: 16, guiDependency: true, formatExtensions: [] }, + { module: "Sandbox", workers: ["sandbox-inspect.worker.ts", "sandbox-python.worker.ts", "sandbox-save.worker.ts", "sandbox.worker.ts"], primaryWorker: "sandbox-inspect.worker.ts", commands: ["sandbox.createRecompute", "sandbox.inspectSourceInventory", "sandbox.pythonApi", "sandbox.pythonFamilyBatch", "sandbox.saveReopen"], objectTypeCount: 2, pythonApiCount: 30, guiDependency: true, formatExtensions: [".ast", ".obj", ".stl"] }, + { module: "Show", workers: ["show-inspect.worker.ts", "show-python.worker.ts"], primaryWorker: "show-inspect.worker.ts", commands: ["show.clipping", "show.documentLifecycle", "show.inspectSourceInventory", "show.pythonApi", "show.pythonFamilyBatch", "show.visibility"], objectTypeCount: 0, pythonApiCount: 104, guiDependency: false, formatExtensions: [] }, + { module: "Sketcher", workers: ["sketcher-inspect.worker.ts", "sketcher-persistence.worker.ts", "sketcher-python.worker.ts", "sketcher.worker.ts"], primaryWorker: "sketcher.worker.ts", commands: ["sketcher.createRecompute", "sketcher.inspectSourceInventory", "sketcher.pythonApi", "sketcher.pythonFamilyBatch", "sketcher.pythonMethod", "sketcher.saveReopen"], objectTypeCount: 10, pythonApiCount: 141, guiDependency: true, formatExtensions: [] }, + { module: "Spreadsheet", workers: ["spreadsheet-inspect.worker.ts", "spreadsheet-python.worker.ts", "spreadsheet-save.worker.ts", "spreadsheet.worker.ts"], primaryWorker: "spreadsheet-inspect.worker.ts", commands: ["spreadsheet.createRecompute", "spreadsheet.importExportCsv", "spreadsheet.inspectSourceInventory", "spreadsheet.pythonApi", "spreadsheet.pythonFamilyBatch", "spreadsheet.saveReopen"], objectTypeCount: 5, pythonApiCount: 63, guiDependency: true, formatExtensions: [".csv"] }, + { module: "Start", workers: ["start-inventory.worker.ts", "start-python.worker.ts", "start.worker.ts"], primaryWorker: "start-inventory.worker.ts", commands: ["Start:desktop:Start_Start", "start.importSvg", "start.inspectSourceInventory", "start.moduleImport", "start.pythonApi"], objectTypeCount: 0, pythonApiCount: 2, guiDependency: true, formatExtensions: [".fcstd", ".svg"] }, + { module: "Surface", workers: ["surface-inspect.worker.ts", "surface-python.worker.ts", "surface-save.worker.ts", "surface.worker.ts"], primaryWorker: "surface-inspect.worker.ts", commands: ["surface.createRecompute", "surface.desktopCommand", "surface.inspectSourceInventory", "surface.objectContractBatch", "surface.pythonApi", "surface.pythonFamilyBatch", "surface.saveReopen"], objectTypeCount: 7, pythonApiCount: 10, guiDependency: true, formatExtensions: [] }, + { module: "TechDraw", workers: ["techdraw-inspect.worker.ts", "techdraw-native.worker.ts", "techdraw-python.worker.ts", "techdraw-save.worker.ts", "techdraw.worker.ts"], primaryWorker: "techdraw-native.worker.ts", commands: ["techdraw.createRecompute", "techdraw.desktopCommand", "techdraw.nativeImportExport", "techdraw.nativeInventory", "techdraw.nativeSaveReopen", "techdraw.pythonApi", "techdraw.pythonFamilyBatch", "techdraw.pythonMethod"], objectTypeCount: 41, pythonApiCount: 247, guiDependency: true, formatExtensions: [".dxf", ".svg"] }, + { module: "TemplatePyMod", workers: ["templatepymod-python.worker.ts", "templatepymod.worker.ts"], primaryWorker: "templatepymod-python.worker.ts", commands: ["templatepymod.inspectSourceInventory", "templatepymod.pythonApi", "templatepymod.pythonFamilyBatch"], objectTypeCount: 0, pythonApiCount: 244, guiDependency: false, formatExtensions: [] }, + { module: "Test", workers: ["test.worker.ts"], primaryWorker: "test.worker.ts", commands: ["test.inspectRegistry"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: true, formatExtensions: [".fcstd", ".obj"] }, + { module: "Tux", workers: ["tux.worker.ts"], primaryWorker: "tux.worker.ts", commands: ["tux.navigationBoundary"], objectTypeCount: 0, pythonApiCount: 25, guiDependency: false, formatExtensions: [] }, + { module: "Web", workers: ["stateful-family.worker.ts", "web-dock-overlay.worker.ts", "web-persistence.worker.ts", "web.worker.ts"], primaryWorker: "stateful-family.worker.ts", commands: ["web.dockOverlay", "web.saveReopenBoundary", "web.serverContract", "web.statefulFamilyBatch"], objectTypeCount: 0, pythonApiCount: 0, guiDependency: false, formatExtensions: [] }, +] as const satisfies readonly WebModuleRoute[]; + +const ROUTES: ReadonlyMap = new Map(WEB_MODULE_REGISTRY.map((route) => [route.module, route])); + +export function getWebModuleRoute(module: string): WebModuleRoute | undefined { + return ROUTES.get(module); +} + +export function listWebModuleCommands(module?: string): string[] { + if (module) return [...(ROUTES.get(module)?.commands ?? [])]; + return WEB_MODULE_REGISTRY.flatMap((route) => route.commands); +} + +export function createWebModuleWorker(module: string, workerFile?: string, artifact?: WebModuleArtifact): Worker | undefined { + const route = ROUTES.get(module); + const selectedWorker = workerFile ?? route?.primaryWorker; + if (!route || !selectedWorker) return undefined; + const entryUrl = (() => { switch (`${module}:${selectedWorker}`) { + case "Assembly:assembly.worker.ts": return new URL(workerEntry0, import.meta.url); + case "BIM:bim.worker.ts": return new URL(workerEntry1, import.meta.url); + case "CAM:cam.worker.ts": return new URL(workerEntry2, import.meta.url); + case "Cloud:cloud.worker.ts": return new URL(workerEntry3, import.meta.url); + case "Draft:draft.worker.ts": return new URL(workerEntry4, import.meta.url); + case "Fem:fem.worker.ts": return new URL(workerEntry5, import.meta.url); + case "Help:help.worker.ts": return new URL(workerEntry6, import.meta.url); + case "Import:import.worker.ts": return new URL(workerEntry7, import.meta.url); + case "Inspection:inspection.worker.ts": return new URL(workerEntry8, import.meta.url); + case "JtReader:jtreader.worker.ts": return new URL(workerEntry9, import.meta.url); + case "Material:material-python.worker.ts": return new URL(workerEntry10, import.meta.url); + case "Material:material.worker.ts": return new URL(workerEntry11, import.meta.url); + case "Measure:measure.worker.ts": return new URL(workerEntry12, import.meta.url); + case "Mesh:mesh.worker.ts": return new URL(workerEntry13, import.meta.url); + case "MeshPart:meshpart.worker.ts": return new URL(workerEntry14, import.meta.url); + case "Part:part-save.worker.ts": return new URL(workerEntry15, import.meta.url); + case "Part:part.worker.ts": return new URL(workerEntry16, import.meta.url); + case "PartDesign:partdesign-inspect.worker.ts": return new URL(workerEntry17, import.meta.url); + case "PartDesign:partdesign-python.worker.ts": return new URL(workerEntry18, import.meta.url); + case "PartDesign:partdesign-save.worker.ts": return new URL(workerEntry19, import.meta.url); + case "PartDesign:partdesign.worker.ts": return new URL(workerEntry20, import.meta.url); + case "Plot:plot-python.worker.ts": return new URL(workerEntry21, import.meta.url); + case "Points:points-persistence.worker.ts": return new URL(workerEntry22, import.meta.url); + case "Points:points.worker.ts": return new URL(workerEntry23, import.meta.url); + case "ReverseEngineering:reverseengineering-create.worker.ts": return new URL(workerEntry24, import.meta.url); + case "ReverseEngineering:reverseengineering-inspect.worker.ts": return new URL(workerEntry25, import.meta.url); + case "ReverseEngineering:reverseengineering-python.worker.ts": return new URL(workerEntry26, import.meta.url); + case "ReverseEngineering:reverseengineering-save.worker.ts": return new URL(workerEntry27, import.meta.url); + case "Robot:robot-create.worker.ts": return new URL(workerEntry28, import.meta.url); + case "Robot:robot-inspect.worker.ts": return new URL(workerEntry29, import.meta.url); + case "Robot:robot-python.worker.ts": return new URL(workerEntry30, import.meta.url); + case "Robot:robot-save.worker.ts": return new URL(workerEntry31, import.meta.url); + case "Sandbox:sandbox-inspect.worker.ts": return new URL(workerEntry32, import.meta.url); + case "Sandbox:sandbox-python.worker.ts": return new URL(workerEntry33, import.meta.url); + case "Sandbox:sandbox-save.worker.ts": return new URL(workerEntry34, import.meta.url); + case "Sandbox:sandbox.worker.ts": return new URL(workerEntry35, import.meta.url); + case "Show:show-inspect.worker.ts": return new URL(workerEntry36, import.meta.url); + case "Show:show-python.worker.ts": return new URL(workerEntry37, import.meta.url); + case "Sketcher:sketcher-inspect.worker.ts": return new URL(workerEntry38, import.meta.url); + case "Sketcher:sketcher-persistence.worker.ts": return new URL(workerEntry39, import.meta.url); + case "Sketcher:sketcher-python.worker.ts": return new URL(workerEntry40, import.meta.url); + case "Sketcher:sketcher.worker.ts": return new URL(workerEntry41, import.meta.url); + case "Spreadsheet:spreadsheet-inspect.worker.ts": return new URL(workerEntry42, import.meta.url); + case "Spreadsheet:spreadsheet-python.worker.ts": return new URL(workerEntry43, import.meta.url); + case "Spreadsheet:spreadsheet-save.worker.ts": return new URL(workerEntry44, import.meta.url); + case "Spreadsheet:spreadsheet.worker.ts": return new URL(workerEntry45, import.meta.url); + case "Start:start-inventory.worker.ts": return new URL(workerEntry46, import.meta.url); + case "Start:start-python.worker.ts": return new URL(workerEntry47, import.meta.url); + case "Start:start.worker.ts": return new URL(workerEntry48, import.meta.url); + case "Surface:surface-inspect.worker.ts": return new URL(workerEntry49, import.meta.url); + case "Surface:surface-python.worker.ts": return new URL(workerEntry50, import.meta.url); + case "Surface:surface-save.worker.ts": return new URL(workerEntry51, import.meta.url); + case "Surface:surface.worker.ts": return new URL(workerEntry52, import.meta.url); + case "TechDraw:techdraw-inspect.worker.ts": return new URL(workerEntry53, import.meta.url); + case "TechDraw:techdraw-native.worker.ts": return new URL(workerEntry54, import.meta.url); + case "TechDraw:techdraw-python.worker.ts": return new URL(workerEntry55, import.meta.url); + case "TechDraw:techdraw-save.worker.ts": return new URL(workerEntry56, import.meta.url); + case "TechDraw:techdraw.worker.ts": return new URL(workerEntry57, import.meta.url); + case "TemplatePyMod:templatepymod-python.worker.ts": return new URL(workerEntry58, import.meta.url); + case "TemplatePyMod:templatepymod.worker.ts": return new URL(workerEntry59, import.meta.url); + case "Test:test.worker.ts": return new URL(workerEntry60, import.meta.url); + case "Tux:tux.worker.ts": return new URL(workerEntry61, import.meta.url); + case "Web:web-dock-overlay.worker.ts": return new URL(workerEntry62, import.meta.url); + case "Web:web-persistence.worker.ts": return new URL(workerEntry63, import.meta.url); + case "Web:web.worker.ts": return new URL(workerEntry64, import.meta.url); + default: return undefined; + } })(); + return entryUrl ? createDynamicModuleWorker(entryUrl, artifactForWorker(artifact, selectedWorker)) : undefined; +} + +export function getWebModuleWorkerForCommand(module: string, command: string): string | undefined { + const route = ROUTES.get(module); + if (!route) return undefined; + switch (`${module}:${command}`) { + case "Assembly:assembly.nativeTypeProbe": return "assembly.worker.ts"; + case "Assembly:assembly.saveReopen": return "assembly.worker.ts"; + case "BIM:bim.createAxis": return "bim.worker.ts"; + case "BIM:bim.extrusionData": return "bim.worker.ts"; + case "CAM:cam.pythonFamilyBatch": return "cam.worker.ts"; + case "CAM:cam.saveReopen": return "cam.worker.ts"; + case "Cloud:cloud.pythonFamilyBatch": return "cloud.worker.ts"; + case "Cloud:cloud.saveReopen": return "cloud.worker.ts"; + case "Draft:draft.pythonFamilyBatch": return "draft.worker.ts"; + case "Fem:fem.pythonFamilyBatch": return "fem.worker.ts"; + case "Import:import.pythonFamilyBatch": return "import.worker.ts"; + case "Import:import.saveReopen": return "import.worker.ts"; + case "Inspection:inspection.pythonFamilyBatch": return "inspection.worker.ts"; + case "Inspection:inspection.saveReopen": return "inspection.worker.ts"; + case "JtReader:jtreader.saveReopen": return "jtreader.worker.ts"; + case "Material:material.pythonApi": return "material.worker.ts"; + case "Material:material.pythonFamilyBatch": return "material.worker.ts"; + case "Material:material.saveReopen": return "material.worker.ts"; + case "Measure:measure.pythonFamilyBatch": return "measure.worker.ts"; + case "Measure:measure.saveReopen": return "measure.worker.ts"; + case "Mesh:mesh.pythonFamilyBatch": return "mesh.worker.ts"; + case "Mesh:mesh.saveReopen": return "mesh.worker.ts"; + case "MeshPart:meshpart.pythonFamilyBatch": return "meshpart.worker.ts"; + case "Part:part.document": return "part-save.worker.ts"; + case "Part:part.documentViewCommand": return "part-save.worker.ts"; + case "Part:part.saveReopen": return "part-save.worker.ts"; + case "Part:part.viewCommand": return "part.worker.ts"; + case "PartDesign:PartDesign_AdditiveHelix": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_AdditiveLoft": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_AdditivePipe": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Body": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Boolean": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Chamfer": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Clone": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_CompDatums": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_CompPrimitiveAdditive": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_CompPrimitiveSubtractive": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_CompSketches": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_CoordinateSystem": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Draft": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_DuplicateSelection": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Fillet": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Groove": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Hole": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_InvoluteGear": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Line": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_LinearPattern": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Migrate": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Mirrored": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_MoveFeature": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_MoveFeatureInTree": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_MoveTip": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_MultiTransform": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_NewSketch": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Pad": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Plane": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Pocket": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Point": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_PolarPattern": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Revolution": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Scaled": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_ShapeBinder": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Sprocket": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_SubShapeBinder": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_SubtractiveHelix": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_SubtractiveLoft": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_SubtractivePipe": return "partdesign-python.worker.ts"; + case "PartDesign:PartDesign_Thickness": return "partdesign-python.worker.ts"; + case "PartDesign:Sketcher_EditSketch": return "partdesign-python.worker.ts"; + case "PartDesign:Sketcher_MapSketch": return "partdesign-python.worker.ts"; + case "PartDesign:partdesign.geometryFamily": return "partdesign.worker.ts"; + case "PartDesign:partdesign.inspectSourceInventory": return "partdesign-inspect.worker.ts"; + case "PartDesign:partdesign.pythonApi": return "partdesign-python.worker.ts"; + case "PartDesign:partdesign.pythonFamilyBatch": return "partdesign-python.worker.ts"; + case "PartDesign:partdesign.saveReopen": return "partdesign.worker.ts"; + case "Plot:plot.pythonApi": return "plot-python.worker.ts"; + case "Points:points.createRecompute": return "points.worker.ts"; + case "Points:points.desktopBatch": return "points.worker.ts"; + case "Points:points.document": return "points.worker.ts"; + case "Points:points.inspectSource": return "points.worker.ts"; + case "Points:points.pythonApi": return "points.worker.ts"; + case "Points:points.saveReopen": return "points.worker.ts"; + case "ReverseEngineering:reverseengineering.createRecompute": return "reverseengineering-create.worker.ts"; + case "ReverseEngineering:reverseengineering.inspectSourceInventory": return "reverseengineering-inspect.worker.ts"; + case "ReverseEngineering:reverseengineering.pythonApi": return "reverseengineering-python.worker.ts"; + case "ReverseEngineering:reverseengineering.pythonFamilyBatch": return "reverseengineering-python.worker.ts"; + case "ReverseEngineering:reverseengineering.saveReopen": return "reverseengineering-save.worker.ts"; + case "Robot:robot.createRecompute": return "robot-create.worker.ts"; + case "Robot:robot.inspectSourceInventory": return "robot-inspect.worker.ts"; + case "Robot:robot.pythonApi": return "robot-python.worker.ts"; + case "Robot:robot.saveReopen": return "robot-save.worker.ts"; + case "Sandbox:sandbox.createRecompute": return "sandbox.worker.ts"; + case "Sandbox:sandbox.inspectSourceInventory": return "sandbox-inspect.worker.ts"; + case "Sandbox:sandbox.pythonApi": return "sandbox-python.worker.ts"; + case "Sandbox:sandbox.pythonFamilyBatch": return "sandbox-python.worker.ts"; + case "Sandbox:sandbox.saveReopen": return "sandbox.worker.ts"; + case "Show:show.clipping": return "show-python.worker.ts"; + case "Show:show.documentLifecycle": return "show-python.worker.ts"; + case "Show:show.inspectSourceInventory": return "show-inspect.worker.ts"; + case "Show:show.pythonApi": return "show-python.worker.ts"; + case "Show:show.pythonFamilyBatch": return "show-python.worker.ts"; + case "Show:show.visibility": return "show-python.worker.ts"; + case "Sketcher:sketcher.inspectSourceInventory": return "sketcher-inspect.worker.ts"; + case "Sketcher:sketcher.pythonApi": return "sketcher-python.worker.ts"; + case "Sketcher:sketcher.pythonFamilyBatch": return "sketcher-python.worker.ts"; + case "Sketcher:sketcher.pythonMethod": return "sketcher-python.worker.ts"; + case "Sketcher:sketcher.saveReopen": return "sketcher-python.worker.ts"; + case "Spreadsheet:spreadsheet.createRecompute": return "spreadsheet.worker.ts"; + case "Spreadsheet:spreadsheet.inspectSourceInventory": return "spreadsheet-inspect.worker.ts"; + case "Spreadsheet:spreadsheet.pythonApi": return "spreadsheet-python.worker.ts"; + case "Spreadsheet:spreadsheet.pythonFamilyBatch": return "spreadsheet-python.worker.ts"; + case "Spreadsheet:spreadsheet.saveReopen": return "spreadsheet-save.worker.ts"; + case "Start:Start:desktop:Start_Start": return "start.worker.ts"; + case "Start:start.importSvg": return "start.worker.ts"; + case "Start:start.inspectSourceInventory": return "start-inventory.worker.ts"; + case "Start:start.moduleImport": return "start.worker.ts"; + case "Start:start.pythonApi": return "start-python.worker.ts"; + case "Surface:surface.createRecompute": return "surface.worker.ts"; + case "Surface:surface.inspectSourceInventory": return "surface-inspect.worker.ts"; + case "Surface:surface.pythonApi": return "surface-python.worker.ts"; + case "Surface:surface.pythonFamilyBatch": return "surface-python.worker.ts"; + case "Surface:surface.saveReopen": return "surface-save.worker.ts"; + case "TechDraw:techdraw.createRecompute": return "techdraw-python.worker.ts"; + case "TechDraw:techdraw.desktopCommand": return "techdraw-python.worker.ts"; + case "TechDraw:techdraw.nativeInventory": return "techdraw-inspect.worker.ts"; + case "TechDraw:techdraw.nativeSaveReopen": return "techdraw-python.worker.ts"; + case "TechDraw:techdraw.pythonApi": return "techdraw-python.worker.ts"; + case "TechDraw:techdraw.pythonFamilyBatch": return "techdraw-python.worker.ts"; + case "TechDraw:techdraw.pythonMethod": return "techdraw-python.worker.ts"; + case "TemplatePyMod:templatepymod.pythonApi": return "templatepymod-python.worker.ts"; + case "Web:web.dockOverlay": return "web-dock-overlay.worker.ts"; + case "Web:web.saveReopenBoundary": return "web-persistence.worker.ts"; + case "Web:web.statefulFamilyBatch": return "stateful-family.worker.ts"; + default: return route.primaryWorker ?? undefined; + } +} diff --git a/web/src/module-router.ts b/web/src/module-router.ts new file mode 100644 index 00000000..62cb02b7 --- /dev/null +++ b/web/src/module-router.ts @@ -0,0 +1,352 @@ +import type { TestViewExampleResult } from "./test-facade.js"; +import { executeMeasureDocument } from "./measure-document-adapter.js"; +import { executeMeshPartCurve } from "./meshpart-desktop-adapter.js"; +import { executeSurfaceDocument } from "./surface-document-adapter.js"; +import { + createFailure, + createSuccess, + createCancel, + createRequest, + type FacadeFailure, + type FacadeRequest, + type FacadeResponse, +} from "./facade-envelope.js"; +import { createWebModuleWorker, getWebModuleRoute, getWebModuleWorkerForCommand, type WebModuleRoute } from "./module-registry.generated.js"; +import { loadWebModuleManifest, type WebModuleArtifact } from "./module-loader.js"; +import { ResourceLifecycle } from "./resource-lifecycle.js"; +import { nativeSourceDecision } from "./native-source-policy.js"; + +type WorkerReady = { kind: "ready"; action: string }; +type WorkerReset = { kind: "reset"; requestId: string }; +type WorkerBootstrapError = { kind: "bootstrap-error"; message: string }; +type WorkerMessage = FacadeResponse | WorkerReady | WorkerReset | WorkerBootstrapError; + +interface PendingRequest { + resolve: (response: FacadeResponse) => void; + reject: (error: Error) => void; + cleanup?: () => void; +} + +interface ModuleSession { + readonly route: WebModuleRoute; + readonly worker: Worker; + readonly ready: Promise; + readonly failReady: (error: Error) => void; + readonly pending: Map; + readonly artifactRevision?: string; +} + +/** Routes typed facade envelopes to the existing native module workers. */ +export class WebModuleRouter { + private readonly sessions = new Map(); + private readonly artifacts = new Map(); + private readonly lifecycle = new ResourceLifecycle(); + private sequence = 0; + readonly testSceneDocuments = new Map(); + // These documents remain in the Assembly Worker while using the shared body editor. + readonly assemblyModelingDocuments = new Set(); + private readonly inspectionDocumentOwners = new Map(); + readonly meshPartCurveDocuments = new Set(); + readonly meshPartMesherDocuments = new Map(); + readonly modelingDocumentOwners = new Map(); + /** Capture the retained worker identity, without an unrelated-worker fallback. */ + graphicsDocumentReader(documentId: string): (() => Promise) | undefined { + const document = this.modelingDocumentOwners.get(documentId)?.document ?? documentId; + const owner = this.inspectionDocumentOwners.get(document); + if (!owner) return; + return () => { + const current = this.inspectionDocumentOwners.get(document); + if (current?.module !== owner.module || current?.workerFile !== owner.workerFile) + return Promise.resolve(createFailure("graphics-scene", "document_closed", "The originating document owner is no longer available")); + return this.request("Inspection", "inspection.pythonFamilyBatch", { + schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", + records: [{ apiId: "Inspection:desktop:Inspection_VisualInspection", name: "Inspection_VisualInspection", + family: "desktop-command", args: { document, action: "read", graphicsSceneRead: true } }], + }, document); + }; + } + private readonly completionListeners = new Set<(module: string, command: string, payload: unknown, documentId: string, response: FacadeResponse) => void>(); + + onRequestCompleted(listener: (module: string, command: string, payload: unknown, documentId: string, response: FacadeResponse) => void): () => void { + this.completionListeners.add(listener); + return () => { this.completionListeners.delete(listener); }; + } + + route(module: string): WebModuleRoute | undefined { + return getWebModuleRoute(module); + } + + private open(module: string, workerFile?: string): ModuleSession | undefined { + const route = getWebModuleRoute(module); + const selectedWorker = workerFile ?? route?.primaryWorker ?? undefined; + const sessionKey = `${module}:${selectedWorker ?? ""}`; + const existing = this.sessions.get(sessionKey); + if (existing) return existing; + const artifact = this.artifacts.get(module); + const worker = createWebModuleWorker(module, selectedWorker, artifact); + if (!route || !worker) return undefined; + const pending = new Map(); + let resolveReady!: () => void; + let rejectReady!: (error: Error) => void; + const ready = new Promise((resolve, reject) => { resolveReady = resolve; rejectReady = reject; }); + const session: ModuleSession = { route, worker, ready, failReady: rejectReady, pending, artifactRevision: artifact?.revision }; + const failSession = (error: Error) => { + rejectReady(error); + for (const request of pending.values()) { request.cleanup?.(); request.reject(error); } + pending.clear(); + if (this.sessions.get(sessionKey) === session) { + this.sessions.delete(sessionKey); + this.lifecycle.release(`worker:${sessionKey}`); + } + }; + worker.onmessage = (event: MessageEvent) => { + const message = event.data; + if (message.kind === "ready") { resolveReady(); return; } + if (message.kind === "reset") return; + if (message.kind === "bootstrap-error") { + failSession(new Error(`${module} worker bootstrap failed: ${message.message}`)); + return; + } + const request = pending.get(message.requestId); + if (!request) { + // Older workers use these sentinel IDs for startup/protocol errors. + // They cannot be correlated to one command, so fail the broken session. + if (message.kind === "error" && ["initialization", "invalid"].includes(message.requestId)) { + failSession(new Error(`${module} ${selectedWorker} failed: ${message.error.code}: ${message.error.message}`)); + } + return; + } + pending.delete(message.requestId); + request.cleanup?.(); + request.resolve(message); + }; + worker.onerror = (event) => { + const error = new Error(`${module} worker failed: ${event.message}`); + failSession(error); + }; + this.sessions.set(sessionKey, session); + this.lifecycle.track({ label: `worker:${sessionKey}`, dispose: () => worker.terminate() }); + return session; + } + + /** Register or replace the independently built artifact for one module. */ + setArtifact(module: string, artifact: WebModuleArtifact): void { + if (!getWebModuleRoute(module)) throw new Error(`module ${module} is not registered`); + const previous = this.artifacts.get(module); + this.artifacts.set(module, artifact); + if (previous?.revision === artifact.revision) return; + if (module === "Test") this.testSceneDocuments.clear(); + this.closeSessions(module, new Error(`module ${module} artifact changed to ${artifact.revision}`)); + } + + clearArtifact(module: string): void { + this.artifacts.delete(module); + if (module === "Test") this.testSceneDocuments.clear(); + this.closeSessions(module, new Error(`module ${module} artifact cleared`)); + } + + getArtifact(module: string): WebModuleArtifact | undefined { + return this.artifacts.get(module); + } + + async loadManifest(url: string, init?: RequestInit): Promise { + const manifest = await loadWebModuleManifest(url, init); + const loaded: string[] = []; + for (const [module, artifact] of Object.entries(manifest.modules)) { + if (!getWebModuleRoute(module)) continue; + this.setArtifact(module, artifact); + loaded.push(module); + } + return loaded.sort(); + } + + listLoaded(): Array<{ module: string; worker: string; revision?: string }> { + return [...this.sessions.entries()].map(([key, session]) => { + const separator = key.indexOf(":"); + return { + module: separator < 0 ? key : key.slice(0, separator), + worker: separator < 0 ? key : key.slice(separator + 1), + revision: session.artifactRevision, + }; + }); + } + + /** Preload one command worker without issuing a native command. */ + async preload(module: string, workerFile?: string): Promise { + const selectedWorker = workerFile ?? getWebModuleRoute(module)?.primaryWorker ?? undefined; + const session = this.open(module, selectedWorker); + if (!session) throw new Error(`${module} has no runnable Web Worker route`); + await session.ready; + } + + private closeSessions(module?: string, error?: Error): void { + if (!module || module === "MeshPart") { this.meshPartCurveDocuments.clear(); this.meshPartMesherDocuments.clear(); } + for (const [name, owner] of this.inspectionDocumentOwners) if (!module || owner.module === module) this.inspectionDocumentOwners.delete(name); + for (const [key, session] of this.sessions) { + if (module && !key.startsWith(`${module}:`)) continue; + this.sessions.delete(key); + session.failReady(error ?? new Error(`module ${key} closed`)); + if (error) for (const request of session.pending.values()) { request.cleanup?.(); request.reject(error); } + session.pending.clear(); + session.worker.terminate(); + this.lifecycle.release(`worker:${key}`); + } + } + + async request(module: string, command: string, payload: Payload, documentId = `${module.toLowerCase()}-document`, signal?: AbortSignal): Promise { + if (module === "ReverseEngineering" && command === "reverseengineering.pythonFamilyBatch") { + const records = (payload as any)?.records; + if (records?.some((row: any) => ["Reen_ApproxPlane", "Reen_ApproxCylinder", "Reen_ApproxSphere", "Reen_ApproxPolynomial"].includes(row.name))) { + if (records.length !== 1) return createFailure("native-fit", "invalid_request", "Run one approximation command at a time"); + if (signal?.aborted) return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch"); + if (!this.inspectionDocumentOwners.has(documentId)) + return createFailure("native-fit", "missing_document", "Select geometry in an open native document"); + const response = await this.request("Inspection", "inspection.pythonFamilyBatch", { + schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", + records: [{ apiId: "Inspection:desktop:Inspection_InspectElement", name: "Inspection_InspectElement", family: "desktop-command", + args: { ...records[0].args, document: documentId, approximationCommand: records[0].name } }], + }, documentId, signal); + if (response.kind !== "result") return response; + const batch = response.result as any; + if (batch.ok === false || !Array.isArray(batch.records)) + return createFailure("native-fit", batch.code || "native_error", batch.error || "Native fitting failed"); + return createSuccess(response.requestId, { ...batch, module: "ReverseEngineering", + schema: "freecad-web-reverseengineering/python-family-batch/v1", + records: batch.records.map((row: any) => ({ ...row, apiId: records[0].apiId, name: records[0].name, value: row.result })) }); + } + if (records?.some((row: any) => ["Reen_Segmentation", "Reen_SegmentationManual", "Reen_SegmentationFromComponents"].includes(row.name))) { + if (records.length !== 1) return createFailure("manual-segmentation", "active_task", "Open one manual segmentation task at a time"); + if (!this.inspectionDocumentOwners.has(documentId)) + return createFailure("manual-segmentation", "missing_document", "Choose an active native document before opening manual segmentation"); + const response = await this.request("Inspection", "inspection.pythonFamilyBatch", { + schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", + records: [{ apiId: "Inspection:desktop:Inspection_InspectElement", name: "Inspection_InspectElement", family: "desktop-command", + args: { ...records[0].args, document: documentId, manualSegmentation: records[0].name === "Reen_SegmentationManual", + automaticSegmentation: records[0].name === "Reen_Segmentation", + componentsSegmentation: records[0].name === "Reen_SegmentationFromComponents" } }], + }, documentId, signal); + if (response.kind !== "result") return response; + const batch = response.result as any; + return createSuccess(response.requestId, { ...batch, module: "ReverseEngineering", + schema: "freecad-web-reverseengineering/python-family-batch/v1", + records: batch.records.map((row: any) => ({ ...row, apiId: records[0].apiId, name: records[0].name, value: row.result })) }); + } + } + if (module === "Measure" && command === "measure.pythonFamilyBatch") { + const records = (payload as { records?: Array<{ apiId: string; args?: Record }> }).records; + if (records?.some(r => ["Measure:desktop:Std_Measure", "Measure:desktop:Std_MassProperties"].includes(r.apiId))) { + if (records.length !== 1) return createFailure("measure-document", "invalid_request", "Measure one selection at a time"); + return executeMeasureDocument(this, { ...records[0].args, ...(records[0].apiId.endsWith(":Std_MassProperties") ? { action: "massProperties" } : {}) }, documentId); + } + } + if (module === "Surface" && command === "Surface_CurveOnMesh") { + const args = payload as Record; + return executeMeshPartCurve(this, { id: "MeshPart:desktop:MeshPart_CurveOnMesh", module: "MeshPart", + command: "MeshPart_CurveOnMesh", kind: "desktop-gui", sourcePath: "src/Mod/Surface/Gui/Command.cpp" }, + args, typeof args.documentId === "string" ? args.documentId : documentId); + } + if (module === "Surface" && ["Surface_BlendCurve", "Surface_ExtendFace"].includes(command)) + return (await executeSurfaceDocument(this, command, payload as Record, documentId))!; + if (module === "Surface" && ["surface.desktopCommand", "surface.pythonFamilyBatch"].includes(command)) { + const commands = (payload as { commands?: Array<{ apiId: string; args?: Record }>; records?: Array<{ apiId: string; args?: Record }> })?.[command === "surface.desktopCommand" ? "commands" : "records"]; + if (commands?.some(item => item.apiId === "Surface:desktop:Surface_CurveOnMesh")) { + if (commands.length !== 1) return createFailure("surface-curve", "active_task", "Open one curve task at a time"); + return this.request("Surface", "Surface_CurveOnMesh", commands[0].args ?? {}, documentId, signal); + } + if (commands?.some(item => ["Surface:desktop:Surface_BlendCurve", "Surface:desktop:Surface_Filling", "Surface:desktop:Surface_Sections", "Surface:desktop:Surface_ExtendFace"].includes(item.apiId))) { + if (commands.length !== 1) return createFailure("surface-document", "invalid_request", "Edit one Surface feature at a time"); + const response = await executeSurfaceDocument(this, commands[0].apiId.split(":").pop()!, commands[0].args ?? {}, documentId); + if (!response || response.kind === "error") return response!; + return createSuccess(response.requestId, { ok: true, cmd: command, module: "Surface", source: "freecad-source", count: 1, + results: [{ apiId: commands[0].apiId, status: "exposed", native: true, runtimeOwner: "DocumentProbe", ...response.result as object }] }); + } + } + if (module === "Points" && ["points.saveReopen", "points.createRecompute"].includes(command)) { + const args = payload as Record; + payload = { ...args, document: args.document ?? documentId } as Payload; + } + const inspectionTask = module === "Inspection" && command === "inspection.pythonFamilyBatch" + && (payload as any)?.records?.every((record: any) => ["Inspection_VisualInspection", "Inspection_InspectElement"].includes(record.name)); + const inspectionOwner = inspectionTask ? this.inspectionDocumentOwners.get(documentId) : undefined; + if (module === "Test") { + const scenePayload = payload as { command?: string; args?: Record }; + if (["Std_ViewExample1", "Std_ViewExample2", "Std_ViewExample3"].includes(scenePayload.command ?? "")) { + const id = String(scenePayload.args?.documentId ?? documentId); + scenePayload.args = { ...scenePayload.args, documentId: id.startsWith("test-scene-") ? id : `test-scene-${id}` }; + } + } + const sourceDecision = nativeSourceDecision(module, command); + if (sourceDecision) return createFailure(`module-${module.toLowerCase()}-native-source`, sourceDecision.code, sourceDecision.message, sourceDecision.diagnostic); + const route = getWebModuleRoute(module); + if (!route) return createFailure("invalid", "unknown_module", `module ${module} is not registered`, { module }); + const pointsCurveTask = module === "Points" && command === "reverseengineering.pythonFamilyBatch"; + if (!pointsCurveTask && !route.commands.includes(command)) return createFailure("invalid", "not_implemented", `command ${command} is not registered for ${module}`, { module, command }); + const assemblyModeling = command === "partdesign.document" && this.assemblyModelingDocuments.has(documentId); + const workerFile = assemblyModeling ? "assembly.worker.ts" : inspectionOwner?.workerFile ?? (pointsCurveTask ? "points.worker.ts" : getWebModuleWorkerForCommand(module, command)); + const ownerModule = assemblyModeling ? "Assembly" : inspectionOwner?.module ?? module; + const session = this.open(ownerModule, workerFile); + if (!session) return createFailure("invalid", "not_implemented", `${module} has no runnable Web Worker route`, { module }); + await session.ready; + if (inspectionTask && (payload as any)?.records?.some((row: any) => row.args?.approximationCommand) && signal?.aborted) + return createFailure("native-fit", "cancelled", "Fitting cancelled before dispatch"); + const requestId = `module-${module.toLowerCase()}-${++this.sequence}`; + const request = createRequest(requestId, command, payload, documentId) as FacadeRequest; + return new Promise((resolve, reject) => { + const onAbort = () => session.worker.postMessage(createCancel(`module-cancel-${++this.sequence}`, requestId, documentId)); + signal?.addEventListener("abort", onAbort, { once: true }); + session.pending.set(requestId, { resolve: (response) => { + if ((command === "part.document" || command === "partdesign.document") && response.kind === "result") { + const result = response.result as { document?: string; closed?: boolean }; + if (result.document) { + if (result.closed) { for (const [key, owner] of this.modelingDocumentOwners) if (owner.document === result.document) this.modelingDocumentOwners.delete(key); } + else { const owner = { document: result.document, module: command === "part.document" ? "Part" as const : "PartDesign" as const }; + this.modelingDocumentOwners.set(documentId, owner); this.modelingDocumentOwners.set(result.document, owner); } + } + } + if (response.kind === "result" && workerFile && ["part-save.worker.ts", "part.worker.ts", "partdesign.worker.ts", "partdesign-python.worker.ts", "sketcher.worker.ts", "sketcher-python.worker.ts", "draft.worker.ts", "bim.worker.ts", "points.worker.ts", "mesh.worker.ts", "inspection.worker.ts"].includes(workerFile)) { + const value = response.result as any; + const candidates = [value, ...(value.records ?? []).flatMap((row: any) => row.status === "exposed" ? [row, row.result, row.value] : [])]; + for (const candidate of candidates) { + const name = candidate?.documentId ?? candidate?.document ?? candidate?.documentHandle; + if (typeof name === "string" && (Array.isArray(candidate?.objects) || Array.isArray(candidate?.shapes) || typeof candidate?.geometryCount === "number" || candidate?.closed)) { + if (candidate.closed) this.inspectionDocumentOwners.delete(name); + else this.inspectionDocumentOwners.set(name, { module: ownerModule, workerFile }); + } + } + } + if (module === "Test" && response.kind === "result") { + const result = response.result as TestViewExampleResult; + if (result.operation === "view-example") { + if (result.closed) this.testSceneDocuments.delete(result.documentId); + else if (result.documentName) this.testSceneDocuments.set(result.documentId, result); + } + } + resolve(response); + for (const listener of this.completionListeners) listener(module, command, payload, documentId, response); + }, reject, cleanup: signal ? () => signal.removeEventListener("abort", onAbort) : undefined }); + session.worker.postMessage(request); + }); + } + + reset(module?: string): void { + if (!module || module === "Test") this.testSceneDocuments.clear(); + for (const [name, owner] of this.inspectionDocumentOwners) if (!module || owner.module === module) this.inspectionDocumentOwners.delete(name); + const sessions = module + ? [...this.sessions.entries()].filter(([key]) => key.startsWith(`${module}:`)).map(([, session]) => session) + : [...this.sessions.values()]; + for (const session of sessions) { + const requestId = `module-reset-${++this.sequence}`; + session.worker.postMessage({ kind: "reset", requestId }); + } + } + + dispose(): void { + this.closeSessions(undefined, new Error("module router disposed")); + this.lifecycle.disposeAll(); + this.testSceneDocuments.clear(); + this.sessions.clear(); + this.artifacts.clear(); + } +} + +export type WebModuleFailure = FacadeFailure; diff --git a/web/src/project-shell.tsx b/web/src/project-shell.tsx index c62ea14f..e2978c6e 100644 --- a/web/src/project-shell.tsx +++ b/web/src/project-shell.tsx @@ -5,11 +5,9 @@ import { PartAttachmentTask } from "./part-attachment-task.js"; import { PartTubeTask } from "./part-tube-task.js"; import { PartToleranceTask } from "./part-tolerance-task.js"; import { PartPrimitivesTask } from "./part-primitives-task.js"; -import { requestOpenScadExport, requestOpenScadExportPreferences } from "./openscad-format-facade.js"; import { saved as savedExportPreferences, persist as persistExportPreferences } from "./parameter-storage.js"; -import { requestOpenScadFile, type OpenScadFileArgs } from "./openscad-format-facade.js"; -import { openScadDocumentSnapshot, saveOpenScadFile, type OpenScadDocument } from "./openscad-desktop-adapter.js"; -import { OpenScadDesktopView } from "./openscad-desktop-view.js"; +import type { SceneDocument } from "./scene-document.js"; +import { SceneViewport } from "./scene-viewport.js"; import { MaterialDesktopTask } from "./material-desktop-task.js"; import { SHOW_DOCUMENT_LIFECYCLE_COMMAND, type ShowDocumentLifecyclePayload, type ShowDocumentLifecycleResult } from "./show-python-family-facade.js"; import { ShowClippingTask } from "./show-clipping-task.js"; @@ -239,15 +237,6 @@ function App() { const [exportFileName, setExportFileName] = useState(""); const [exportOptions, setExportOptions] = useState({ exportFa: 12, exportFs: 2, exportConvexity: 10, meshdeflection: 0 }); const exportCancellation = useRef(null); - const [exportPreferencesReady, setExportPreferencesReady] = useState(false); - useEffect(() => { - if (!["csg", "scad"].includes(exportFormat) || exportPreferencesReady) return; - let cancelled = false; - void savedExportPreferences("OpenSCAD-export.FCParam").then(data => requestOpenScadExportPreferences(router, data)) - .then(options => { if (!cancelled) { setExportOptions(options); setExportPreferencesReady(true); } }) - .catch(error => { if (!cancelled) setStatus(String(error)); }); - return () => { cancelled = true; }; - }, [exportFormat, exportPreferencesReady, router]); useEffect(() => () => exportCancellation.current?.abort(), []); const [selectedObjects, setSelectedObjects] = useState>({}); @@ -286,23 +275,6 @@ function App() { const testDocuments = useRef(new Map()); const [testRevision, setTestRevision] = useState(0); const jtDocuments = useRef(new Set()); - const openScadDocuments = useRef(new Map()); - const [openScadSnapshots, setOpenScadSnapshots] = useState>({}); - const rememberOpenScad = (id: string, document: OpenScadDocument) => { - openScadDocuments.current.set(id, document); - nativeDocuments.current.add(id); - setOpenScadSnapshots(previous => ({ ...previous, [id]: document })); - }; - const openScadRequest = async (id: string, action: OpenScadFileArgs["action"], details: Partial = {}) => { - const owner = openScadDocuments.current.get(id); - const result = await requestOpenScadFile(router, { ...details, action, - documentId: owner?.documentId, documentToken: owner?.documentToken }); - if (result.closed) { - openScadDocuments.current.delete(id); nativeDocuments.current.delete(id); - setOpenScadSnapshots(previous => { const next = { ...previous }; delete next[id]; return next; }); - } else rememberOpenScad(id, result); - return result; - }; const remoteOwners = useRef(new Map()); const remoteRequest = (id: string, action: string, details: Record = {}): Promise => new Promise((resolve, reject) => { const owner = remoteOwners.current.get(id); @@ -410,7 +382,7 @@ function App() { return () => window.removeEventListener("freecad-document-framing", receive); }, [renderBridge, store]); useEffect(() => { const stage = document.querySelector("[data-developer-panel]"); if (!stage || !developerMode) return; const previous = stage.querySelector("[data-queue-recovery]"); previous?.remove(); return mountQueueRecoveryPanel(stage, store, recovery, () => setRecoveryVersion((value) => value + 1)); }, [recovery, recoveryVersion, store, developerMode]); - const nativeName = (id: string) => openScadDocuments.current.get(id)?.documentId ?? testDocuments.current.get(id)?.documentName ?? remoteOwners.current.get(id)?.document ?? `web_${id.replace(/\W/g, "_")}`; + const nativeName = (id: string) => testDocuments.current.get(id)?.documentName ?? remoteOwners.current.get(id)?.document ?? `web_${id.replace(/\W/g, "_")}`; const refresh = () => setDocuments(store.list()); const currentDocument = documents.find(document => document.id === active); const objects = Object.values(currentDocument?.objects ?? {}); @@ -603,12 +575,6 @@ function App() { }; const nativeOwnerRequest = async (id: string, action: PartDocumentAction, details: Partial = {}) => { validateRequestDocument(id, details.document); - if (openScadDocuments.current.has(id)) { - const mapped = action === "snapshot" ? "read" : action; - if (!["read", "save", "close", "undo", "redo"].includes(mapped)) - throw new Error(`Use the OpenSCAD document controls for ${action}`); - return openScadDocumentSnapshot(await openScadRequest(id, mapped as OpenScadFileArgs["action"])); - } const testOwner = testDocuments.current.get(id); if (testOwner) { const mapped = action === "snapshot" ? "read" : action; @@ -777,8 +743,8 @@ function App() { && document.objects[`native:${owner.name}`]?.properties.tip !== owner.tip ? object.name === owner.tip : undefined; const nativeProperties = Object.fromEntries(Object.entries(object).filter(([key]) => key !== "mesh")); - nextObjects[objectId] = { id: objectId, module: openScadDocuments.current.has(id) ? "OpenSCAD" : jtDocuments.current.has(id) ? "JtReader" : designDocuments.current.has(id) ? "PartDesign" : "Part", - command: openScadDocuments.current.has(id) ? "openscad.pythonFamilyBatch" : jtDocuments.current.has(id) ? JTREADER_DOCUMENT_COMMAND : designDocuments.current.has(id) ? PARTDESIGN_DOCUMENT_COMMAND : PART_DOCUMENT_COMMAND, type: object.type, + nextObjects[objectId] = { id: objectId, module: jtDocuments.current.has(id) ? "JtReader" : designDocuments.current.has(id) ? "PartDesign" : "Part", + command: jtDocuments.current.has(id) ? JTREADER_DOCUMENT_COMMAND : designDocuments.current.has(id) ? PARTDESIGN_DOCUMENT_COMMAND : PART_DOCUMENT_COMMAND, type: object.type, links: [...new Set(object.dependencies ?? [object.base, object.tool, ...(object.tools ?? []), ...(object.links ?? [])].filter((name): name is string => Boolean(name)))].map(name => `native:${name}`), properties: { ...document.objects[objectId]?.properties, ...nativeProperties, ...(object as unknown as { testProperties?: Record }).testProperties, NativeName: object.name, Label: object.label, cells: (object as unknown as { cells?: SheetCell[] }).cells, @@ -1177,75 +1143,7 @@ function App() { return false; } finally { importCancellation.current = null; setImporting(false); setCancelRequested(false); setImportPhase(""); } }; - const importOpenScadFile = async (file: File, newDocument: boolean) => { - if ((!active && !newDocument) || importing || importCancellation.current) return false; - const id = newDocument ? allocateDocumentId() : active; - const cancellation = new AbortController(); importCancellation.current = cancellation; - setImporting(true); setCancelRequested(false); setImportPhase("reading"); - const owner = openScadDocuments.current.get(id); - let pending: Awaited> | undefined; - let committed = false; - try { - if (!file.size || file.size > 64 * 1024 * 1024) throw new Error("Choose a SCAD or CSG file between 1 byte and 64 MiB"); - const contentBase64 = encodeSceneFile(await file.arrayBuffer()); - cancellation.signal.throwIfAborted(); - let documentBase64: string | undefined; - let documentObjects: Array<{ name: string; type: string }> | undefined; - const hasOriginal = !newDocument && nativeDocuments.current.has(id) && !owner; - if (!newDocument && !owner && Object.values(store.list().find(value => value.id === id)?.objects ?? {}).some(object => !object.properties.NativeName)) - throw new Error("Save or attach the existing imported views before inserting OpenSCAD source"); - if (hasOriginal) { - const original = await nativeRequest(id, "save", { path: `/tmp/${nativeName(id)}.FCStd`, includeMesh: false }); - if (!original.bytes) throw new Error("The active document owner returned no FCStd data"); - if (!original.objects) throw new Error("The active document owner returned no object manifest"); - documentObjects = original.objects.map(object => ({ name: object.name, type: object.type })); - documentBase64 = encodeSceneFile(original.bytes); - } - cancellation.signal.throwIfAborted(); - setImportPhase("native"); setStatus(`${newDocument ? "Opening" : "Inserting"} ${file.name}...`); - pending = await requestOpenScadFile(router, { action: "import", fileName: file.name, - extension: file.name.split(".").pop()!.toLowerCase(), contentBase64, documentBase64, documentObjects, - newDocument: newDocument || (!owner && !documentBase64), documentId: owner?.documentId, - documentToken: owner?.documentToken, operationToken: crypto.randomUUID() }); - cancellation.signal.throwIfAborted(); - // Geometry and identity are returned before acceptance. Cancellation stays - // local until this point because synchronous native parsing cannot yield. - importCancellation.current = null; setImportPhase("finishing"); - const result = await requestOpenScadFile(router, { action: "finishImport", documentId: pending.documentId, - documentToken: pending.documentToken, operationToken: pending.operationToken, commitImport: true }); - if (result.cancelled) throw new Error("OpenSCAD import transaction expired before commit"); - committed = true; pending = undefined; - let retirementError = ""; - if (hasOriginal) { - try { await nativeOwnerRequest(id, "close", { includeMesh: false }); } - catch (error) { retirementError = `; previous document owner could not close: ${String(error)}`; } - } - designDocuments.current.delete(id); jtDocuments.current.delete(id); remoteOwners.current.delete(id); testDocuments.current.delete(id); - rememberOpenScad(id, result); - if (newDocument) store.open(id, file.name); - applyNativeDocument(id, openScadDocumentSnapshot(result)); - store.switchTo(id); setActive(id); setStartVisible(false); - setSelectedObjects(previous => ({ ...previous, [id]: result.selection[0] ? `native:${result.selection[0]}` : null })); - setNativeBytes(null); - store.touchFile({ path: file.name, module: "OpenSCAD", format: file.name.split(".").pop()!.toLowerCase(), updatedAt: new Date().toISOString() }); - refresh(); setStatus(`${newDocument ? "Opened" : "Inserted"} ${file.name}${retirementError}`); - return true; - } catch (error) { - if (pending && !committed) { - try { await requestOpenScadFile(router, { action: "finishImport", documentId: pending.documentId, - documentToken: pending.documentToken, operationToken: pending.operationToken, commitImport: false }); } - catch (rollback) { setStatus(`OpenSCAD rollback: ${String(rollback)}; ${String(error)}`); return false; } - } - setStatus(cancellation.signal.aborted ? "OpenSCAD import cancelled; original document preserved" : String(error)); - if (newDocument && !cancellation.signal.aborted) throw error; - return false; - } finally { importCancellation.current = null; setImporting(false); setCancelRequested(false); setImportPhase(""); } - }; const importUserFiles = async (files: File[], desktopCommand?: ImportDesktopCommand, newDocument = false) => { - if (files.some(file => /\.(scad|csg)$/i.test(file.name))) { - if (files.length !== 1) throw new Error("Choose one SCAD or CSG source file at a time"); - return importOpenScadFile(files[0], newDocument); - } if (files.some(file => /\.jt$/i.test(file.name))) { if (files.length !== 1) throw new Error("Choose one standalone JT file at a time"); return newDocument ? openJtFile(files[0]) : insertJtFile(files[0]); @@ -1343,34 +1241,6 @@ function App() { setImporting(true); try { const name = String(selectedObject.properties.NativeName); - if (["csg", "scad"].includes(exportFormat)) { - const id = active; - const cancellation = new AbortController(); exportCancellation.current = cancellation; - const owner = openScadDocuments.current.get(id); - const documentId = nativeName(id); - const names = (compoundSelections[id]?.length ? compoundSelections[id]! : [name]).map(value => value.replace(/^native:/, "")); - const args: OpenScadFileArgs = { action: "export", documentId, documentToken: owner?.documentToken, - selection: names.map(object => ({ documentId, object })), extension: exportFormat, - fileName: exportFileName.trim() || `${name}.${exportFormat}`, exportOptions, - preferencesBase64: await savedExportPreferences("OpenSCAD-export.FCParam") }; - if (!owner) { - const original = await nativeRequest(id, "save", { path: `/tmp/${documentId}.FCStd`, includeMesh: false }); - if (!original.bytes || !original.objects) throw new Error("The active owner returned no FCStd export snapshot"); - args.documentBase64 = encodeSceneFile(original.bytes); - args.documentObjects = original.objects.map(object => ({ name: object.name, type: object.type })); - } - cancellation.signal.throwIfAborted(); - const result = await requestOpenScadExport(router, args); - cancellation.signal.throwIfAborted(); - if (store.active()?.id !== id) throw new Error("Export cancelled because the active document changed"); - await persistExportPreferences(result.preferencesBase64, "OpenSCAD-export.FCParam"); - cancellation.signal.throwIfAborted(); - const bytes = Uint8Array.from(atob(result.base64), character => character.charCodeAt(0)).buffer; - const exported = exporter.download({ module: "OpenSCAD", format: "text/plain", fileName: result.fileName, bytes }); - if (exported.status !== "ok") throw new Error(exported.error?.message || "OPFS write failed"); - setStatus(`已写入 OPFS:${result.fileName} (${bytes.byteLength} bytes)`); - return; - } const result = await nativeRequest(active, "exportShape", { object: name, path: `/tmp/${nativeName(active)}_${name}.${exportFormat}`, includeMesh: false }); if (!result.bytes?.byteLength) throw new Error("Native export returned no file bytes"); @@ -1484,16 +1354,6 @@ function App() { if (!active || importing) return; setImporting(true); try { - if (openScadDocuments.current.has(active)) { - const result = await openScadRequest(active, "save"); - if (!result.file) throw new Error("OpenSCAD returned no FCStd file"); - await saveOpenScadFile(result); - const snapshot = openScadDocumentSnapshot(result); - applyNativeDocument(active, snapshot, false); setNativeBytes(snapshot.bytes!); - setSavedDocuments(await listDocumentFiles()); window.dispatchEvent(new Event("freecad-document-persistence")); setSavedDocument(`OpenSCAD/${result.file.name}`); - setStatus(`Saved ${result.file.name} to OPFS`); - return; - } if (objects.some(object => !object.properties.NativeName)) throw new Error("Imported STEP views are not yet attached to this native FCStd document"); if (!nativeDocuments.current.has(active)) await nativeRequest(active, "create"); const fileName = `${jtDocuments.current.has(active) ? "JtReader_" : designDocuments.current.has(active) ? "PartDesign_" : ""}${nativeName(active)}.FCStd`; @@ -1512,19 +1372,9 @@ function App() { let id = allocateDocumentId(); let registeredDesignOwner = false; try { - if ((requestedFile.includes("/") && !/^(Test|OpenSCAD)\/[^/]+$/.test(requestedFile)) || requestedFile.includes("\\") || !/\.FCStd$/i.test(requestedFile)) + if ((requestedFile.includes("/") && !/^Test\/[^/]+$/.test(requestedFile)) || requestedFile.includes("\\") || !/\.FCStd$/i.test(requestedFile)) throw new Error("Invalid FCStd file name"); const bytes = suppliedBytes ?? await readDocumentFile(requestedFile); - if (requestedFile.startsWith("OpenSCAD/") || requestedFile.startsWith("OpenSCAD_")) { - const result = await openScadRequest(id, "open", { contentBase64: encodeSceneFile(bytes) }); - store.open(id, requestedFile.split("/").pop()); - applyNativeDocument(id, openScadDocumentSnapshot(result), false); - store.switchTo(id); setActive(id); setStartVisible(false); - setSelectedObjects(previous => ({ ...previous, [id]: result.selection[0] ? `native:${result.selection[0]}` : null })); - setNativeBytes(bytes); setStatus(`Opened ${requestedFile}${suppliedBytes ? "" : " from OPFS"}`); - const url = new URL(window.location.href); url.searchParams.delete("fcstd"); window.history.replaceState(null, "", url); - return true; - } if (requestedFile.startsWith("PartDesign_")) { designDocuments.current.add(id); registeredDesignOwner = true; @@ -1636,7 +1486,7 @@ function App() { } setStartVisible(!preferences.closeStart); }; - const downloadFcstd = () => { if (!nativeBytes) return; const result = exporter.download({ module: "Part", format: "application/octet-stream", fileName: `${openScadDocuments.current.has(active) ? "OpenSCAD_" : jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`, bytes: nativeBytes }); setStatus(result.status === "ok" ? "FCStd 已写入 OPFS" : result.error?.message || "FCStd OPFS write failed"); }; + const downloadFcstd = () => { if (!nativeBytes) return; const result = exporter.download({ module: "Part", format: "application/octet-stream", fileName: `${jtDocuments.current.has(active) ? "JtReader_" : ""}${nativeName(active)}.FCStd`, bytes: nativeBytes }); setStatus(result.status === "ok" ? "FCStd 已写入 OPFS" : result.error?.message || "FCStd OPFS write failed"); }; const exportDependencyGraph = async () => { if (importing || !active || !nativeDocuments.current.has(active)) return; const documentId = nativeName(active); @@ -2023,7 +1873,7 @@ function App() { } setWorkspaceTask(""); setViewCommand(""); setWorkbenches(previous => ({ ...previous, [active]: next })); void startParameters(router, { LastModule: `${next}Workbench` }, true).catch(error => setStatus(String(error))); - }}> + }}> {csvPanel && { setSavedDocuments(files); window.dispatchEvent(new Event("freecad-document-persistence")); }).catch(error => setStatus(String(error))); }} /> } - {openScadSnapshots[active] && selectPrimaryObject(`native:${name}`)} />} -
+
{isExternalWorkbench(workbench) && }
{([["translate", "移动"], ["rotate", "旋转"], ["off", "关闭"]] as const).map(([mode, label]) => ( @@ -2298,22 +2145,15 @@ function App() { } -
Files +
Files {importing && importCancellation.current && } - {["csg", "scad"].includes(exportFormat) &&
- Selected-object export - - {([['exportFa', 'Fragment angle'], ['exportFs', 'Fragment size'], ['exportConvexity', 'Convexity'], ['meshdeflection', 'Mesh deflection']] as const).map(([key, label]) => - )} -
} {importing && exportCancellation.current && } - @@ -2894,8 +2734,7 @@ function App() { {workbench === "Part" && active && workspaceTask === "split" && void (async () => { if (importing) return; const id = active; @@ -2922,8 +2761,7 @@ function App() { {workbench === "Part" && active && workspaceTask === "join" && void (async () => { if (importing) return; const id = active; @@ -3222,7 +3060,7 @@ function App() { {shortcutsOpen && setShortcutsOpen(false)} />} {paletteOpen && setPaletteOpen(false)} />} {bottomDockOpen && objects.find(object => String(object.properties.NativeName) === name)?.properties.Label ?? name)} + selection={compoundSelection.map(name => String(objects.find(object => String(object.properties.NativeName) === name)?.properties.Label ?? name))} onClose={() => setBottomDockOpen(false)} />} {lineReferenceOpen && setLineReferenceOpen(false)} />}

{status}

; diff --git a/web/src/python-family-dispatcher.ts b/web/src/python-family-dispatcher.ts new file mode 100644 index 00000000..7da21af9 --- /dev/null +++ b/web/src/python-family-dispatcher.ts @@ -0,0 +1,352 @@ +import { createFailure, type FacadeResponse } from "./facade-envelope.js"; +import { MESH_PYTHON_FIXTURE } from "./mesh-python-facade.js"; +import { MEASURE_PYTHON_FIXTURE } from "./measure-python-facade.js"; +import { MEASUREMENT_API_FIXTURE } from "./measure-measurement-facade.js"; +import { POINTS_PYTHON_FIXTURE } from "./points-python-facade.js"; +import { ROBOT_PYTHON_FIXTURE } from "./robot-python-facade.js"; +import { ROBOT_PYTHON_FAMILY_SCHEMA } from "./robot-python-family-facade.js"; +import { SKETCHER_PY_FIXTURE } from "./sketcher-python-facade.js"; +import { PART_PYTHON_FIXTURE } from "./part-python-facade.js"; +import { PARTDESIGN_PYTHON_FIXTURE } from "./partdesign-python-facade.js"; +import { PLOT_PYTHON_FAMILY_SCHEMA } from "./plot-python-family-facade.js"; +import { POINTS_PYTHON_FAMILY_SCHEMA } from "./points-python-family-facade.js"; +import { TECHDRAW_PY_FIXTURE } from "./techdraw-python-facade.js"; +import { TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA } from "./templatepymod-python-family-facade.js"; +import { IMPORT_PYTHON_FIXTURE } from "./import-python-facade.js"; +import { SANDBOX_PYTHON_FAMILY_SCHEMA } from "./sandbox-python-family-facade.js"; +import { SHOW_PYTHON_FAMILY_SCHEMA } from "./show-python-family-facade.js"; +import { createPythonApiLookup, type PythonApiRecord, type PythonApiRuntimeIndex } from "./python-api-runtime.js"; +import { WebModuleRouter } from "./module-router.js"; + +interface PythonModuleAdapter { module: string; command: string; payload: unknown; buildPayload?: (records: PythonApiRecord[]) => unknown; } +function showSourcePath(name: string): string { + const owner = name.split(".", 1)[0]; + if (["Camera", "ClipPlane", "Pickability", "Workbench"].includes(owner)) return `src/Mod/Show/SceneDetails/${owner}.py`; + if (["Container", "ContainerError", "ContainerTreeError", "NotAContainerError"].includes(owner)) return "src/Mod/Show/Containers.py"; + if (["MAINSTACK", "TempoVis"].includes(owner)) return "src/Mod/Show/mTempoVis.py"; + if (owner === "TVObserver") return "src/Mod/Show/TVObserver.py"; + if (owner === "TVStack") return "src/Mod/Show/TVStack.py"; + if (owner === "SceneDetail") return "src/Mod/Show/SceneDetail.py"; + return "src/Mod/Show/__init__.py"; +} +function sketcherSourcePath(name: string): string { + const owner = name.split(".", 1)[0]; + if (owner === "SketcherWorkbench") return "src/Mod/Sketcher/InitGui.py"; + if (owner.startsWith("ViewProvider")) return "src/Mod/Sketcher/Gui/ViewProviderSketchGeometryExtension.pyi"; + return `src/Mod/Sketcher/App/${owner}.pyi`; +} +function spreadsheetSourcePath(name: string): string { + const owner = name.split(".", 1)[0]; + if (owner === "FormulaTranslator" || owner === "exprNode") return "src/Mod/Spreadsheet/importXLSX.py"; + if (owner.startsWith("ViewProvider")) return "src/Mod/Spreadsheet/Gui/ViewProviderSpreadsheet.pyi"; + return `src/Mod/Spreadsheet/App/${owner}.pyi`; +} +function surfaceSourcePath(name: string): string { + const owner = name.split(".", 1)[0]; + if (owner === "SurfaceWorkbench") return "src/Mod/Surface/InitGui.py"; + if (owner === "BlendCurve" || owner === "BlendPoint") return `src/Mod/Surface/App/Blending/${owner}.pyi`; + return `src/Mod/Surface/App/Blending/${owner}.pyi`; +} +function techdrawSourcePath(name: string): string { + const owner = name.split(".", 1)[0]; + if (owner.startsWith("Command")) return `src/Mod/TechDraw/TechDrawTools/${owner}.py`; + if (owner.endsWith("Test")) return `src/Mod/TechDraw/TDTest/${owner}.py`; + if (owner.startsWith("ViewProvider")) return `src/Mod/TechDraw/Gui/${owner}.pyi`; + return `src/Mod/TechDraw/App/${owner}.pyi`; +} +function templatePyModSourcePath(name: string): string { + const owner = name.split(".", 1)[0]; + if (owner === "DocumentObject" || owner === "ViewProvider") return "src/Mod/TemplatePyMod/DocumentObject.py"; + if (owner === "TaskPanel" || owner.startsWith("Task")) return "src/Mod/TemplatePyMod/TaskPanel.py"; + if (owner === "MainWindow" || owner === "PythonQtWorkbench") return "src/Mod/TemplatePyMod/PythonQt.py"; + if (owner === "Texture" || owner === "ViewProviderTexture") return "src/Mod/TemplatePyMod/Texture.py"; + if (owner.startsWith("ViewProvider")) return "src/Mod/TemplatePyMod/FeaturePython.py"; + if (owner.startsWith("TemplatePy") || owner === "SphereCreator") return "src/Mod/TemplatePyMod/Commands.py"; + return "src/Mod/TemplatePyMod/FeaturePython.py"; +} +const ADAPTERS: Record = { + Assembly: { + module: "Assembly", + command: "assembly.pythonFamily", + payload: { schema: "freecad-web-assembly/python-family/v1", module: "Assembly", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-assembly/python-family/v1", + module: "Assembly", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })), + }), + }, + BIM: { + module: "BIM", + command: "bim.pythonFamilyBatch", + payload: { schema: "freecad-web-bim/python-family-batch/v1", module: "BIM", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-bim/python-family-batch/v1", + module: "BIM", + tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, sourcePath: record.sourcePath, sourceLine: record.sourceLine, disposition: record.disposition })), + }), + }, + CAM: { + module: "CAM", + command: "cam.pythonFamilyBatch", + payload: { schema: "freecad-web-cam/python-family-batch/v1", module: "CAM", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-cam/python-family-batch/v1", + module: "CAM", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })), + }), + }, + Measure: { module: "Measure", command: "measure.pythonApi", payload: MEASURE_PYTHON_FIXTURE }, + "Measure.family": { module: "Measure", command: "measure.pythonFamilyBatch", payload: { schema: "freecad-web-measure/python-family-batch/v1", module: "Measure", tier: "tier-1-readonly", records: [] }, buildPayload: (records) => ({ schema: "freecad-web-measure/python-family-batch/v1", module: "Measure", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })) }) }, + "Mesh.family": { module: "Mesh", command: "mesh.pythonFamilyBatch", payload: { schema: "freecad-web-mesh/python-family-batch/v1", module: "Mesh", tier: "tier-1-readonly", records: [] }, buildPayload: (records) => ({ schema: "freecad-web-mesh/python-family-batch/v1", module: "Mesh", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })) }) }, + "MeshPart.family": { module: "MeshPart", command: "meshpart.pythonFamilyBatch", payload: { schema: "freecad-web-meshpart/python-family-batch/v1", module: "MeshPart", tier: "tier-1-readonly", records: [] }, buildPayload: (records) => ({ schema: "freecad-web-meshpart/python-family-batch/v1", module: "MeshPart", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })) }) }, + "Measure.measurementApi": { module: "Measure", command: "measure.measurementApi", payload: MEASUREMENT_API_FIXTURE }, + Mesh: { module: "Mesh", command: "mesh.pythonApi", payload: MESH_PYTHON_FIXTURE }, + Sketcher: { module: "Sketcher", command: "sketcher.pythonApi", payload: SKETCHER_PY_FIXTURE }, + "Sketcher.family": { + module: "Sketcher", + command: "sketcher.pythonFamilyBatch", + payload: { schema: "freecad-web-sketcher/python-family-batch/v1", module: "Sketcher", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-sketcher/python-family-batch/v1", + module: "Sketcher", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: sketcherSourcePath(record.name), disposition: record.disposition })), + }), + }, + "Spreadsheet.family": { + module: "Spreadsheet", + command: "spreadsheet.pythonFamilyBatch", + payload: { schema: "freecad-web-spreadsheet/python-family-batch/v1", module: "Spreadsheet", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-spreadsheet/python-family-batch/v1", + module: "Spreadsheet", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: spreadsheetSourcePath(record.name), disposition: record.disposition })), + }), + }, + "Surface.family": { + module: "Surface", + command: "surface.pythonFamilyBatch", + payload: { schema: "freecad-web-surface/python-family-batch/v1", module: "Surface", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-surface/python-family-batch/v1", + module: "Surface", + tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: surfaceSourcePath(record.name), disposition: record.disposition })), + }), + }, + "TechDraw.family": { + module: "TechDraw", + command: "techdraw.pythonFamilyBatch", + payload: { schema: "freecad-web-techdraw/python-family-batch/v1", module: "TechDraw", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-techdraw/python-family-batch/v1", + module: "TechDraw", + tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, sourcePath: techdrawSourcePath(record.name), disposition: record.disposition })), + }), + }, + "TemplatePyMod.family": { + module: "TemplatePyMod", + command: "templatepymod.pythonFamilyBatch", + payload: { schema: TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA, module: "TemplatePyMod", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: TEMPLATEPYMOD_PYTHON_FAMILY_SCHEMA, + module: "TemplatePyMod", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, sourcePath: templatePyModSourcePath(record.name), disposition: record.disposition })), + }), + }, + Robot: { module: "Robot", command: "robot.pythonApi", payload: ROBOT_PYTHON_FIXTURE }, + "Robot.family": { + module: "Robot", + command: "robot.pythonFamilyBatch", + payload: { schema: ROBOT_PYTHON_FAMILY_SCHEMA, module: "Robot", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ schema: ROBOT_PYTHON_FAMILY_SCHEMA, module: "Robot", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })) }), + }, + Points: { module: "Points", command: "points.pythonApi", payload: POINTS_PYTHON_FIXTURE }, + Part: { module: "Part", command: "part.pythonApi", payload: PART_PYTHON_FIXTURE }, + "Part.family": { + module: "Part", + command: "part.pythonFamilyBatch", + payload: { schema: "freecad-web-part/python-family-batch/v1", module: "Part", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-part/python-family-batch/v1", + module: "Part", + tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, kind: record.kind, disposition: record.disposition })), + }), + }, + "PartDesign.family": { + module: "PartDesign", + command: "partdesign.pythonFamilyBatch", + payload: { schema: "freecad-web-partdesign/python-family-batch/v1", module: "PartDesign", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-partdesign/python-family-batch/v1", + module: "PartDesign", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + PartDesign: { module: "PartDesign", command: "partdesign.pythonApi", payload: PARTDESIGN_PYTHON_FIXTURE }, + "Plot.family": { + module: "Plot", + command: "plot.pythonFamilyBatch", + payload: { schema: PLOT_PYTHON_FAMILY_SCHEMA, module: "Plot", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ schema: PLOT_PYTHON_FAMILY_SCHEMA, module: "Plot", tier: records[0]?.tier === "tier-2-pure" ? "tier-2-pure" : "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })) }), + }, + "Points.family": { + module: "Points", + command: "points.pythonFamilyBatch", + payload: { schema: POINTS_PYTHON_FAMILY_SCHEMA, module: "Points", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ schema: POINTS_PYTHON_FAMILY_SCHEMA, module: "Points", tier: "tier-1-readonly", records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })) }), + }, + TechDraw: { module: "TechDraw", command: "techdraw.pythonApi", payload: TECHDRAW_PY_FIXTURE }, + "Import.pythonApi": { module: "Import", command: "import.pythonApi", payload: IMPORT_PYTHON_FIXTURE }, + Cloud: { + module: "Cloud", + command: "cloud.pythonFamilyBatch", + payload: { schema: "freecad-web-cloud/python-family-batch/v1", module: "Cloud", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-cloud/python-family-batch/v1", + module: "Cloud", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family })), + }), + }, + Draft: { + module: "Draft", + command: "draft.pythonFamilyBatch", + payload: { schema: "freecad-web-draft/python-family-batch/v1", module: "Draft", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-draft/python-family-batch/v1", + module: "Draft", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + Fem: { + module: "Fem", + command: "fem.pythonFamilyBatch", + payload: { schema: "freecad-web-fem/python-family-batch/v1", module: "Fem", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-fem/python-family-batch/v1", + module: "Fem", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + Import: { + module: "Import", + command: "import.pythonFamilyBatch", + payload: { schema: "freecad-web-import/python-family-batch/v1", module: "Import", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-import/python-family-batch/v1", + module: "Import", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + "ReverseEngineering.family": { + module: "ReverseEngineering", + command: "reverseengineering.pythonFamilyBatch", + payload: { schema: "freecad-web-reverseengineering/python-family-batch/v1", module: "ReverseEngineering", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-reverseengineering/python-family-batch/v1", + module: "ReverseEngineering", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + Inspection: { + module: "Inspection", + command: "inspection.pythonFamilyBatch", + payload: { schema: "freecad-web-inspection/python-family-batch/v1", module: "Inspection", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: "freecad-web-inspection/python-family-batch/v1", + module: "Inspection", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + "Sandbox.family": { + module: "Sandbox", + command: "sandbox.pythonFamilyBatch", + payload: { schema: SANDBOX_PYTHON_FAMILY_SCHEMA, module: "Sandbox", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: SANDBOX_PYTHON_FAMILY_SCHEMA, + module: "Sandbox", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, disposition: record.disposition })), + }), + }, + "Show.family": { + module: "Show", + command: "show.pythonFamilyBatch", + payload: { schema: SHOW_PYTHON_FAMILY_SCHEMA, module: "Show", tier: "tier-1-readonly", records: [] }, + buildPayload: (records) => ({ + schema: SHOW_PYTHON_FAMILY_SCHEMA, + module: "Show", + tier: "tier-1-readonly", + records: records.map((record) => ({ apiId: record.id, name: record.name, family: record.family, sourcePath: showSourcePath(record.name), disposition: record.disposition })), + }), + }, +}; + +export interface PythonFamilyResult { apiId: string; module: string; name: string; disposition?: string; status: string; nativeSchema?: string; nativeResult?: unknown; error?: unknown; } + +export class PythonFamilyDispatcher { + private readonly lookup: Map; + + constructor(private readonly router: WebModuleRouter, index: PythonApiRuntimeIndex) { + this.lookup = createPythonApiLookup(index); + } + + async dispatchBatch(apiIds: string[], documentId = "main-chain-document", options: { includePlanned?: boolean } = {}): Promise<{ schema: string; count: number; results: PythonFamilyResult[]; resourcesReleased: boolean }> { + const results: PythonFamilyResult[] = []; + const grouped = new Map(); + for (const apiId of apiIds) { + const record = this.lookup.get(apiId); + if (!record) { results.push({ apiId, module: "", name: "", status: "not_implemented", error: { code: "unknown_api_id", message: "API ID is not present in the generated runtime index" } }); continue; } + const pending = record.disposition === "planned" && options.includePlanned === true; + if (record.disposition !== "exposed" && !pending) { results.push({ apiId, module: record.module, name: record.name, disposition: record.disposition, status: record.disposition, error: { code: "capability_denied", message: `API disposition is ${record.disposition}` } }); continue; } + const adapterKey = record.module === "Measure" && record.tier === "tier-1-readonly" ? "Measure.family" : record.module === "Measure" && record.name.startsWith("Measurement.") ? "Measure.measurementApi" : record.module === "Mesh" && record.tier === "tier-1-readonly" ? "Mesh.family" : record.module === "MeshPart" && record.tier === "tier-1-readonly" ? "MeshPart.family" : record.module === "Part" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "Part.family" : record.module === "PartDesign" && record.tier === "tier-1-readonly" ? "PartDesign.family" : record.module === "Plot" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "Plot.family" : record.module === "Points" && record.tier === "tier-1-readonly" ? "Points.family" : record.module === "ReverseEngineering" && record.tier === "tier-1-readonly" ? "ReverseEngineering.family" : record.module === "Robot" && record.tier === "tier-1-readonly" ? "Robot.family" : record.module === "Sandbox" && record.tier === "tier-1-readonly" ? "Sandbox.family" : record.module === "Show" && record.tier === "tier-1-readonly" ? "Show.family" : record.module === "Sketcher" && record.tier === "tier-1-readonly" ? "Sketcher.family" : record.module === "Spreadsheet" && record.tier === "tier-1-readonly" ? "Spreadsheet.family" : record.module === "Surface" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "Surface.family" : record.module === "TechDraw" && (record.tier === "tier-1-readonly" || record.tier === "tier-2-pure") ? "TechDraw.family" : record.module === "TemplatePyMod" && record.tier === "tier-1-readonly" ? "TemplatePyMod.family" : record.module === "Import" && record.tier !== "tier-1-readonly" ? "Import.pythonApi" : record.module; + const group = grouped.get(adapterKey) ?? { record, ids: [], adapterKey }; + group.ids.push(apiId); grouped.set(adapterKey, group); + } + for (const [adapterKey, group] of grouped) { + const module = group.record.module; + const adapter = ADAPTERS[adapterKey]; + if (!adapter) { + for (const apiId of group.ids) results.push({ apiId, module, name: group.record.name, status: "not_implemented", error: { code: "module_adapter_pending", message: `No Python module adapter is registered for ${module}` } }); + continue; + } + const response: FacadeResponse = await this.router.request(adapter.module, adapter.command, adapter.buildPayload ? adapter.buildPayload(group.ids.map((id) => this.lookup.get(id)!)) : adapter.payload, documentId); + for (const apiId of group.ids) { + const record = this.lookup.get(apiId)!; + if (response.kind !== "result") { + results.push({ apiId, module, name: record.name, disposition: record.disposition, status: "adapter_error", error: response.error }); + continue; + } + const nativeResult = response.result; + const nativeRecords = nativeResult && typeof nativeResult === "object" && Array.isArray((nativeResult as Record).records) + ? (nativeResult as Record).records as Array> + : []; + const nativeRecord = nativeRecords.find((item) => item.apiId === apiId); + if (nativeRecord?.status === "restricted" || nativeRecord?.status === "not_implemented") { + results.push({ apiId, module, name: record.name, disposition: nativeRecord.status, status: nativeRecord.status, nativeSchema: String((nativeResult as Record).schema ?? ""), nativeResult: nativeRecord, error: { code: nativeRecord.code, message: nativeRecord.message } }); + } else { + results.push({ apiId, module, name: record.name, disposition: record.disposition, status: record.disposition === "planned" ? "module_adapter_ready_pending_method" : "module_adapter_ready", nativeSchema: String((nativeResult as Record).schema ?? ""), nativeResult }); + } + } + } + return { schema: "freecad-web-python-family-result/v1", count: results.length, results, resourcesReleased: results.every((result) => result.status !== "adapter_error") }; + } +} + +export function pythonFamilyFailure(apiId: string, message: string): FacadeResponse { + return createFailure(`python-${apiId}`, "python_family_error", message, { apiId }); +} diff --git a/web/src/scene-command-host.ts b/web/src/scene-command-host.ts new file mode 100644 index 00000000..45ae07db --- /dev/null +++ b/web/src/scene-command-host.ts @@ -0,0 +1,310 @@ +import * as THREE from "three"; +import type { OrbitControls } from "three/addons/controls/OrbitControls.js"; +import { createElement, ZoomIn, ZoomOut, Maximize, RotateCcw, RotateCw, Save, History, MousePointer2, Move, Rotate3d, Hand, Compass, Crosshair, Scan, Mouse, Navigation, LocateFixed, Orbit, Smartphone, type IconNode } from "lucide"; +import { registerSceneCommandHost, type SceneDisplayState } from "./scene-command-adapter.js"; +import "./scene-command-host.css"; +import { attachOverlapPicker, type PickableSceneObject } from "./scene-overlap-picker.js"; +import { attachCameraCommands } from "./scene-camera-commands.js"; +import { orbitStyles, orbitStyle } from "./scene-orbit-model.js"; +import { navigationStyles, defaultNavigationStyle } from "./scene-navigation.js"; +import type { NavigationPreferenceSource, ViewPreferences } from "./view-navigation-preferences.js"; + +export function attachSceneCommands(scene: THREE.Scene, controls: OrbitControls, container: HTMLElement, + documentId: () => string, invalidate: () => void, + picking?: { canvas: HTMLCanvasElement; objects(): PickableSceneObject[]; select(id: string): void }, + onControlsChanged?: (next: OrbitControls) => void, + navigation?: { source: NavigationPreferenceSource; apply(values: ViewPreferences): void; cancel(): void }) { + const picker = picking ? attachOverlapPicker(picking.canvas, container, () => controls.object, + documentId, picking.objects, picking.select) : undefined; + const cross = new THREE.AxesHelper(10); + cross.visible = false; + scene.add(cross); + const toolbar = document.createElement("div"); + toolbar.className = "scene-display-tools"; + toolbar.setAttribute("aria-label", "3D display controls"); + const axes = document.createElement("input"); + axes.type = "checkbox"; axes.setAttribute("aria-label", "Axis cross"); + const play = document.createElement("input"); + play.type = "checkbox"; play.setAttribute("aria-label", "Turntable"); + const speed = document.createElement("input"); + speed.type = "range"; speed.min = "-10"; speed.max = "10"; speed.step = "0.25"; speed.value = "2"; + speed.setAttribute("aria-label", "Turntable speed"); + const label = (text: string, control: HTMLElement) => { + const element = document.createElement("label"); + element.append(control, document.createTextNode(text)); + toolbar.append(element); + }; + label("轴十字", axes); label("转台", play); label("速度", speed); + const stop = document.createElement("button"); + stop.type = "button"; stop.textContent = "停止"; stop.title = "停止转台"; + toolbar.append(stop); + if (picker) { + const choose = document.createElement("button"); + choose.type = "button"; choose.textContent = "选择重叠对象"; choose.title = "选择重叠对象"; + choose.onclick = () => picker.show(); + toolbar.append(choose); + } + let disposed = false; + let unsubscribeNavigation: (() => void) | undefined; + if (navigation) { + const select = document.createElement("select"); + select.setAttribute("aria-label", "Navigation style"); select.disabled = true; + for (const style of navigationStyles) { + const option = document.createElement("option"); + option.id = style.id; option.value = style.value; option.textContent = style.label; + select.append(option); + } + select.value = defaultNavigationStyle; + const orbit = document.createElement("select"); + orbit.setAttribute("aria-label", "Orbit style"); orbit.disabled = true; + orbitStyles.forEach((name, value) => { + const option = document.createElement("option"); + option.value = String(value); option.textContent = name; orbit.append(option); + }); + orbit.value = "4"; + const error = document.createElement("span"); + error.setAttribute("role", "alert"); error.className = "scene-camera-error"; error.hidden = true; + const indicator = document.createElement("label"); + indicator.className = "scene-navigation-indicator"; indicator.hidden = true; + const caption = document.createElement("span"); caption.textContent = "Navigation"; + const iconNodes: Record = { + Blender: Move, CAD: MousePointer2, Gesture: Rotate3d, MayaGesture: Hand, + OpenCascade: Compass, OpenInventor: Crosshair, Revit: Mouse, + SiemensNX: Navigation, SolidWorks: LocateFixed, TinkerCAD: Orbit, Touchpad: Smartphone, + }; + let icon = createElement(MousePointer2, { width: 16, height: 16, "aria-hidden": "true" }); + indicator.append(icon, select, caption); + const settings = document.createElement("details"); + const summary = document.createElement("summary"); summary.textContent = "Navigation settings"; + settings.append(summary); + settings.addEventListener("keydown", event => { + if (event.key === "Escape") { event.stopPropagation(); settings.open = false; summary.focus(); } + }); + const toggles = new Map(); + let presentation: ViewPreferences = {}; + let styleHelp = ""; + const effectiveTheme = () => { + const root = document.documentElement; + const forced = root.dataset.theme || root.getAttribute("data-color-scheme") || + (root.classList.contains("dark") ? "dark" : root.classList.contains("light") ? "light" : ""); + if (forced) return forced.toLowerCase().includes("dark") ? "dark" : "light"; + return getComputedStyle(root).colorScheme.toLowerCase().includes("dark") || + (window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false) ? "dark" : "light"; + }; + const refreshIcon = () => { + const style = navigationStyles.find(item => item.value === select.value); + const name = style?.id.replace("Indicator_Navigation", "") ?? "CAD"; + const next = createElement(iconNodes[name] ?? MousePointer2, { width: 16, height: 16, "aria-hidden": "true" }); + next.dataset.theme = effectiveTheme(); + icon.replaceWith(next); icon = next; + }; + const renderPresentation = () => { + indicator.hidden = presentation.Enabled === false; + indicator.classList.toggle("is-compact", presentation.Compact === true); + select.title = presentation.Tooltip === false ? "" : styleHelp; + for (const [name, input] of toggles) input.checked = name === "Compact" ? presentation[name] === true : presentation[name] !== false; + }; + for (const [name, text] of [["Enabled", "Show navigation indicator"], ["Compact", "Compact"], ["Tooltip", "Tooltip"]]) { + const row = document.createElement("label"); + const input = document.createElement("input"); input.type = "checkbox"; input.disabled = true; + toggles.set(name, input); row.append(input, document.createTextNode(text)); settings.append(row); + input.onchange = async () => { + const value = input.checked; + toggles.forEach(toggle => { toggle.disabled = true; }); + try { + const result = await navigation.source.writeIndicator(name, value); + if (disposed) return; + presentation = result.values; renderPresentation(); + error.textContent = result.error ?? ""; error.hidden = !result.error; + } catch (cause) { + if (!disposed) { renderPresentation(); error.textContent = String(cause); error.hidden = false; } + } finally { if (!disposed) toggles.forEach(toggle => { toggle.disabled = false; }); } + }; + } + let revision = 0; + const apply = (result: { values: ViewPreferences; error?: string }) => { + navigation.apply(result.values); + orbit.value = String(orbitStyle(result.values.OrbitStyle)); + const value = String(result.values.NavigationStyle || defaultNavigationStyle); + const normalized = value === "Undefined" ? defaultNavigationStyle : value; + select.querySelector("[data-unknown-style]")?.remove(); + const known = navigationStyles.find(style => style.value === normalized); + if (!known) { + const option = document.createElement("option"); option.value = normalized; + option.textContent = `Unknown: ${normalized} (CAD input)`; option.dataset.unknownStyle = "true"; + select.append(option); + } + select.value = normalized; + select.setAttribute("aria-label", `Navigation style: ${known?.label ?? normalized}`); + styleHelp = known?.help ?? `Unknown native navigation style: ${normalized}. CAD input fallback.`; + refreshIcon(); + renderPresentation(); + error.textContent = result.error ?? ""; error.hidden = !result.error; + }; + const refresh = async () => { + const token = ++revision; + try { + const result = await navigation.source.read(); + const indicatorResult = await navigation.source.readIndicator(); + if (!disposed && token === revision) { + presentation = indicatorResult.values; + apply({ ...result, error: result.error ?? indicatorResult.error }); + toggles.forEach(toggle => { toggle.disabled = false; }); + } + } + catch (cause) { if (!disposed && token === revision) { error.textContent = String(cause); error.hidden = false; } } + finally { if (!disposed && token === revision) select.disabled = orbit.disabled = false; } + }; + select.onchange = async () => { + const value = select.value; + if (!navigationStyles.some(style => style.value === value)) return; + navigation.cancel(); select.disabled = orbit.disabled = true; + ++revision; + try { + const result = await navigation.source.write(value); + if (!disposed) apply(result); + } catch (cause) { + if (!disposed) { await refresh(); error.textContent = String(cause); error.hidden = false; } + } finally { if (!disposed) select.disabled = orbit.disabled = false; } + }; + select.addEventListener("pointerdown", refreshIcon); + select.addEventListener("focus", refreshIcon); + const themeObserver = new MutationObserver(refreshIcon); + themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ["class", "style", "data-theme", "data-color-scheme"] }); + const themeMedia = window.matchMedia?.("(prefers-color-scheme: dark)"); + themeMedia?.addEventListener("change", refreshIcon); + orbit.onchange = async () => { + const value = Number(orbit.value); + navigation.cancel(); select.disabled = orbit.disabled = true; + ++revision; + try { + const result = await navigation.source.writeOrbit(value); + if (!disposed) apply(result); + } catch (cause) { + if (!disposed) { await refresh(); error.textContent = String(cause); error.hidden = false; } + } finally { if (!disposed) select.disabled = orbit.disabled = false; } + }; + toolbar.append(indicator, settings); label("Orbit style", orbit); toolbar.append(error); + unsubscribeNavigation = navigation.source.subscribe(() => { void refresh(); }); + void refresh(); + const oldUnsubscribe = unsubscribeNavigation; + unsubscribeNavigation = () => { + oldUnsubscribe?.(); themeObserver.disconnect(); themeMedia?.removeEventListener("change", refreshIcon); + }; + } + const oldPosition = container.style.position; + if (getComputedStyle(container).position === "static") container.style.position = "relative"; + container.append(toolbar); + const states = new Map(); + const state = () => states.get(documentId()) ?? { axes: false, rotating: false, speed: 2 }; + const apply = (next: SceneDisplayState) => { + states.set(documentId(), next); + cross.visible = next.axes; + controls.autoRotate = next.rotating; + controls.autoRotateSpeed = next.speed; + axes.checked = next.axes; play.checked = next.rotating; speed.value = String(next.speed); + invalidate(); + return { ...next }; + }; + axes.onchange = () => apply({ ...state(), axes: axes.checked }); + play.onchange = () => apply({ ...state(), rotating: play.checked }); + speed.oninput = () => apply({ ...state(), speed: Number(speed.value) }); + stop.onclick = () => apply({ ...state(), rotating: false }); + const replaceControls = (next: OrbitControls) => { + controls.removeEventListener("change", changed); + controls = next; + controls.addEventListener("change", changed); + picker?.close(); + onControlsChanged?.(next); + }; + const cameraCommands = onControlsChanged ? attachCameraCommands(() => controls, replaceControls, documentId, () => picking?.objects() ?? []) : undefined; + const runCameraCommand = (command: string, action: unknown) => { + const camera = cameraCommands?.execute(command, action); + if (!camera) return; + const next = { ...state(), camera }; + return action === "read" || action === "cancel" ? next : apply({ ...next, rotating: controls.autoRotate }); + }; + if (cameraCommands) { + const error = document.createElement("span"); + error.className = "scene-camera-error"; error.setAttribute("role", "alert"); error.hidden = true; + const execute = (command: string) => { + try { runCameraCommand(command, "apply"); error.hidden = true; error.textContent = ""; } + catch (cause) { error.textContent = cause instanceof Error ? cause.message : String(cause); error.hidden = false; } + }; + const views = document.createElement("select"); + views.setAttribute("aria-label", "标准视图"); views.title = "标准视图"; + for (const [command, title] of [["", "视图"], ["Std_ViewTop", "顶视图"], ["Std_ViewBottom", "底视图"], + ["Std_ViewFront", "前视图"], ["Std_ViewRear", "后视图"], ["Std_ViewLeft", "左视图"], ["Std_ViewRight", "右视图"], + ["Std_ViewIsometric", "等轴测"], ["Std_ViewDimetric", "正二轴测"], ["Std_ViewTrimetric", "正三轴测"]]) { + const option = document.createElement("option"); option.value = command; option.textContent = title; views.append(option); + } + views.onchange = () => { if (views.value) execute(views.value); views.value = ""; }; + toolbar.append(views); + const button = (command: string, title: string, icon: IconNode) => { + const element = document.createElement("button"); element.type = "button"; + element.className = "scene-camera-button"; element.title = title; element.setAttribute("aria-label", title); + element.append(createElement(icon, { width: 16, height: 16, "aria-hidden": "true" })); + element.onclick = () => execute(command); toolbar.append(element); + }; + button("Std_ViewZoomIn", "放大", ZoomIn); button("Std_ViewZoomOut", "缩小", ZoomOut); + button("Std_ViewFitAll", "适配全部", Maximize); + button("Std_ViewRotateLeft", "向左旋转视图", RotateCcw); button("Std_ViewRotateRight", "向右旋转视图", RotateCw); + button("Std_StoreWorkingView", "存储工作视图", Save); button("Std_RecallWorkingView", "恢复工作视图", History); + toolbar.append(error); + } + const unregister = registerSceneCommandHost({ + documentId, + widgetSurface: container, + visible: () => container.isConnected && container.getClientRects().length > 0, + execute(command, args) { + const action = args.action ?? "apply"; + if (!["read", "apply", "accept", "cancel"].includes(String(action))) throw new Error("Unknown view action"); + const next = { ...state() }; + const cameraResult = runCameraCommand(command, action); + if (cameraResult) return cameraResult; + if (command === "Std_ClarifySelection") { + if (!picker) throw new Error("This view has no object picking provider"); + if (action === "read") return { ...next, selectionScope: "rendered-object", ...picker.snapshot() }; + if (action === "cancel") { picker.close(); return { ...next, selectionScope: "rendered-object", selectionPending: false, candidates: [] }; } + const point = args.point; + if (point !== undefined && (!Array.isArray(point) || point.length !== 2 || point.some(value => typeof value !== "number" || !Number.isFinite(value)))) + throw new Error("point requires two finite canvas coordinates"); + const bounds = picking!.canvas.getBoundingClientRect(); + const candidates = picker.show(Array.isArray(point) ? { x: bounds.left + point[0], y: bounds.top + point[1] } : undefined); + return { ...next, selectionScope: "rendered-object", selectionPending: candidates.length > 0, candidates }; + } + if (action === "read") return next; + if (command === "Std_AxisCross") { + if (args.enabled !== undefined && typeof args.enabled !== "boolean") throw new Error("enabled must be boolean"); + if (action === "cancel") return next; + next.axes = typeof args.enabled === "boolean" ? args.enabled : !next.axes; + } else if (command === "Std_DemoMode") { + if (args.speed !== undefined && (typeof args.speed !== "number" || !Number.isFinite(args.speed) || Math.abs(args.speed) > 10)) throw new Error("Turntable speed must be between -10 and 10"); + if (args.play !== undefined && typeof args.play !== "boolean") throw new Error("play must be boolean"); + next.rotating = action === "cancel" ? false : typeof args.play === "boolean" ? args.play : !next.rotating; + if (typeof args.speed === "number") next.speed = args.speed; + toolbar.hidden = false; + } else throw new Error("This view has no handler for the requested command"); + return apply(next); + }, + }); + // A view may switch documents without being remounted. + let active = documentId(); + const changed = () => { + if (active === documentId()) return; + active = documentId(); + picker?.close(); + apply({ ...state(), rotating: false }); + }; + controls.addEventListener("change", changed); + return { replaceControls, executeCamera: (command: string) => runCameraCommand(command, "apply"), dispose() { + disposed = true; unsubscribeNavigation?.(); + cameraCommands?.dispose(); + picker?.dispose(); + unregister(); controls.removeEventListener("change", changed); controls.autoRotate = false; + toolbar.remove(); cross.removeFromParent(); cross.geometry.dispose(); + const materials = Array.isArray(cross.material) ? cross.material : [cross.material]; + materials.forEach(material => material.dispose()); + container.style.position = oldPosition; + } }; +} diff --git a/web/src/scene-document.ts b/web/src/scene-document.ts new file mode 100644 index 00000000..33ecb827 --- /dev/null +++ b/web/src/scene-document.ts @@ -0,0 +1,22 @@ +export interface SceneDocument { + documentId: string; + documentToken?: string; + action?: string; + undoCount?: number; + redoCount?: number; + selection: string[]; + created?: string[]; + removed?: string[]; + modified?: string[]; + file?: { name: string; base64: string }; + objects: Array<{ + name: string; label: string; typeId: string; dependencies: string[]; + measurement?: import("./measure-document-adapter.js").DistanceAnnotation; + faceCount?: number; edgeCount?: number; visible?: boolean; + explodeGroup?: { eligible: boolean; reason: string }; + color?: number[]; colors?: number[]; opacity?: number; points?: number[][]; facets?: number[][]; lines?: number[][][]; pointMarkers?: number[][]; + placement?: number[]; + tolerance?: { vertex: number; edge: number; face: number }; + base?: string | null; + }>; +} diff --git a/web/src/scene-navigation.ts b/web/src/scene-navigation.ts new file mode 100644 index 00000000..67cca2f3 --- /dev/null +++ b/web/src/scene-navigation.ts @@ -0,0 +1,414 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +// Input sequences ported from src/Gui/Navigation/*NavigationStyle.cpp. +// Camera motion remains on the scene's existing OrbitControls/camera/target. +import * as THREE from "three"; +import { orbitStyle, rotateOrbit } from "./scene-orbit-model.js"; +import { OrbitControls } from "three/addons/controls/OrbitControls.js"; +import type { ViewPreferences } from "./view-navigation-preferences.js"; + +export const navigationStyles = [ + ["Blender", "Blender", "Shift+middle: pan; middle: rotate; Ctrl+middle: zoom; left+right: pan"], + ["CAD", "CAD", "Middle: pan; hold middle then left/right: rotate; click and release left/right while holding middle: zoom; Ctrl+right: pan; Shift+right: rotate; Ctrl+Shift+right: zoom"], + ["Gesture", "Gesture", "Left drag: rotate; right drag or hold left then drag: pan; left+right drag: tilt; one finger: rotate; two fingers: pan/pinch zoom; H or middle: recenter"], + ["MayaGesture", "MayaGesture", "Alt+left: rotate; Alt+middle: pan; Alt+right: zoom; one finger: rotate; two fingers: pan/pinch zoom/twist"], + ["OpenCascade", "OpenCascade", "Middle or Ctrl+middle: pan; Ctrl+right: rotate; Ctrl+left horizontal drag: zoom"], + ["OpenInventor", "Inventor", "Ctrl/Shift+left: select; left: rotate; middle or Ctrl+Shift: pan; left+middle or Ctrl+middle: zoom"], + ["Revit", "Revit", "Middle or left+right: pan; Shift+middle: rotate; Ctrl+middle: zoom"], + ["SiemensNX", "SiemensNX", "Middle: rotate; middle+right or Shift+middle: pan; middle+left or Ctrl+middle: zoom; Home: isometric; End: trimetric; F8: top; Ctrl+F: fit"], + ["SolidWorks", "SolidWorks", "Middle: rotate; Ctrl+middle: pan; Shift+middle: zoom"], + ["TinkerCAD", "TinkerCAD", "Middle: pan; right: rotate"], + ["Touchpad", "Touchpad", "Shift and pointer motion: pan; Alt or Shift+left and motion: rotate; Ctrl+Shift and motion: zoom"], +].map(([id, native, help]) => ({ id: `Indicator_Navigation${id}`, value: `Gui::${native}NavigationStyle`, + label: id === "SiemensNX" ? "Siemens NX" : id, help: `${help}. Left click selects (OpenInventor: Ctrl/Shift+left); Ctrl adds selection. Wheel or PageUp/PageDown: zoom.` })); +export const defaultNavigationStyle = "Gui::CADNavigationStyle"; +type Mode = "idle" | "select" | "pan" | "rotate" | "zoom" | "tilt"; +type Point = { x: number; y: number }; + +export class SceneNavigation { + enabled = true; + // Set while a transform controller is attached. Left-button presses land on + // the gizmo (which paints its own handles); everything else, including + // middle-drag orbit and wheel zoom, still belongs to the navigation. + gizmoActive = false; + gizmoHover = false; + private controls: OrbitControls; + private style = "CAD"; + private preferences: ViewPreferences = {}; + private mode: Mode = "idle"; + private buttons = 0; + private start: Point | null = null; + private last: Point | null = null; + private started = 0; + private chordStarted = 0; + private moved = false; + private consumed = false; + private cancelled = false; + private cadZoom = false; + private seek = false; + private touch = new Map(); + private captured = new Set(); + private over = false; + private blockContext = false; + private gestureMode: Mode | null = null; + private readonly originalTouchAction: string; + constructor(private canvas: HTMLCanvasElement, controls: OrbitControls, + private pick: (point: Point, additive: boolean) => void, + private hitPoint: (point: Point) => THREE.Vector3 | undefined, + private command: (command: string) => void, + private invalidate: () => void, + private replaceControls: (controls: OrbitControls) => void) { + this.controls = controls; + this.originalTouchAction = canvas.style.touchAction; + this.bind(controls); + canvas.tabIndex = 0; + canvas.setAttribute("aria-label", "3D viewport"); + canvas.addEventListener("pointerdown", this.pointer, true); + canvas.addEventListener("pointermove", this.pointer, true); + canvas.addEventListener("pointerup", this.pointer, true); + canvas.addEventListener("blur", this.cancelEvent); + canvas.addEventListener("pointercancel", this.cancelEvent, true); + canvas.addEventListener("lostpointercapture", this.lostCapture, true); + canvas.addEventListener("pointerenter", this.enter); + canvas.addEventListener("pointerleave", this.leave); + canvas.addEventListener("wheel", this.wheel, { passive: false, capture: true }); + canvas.addEventListener("contextmenu", this.context, true); + window.addEventListener("keydown", this.key, true); + window.addEventListener("keyup", this.key, true); + window.addEventListener("blur", this.cancelEvent); + document.addEventListener("visibilitychange", this.visibility); + } + bind(controls: OrbitControls) { + this.cancel(); this.controls = controls; + // Disconnect only OrbitControls' default input listeners. Its camera, + // public motion methods, change events and scene commands are reused. + controls.disconnect(); controls.enableDamping = false; + this.canvas.style.touchAction = "none"; + } + apply(preferences: ViewPreferences) { + this.cancel(); this.preferences = preferences; + const value = String(preferences.NavigationStyle || defaultNavigationStyle); + this.style = navigationStyles.find(item => item.value === value)?.label.replace(" ", "") ?? "CAD"; + } + cancel() { + this.cancelled = true; this.consumed = true; this.seek = false; + this.start = null; this.last = null; this.mode = "idle"; this.buttons = 0; + this.cadZoom = false; this.gestureMode = null; this.touch.clear(); + const captured = [...this.captured]; + this.captured.clear(); + for (const id of captured) if (this.canvas.hasPointerCapture(id)) this.canvas.releasePointerCapture(id); + } + private enter = () => { this.over = true; }; + private leave = () => { this.over = false; if (!this.buttons) this.last = null; }; + private cancelEvent = () => { this.blockContext = true; this.cancel(); }; + private lostCapture = (event: PointerEvent) => { if (this.captured.has(event.pointerId)) this.cancelEvent(); }; + private visibility = () => { if (document.hidden) this.cancelEvent(); }; + private choose(event: MouseEvent | KeyboardEvent, buttons: number): Mode { + const l = !!(buttons & 1), r = !!(buttons & 2), m = !!(buttons & 4); + const c = event.ctrlKey, s = event.shiftKey, a = event.altKey; + switch (this.style) { + case "CAD": + if (m && (l || r)) return "rotate"; + if (m) return this.cadZoom ? "zoom" : "pan"; + if (r && c && s) return "zoom"; + if (r && c) return "pan"; + if (r && s) return "rotate"; + break; + case "Blender": + if (l && r) return "pan"; + if ((m && c) || (r && c && s)) return "zoom"; + if (m && s) return "pan"; + if (m) return "rotate"; + break; + case "Revit": + if (l && r) return "pan"; + if ((m && c) || (r && c && s)) return "zoom"; + if (m && s) return "rotate"; + if (m) return "pan"; + break; + case "SolidWorks": + if (m && c) return "pan"; + if (m && s) return "zoom"; + if (m) return "rotate"; + break; + case "SiemensNX": + if (m && (r || s)) return "pan"; + if (m && (l || c)) return "zoom"; + if (m) return "rotate"; + break; + case "OpenCascade": + if (l && c) return "zoom"; + if (r && c) return "rotate"; + if (m) return "pan"; + break; + case "OpenInventor": + if ((l && m) || (c && m) || (c && s && r)) return "zoom"; + if (m || (c && s)) return "pan"; + if (l) return c || s ? "select" : "rotate"; + break; + case "TinkerCAD": + if (m) return "pan"; + if (r) return "rotate"; + break; + case "Touchpad": + if (c && s) return "zoom"; + if (a || (s && l)) return "rotate"; + if (s) return "pan"; + break; + case "Gesture": + if (l && r) return "tilt"; + if (this.gestureMode && buttons) return this.gestureMode; + if (r) return "pan"; + if (l && !a && !c && !s) return performance.now() - this.started >= this.holdTime() ? "pan" : "rotate"; + break; + case "MayaGesture": + if (a && l && r) return "tilt"; + if (a && m) return "pan"; + if (a && r) return "zoom"; + if (a && l) return "rotate"; + break; + } + return l ? "select" : "idle"; + } + private holdTime() { return Math.max(1, Number(this.preferences.GestureTapHoldTimeout) || 650); } + private threshold() { return Math.max(1, Number(this.preferences.GestureMoveThreshold) || 5); } + private isGesture() { return this.style === "Gesture" || this.style === "MayaGesture"; } + private pointer = (event: PointerEvent) => { + if (!this.enabled) return; + if (this.gizmoActive && this.gizmoHover && event.pointerType !== "touch") { + const leftDrag = (event.buttons & 1) === 1 && (event.buttons & 6) === 0; + const leftRelease = event.type === "pointerup" && event.button === 0 && !event.buttons; + if (leftDrag || leftRelease) return; + } + const point = { x: event.clientX, y: event.clientY }; + if (event.type === "pointerdown") { + this.canvas.focus({ preventScroll: true }); + if (!this.buttons && !this.touch.size) { + this.cancelled = false; this.consumed = false; this.moved = false; this.blockContext = false; + this.start = point; this.last = point; this.started = performance.now(); this.gestureMode = null; + } + this.captured.add(event.pointerId); this.canvas.setPointerCapture(event.pointerId); + } + if (this.cancelled && event.buttons) return; + if (event.pointerType === "touch" && this.isGesture()) { + this.touchPointer(event, point); event.preventDefault(); return; + } + const before = this.buttons; + this.buttons = event.buttons; + const added = this.buttons & ~before, removed = before & ~this.buttons; + // A mouse emits pointermove, not pointerdown/up, for additional buttons. + if (this.style === "CAD") { + if ((before & 4) && (added & 3)) { this.chordStarted = performance.now(); this.cadZoom = false; } + if ((this.buttons & 4) && (removed & 3) && this.mode === "rotate") + this.cadZoom = performance.now() - this.chordStarted < 400; + if (!(this.buttons & 4)) this.cadZoom = false; + } + if ((this.buttons & (this.buttons - 1)) !== 0) this.consumed = true; + const mode = this.choose(event, this.buttons); + if (event.type === "pointermove") { + const delta = this.last ? { x: point.x - this.last.x, y: point.y - this.last.y } : { x: 0, y: 0 }; + if (this.start && Math.hypot(point.x - this.start.x, point.y - this.start.y) > this.threshold()) this.moved = true; + if (mode !== "idle" && mode !== "select" && (this.moved || !this.buttons)) { + this.consumed = true; this.blockContext = true; + if (this.style === "Gesture") this.gestureMode = mode; + this.motion(mode, delta, point); + } + if (this.moved) this.consumed = true; + this.last = point; + } + if (mode !== "idle" && mode !== "select" && !["Gesture"].includes(this.style)) this.consumed = true; + if (event.type === "pointerup") { + const selectionClick = !this.consumed && !this.moved && this.start && event.button === 0; + if (this.seek && event.button === 0) { this.recenter(point); this.seek = false; } + else if (selectionClick) { + if (this.style === "Gesture" && performance.now() - this.started >= this.holdTime()) this.showContext(point); + else this.pick(point, event.ctrlKey || (this.style === "OpenInventor" && event.shiftKey)); + } + if (event.button === 1 && !this.moved && this.start && performance.now() - this.started < 400 + && ["CAD", "Blender", "Revit", "SolidWorks", "SiemensNX", "Gesture", "MayaGesture"].includes(this.style)) this.recenter(point); + this.captured.delete(event.pointerId); + if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId); + this.start = null; this.cadZoom = false; this.gestureMode = null; + } + this.mode = mode; + if (event.buttons || event.type === "pointerup") event.preventDefault(); + }; + private touchPointer(event: PointerEvent, point: Point) { + const before = [...this.touch.values()]; + if (event.type === "pointerdown") { + this.touch.set(event.pointerId, point); + if (this.touch.size > 1) { this.consumed = true; this.blockContext = true; } + return; + } + if (!this.touch.has(event.pointerId)) return; + if (event.type === "pointerup") { + if (this.touch.size === 1 && !this.consumed && !this.moved) { + if (performance.now() - this.started >= this.holdTime()) this.showContext(point); + else this.pick(point, event.ctrlKey); + } + this.touch.delete(event.pointerId); this.captured.delete(event.pointerId); + if (this.canvas.hasPointerCapture(event.pointerId)) this.canvas.releasePointerCapture(event.pointerId); + if (!this.touch.size) { this.start = null; this.gestureMode = null; } + return; + } + this.touch.set(event.pointerId, point); + const after = [...this.touch.values()]; + if (after.length >= 2) { + const center = (p: Point[]) => ({ x: (p[0].x + p[1].x) / 2, y: (p[0].y + p[1].y) / 2 }); + const a = center(before), b = center(after); + this.motion("pan", { x: b.x - a.x, y: b.y - a.y }, b); + const distance = (p: Point[]) => Math.hypot(p[1].x - p[0].x, p[1].y - p[0].y); + if (distance(before) > 0 && distance(after) > 0) this.zoom(Math.log(distance(before) / distance(after)), b); + if (this.style === "MayaGesture" || this.preferences.DisableTouchTilt === false) { + const angle = (p: Point[]) => Math.atan2(p[1].y - p[0].y, p[1].x - p[0].x); + this.roll(angle(before) - angle(after)); + } + this.consumed = true; this.moved = true; + } else if (this.start && Math.hypot(point.x - this.start.x, point.y - this.start.y) > this.threshold()) { + this.moved = true; this.consumed = true; this.blockContext = true; + const mode = this.gestureMode ?? (this.style === "Gesture" && performance.now() - this.started >= this.holdTime() ? "pan" : "rotate"); + this.gestureMode = mode; + this.motion(mode, { x: point.x - before[0].x, y: point.y - before[0].y }, point); + } + } + private motion(mode: Mode, delta: Point, point: Point) { + const controls = this.controls; + controls.autoRotate = false; + const height = Math.max(this.canvas.clientHeight, 1), width = Math.max(this.canvas.clientWidth, 1); + if (mode === "pan") controls.pan(delta.x, delta.y); + if (mode === "rotate") { + const bounds = this.canvas.getBoundingClientRect(); + const normalize = (x: number, y: number) => ({ + x: 2 * (x - bounds.left) / Math.max(bounds.width - 1, 1) - 1, + y: 1 - 2 * (y - bounds.top) / Math.max(bounds.height - 1, 1), + }); + rotateOrbit(controls.object, controls.target, orbitStyle(this.preferences.OrbitStyle), + normalize(point.x - delta.x, point.y - delta.y), normalize(point.x, point.y)); + this.replaceMotionControls(); + } + if (mode === "tilt") this.roll(-2 * Math.PI * delta.x / width); + if (mode === "zoom") { + const value = this.style === "OpenCascade" ? delta.x / width + : this.style === "MayaGesture" ? delta.x / width + delta.y / height : -delta.y / height; + this.zoom(value * 10 * (this.preferences.InvertZoom ? -1 : 1), point); + } + this.invalidate(); + } + private planePoint(point: Point): THREE.Vector3 | undefined { + const bounds = this.canvas.getBoundingClientRect(); + const camera = this.controls.object; + camera.updateMatrixWorld(); + const ray = new THREE.Raycaster(); + ray.setFromCamera(new THREE.Vector2((point.x - bounds.left) / bounds.width * 2 - 1, + 1 - (point.y - bounds.top) / bounds.height * 2), camera); + return ray.ray.intersectPlane(new THREE.Plane().setFromNormalAndCoplanarPoint( + camera.getWorldDirection(new THREE.Vector3()), this.controls.target), new THREE.Vector3()) ?? undefined; + } + private zoom(amount: number, point?: Point) { + const controls = this.controls; + const anchor = point && this.preferences.ZoomAtCursor !== false ? this.planePoint(point) : undefined; + controls.autoRotate = false; + controls.dollyIn(Math.exp(Math.max(-2, Math.min(2, amount)))); + if (anchor && point) { + const next = this.planePoint(point); + if (next) { const delta = anchor.sub(next); controls.target.add(delta); controls.object.position.add(delta); controls.update(); } + } + this.invalidate(); + } + private roll(angle: number) { + const camera = this.controls.object; + const rotation = new THREE.Quaternion().setFromAxisAngle(camera.getWorldDirection(new THREE.Vector3()), angle); + camera.up.applyQuaternion(rotation); camera.quaternion.premultiply(rotation); + this.replaceMotionControls(); + } + private replaceMotionControls() { + const camera = this.controls.object; + // OrbitControls caches its up-axis basis at construction, so a rotation must + // replace the controls through the same scene owner as camera commands. + const old = this.controls; + const next = new OrbitControls(camera, this.canvas); + next.target.copy(old.target); + next.minDistance = old.minDistance; next.maxDistance = old.maxDistance; + next.minZoom = old.minZoom; next.maxZoom = old.maxZoom; + next.autoRotate = false; + old.dispose(); + // Preserve the in-progress gesture; bind() deliberately cancels gestures + // for external camera replacements, but this replacement is part of one. + const gesture = { start: this.start, last: this.last, mode: this.mode, + buttons: this.buttons, touch: new Map(this.touch), captured: new Set(this.captured), + gestureMode: this.gestureMode, consumed: this.consumed, cancelled: this.cancelled }; + this.captured.clear(); + this.replaceControls(next); + Object.assign(this, gesture); + next.update(); this.invalidate(); + } + private recenter(point: Point) { + const hit = this.hitPoint(point) ?? this.planePoint(point); + if (!hit) return; + const delta = hit.clone().sub(this.controls.target); + this.controls.object.position.add(delta); this.controls.target.copy(hit); + this.controls.update(); this.invalidate(); + } + private showContext(point: Point) { + this.blockContext = false; + this.canvas.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: point.x, clientY: point.y })); + this.blockContext = true; + } + private context = (event: MouseEvent) => { + if (this.blockContext || this.buttons > 2 || this.touch.size > 1) { event.preventDefault(); event.stopImmediatePropagation(); } + }; + private wheel = (event: WheelEvent) => { + if (!this.enabled) return; + // TransformControls never listens to wheel, so zoom must always reach the + // navigation -- including while the pointer hovers a gizmo handle. + event.preventDefault(); event.stopImmediatePropagation(); this.consumed = true; + const step = Number(this.preferences.ZoomStep) || 0.2; + const amount = event.deltaY * (event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? this.canvas.clientHeight : 1); + this.zoom(amount / 100 * step * (this.preferences.InvertZoom ? -1 : 1), { x: event.clientX, y: event.clientY }); + }; + private key = (event: KeyboardEvent) => { + if (!this.enabled) return; + const target = event.target as HTMLElement; + if (target !== this.canvas && (!this.over || target?.closest("input,textarea,select,button,[contenteditable=true]"))) return; + if (event.key === "Escape") { this.cancelEvent(); return; } + if (["Shift", "Control", "Alt"].includes(event.key)) { + this.mode = this.choose(event, this.buttons); + if (this.style === "Touchpad") { event.preventDefault(); this.last = null; } + return; + } + if (event.type !== "keydown") return; + let command = ""; + if (this.style === "SiemensNX") { + if (event.key === "Home") command = "Std_ViewIsometric"; + if (event.key === "End") command = "Std_ViewTrimetric"; + if (event.key === "F8") command = "Std_ViewTop"; + if (event.ctrlKey && event.key.toLowerCase() === "f") command = "Std_ViewFitAll"; + } else if (event.key === "Home") command = "Std_ViewFitAll"; + if (command) { event.preventDefault(); this.cancel(); this.command(command); return; } + if (event.key === "PageUp" || event.key === "PageDown") { + event.preventDefault(); this.zoom((event.key === "PageUp" ? -1 : 1) * (Number(this.preferences.ZoomStep) || 0.2), this.last ?? undefined); + } else if (event.key.toLowerCase() === "s") { this.seek = !this.seek; event.preventDefault(); } + else if (this.style === "Gesture" && event.key.toLowerCase() === "h" && this.last) { this.recenter(this.last); event.preventDefault(); } + else if (event.key.startsWith("Arrow")) { + event.preventDefault(); + this.controls.pan(event.key === "ArrowLeft" ? 10 : event.key === "ArrowRight" ? -10 : 0, + event.key === "ArrowUp" ? 10 : event.key === "ArrowDown" ? -10 : 0); + this.invalidate(); + } + }; + dispose() { + this.cancel(); + this.canvas.removeEventListener("pointerdown", this.pointer, true); + this.canvas.removeEventListener("pointermove", this.pointer, true); + this.canvas.removeEventListener("pointerup", this.pointer, true); + this.canvas.removeEventListener("blur", this.cancelEvent); + this.canvas.removeEventListener("pointercancel", this.cancelEvent, true); + this.canvas.removeEventListener("lostpointercapture", this.lostCapture, true); + this.canvas.removeEventListener("pointerenter", this.enter); + this.canvas.removeEventListener("pointerleave", this.leave); + this.canvas.removeEventListener("wheel", this.wheel, true); + this.canvas.removeEventListener("contextmenu", this.context, true); + window.removeEventListener("keydown", this.key, true); window.removeEventListener("keyup", this.key, true); + window.removeEventListener("blur", this.cancelEvent); document.removeEventListener("visibilitychange", this.visibility); + this.canvas.style.touchAction = this.originalTouchAction; + } +} diff --git a/web/src/scene-viewport.tsx b/web/src/scene-viewport.tsx new file mode 100644 index 00000000..534c2687 --- /dev/null +++ b/web/src/scene-viewport.tsx @@ -0,0 +1,595 @@ +import type { InspectionDisplayAttributes } from "./inspection-result-display.js"; +import { distanceAnnotation } from "./measure-annotation.js"; +import React, { useEffect, useRef } from "react"; +import * as THREE from "three"; +import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js"; +import type { SceneDocument } from "./scene-document.js"; +import { attachSceneCommands } from "./scene-command-host.js"; +import { SelectionDecoration } from "./selection-decoration.js"; +import type { PointsViewState } from "./points-document-facade.js"; + +export type ViewPolygon = { polygon: { x: number; y: number }[]; viewProjection: number[] }; + +export interface FacetInteraction { + mode: "triangle" | "region" | "box" | "navigate"; + visibleOnly: boolean; frontOnly: boolean; + components: Record; componentOnClick: boolean; + selected: Record; + request?: { id: number; mode: "all" | "small"; maximum: number }; + onFacets: (facets: Record, toggle?: boolean) => void; +} + +export type InspectionHit = { object: string; index?: number; facet?: number; point: [number, number, number] }; + +export function SceneViewport({ viewportHeight = 420, onReady, facetInteraction, polygonMode = false, onPolygon, onCancelPolygon, inspectionMode, onInspect, inspectionAnnotations = [], document, selected, onSelect, onPickMesh, meshInfoMode = false, onHoverMesh, onPickPoint, onPickVertex, onPickLocation, onCancelPick, onViewDirection, ariaLabel = "Geometry viewport", reserveControlsSpace = false, preserveCamera = false, onPickEdge }: { + document: SceneDocument & { objects: Array }; selected: string[]; onSelect: (name: string) => void; ariaLabel?: string; reserveControlsSpace?: boolean; preserveCamera?: boolean; + meshInfoMode?: boolean; + onHoverMesh?: (facet: number | null) => void; + onPickEdge?: (object: string, subelement: string) => void; + onReady?: () => void; + viewportHeight?: number; + facetInteraction?: FacetInteraction; + polygonMode?: boolean; + onPolygon?: (capture: ViewPolygon) => void; + onCancelPolygon?: () => void; + inspectionMode?: "inspect" | "navigate"; + onInspect?: (hit: InspectionHit) => void; + inspectionAnnotations?: Array<{ text: string; point: [number, number, number] }>; + onPickMesh?: (pick: { object: string; facet: number; point: [number, number, number]; direction: [number, number, number] }) => void; + onPickPoint?: (point: [number, number, number]) => void; + onPickVertex?: (point: [number, number, number]) => void; + onPickLocation?: (point: [number, number, number], normal?: [number, number, number]) => void; + onCancelPick?: () => void; + onViewDirection?: (direction: [number, number, number]) => void; +}) { + const meshInfo = useRef({ active: meshInfoMode, hover: onHoverMesh }); + meshInfo.current = { active: meshInfoMode, hover: onHoverMesh }; + const pickEdge = useRef(onPickEdge); pickEdge.current = onPickEdge; + const ready = useRef(onReady); ready.current = onReady; + const facets = useRef(facetInteraction); + facets.current = facetInteraction; + const handledFacetRequest = useRef(); + const polygonCallbacks = useRef({ onPolygon, onCancelPolygon }); + polygonCallbacks.current = { onPolygon, onCancelPolygon }; + const host = useRef(null); + const inspection = useRef({ mode: inspectionMode, pick: onInspect, annotations: inspectionAnnotations }); + inspection.current = { mode: inspectionMode, pick: onInspect, annotations: inspectionAnnotations }; + const savedCamera = useRef<{ documentId: string; position: THREE.Vector3; target: THREE.Vector3 }>(); + const select = useRef(onSelect); + select.current = onSelect; + const pickMesh = useRef(onPickMesh); + pickMesh.current = onPickMesh; + const pickPoint = useRef(onPickPoint); + pickPoint.current = onPickPoint; + const pickVertex = useRef(onPickVertex); + pickVertex.current = onPickVertex; + const pickLocation = useRef(onPickLocation); + pickLocation.current = onPickLocation; + const cancelPick = useRef(onCancelPick); + cancelPick.current = onCancelPick; + const viewDirection = useRef(onViewDirection); + viewDirection.current = onViewDirection; + useEffect(() => { + if (!host.current) return; + const container = host.current; + const renderer = new THREE.WebGLRenderer({ antialias: true }); + renderer.setPixelRatio(window.devicePixelRatio); + container.appendChild(renderer.domElement); + const scene = new THREE.Scene(); + scene.background = new THREE.Color(0xf1f3f5); + const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000000); + camera.up.set(0, 0, 1); + let controls: OrbitControls = new OrbitControls(camera, renderer.domElement); + const content = new THREE.Group(); + scene.add(content, new THREE.HemisphereLight(0xffffff, 0x555555, 3)); + // Shared selection decoration: the local frame is anchored at the selected + // object's bounding-box centre rather than at a scene origin. + const decoration = new SelectionDecoration(scene); + const publishDecoration = (value: SelectionDecoration) => { + (window as unknown as { __freecadSceneDecorationState?: unknown }).__freecadSceneDecorationState = value.snapshot(); + }; + const sceneCommands = attachSceneCommands(scene, controls, container, () => document.documentId, () => {}, { + canvas: renderer.domElement, + objects: () => content.children.filter(object => !object.userData.pointsDecoration && object.userData.selectable !== false).map(object => ({ + id: String(object.userData.name), + label: document.objects.find(entry => entry.name === object.userData.name)?.label || String(object.userData.name), + object, + })), + select: id => { if (!meshInfo.current.active && !inspection.current.mode && (!facets.current || facets.current.mode === "navigate")) select.current(id); }, + }, next => { controls = next; }); + const geometries: THREE.BufferGeometry[] = []; + const materials: THREE.Material[] = []; + for (const object of document.objects) { + if (object.visible === false) continue; + const pointView = object as typeof object & Partial; + const shapeSelection = selected.includes(object.name) && pointView.selectionStyle !== "Box"; + const color = shapeSelection ? new THREE.Color(0x16846b) + : object.color ? new THREE.Color(object.color[0], object.color[1], object.color[2]) : new THREE.Color(0xa3abb6); + if (object.points?.length && object.facets?.length) { + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(object.points.flat(), 3)); + geometry.setIndex(object.facets.flat()); + geometry.computeVertexNormals(); + const vertexColors = object.colors?.length === object.points.length * 3; + const vertexAlphas = vertexColors && object.alphas?.length === object.points.length; + if (vertexColors) { + const stride = vertexAlphas ? 4 : 3; + const values = new Float32Array(object.points.length * stride); + const value = new THREE.Color(); + for (let index = 0; index < object.points.length; ++index) { + value.setRGB(object.colors![index * 3], object.colors![index * 3 + 1], object.colors![index * 3 + 2], THREE.SRGBColorSpace).toArray(values, index * stride); + if (vertexAlphas) values[index * stride + 3] = object.alphas![index]; + } + geometry.setAttribute("color", new THREE.BufferAttribute(values, stride)); + } + const opacity = object.opacity ?? 1; + const transparent = opacity < 1 || Boolean(vertexAlphas && object.alphas!.some(alpha => alpha < 1)); + const material = new THREE.MeshStandardMaterial({ color: vertexColors ? 0xffffff : color, vertexColors, + opacity, transparent, depthWrite: !transparent, + emissive: vertexColors && selected.includes(object.name) ? 0x16846b : 0, emissiveIntensity: 0.1, side: THREE.DoubleSide }); + const mesh = new THREE.Mesh(geometry, material); + mesh.userData.name = object.name; + content.add(mesh); geometries.push(geometry); materials.push(material); + } + if (object.pointMarkers?.length) { + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(object.pointMarkers.flat(), 3)); + const requestedPointSize = (object as typeof object & InspectionDisplayAttributes).pointSize; + const pointSize = typeof requestedPointSize === "number" && Number.isFinite(requestedPointSize) + && requestedPointSize > 0 ? requestedPointSize : 7; + const attributes = object.pointAttributes; + const mode = object.pointDisplayMode; + const count = object.pointMarkers.length; + const opacity = object.opacity ?? 1; + let material: THREE.Material; + if (mode === "Shaded" && attributes?.Normal?.length === count) { + geometry.setAttribute("pointNormal", new THREE.Float32BufferAttribute(attributes.Normal.flat(), 3)); + material = new THREE.ShaderMaterial({ + transparent: opacity < 1, depthWrite: opacity >= 1, + uniforms: { baseColor: { value: color }, opacity: { value: opacity }, pixelRatio: { value: renderer.getPixelRatio() }, pointSize: { value: pointSize } }, + vertexShader: `attribute vec3 pointNormal; varying float shade; uniform float pixelRatio; uniform float pointSize; + void main() { vec3 n = normalMatrix * pointNormal; + shade = 0.25 + 0.75 * abs(dot(normalize(n), normalize(vec3(0.3, 0.5, 1.0)))); + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); gl_PointSize = pointSize * pixelRatio; }`, + fragmentShader: `uniform vec3 baseColor; uniform float opacity; varying float shade; + void main() { gl_FragColor = vec4(baseColor * shade, opacity); + #include + #include + }`, + }); + } else { + const colors = mode === "Color" && attributes?.Color?.length === count ? attributes.Color : undefined; + const intensities = mode === "Intensity" && attributes?.Intensity?.length === count ? attributes.Intensity + : mode === "Intensity" && object.curvature?.length === count ? object.curvature : undefined; + const alphas = colors && object.alphas?.length === count ? object.alphas : undefined; + const stride = alphas ? 4 : 3; + if (colors || intensities) { + const values = new Float32Array(count * stride); + for (let i = 0; i < count; ++i) { + const rgb = colors?.[i]; + const grey = Math.max(0, Math.min(1, intensities?.[i] ?? 0)); + new THREE.Color().setRGB(rgb?.[0] ?? grey, rgb?.[1] ?? grey, rgb?.[2] ?? grey, THREE.SRGBColorSpace).toArray(values, i * stride); + if (alphas) values[i * stride + 3] = alphas[i]; + } + geometry.setAttribute("color", new THREE.BufferAttribute(values, stride)); + } + material = new THREE.PointsMaterial({ color: shapeSelection ? color : colors || intensities ? 0xffffff : color, + vertexColors: Boolean(colors || intensities), opacity, transparent: Boolean(alphas) || opacity < 1, + depthWrite: !alphas && opacity >= 1, size: pointSize, sizeAttenuation: false }); + } + const points = new THREE.Points(geometry, material); + points.userData.name = object.name; + points.userData.selectable = pointView.selectable; + if (pointView.selectable === false) points.raycast = () => {}; + content.add(points); geometries.push(geometry); materials.push(material); + if (pointView.boundingBox || (pointView.selectionStyle === "Box" && selected.includes(object.name))) { + geometry.computeBoundingBox(); + if (geometry.boundingBox && !geometry.boundingBox.isEmpty()) { + const box = new THREE.Box3Helper(geometry.boundingBox, selected.includes(object.name) ? 0x16846b : 0x42484f); + box.userData.pointsDecoration = true; + box.raycast = () => {}; + content.add(box); geometries.push(box.geometry); materials.push(box.material as THREE.Material); + } + } + } + if (object.measurement) content.add(distanceAnnotation(object.measurement)); + const segments: number[] = []; + const inspectionLines = object as typeof object & { + inspectionLineIndices?: number[][]; + inspectionSampleColors?: number[][]; + inspectionSampleAlphas?: number[]; + }; + const segmentColors: number[] = []; + const segmentEdges: Array = []; + for (const [index, line] of (object.lines ?? []).entries()) { + const sub = object.lineSubelements?.[index]; + for (let i = 1; i < line.length; i++) { + segments.push(...line[i - 1], ...line[i]); + if (inspectionLines.inspectionLineIndices && inspectionLines.inspectionSampleColors) { + for (const vertex of [i - 1, i]) { + const sample = inspectionLines.inspectionLineIndices[index][vertex]; + const rgb = inspectionLines.inspectionSampleColors[sample]; + const color = new THREE.Color().setRGB(rgb[0], rgb[1], rgb[2], THREE.SRGBColorSpace); + segmentColors.push(color.r, color.g, color.b, inspectionLines.inspectionSampleAlphas?.[sample] ?? 1); + } + } + segmentEdges.push(sub && object.directionEdges?.includes(sub) ? sub : undefined); + } + } + if (segments.length) { + const geometry = new THREE.BufferGeometry(); + geometry.setAttribute("position", new THREE.Float32BufferAttribute(segments, 3)); + if (segmentColors.length) geometry.setAttribute("color", new THREE.Float32BufferAttribute(segmentColors, 4)); + const material = new THREE.LineBasicMaterial({ vertexColors: segmentColors.length > 0, + transparent: segmentColors.length > 0, color: segmentColors.length ? 0xffffff : object.typeId === "Part::Section" && object.color + ? color : selected.includes(object.name) ? 0x16846b : 0x42484f }); + const lines = new THREE.LineSegments(geometry, material); + lines.userData.name = object.name; + lines.userData.segmentEdges = segmentEdges; + lines.userData.inspectionLineIndices = inspectionLines.inspectionLineIndices; + content.add(lines); geometries.push(geometry); materials.push(material); + } + } + const highlight = new THREE.Group(); scene.add(highlight); + let previousFacetSelection: Record | undefined; + const updateFacetHighlights = () => { + if (previousFacetSelection === facets.current?.selected) return; + previousFacetSelection = facets.current?.selected; + for (const child of [...highlight.children]) { + const mesh = child as THREE.Mesh; mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); highlight.remove(child); + } + for (const object of document.objects) { + if (object.visible === false) continue; + const indices = facets.current?.selected[object.name]; + if (!indices?.length || !object.points || !object.facets) continue; + const positions = indices.flatMap(index => (object.facets![index] ?? []).flatMap(vertex => object.points![vertex])); + const geometry = new THREE.BufferGeometry(); geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3)); + const material = new THREE.MeshBasicMaterial({ color: 0xff8c18, side: THREE.DoubleSide, transparent: true, + opacity: 0.72, polygonOffset: true, polygonOffsetFactor: -1, polygonOffsetUnits: -1 }); + highlight.add(new THREE.Mesh(geometry, material)); + } + }; + const bounds = new THREE.Box3().setFromObject(content); + const center = bounds.isEmpty() ? new THREE.Vector3() : bounds.getCenter(new THREE.Vector3()); + const radius = bounds.isEmpty() ? 10 : Math.max(bounds.getSize(new THREE.Vector3()).length(), 0.01); + controls.target.copy(center); + camera.position.copy(center).add(new THREE.Vector3(1, -1, 0.8).normalize().multiplyScalar(radius * 1.7)); + if (preserveCamera && savedCamera.current?.documentId === document.documentId) { + camera.position.copy(savedCamera.current.position); controls.target.copy(savedCamera.current.target); + } + camera.near = radius / 10000; camera.far = radius * 100; + const toolbar = container.querySelector(".scene-display-tools"); + if (reserveControlsSpace) { + renderer.domElement.style.position = "absolute"; renderer.domElement.style.bottom = "0"; + } + const resize = () => { + const reserved = reserveControlsSpace && toolbar ? toolbar.offsetTop + toolbar.offsetHeight + 8 : 0; + const width = Math.max(container.clientWidth, 1), height = Math.max(container.clientHeight - reserved, 1); + renderer.setSize(width, height); camera.aspect = width / height; camera.updateProjectionMatrix(); + }; + const observer = new ResizeObserver(resize); observer.observe(container); if (toolbar && reserveControlsSpace) observer.observe(toolbar); resize(); + const facetMeshes = () => content.children.filter((object): object is THREE.Mesh => object instanceof THREE.Mesh); + const eligibleFacet = (mesh: THREE.Mesh, index: number) => { + const position = mesh.geometry.getAttribute("position"), indices = mesh.geometry.index!; + const a = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3)).applyMatrix4(mesh.matrixWorld); + const b = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3 + 1)).applyMatrix4(mesh.matrixWorld); + const c = new THREE.Vector3().fromBufferAttribute(position, indices.getX(index * 3 + 2)).applyMatrix4(mesh.matrixWorld); + const center = a.clone().add(b).add(c).multiplyScalar(1 / 3); + if (facets.current?.frontOnly && b.clone().sub(a).cross(c.clone().sub(a)).dot(camera.position.clone().sub(center)) <= 0) return false; + if (facets.current?.visibleOnly) { + const samples = [center, a.clone().lerp(center, 0.001), b.clone().lerp(center, 0.001), c.clone().lerp(center, 0.001)]; + if (!samples.some(point => { + const projected = point.project(camera); + if (projected.z < -1 || projected.z > 1 || Math.abs(projected.x) > 1 || Math.abs(projected.y) > 1) return false; + const ray = new THREE.Raycaster(); ray.setFromCamera(new THREE.Vector2(projected.x, projected.y), camera); + const hit = ray.intersectObjects(facetMeshes())[0]; + return hit?.object === mesh && hit.faceIndex === index; + })) return false; + } + return true; + }; + const collectFacets = (polygon?: { x: number; y: number }[]) => { + camera.updateMatrixWorld(true); content.updateMatrixWorld(true); + const inside = (point: THREE.Vector3) => { + if (!polygon) return true; + const p = point.project(camera); if (p.z < -1 || p.z > 1) return false; + const x = (p.x + 1) / 2, y = (p.y + 1) / 2; + let hit = false; + for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) { + const a = polygon[i], b = polygon[j]; + if ((a.y > y) !== (b.y > y) && x < (b.x - a.x) * (y - a.y) / (b.y - a.y) + a.x) hit = !hit; + } + return hit; + }; + const result: Record = {}; + for (const mesh of facetMeshes()) { + const indices = mesh.geometry.index!, points = mesh.geometry.getAttribute("position"); + const selected: number[] = []; + for (let index = 0; index < indices.count / 3; ++index) { + if (!eligibleFacet(mesh, index)) continue; + const corners = [0, 1, 2].map(offset => new THREE.Vector3().fromBufferAttribute(points, indices.getX(index * 3 + offset)).applyMatrix4(mesh.matrixWorld)); + if (corners.some(point => inside(point.clone())) || inside(corners[0].clone().add(corners[1]).add(corners[2]).multiplyScalar(1 / 3))) selected.push(index); + } + result[String(mesh.userData.name)] = selected; + } + return result; + }; + const polygonLayer = window.document.createElement("div"); + if (polygonMode || (facetInteraction?.mode === "region" || facetInteraction?.mode === "box")) { + controls.enabled = false; + polygonLayer.style.cssText = "position:absolute;inset:0;z-index:10;cursor:crosshair;touch-action:none"; + const svg = window.document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("viewBox", "0 0 1 1"); svg.setAttribute("preserveAspectRatio", "none"); + svg.style.cssText = "position:absolute;width:100%;height:100%;pointer-events:none"; + const outline = window.document.createElementNS(svg.namespaceURI, "polygon"); + outline.setAttribute("fill", "#16846b33"); outline.setAttribute("stroke", "#16846b"); outline.setAttribute("stroke-width", "0.004"); + svg.appendChild(outline); polygonLayer.appendChild(svg); + const vertices: { x: number; y: number }[] = []; + const buttons = window.document.createElement("div"); buttons.style.cssText = "position:absolute;top:8px;left:8px"; + const complete = window.document.createElement("button"); complete.textContent = facetInteraction ? "Select region" : "Complete cut"; complete.disabled = true; + const cancel = window.document.createElement("button"); cancel.textContent = "Cancel polygon"; + buttons.append(complete, cancel); polygonLayer.appendChild(buttons); + let drawing = false; + const add = (event: PointerEvent) => { + const rect = renderer.domElement.getBoundingClientRect(); + const x = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)); + const y = Math.max(0, Math.min(1, 1 - (event.clientY - rect.top) / rect.height)); + if (facets.current?.mode === "box" && vertices.length) { + const first = vertices[0]; + vertices.splice(1, vertices.length - 1, { x, y: first.y }, { x, y }, { x: first.x, y }); + outline.setAttribute("points", vertices.map(p => `${p.x},${1-p.y}`).join(" ")); + complete.disabled = x === first.x || y === first.y; + return; + } + const last = vertices[vertices.length - 1]; + if (last && Math.hypot(x - last.x, y - last.y) < 0.003) return; + vertices.push({ x, y }); + outline.setAttribute("points", vertices.map(p => `${p.x},${1-p.y}`).join(" ")); + const noncollinear = vertices.length >= 3 && vertices.slice(2).some(p => Math.abs((vertices[1].x-vertices[0].x)*(p.y-vertices[0].y) - (vertices[1].y-vertices[0].y)*(p.x-vertices[0].x)) > 1e-10); + complete.disabled = !noncollinear; + }; + polygonLayer.onpointerdown = event => { + if (buttons.contains(event.target as Node) || event.button !== 0) return; + if (facets.current?.mode === "box") vertices.length = 0; + drawing = true; polygonLayer.setPointerCapture(event.pointerId); add(event); + }; + polygonLayer.onpointermove = event => { if (drawing) add(event); }; + polygonLayer.onpointerup = () => { drawing = false; if (facets.current?.mode === "box" && !complete.disabled) facets.current.onFacets(collectFacets(vertices)); }; + polygonLayer.onpointercancel = () => { drawing = false; }; + complete.onclick = () => { + if (complete.disabled) return; + camera.updateMatrixWorld(true); + if (facets.current) { facets.current.onFacets(collectFacets(vertices)); return; } + polygonCallbacks.current.onPolygon?.({ polygon: vertices, viewProjection: new THREE.Matrix4().multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse).toArray() }); + }; + cancel.onclick = () => polygonCallbacks.current.onCancelPolygon?.(); + polygonLayer.tabIndex = 0; + polygonLayer.onkeydown = event => { if (event.key === "Escape") polygonCallbacks.current.onCancelPolygon?.(); }; + container.appendChild(polygonLayer); polygonLayer.focus(); + } + let downX = 0, downY = 0; + const down = (event: PointerEvent) => { downX = event.clientX; downY = event.clientY; }; + const hover = (event: PointerEvent) => { + if (!meshInfo.current.active || event.buttons) return; + const rect = renderer.domElement.getBoundingClientRect(); + camera.updateMatrixWorld(true); content.updateMatrixWorld(true); + const ray = new THREE.Raycaster(); + ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, + 1 - (event.clientY - rect.top) / rect.height * 2), camera); + const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.Mesh))[0]; + meshInfo.current.hover?.(hit?.faceIndex ?? null); + }; + const leave = () => meshInfo.current.hover?.(null); + const pick = (event: PointerEvent) => { + if (event.button === 2 && !meshInfo.current.active && (pickLocation.current || pickMesh.current)) { cancelPick.current?.(); return; } + if (event.button !== 0 || Math.hypot(event.clientX - downX, event.clientY - downY) > 4) return; + const rect = renderer.domElement.getBoundingClientRect(); + if (facets.current && facets.current.mode !== "navigate") { + if (facets.current.mode !== "triangle") return; + camera.updateMatrixWorld(true); content.updateMatrixWorld(true); + const ray = new THREE.Raycaster(); + ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, + 1 - (event.clientY - rect.top) / rect.height * 2), camera); + const hits = ray.intersectObjects(facetMeshes()); + const candidates = facets.current.visibleOnly ? hits.slice(0, 1) : hits; + const hit = candidates.find(item => item.faceIndex != null && eligibleFacet(item.object as THREE.Mesh, item.faceIndex)); + if (hit?.faceIndex != null) { + const name = String(hit.object.userData.name); + const indices = facets.current.componentOnClick + ? facets.current.components[name]?.find(group => group.includes(hit.faceIndex!)) ?? [hit.faceIndex] : [hit.faceIndex]; + facets.current.onFacets({ [name]: indices.filter(index => eligibleFacet(hit.object as THREE.Mesh, index)) }, true); + } + return; + } + if (inspection.current.mode) { + if (inspection.current.mode === "navigate") return; + const ray = new THREE.Raycaster(); + ray.params.Points.threshold = radius / 100; + ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, + 1 - (event.clientY - rect.top) / rect.height * 2), camera); + const hit = ray.intersectObjects(content.children.filter(object => + document.objects.some(item => item.name === object.userData.name && item.typeId === "Inspection::Feature")))[0]; + if (hit?.object instanceof THREE.Points && hit.index !== undefined) { + const point = hit.object.localToWorld(new THREE.Vector3().fromBufferAttribute(hit.object.geometry.getAttribute("position"), hit.index)); + inspection.current.pick?.({ object: hit.object.userData.name, index: hit.index, point: [point.x,point.y,point.z] }); + } else if (hit?.faceIndex != null) { + inspection.current.pick?.({ object: hit.object.userData.name, facet: hit.faceIndex, point: [hit.point.x,hit.point.y,hit.point.z] }); + } + return; + } + if (pickMesh.current) { + const ray = new THREE.Raycaster(); + ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, + 1 - (event.clientY - rect.top) / rect.height * 2), camera); + const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.Mesh))[0]; + if (hit && hit.faceIndex != null) { + const direction = camera.getWorldDirection(new THREE.Vector3()); + pickMesh.current({ object: hit.object.userData.name, facet: hit.faceIndex, + point: [hit.point.x, hit.point.y, hit.point.z], direction: [direction.x, direction.y, direction.z] }); + } + return; + } + if (pickVertex.current || pickLocation.current) { + // Snap to native topology in screen space, independent of tessellation density. + let nearest: { point: THREE.Vector3; pixels: number; depth: number; normal?: THREE.Vector3 } | undefined; + const occlusion = new THREE.Raycaster(); + const meshes = content.children.filter(object => object instanceof THREE.Mesh); + for (const object of document.objects) { + if (object.visible === false) continue; + for (const position of object.vertices ?? object.pointMarkers ?? []) { + const point = new THREE.Vector3(...position); + const projected = point.clone().project(camera); + if (projected.z < -1 || projected.z > 1) continue; + const pixels = Math.hypot((projected.x + 1) * rect.width / 2 + rect.left - event.clientX, + (1 - projected.y) * rect.height / 2 + rect.top - event.clientY); + if (pixels > 10) continue; + occlusion.setFromCamera(new THREE.Vector2(projected.x, projected.y), camera); + const obstruction = occlusion.intersectObjects(meshes)[0]; + const depth = point.distanceTo(occlusion.ray.origin); + if (obstruction && obstruction.distance < depth - radius * 1e-6) continue; + if (!nearest || pixels < nearest.pixels - 0.01 || Math.abs(pixels - nearest.pixels) <= 0.01 && depth < nearest.depth) { + let normal: THREE.Vector3 | undefined; + if (pickLocation.current) { + const mesh = meshes.find(item => item.userData.name === object.name); + if (mesh instanceof THREE.Mesh) { + if (obstruction?.object === mesh && obstruction.face) { + normal = obstruction.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld)); + } else { + // A ray through a boundary vertex can miss every triangle by roundoff. + // Use that vertex's displayed normal from the same native mesh. + const positions = mesh.geometry.getAttribute("position"), normals = mesh.geometry.getAttribute("normal"); + const vertex = new THREE.Vector3(); + let facing = -Infinity; + for (let index = 0; normals && index < positions.count; ++index) { + vertex.fromBufferAttribute(positions, index).applyMatrix4(mesh.matrixWorld); + if (vertex.distanceTo(point) > radius * 1e-6) continue; + const candidate = new THREE.Vector3().fromBufferAttribute(normals, index) + .applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld)); + const score = -candidate.dot(occlusion.ray.direction); + if (score > facing) { normal = candidate; facing = score; } + } + } + } + } + nearest = { point, pixels, depth, normal }; + } + } + } + if (nearest) { + const point: [number, number, number] = [nearest.point.x, nearest.point.y, nearest.point.z]; + if (pickVertex.current) pickVertex.current(point); + else pickLocation.current?.(point, nearest.normal ? [nearest.normal.x, nearest.normal.y, nearest.normal.z] : undefined); + return; + } + if (pickVertex.current) return; + } + const ray = new THREE.Raycaster(); + ray.params.Line.threshold = radius / 200; + ray.setFromCamera(new THREE.Vector2((event.clientX - rect.left) / rect.width * 2 - 1, + 1 - (event.clientY - rect.top) / rect.height * 2), camera); + if (pickEdge.current) { + const hit = ray.intersectObjects(content.children.filter(object => object instanceof THREE.LineSegments)) + .find(hit => hit.index !== undefined && hit.object.userData.segmentEdges?.[Math.floor(hit.index / 2)]); + if (hit) pickEdge.current(String(hit.object.userData.name), hit.object.userData.segmentEdges[Math.floor(hit.index! / 2)]); + return; + } + const hit = ray.intersectObjects(content.children)[0]; + if (pickLocation.current) { + if (hit?.face) { + const normal = hit.face.normal.clone().applyNormalMatrix(new THREE.Matrix3().getNormalMatrix(hit.object.matrixWorld)); + pickLocation.current([hit.point.x, hit.point.y, hit.point.z], [normal.x, normal.y, normal.z]); + } else if (hit?.object instanceof THREE.LineSegments) { + pickLocation.current([hit.point.x, hit.point.y, hit.point.z]); + } + return; + } + if (hit && pickPoint.current) { + // Point raycasts report the closest point on the ray, not the vertex itself. + const point = hit.object instanceof THREE.Points && hit.index !== undefined + ? hit.object.localToWorld(new THREE.Vector3().fromBufferAttribute(hit.object.geometry.getAttribute("position"), hit.index)) + : hit.point; + pickPoint.current([point.x, point.y, point.z]); + } else if (hit) select.current(hit.object.userData.name); + }; + renderer.domElement.addEventListener("pointerdown", down); + renderer.domElement.addEventListener("pointerup", pick); + renderer.domElement.addEventListener("pointermove", hover); + renderer.domElement.addEventListener("pointerleave", leave); + const labels = window.document.createElement("div"); + labels.style.cssText = "position:absolute;inset:0;pointer-events:none;overflow:hidden"; + container.style.position = "relative"; container.appendChild(labels); + let previousAnnotations: typeof inspectionAnnotations | undefined; + let controlsBeforeInspection: boolean | undefined; + const direction = new THREE.Vector3(); + let announcedReady = false; + const syncDecoration = () => { + const name = selected[0]; + const target = name ? content.children.find(child => child.userData.name === name) : undefined; + if (!target) { publishDecoration(decoration); decoration.clear(); publishDecoration(decoration); return; } + const box = new THREE.Box3().setFromObject(target); + if (box.isEmpty()) { decoration.clear(); publishDecoration(decoration); return; } + decoration.setTarget(box.getCenter(new THREE.Vector3()).toArray(), new THREE.Quaternion(), target); + publishDecoration(decoration); + }; + syncDecoration(); + renderer.setAnimationLoop(() => { + decoration.updateFrame(camera); + if (meshInfo.current.active || inspection.current.mode === "inspect") { + controlsBeforeInspection ??= controls.enabled; + controls.enabled = false; renderer.domElement.style.cursor = "crosshair"; + } else if (controlsBeforeInspection !== undefined) { + controls.enabled = controlsBeforeInspection; controlsBeforeInspection = undefined; + renderer.domElement.style.cursor = ""; + } + const annotations = inspection.current.annotations; + if (annotations !== previousAnnotations) { + labels.replaceChildren(...annotations.map(annotation => { + const label = window.document.createElement("span"); label.textContent = annotation.text; + label.style.cssText = "position:absolute;background:#55007f;color:#ddd;padding:4px;white-space:nowrap"; + return label; + })); previousAnnotations = annotations; + } + annotations.forEach((annotation, index) => { + const p = new THREE.Vector3(...annotation.point).project(camera); + const label = labels.children[index] as HTMLElement; + label.style.display = p.z < -1 || p.z > 1 ? "none" : "block"; + label.style.left = `${(p.x+1)*renderer.domElement.clientWidth/2}px`; + label.style.top = `${(1-p.y)*renderer.domElement.clientHeight/2}px`; + }); + controls.update(); + updateFacetHighlights(); + const request = facets.current?.request; + if (request && request.id !== handledFacetRequest.current) { + handledFacetRequest.current = request.id; + const picked = collectFacets(); + if (request.mode === "small") for (const name of Object.keys(picked)) { + const small = new Set(facets.current?.components[name]?.filter(group => group.length <= request.maximum).flat() ?? []); + picked[name] = picked[name].filter(index => small.has(index)); + } + facets.current?.onFacets(picked); + } + if (viewDirection.current) { + controls.object.getWorldDirection(direction); + viewDirection.current([direction.x, direction.y, direction.z]); + } + renderer.render(scene, camera); + if (!announcedReady) { announcedReady = true; ready.current?.(); } + }); + return () => { + if (preserveCamera) savedCamera.current = { documentId: document.documentId, position: camera.position.clone(), target: controls.target.clone() }; + for (const child of highlight.children) { + const mesh = child as THREE.Mesh; mesh.geometry.dispose(); (mesh.material as THREE.Material).dispose(); + } + polygonLayer.remove(); + labels.remove(); + observer.disconnect(); renderer.setAnimationLoop(null); sceneCommands.dispose(); decoration.dispose(); controls.dispose(); + renderer.domElement.removeEventListener("pointerdown", down); + renderer.domElement.removeEventListener("pointerup", pick); + renderer.domElement.removeEventListener("pointermove", hover); + renderer.domElement.removeEventListener("pointerleave", leave); + geometries.forEach(item => item.dispose()); materials.forEach(item => item.dispose()); + content.children.forEach(child => child.userData.dispose?.()); renderer.dispose(); renderer.domElement.remove(); + }; + }, [document, selected.join("\0"), reserveControlsSpace, polygonMode, facetInteraction?.mode]); + return
; +} diff --git a/web/src/selection-decoration.ts b/web/src/selection-decoration.ts new file mode 100644 index 00000000..89dbba2c --- /dev/null +++ b/web/src/selection-decoration.ts @@ -0,0 +1,135 @@ +// Shared selection decoration for every three.js scene in the project: an X/Y/Z +// triad at the object's local frame plus a wireframe focus box around the picked +// shape. Both keep a constant size on screen by scaling against the camera +// distance each frame, and both draw above geometry (depthTest off) so the frame +// stays legible inside solids. The ImportRenderBridge and the standalone viewers +// (standalone test view) all use this one implementation. +import * as THREE from "three"; + +export type SelectionDecorationSnapshot = { + axesVisible: boolean; + axesPosition: number[]; + axesScale: number; + focusVisible: boolean; + focusMin: number[] | null; + focusMax: number[] | null; +}; + +export class SelectionDecoration { + private axes: THREE.Group | null = null; + private focus: THREE.Box3Helper | null = null; + private origin: THREE.Vector3 | null = null; + private readonly quaternion = new THREE.Quaternion(); + + constructor(private readonly scene: THREE.Scene) {} + + setTarget(position: number[], quaternion: THREE.Quaternion, object?: THREE.Object3D | null): void { + const axes = this.ensureAxes(); + axes.position.fromArray(position); + axes.quaternion.copy(quaternion); + axes.visible = true; + this.quaternion.copy(quaternion); + this.origin = axes.position.clone(); + this.setFocus(object ?? null); + } + + // Called while a gizmo drag is in flight so the triad follows the handle. + follow(position: THREE.Vector3, quaternion: THREE.Quaternion): void { + if (!this.axes) return; + this.axes.position.copy(position); + this.axes.quaternion.copy(quaternion); + this.origin?.copy(position); + } + + clear(): void { + if (this.axes) this.axes.visible = false; + this.origin = null; + this.setFocus(null); + } + + updateFrame(camera: THREE.Camera): void { + const axes = this.axes; + if (!axes || !axes.visible || !this.origin) return; + camera.updateMatrixWorld(); + const distance = Math.max(camera.position.distanceTo(this.origin), 1e-4); + const scale = camera instanceof THREE.PerspectiveCamera + ? distance * Math.tan(THREE.MathUtils.degToRad(camera.getEffectiveFOV()) / 2) * 0.18 + : camera instanceof THREE.OrthographicCamera + ? ((camera.top - camera.bottom) / Math.max(camera.zoom, 1e-6)) * 0.18 + : 1; + axes.scale.setScalar(Math.max(scale, 1e-4)); + } + + snapshot(): SelectionDecorationSnapshot { + const axes = this.axes; + const focus = this.focus; + return { + axesVisible: Boolean(axes?.visible), + axesPosition: axes ? axes.position.toArray().map(value => Math.round(value * 1000) / 1000) : [], + axesScale: axes ? Math.round(axes.scale.x * 1000) / 1000 : 0, + focusVisible: Boolean(focus?.visible), + focusMin: focus ? focus.box.min.toArray().map(value => Math.round(value * 1000) / 1000) : null, + focusMax: focus ? focus.box.max.toArray().map(value => Math.round(value * 1000) / 1000) : null, + }; + } + + dispose(): void { + if (this.axes) { + this.axes.traverse(child => { + const mesh = child as THREE.Mesh; + mesh.geometry?.dispose?.(); + const materials = Array.isArray(mesh.material) ? mesh.material : mesh.material ? [mesh.material] : []; + for (const material of materials) material.dispose(); + }); + this.scene.remove(this.axes); + this.axes = null; + } + this.setFocus(null); + } + + private ensureAxes(): THREE.Group { + if (this.axes) return this.axes; + const group = new THREE.Group(); + group.name = "selection-local-axes"; + const arrows: Array<[number[], number]> = [[[1, 0, 0], 0xd9534f], [[0, 1, 0], 0x5cb85c], [[0, 0, 1], 0x4a90d9]]; + for (const [direction, color] of arrows) { + const arrow = new THREE.ArrowHelper(new THREE.Vector3(direction[0], direction[1], direction[2]).normalize(), + new THREE.Vector3(), 1, color, 0.22, 0.09); + arrow.userData.selectionHelper = true; + arrow.traverse(child => { + const material = (child as THREE.Mesh).material as THREE.Material | undefined; + if (material) { material.depthTest = false; material.transparent = true; } + child.renderOrder = 5; + }); + group.add(arrow); + } + const origin = new THREE.Mesh(new THREE.SphereGeometry(0.06, 16, 12), + new THREE.MeshBasicMaterial({ color: "#ffffff", depthTest: false, transparent: true, opacity: 0.9 })); + origin.userData.selectionHelper = true; origin.renderOrder = 5; group.add(origin); + group.visible = false; + this.scene.add(group); + this.axes = group; + return group; + } + + private setFocus(object: THREE.Object3D | null): void { + if (this.focus) { + this.scene.remove(this.focus); + this.focus.geometry.dispose(); + (this.focus.material as THREE.Material).dispose(); + this.focus = null; + } + if (!object || !object.visible) return; + const box = new THREE.Box3().setFromObject(object); + if (box.isEmpty()) return; + const helper = new THREE.Box3Helper(box, new THREE.Color("#65d9ed")); + helper.userData.selectionHelper = true; + helper.traverse(child => { + const material = (child as THREE.LineSegments).material as THREE.Material | undefined; + if (material) { material.depthTest = false; material.transparent = true; material.opacity = 0.75; } + child.renderOrder = 4; + }); + this.scene.add(helper); + this.focus = helper; + } +} diff --git a/web/src/storage.ts b/web/src/storage.ts new file mode 100644 index 00000000..70ab8a76 --- /dev/null +++ b/web/src/storage.ts @@ -0,0 +1,226 @@ +const STORE_DIRECTORY = "freecad-1-2"; + +interface OpfsFileHandle { + createWritable(): Promise<{ write(data: ArrayBuffer): Promise; close(): Promise; abort(): Promise }>; + getFile(): Promise<{ arrayBuffer(): Promise }>; +} + +interface OpfsDirectoryHandle { + getDirectoryHandle(name: string, options?: { create?: boolean }): Promise; + getFileHandle(name: string, options?: { create?: boolean }): Promise; + removeEntry(name: string): Promise; + entries(): AsyncIterableIterator<[string, unknown]>; +} + +type StorageWithOpfs = StorageManager & { + getDirectory?: () => Promise; +}; + +function sanitizeName(name: string): string { + const baseName = name.split(/[\\/]/).pop() || "unnamed.step"; + return baseName.replace(/[^a-zA-Z0-9._-]/g, "_"); +} + +async function getStore(directory = STORE_DIRECTORY): Promise { + const storage = navigator.storage as StorageWithOpfs; + if (!storage.getDirectory) { + throw new Error("当前浏览器不支持 OPFS"); + } + const root = await storage.getDirectory(); + return root.getDirectoryHandle(directory, { create: true }); +} + +export function isOpfsSupported(): boolean { + return typeof navigator !== "undefined" && typeof (navigator.storage as StorageWithOpfs | undefined)?.getDirectory === "function"; +} + +export async function writeRawStep(name: string, bytes: ArrayBuffer): Promise { + const safeName = sanitizeName(name); + const file = await (await getStore()).getFileHandle(safeName, { create: true }); + const writable = await file.createWritable(); + await writable.write(bytes); + await writable.close(); + return safeName; +} + +export async function readRawStep(name: string): Promise { + const file = await (await getStore()).getFileHandle(sanitizeName(name)); + return file.getFile().then((value) => value.arrayBuffer()); +} + +export async function deleteRawStep(name: string): Promise { + await (await getStore()).removeEntry(sanitizeName(name)); +} + +export async function listRawSteps(): Promise { + const store = await getStore(); + const names: string[] = []; + for await (const [name] of store.entries()) { + names.push(name); + } + return names.sort(); +} + +const DOCUMENT_DIRECTORY = "freecad-documents"; +// Exported geometry (STEP/BREP/IGES/STL/...) lives in OPFS. A local download +// only happens when the user explicitly asks for one; exports never auto-save. +const EXPORT_DIRECTORY = "freecad-exports"; +function exportFilename(name: string): string { + const safeName = sanitizeName(name); + if (!/\.[a-z0-9]+$/i.test(safeName)) throw new Error("Export filename needs an extension"); + return safeName; +} +export async function writeExportFile(name: string, bytes: ArrayBuffer): Promise { + const safeName = exportFilename(name); + if (!bytes.byteLength) throw new Error("A nonempty export file is required"); + const file = await (await getStore(EXPORT_DIRECTORY)).getFileHandle(safeName, { create: true }); + const writable = await file.createWritable(); + try { + await writable.write(bytes); + await writable.close(); + } catch (error) { + await writable.abort().catch(() => undefined); + throw error; + } + return safeName; +} +export async function listExportFiles(): Promise { + try { + const names: string[] = []; + for await (const [name] of (await getStore(EXPORT_DIRECTORY)).entries()) names.push(name); + return names.sort(); + } catch (error) { + if (error instanceof DOMException && error.name === "NotFoundError") return []; + throw error; + } +} +export async function readExportFile(name: string): Promise { + const file = await (await getStore(EXPORT_DIRECTORY)).getFileHandle(exportFilename(name)); + return file.getFile().then((value) => value.arrayBuffer()); +} +export async function deleteExportFile(name: string): Promise { + await (await getStore(EXPORT_DIRECTORY)).removeEntry(exportFilename(name)); +} + +// Plot images are independent of editable CAD documents. +export async function writePlotSvg(name: string, bytes: ArrayBuffer, signal: AbortSignal, commit: () => void): Promise { + const safeName = sanitizeName(name); + if (!/\.svg$/i.test(safeName) || !bytes.byteLength) throw new Error("A nonempty SVG image is required"); + signal.throwIfAborted(); + const store = await getStore("freecad-plot-images"); + let created = false; + let writable: Awaited> | undefined; + try { + let file: OpfsFileHandle; + try { file = await store.getFileHandle(safeName); } + catch (error) { + if (!(error instanceof DOMException) || error.name !== "NotFoundError") throw error; + signal.throwIfAborted(); + file = await store.getFileHandle(safeName, { create: true }); + created = true; + } + signal.throwIfAborted(); + writable = await file.createWritable(); + signal.throwIfAborted(); + await writable.write(bytes); + signal.throwIfAborted(); + commit(); + await writable.close(); + } catch (error) { + await writable?.abort().catch(() => undefined); + if (created) await store.removeEntry(safeName).catch(() => undefined); + throw error; + } + return safeName; +} + +export async function writeDocumentFile(name: string, bytes: ArrayBuffer, signal?: AbortSignal, commit?: () => void): Promise { + const safeName = sanitizeName(name); + if (!/\.FCStd$/i.test(safeName) || !bytes.byteLength) throw new Error("A nonempty FCStd document is required"); + signal?.throwIfAborted(); + const store = await getStore(DOCUMENT_DIRECTORY); + let created = false; + let writable: Awaited> | undefined; + try { + let file: OpfsFileHandle; + try { file = await store.getFileHandle(safeName); } + catch (error) { + if (!(error instanceof DOMException) || error.name !== "NotFoundError") throw error; + signal?.throwIfAborted(); + file = await store.getFileHandle(safeName, { create: true }); + created = true; + } + signal?.throwIfAborted(); + writable = await file.createWritable(); + signal?.throwIfAborted(); + await writable.write(bytes); + signal?.throwIfAborted(); + // Closing commits the complete replacement. Cancellation ends at this boundary. + commit?.(); + await writable.close(); + } catch (error) { + await writable?.abort().catch(() => undefined); + if (created) await store.removeEntry(safeName).catch(() => undefined); + throw error; + } + return safeName; +} + +export async function readDocumentFile(name: string): Promise { + const legacy = name.startsWith("Test/") ? "Test" : DOCUMENT_DIRECTORY; + const file = await (await getStore(legacy)).getFileHandle(sanitizeName(name)); + return file.getFile().then(value => value.arrayBuffer()); +} + +// Save review must not create directories or files before acceptance. +export async function listSaveDestinations(): Promise { + const storage = navigator.storage as StorageWithOpfs; + if (!storage.getDirectory) throw new Error("当前浏览器不支持 OPFS"); + try { + const store = await (await storage.getDirectory()).getDirectoryHandle(DOCUMENT_DIRECTORY); + const names: string[] = []; + for await (const [name] of store.entries()) names.push(name); + return names; + } catch (error) { + if (error instanceof DOMException && error.name === "NotFoundError") return []; + throw error; + } +} + +export async function listDocumentFiles(): Promise { + const names: string[] = []; + for await (const [name] of (await getStore(DOCUMENT_DIRECTORY)).entries()) { + if (/\.FCStd$/i.test(name)) names.push(name); + } + for await (const [name] of (await getStore("Test")).entries()) { + if (/\.FCStd$/i.test(name)) names.push(`Test/${name}`); + } + return names.sort(); +} + +const MACRO_DIRECTORY = "freecad-macros"; +function macroFilename(name: string): string { + if (!name || /[\\/]/.test(name) || !/\.(FCMacro|py)$/i.test(name)) + throw new Error("Enter a macro filename ending in .FCMacro or .py"); + return name; +} +export async function writeMacroFile(name: string, source: string): Promise { + const file = await (await getStore(MACRO_DIRECTORY)).getFileHandle(macroFilename(name), { create: true }); + const writable = await file.createWritable(); + try { await writable.write(new TextEncoder().encode(source).buffer as ArrayBuffer); await writable.close(); } + catch (error) { await writable.abort().catch(() => undefined); throw error; } +} +export async function readMacroFiles(): Promise> { + const store = await getStore(MACRO_DIRECTORY); + const files: Array<{ filename: string; source: string }> = []; + for await (const [name] of store.entries()) { + if (!/\.(FCMacro|py)$/i.test(name)) continue; + const file = await (await store.getFileHandle(name)).getFile(); + files.push({ filename: name, source: new TextDecoder().decode(await file.arrayBuffer()) }); + } + return files; +} + +export async function deleteDocumentFile(name: string): Promise { + await (await getStore(DOCUMENT_DIRECTORY)).removeEntry(sanitizeName(name)); +} diff --git a/web/src/web-open-adapter.ts b/web/src/web-open-adapter.ts new file mode 100644 index 00000000..105306c5 --- /dev/null +++ b/web/src/web-open-adapter.ts @@ -0,0 +1,156 @@ +import { readDocumentFile } from "./storage.js"; +import { encodeSceneFile } from "./test-scene-session.js"; +import { createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js"; +import type { WebModuleRouter } from "./module-router.js"; +import { viewEndpoint, type DocumentViewResult } from "./part-view-facade.js"; +import { validOpenResult, type OpenFileEntry, type OpenResult } from "./web-open-contract.js"; + +type Directory = FileSystemDirectoryHandle & { entries(): AsyncIterableIterator<[string, FileSystemHandle]> }; +async function openStore(): Promise { + if (typeof navigator.storage?.getDirectory !== "function") throw new Error("OPFS is unavailable"); + return await (await navigator.storage.getDirectory()).getDirectoryHandle("freecad-open-files", { create: true }) as Directory; +} +async function storedFiles() { + const root = await openStore(), files: Array<{ key: string; filename: string }> = []; + for await (const [hash, handle] of root.entries()) { + if (handle.kind !== "directory" || !/^[a-f0-9]{64}$/.test(hash)) continue; + const directory = await root.getDirectoryHandle(hash) as Directory; + for await (const [name, item] of directory.entries()) + if (item.kind === "file") files.push({ key: `${hash}/${name}`, filename: name }); + } + return files.sort((a, b) => a.filename.localeCompare(b.filename) || a.key.localeCompare(b.key)); +} +export function pickFiles(): Promise { + return new Promise((resolve, reject) => { + const input = document.createElement("input"); input.type = "file"; input.multiple = true; input.accept = ".fcstd,.jt,.step,.stp,.iges,.igs,.brep,.brp,.rle,.stl,.scad,.csg"; input.hidden = true; + const finish = (files: File[]) => { input.remove(); resolve(files); }; + input.onchange = () => finish(Array.from(input.files ?? [])); + input.addEventListener("cancel", () => finish([]), { once: true }); + document.body.appendChild(input); + try { input.click(); } catch (error) { input.remove(); reject(error); } + }); +} +async function prepareFile(file: File | OpenFileEntry): Promise { + const filename = file instanceof File ? file.name : file.filename; + if (!filename || filename === "." || filename === ".." || /[\\/]/.test(filename)) throw new Error("Invalid file name"); + let bytes: Uint8Array; + if (file instanceof File) bytes = new Uint8Array(await file.arrayBuffer()); + else bytes = Uint8Array.from(atob(file.fileData), char => char.charCodeAt(0)); + const hash = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map(value => value.toString(16).padStart(2, "0")).join(""); + const directory = await (await openStore()).getDirectoryHandle(hash, { create: true }); + const writable = await (await directory.getFileHandle(filename, { create: true })).createWritable(); + try { await writable.write(bytes); await writable.close(); } + catch (error) { await writable.abort().catch(() => {}); throw error; } + let binary = ""; + for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192)); + return { filename, fileData: btoa(binary), sha256: hash, ...(!(file instanceof File) && file.module ? { module: file.module } : {}) }; +} + +function base64Bytes(value: string): ArrayBuffer { + const binary = atob(value), bytes = new Uint8Array(binary.length); + for (let index = 0; index < binary.length; index++) bytes[index] = binary.charCodeAt(index); + return bytes.buffer; +} + +async function openPartNativeFile(router: WebModuleRouter, owner: string, documentId: string, file: OpenFileEntry, + applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise { + const nativeDocument = documentId.replace(/[^A-Za-z0-9_]/g, "_").replace(/^[^A-Za-z_]/, "_"); + const extension = file.filename.split(".").pop()?.toLowerCase() ?? ""; + const command = extension === "step" || extension === "stp" ? "Part_ImportStep" + : extension === "iges" || extension === "igs" ? "Import_Iges" + : extension === "brep" || extension === "brp" || extension === "rle" ? "Import_ReadBREP" : undefined; + // Desktop naming for Std_Open comes from the file stem: Part.insert() creates + // the feature with file.fileNamePure() and the native preflight snapshot uses + // the same name, so the Web tree must match instead of using a fixed name. + const stem = file.filename.replace(/\.[^.]+$/, ""); + const object = (stem.replace(/[^A-Za-z0-9_]/g, "_").replace(/^[^A-Za-z_]/, "_") || "Imported1"); + const path = `/tmp/${nativeDocument}_${object}.${extension}`; + const schema = "freecad-web-part/document/v1"; + const request = (action: string, extra: Record = {}) => router.request("Part", "part.document", { + schema, module: "Part", document: nativeDocument, action, object, includeMesh: true, ...extra, + }, documentId); + const created = await request("create"); + if (created.kind === "error") throw new Error(created.error.message); + const imported = await request("importShape", { + label: stem, path, bytes: base64Bytes(file.fileData), + ...(command ? { desktopImportCommand: command } : {}), + }); + if (imported.kind === "error") throw new Error(imported.error.message); + const native = imported.result as { objects?: Array<{ name: string }>; objectCount?: number }; + const firstObject = native.objects?.[0]?.name; + if (!firstObject) throw new Error("Native import produced no document object"); + applySelection?.(nativeDocument, [{ documentId: nativeDocument, object: firstObject }]); + return { command: "Std_Open", documentId, operation: "open", activeDocument: nativeDocument, + formats: [], errors: [], opened: [{ filename: file.filename, sha256: file.sha256 ?? "0".repeat(64), reused: false, + documents: [{ name: nativeDocument, label: file.filename, filename: file.filename, objectCount: native.objectCount ?? native.objects?.length ?? 0, partialRestore: false, restoreError: false }] }], + scene: undefined }; +} +export async function executeOpenDocument(router: WebModuleRouter, args: Record, documentId: string, + applySelection?: (documentId: string, selection: Array<{ documentId: string; object: string }>) => void): Promise { + const owner = args.runtimeOwner ?? "PartBox"; + if (owner !== "PartBox" && owner !== "DocumentProbe") return createFailure("desktop-open", "wrong_document_owner", "Choose the native document runtime"); + if (args.documentId !== undefined && args.documentId !== documentId) + return createFailure("desktop-open", "document_mismatch", "Open request belongs to another document"); + if (args.activeTask === true) return createFailure("desktop-open", "active_task", "Finish the active task before opening files"); + if (args.operation !== undefined && args.operation !== "list" && args.operation !== "open") + return createFailure("desktop-open", "invalid_request", "Open operation must be list or open"); + try { + const signal = args.signal instanceof AbortSignal ? args.signal : undefined; + let inputs: Array = []; + if (args.operation === "list") inputs = []; + else if (typeof args.storedKey === "string") { + const match = /^([a-f0-9]{64})\/([^/\\]+)$/.exec(args.storedKey); + if (!match) throw new Error("Invalid stored file key"); + const directory = await (await openStore()).getDirectoryHandle(match[1]); + inputs = [await (await directory.getFileHandle(match[2])).getFile()]; + } else if (Array.isArray(args.files)) inputs = args.files as Array; + else inputs = await pickFiles(); + if (args.operation !== "list" && !inputs.length) return createFailure("desktop-open", "cancelled", "Open cancelled"); + const files: OpenFileEntry[] = []; + for (const input of inputs) files.push({ ...await prepareFile(input), + ...(typeof args.module === "string" && args.module ? { module: args.module } : {}) }); + const nativePart = files.length === 1 && /\.(step|stp|iges|igs|brep|brp|rle|stl)$/i.test(files[0].filename); + if (nativePart && args.operation !== "list") { + const value = await openPartNativeFile(router, String(owner), documentId, files[0], applySelection); + value.storedFiles = await storedFiles(); + // part.document is routed to the DocumentProbe save worker. Return that + // owner so the scene viewer reads the document from the same native runtime. + return createSuccess("desktop-open-part-native", { owner: "DocumentProbe", records: [{ name: "Std_Open", status: "success", result: value }] }); + } + // FCStd restore and subsequent part.document snapshots share the + // DocumentProbe save worker. Keep the open response and scene on that + // owner instead of creating a PartBox-only document the project bridge + // cannot edit or save. + const nativeFcstd = files.length === 1 && /\.fcstd$/i.test(files[0].filename); + const viewOwner = nativeFcstd ? "DocumentProbe" : owner; + const response = await router.request("Part", viewEndpoint(viewOwner), { + schema: "freecad-web/document-view/v1", owner: viewOwner, document: documentId, command: "Std_Open", + parameters: { documentId, operation: args.operation === "list" ? "list" : "open", files, activeTask: args.activeTask }, + }, documentId); + if (response.kind !== "result") return response; + const value = response.result; + if (!validOpenResult(value, documentId)) return createFailure(response.requestId, "native_protocol_error", "Invalid native open result"); + value.storedFiles = await storedFiles(); + const restoredObjectCount = value.opened[0]?.documents?.reduce((sum, document) => sum + document.objectCount, 0) ?? 0; + const deferLargeScene = restoredObjectCount > 250; + if (deferLargeScene) { + value.sceneError = `Initial scene deferred for ${restoredObjectCount} restored objects; use the project workspace scene after the document tree is ready.`; + } + if (!deferLargeScene && value.opened.length && value.activeDocument) { + applySelection?.(value.activeDocument, []); + try { + const scene = await router.request("Part", viewEndpoint(viewOwner), { + schema: "freecad-web/document-view/v1", owner: viewOwner, document: value.activeDocument, command: "Std_DrawStyle", + parameters: { documentId: value.activeDocument, action: "read", selection: [] }, + }, value.activeDocument); + if (scene.kind === "error") throw new Error(scene.error.message); + if ((scene.result as DocumentViewResult).documentId !== value.activeDocument) throw new Error("Opened document scene identity mismatch"); + value.scene = scene.result as DocumentViewResult; + window.dispatchEvent(new CustomEvent("freecad-document-view", { detail: { owner: viewOwner, documentId: value.activeDocument, value: scene.result } })); + } catch (error) { value.sceneError = String(error); } + } + if (value.errors.length) return createFailure(response.requestId, "file_open_failed", + value.errors.map(error => `${error.filename}: ${error.message}`).join("\n"), { openResult: value }); + return createSuccess(response.requestId, { owner: viewOwner, records: [{ name: "Std_Open", status: "success", result: value }] }); + } catch (error) { return createFailure("desktop-open", "file_open_failed", String(error)); } +} diff --git a/web/src/web-open-task.tsx b/web/src/web-open-task.tsx new file mode 100644 index 00000000..71d48f71 --- /dev/null +++ b/web/src/web-open-task.tsx @@ -0,0 +1,51 @@ +import { useRef, useState } from "react"; +import type { FacadeResponse } from "./facade-envelope.js"; +import { validOpenResult, type OpenResult } from "./web-open-contract.js"; + +export function WebOpenTask({ response, busy, execute }: { + response: FacadeResponse | null; busy: boolean; execute: (args: Record) => void; +}) { + const cancellation = useRef(); + const [owner, setOwner] = useState("PartBox"), [stored, setStored] = useState(""); + const [module, setModule] = useState(""); + const batch = response?.kind === "result" ? response.result as { records?: Array<{ name?: string; result?: unknown }> } : undefined; + const candidate = response?.kind === "error" ? response.error.diagnostic?.openResult + : batch?.records?.find(row => row.name === "Std_Open")?.result; + const value = candidate && validOpenResult(candidate, (candidate as OpenResult).documentId) ? candidate : undefined; + const run = (args: Record) => { + cancellation.current = new AbortController(); + execute({ runtimeOwner: owner, module, ...args, signal: cancellation.current.signal }); + }; + const handlers = [...new Set(value?.formats.flatMap(format => format.modules) ?? [])].filter(name => name !== "FreeCAD"); + return
+
+ Open Documents + + + + + + +
+ {busy && } + {value && <> +
    {value.opened.flatMap(file => file.documents.map(doc =>
  • + {file.filename}: {doc.label} ({doc.objectCount} objects){file.reused ? " - already open" : ""} + {doc.partialRestore &&

    Document was only partially restored.

    } + {doc.restoreError &&

    Native document restore reported errors.

    } +
  • ))}
+ {value.errors.map((error, index) =>

{error.filename}: {error.message}

)} + {value.sceneError &&

{value.sceneError}

} +
Native import formats
    {value.formats.map(format =>
  • + .{format.extension}: {format.modules.join(", ")} +
  • )}
+ } +
; +} diff --git a/web/src/web-owner-standard-adapter.ts b/web/src/web-owner-standard-adapter.ts new file mode 100644 index 00000000..f83b0de8 --- /dev/null +++ b/web/src/web-owner-standard-adapter.ts @@ -0,0 +1,79 @@ +import { FEM_PARAMETER_PATH, isFemParameterPath, requestFemParameters } from "./fem-preferences.js"; +import { helpPreferences, resolveHelp } from "./help-preferences.js"; +import { isToolbarParameterPath, requestToolbarParameters } from "./toolbar-preferences.js"; +import { createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js"; +import type { WebModuleRouter } from "./module-router.js"; +import { viewEndpoint, type DocumentViewResult } from "./part-view-facade.js"; +import { validStandardResult } from "./web-standard-command-contract.js"; +import routes from "./document-view-routes.json"; +import { requestOwnerParameters } from "./view-navigation-preferences.js"; + +/** Commands with existing native semantics and the mounted standard task. */ +export function executeOwnerStandard(router: WebModuleRouter, command: string, + args: Record, documentId: string): Promise | undefined { + if (!routes.standardCommands.includes(command)) return; + if (["Std_DlgParameter", "Std_DlgPreferences"].includes(command) + && (isFemParameterPath(args.path) || args.runtimeOwner === "Fem")) { + return requestFemParameters(router, documentId, { ...args, path: args.path ?? FEM_PARAMETER_PATH }, command).then(response => { + if (response.kind !== "result") return response; + if (!validStandardResult(response.result, command, documentId)) + return createFailure(response.requestId, "native_protocol_error", "Invalid FEM parameter response"); + return createSuccess(response.requestId, { + schema: "freecad-web/document-view-batch/v1", owner: "Fem", documentId, + records: [{ apiId: `Web:desktop:${command}`, name: command, status: "success", native: true, result: response.result }], count: 1, + }); + }); + } + // The standard preferences host keeps its usual owner. Its Material resource + // page sends its reads and durable writes directly to the Material worker. + const owner = command === "Std_DlgPreferences" && args.runtimeOwner === "Material" ? "PartBox" : args.runtimeOwner ?? "PartBox"; + if (owner !== "PartBox" && owner !== "DocumentProbe") + return Promise.resolve(createFailure("desktop-Web", "wrong_document_owner", "Select the document's native runtime")); + if (!documentId.trim() || (args.documentId !== undefined && args.documentId !== documentId)) + return Promise.resolve(createFailure("desktop-Web", "document_mismatch", "Command document identifiers differ")); + const parameterRoot = command === "Std_DlgPreferences" ? "User parameter:BaseApp/Preferences" + : command === "Std_DlgCustomize" ? "User parameter:BaseApp/Workbench" : undefined; + const request = command === "Std_DlgParameter" && isToolbarParameterPath(args.path) + ? requestToolbarParameters(router, owner, documentId, args) + : ["Std_DlgParameter", "Std_DlgPreferences"].includes(command) + ? requestOwnerParameters(router, owner, documentId, { ...args, ...(parameterRoot ? { path: args.path ?? parameterRoot } : {}) }, command) + : router.request("Part", viewEndpoint(owner), { + schema: "freecad-web/document-view/v1", owner, document: documentId, command, + parameters: { ...args, ...(parameterRoot ? { path: args.path ?? parameterRoot } : {}), documentId }, + }, documentId); + return request.then(async response => { + if (response.kind !== "result") return response; + if (!validStandardResult(response.result, command, documentId)) + return createFailure(response.requestId, "native_protocol_error", "Invalid native standard command response"); + const value = response.result; + if (command === "Std_WhatsThis") { + try { + const help = resolveHelp(await helpPreferences(router, owner, documentId), value.page); + Object.assign(value, { help }); + } catch (error) { + return createFailure(response.requestId, "help_unavailable", String(error)); + } + } + if (command === "Std_AnnotationLabel" || command === "Std_TestCmdFuncs") { + // Refresh once through the existing read-only display path. A failed + // refresh must not invite resubmitting an already committed annotation. + try { + const refreshed = await router.request("Part", viewEndpoint(owner), { + schema: "freecad-web/document-view/v1", owner, document: documentId, + command: "Std_DrawStyle", parameters: { documentId, action: "read", selection: args.selection ?? [] }, + }, documentId); + if (refreshed.kind === "result") { + const scene = refreshed.result as DocumentViewResult; + if (scene.documentId !== documentId || !Array.isArray(scene.meshes)) throw new Error("Invalid native scene response"); + window.dispatchEvent(new CustomEvent("freecad-document-view", { + detail: { owner, documentId, value: scene }, + })); + } else value.sceneError = JSON.stringify(refreshed); + } catch (error) { value.sceneError = String(error); } + } + return createSuccess(response.requestId, { + schema: "freecad-web/document-view-batch/v1", owner, documentId, + records: [{ apiId: `Web:desktop:${command}`, name: command, status: "success", native: true, result: value }], count: 1, + }); + }); +} diff --git a/web/src/workbench-shell.tsx b/web/src/workbench-shell.tsx new file mode 100644 index 00000000..b5fccb16 --- /dev/null +++ b/web/src/workbench-shell.tsx @@ -0,0 +1,5263 @@ +import { selectedMeshState } from "./mesh-desktop-adapter.js"; +import { SandboxTaskPanelView } from "./sandbox-task-panel-view.js"; +import { requestOwnerParameters } from "./view-navigation-preferences.js"; +import { ImportExportPreferencesTask } from "./import-export-preferences.js"; +import { SketcherEditSession } from "./sketcher-edit-session.js"; +import { FemPreferencesTask } from "./fem-preferences-task.js"; +import { FEM_PARAMETER_PATH, isFemParameterPath } from "./fem-preferences.js"; +import { AssemblyActivationTask } from "./assembly-activation-task.js"; +import { SandboxRedirectPaintTask } from "./sandbox-redirect-paint-task.js"; +import { SandboxWidgetShapeTask } from "./sandbox-widget-shape-task.js"; +import { SandboxStandardWidgetTask } from "./sandbox-standard-widget-task.js"; +import { SandboxImageNodeTask } from "./sandbox-image-node-task.js"; +import { SandboxGraphicsView, bindGraphicsDocument, type GraphicsBinding } from "./sandbox-graphics-view.js"; +import { AssemblyExplodedViewTask } from "./assembly-exploded-view-task.js"; +import { AssemblySimulationTask } from "./assembly-simulation-task.js"; +import { HelpPreferencesTask } from "./help-preferences-task.js"; +import { ReverseEngineeringAutomaticTask } from "./reverseengineering-automatic-task.js"; +import { ReverseEngineeringManualTask } from "./reverseengineering-manual-task.js"; +import { AssemblyBomTask } from "./assembly-bom-task.js"; +import { AssemblyCreateTask } from "./assembly-create-task.js"; +import { AssemblyInsertLinkTask } from "./assembly-insert-link-task.js"; +import { AssemblyNewPartTask } from "./assembly-new-part-task.js"; +import { MeshPartMesherTask } from "./meshpart-mesher-task.js"; +import { MeshPartTrimTask } from "./meshpart-trim-task.js"; +import { SandboxMeshImportTask } from "./sandbox-mesh-import-task.js"; +import { SANDBOX_MESH_COMMANDS, SANDBOX_ELLIPSOID_COMMANDS } from "./sandbox-mesh-import-adapter.js"; +import { InspectionElementTask } from "./inspection-element-task.js"; +import { InspectionVisualTask } from "./inspection-visual-task.js"; +import { MeasureMassPropertiesTask } from "./measure-mass-properties-task.js"; +import { MeasureDistanceTask } from "./measure-distance-task.js"; +import { MeasurePreferencesTask } from "./measure-preferences-task.js"; +import { AssemblyPreferencesTask } from "./assembly-preferences-task.js"; +import { SurfaceFillingTask } from "./surface-filling-task.js"; +import { SurfaceGeomFillTask } from "./surface-geomfill-task.js"; +import { SandboxArchiveTask } from "./sandbox-archive-task.js"; +import { PlotAxesTask } from "./plot-axes-task.js"; +import { PointsMergeTask } from "./points-merge-task.js"; +import { POINTS_COMMAND_PRESENTATION, POINTS_MENU_ORDER, POINTS_TOOLBAR_ORDER } from "./points-command-presentation.js"; +import { createSuccess as spreadsheetSuccess } from "./facade-envelope.js"; +import { StartPreferencesEditor } from "./start-preferences.js"; +import { RobotWorkbenchUi } from "./robot-workbench-ui.js"; +import { RobotToolShapeTask } from "./robot-tool-shape-task.js"; +import { RobotWaypointTask } from "./robot-waypoint-task.js"; +import { ROBOT_WAYPOINT_COMMANDS } from "./robot-waypoint-adapter.js"; +import { RobotDressUpTask } from "./robot-dressup-task.js"; +import { RobotJointTask } from "./robot-joint-task.js"; +import { RobotPlaybackTask, RobotPoseView, RobotTrajectoryView } from "./robot-playback-task.js"; +import type { RobotScene } from "./robot-scene.js"; +import { RobotExportTask } from "./robot-export-task.js"; +import { AssemblyComponentContextMenu } from "./assembly-component-context-menu.js"; +import { AssemblySolverMessages } from "./assembly-solver-messages.js"; +import { AssemblyToleranceTask } from "./assembly-tolerance-task.js"; +import { BimIfcWorkflowTask } from "./bim-ifc-workflow-task.js"; +import { BimTutorialTask } from "./bim-tutorial-task.js"; +import { BimWelcomeTask } from "./bim-welcome-task.js"; +import { BimViewsTask } from "./bim-views-task.js"; +import { executeOwnerStandard } from "./web-owner-standard-adapter.js"; +import { WEBSITE_COMMANDS } from "./web-website-adapter.js"; +import { WebWebsiteTask } from "./web-website-task.js"; +import { WebGroupTask } from "./web-group-task.js"; +import { WebMacroDebugTask } from "./web-macro-debug-task.js"; +import { WebOpenTask } from "./web-open-task.js"; +import { WebGraphExportTask } from "./web-graph-export-task.js"; +import { WebLinkMutationTask } from "./web-link-mutation-task.js"; +import { WebStructureTask } from "./web-structure-task.js"; +import { isStructureCommand } from "./web-structure-contract.js"; +import { flushSync } from "react-dom"; +import React, { useEffect, useMemo, useState, useRef } from "react"; +import { SketcherInteractionTask, SketcherConstraintTask } from "./sketcher-interaction-task.js"; +import { SKETCHER_PERSISTENCE_FIXTURE, type SketcherPersistenceResult } from "./sketcher-persistence-facade.js"; +import { sketcherConstraintState, type SketcherConstraintState } from "./sketcher-desktop-adapter.js"; +import { sketcherInteractionState, type SketcherInteractionState } from "./sketcher-desktop-adapter.js"; +import { SketcherViewTask } from "./sketcher-view-task.js"; +import { sketcherViewState, type SketcherViewState } from "./sketcher-desktop-adapter.js"; +import { MaterialDesktopTask, MATERIAL_TASK_COMMANDS } from "./material-desktop-task.js"; +import { prepareMaterialDesktopArgs, persistMaterialDesktopResult } from "./material-desktop-adapter.js"; +import { TechDrawStackPageOwner } from "./techdraw-stack-page-owner.js"; +import { TechDrawActiveView } from "./techdraw-active-view.js"; +import { TechDrawProjectionGroupTask } from "./techdraw-projection-group-task.js"; +import { TechDrawCenterLineTask } from "./techdraw-centerline-task.js"; +import { TechDrawHatchTask } from "./techdraw-hatch-task.js"; +import { TechDrawBalloonTask, type BalloonPlacement, type BalloonPagePoint } from "./techdraw-balloon-task.js"; +import { TechDrawWeldTask } from "./techdraw-weld-task.js"; +import { TechDrawLeaderLineTask } from "./techdraw-leader-line-task.js"; +import { TechDrawDimensionRepairTask } from "./techdraw-dimension-repair-task.js"; +import { TechDrawDimensionTask } from "./techdraw-dimension-task.js"; +import { TechDrawFitTask } from "./techdraw-fit-task.js"; +import { TechDrawSurfaceFinishTask } from "./techdraw-surface-finish-task.js"; +import { TechDrawComplexSectionTask } from "./techdraw-complex-section-task.js"; +import { TechDrawSectionViewTask } from "./techdraw-section-view-task.js"; +import { TechDrawLineDecorationTask } from "./techdraw-line-decoration-task.js"; +import { MeshPartCurveTask } from "./meshpart-curve-task.js"; +import { MeshPartCrossSectionsTask } from "./meshpart-cross-sections-task.js"; +import { MeshPartSectionByPlaneTask } from "./meshpart-section-by-plane-task.js"; +import { MeshPartFlatResult } from "./meshpart-flat-result.js"; +import { MeshComponentsTask } from "./mesh-components-task.js"; +import { MeshSegmentationTask } from "./mesh-segmentation-task.js"; +import { MeshPrimitiveTask } from "./mesh-primitive-task.js"; +import { MeshEvaluationTask } from "./mesh-evaluation-task.js"; +import { MeshSelectedTask } from "./mesh-selected-task.js"; +import { MeshPolygonTask } from "./mesh-polygon-task.js"; +import { MeshFaceInfoTask } from "./mesh-face-info-task.js"; +import { PartPrimitivesTask } from "./part-primitives-task.js"; +import { PartSliceTask } from "./part-slice-task.js"; +import { PartSplitDocumentTask } from "./part-split-document-task.js"; +import { PartBuilderTask } from "./part-builder-task.js"; +import { PartProfileTask } from "./part-profile-task.js"; +import { WebViewTask as PartSelectionView } from "./web-view-task.js"; +import { PART_SELECTION_FILTER_COMMANDS, partDesktopMenu } from "./part-desktop-adapter.js"; +import { PartThicknessTask } from "./part-thickness-task.js"; +import { PartRevolveTask } from "./part-revolve-task.js"; +import { PartScaleTask } from "./part-scale-task.js"; +import { PartMirrorTask } from "./part-mirror-task.js"; +import { PartRuledSurfaceTask } from "./part-ruled-surface-task.js"; +import { PartProjectionTask } from "./part-projection-task.js"; +import { PartCleanupTask } from "./part-cleanup-task.js"; +import { PartCopyTask } from "./part-copy-task.js"; +import { PartMeshConversionTask } from "./part-mesh-conversion-task.js"; +import { PartSamplePointsTask } from "./part-sample-points-task.js"; +import { PartSimpleCylinderTask } from "./part-simple-cylinder-task.js"; +import { PartTubeTask } from "./part-tube-task.js"; +import { PartToleranceTask } from "./part-tolerance-task.js"; +import { PartDesignGearTask } from "./partdesign-gear-task.js"; +import { PartDesignShaftTask } from "./partdesign-shaft-task.js"; +import { PartDesignBooleanTask } from "./partdesign-boolean-task.js"; +import { PartDesignFaceColorTask } from "./partdesign-face-color-task.js"; +import { PartFaceColorTask } from "./part-face-color-task.js"; +import { PartOffsetTask } from "./part-offset-task.js"; +import { PartCompoundTask } from "./part-compound-task.js"; +import { PartJoinTask } from "./part-join-task.js"; +import { PartSectionCutTask } from "./part-section-cut-task.js"; +import { PartDatumTask } from "./part-datum-task.js"; +import { PartDatumsGroupTask } from "./part-datums-group-task.js"; +import { PartAttachmentTask } from "./part-attachment-task.js"; +import { PART_DATUM_TYPES, type PartDatumCommand } from "./part-document-facade.js"; +import { PartChamferTask } from "./part-chamfer-task.js"; +import { PartCheckGeometryTask } from "./part-check-geometry-task.js"; +import { PartMakeFaceTask } from "./part-make-face-task.js"; +import { PartCrossSectionsTask } from "./part-cross-sections-task.js"; +import { PartImportTask } from "./part-import-task.js"; +import { PartExportTask } from "./part-export-task.js"; +import { NativeDocumentTree, partDocumentTreeState, type NativeDocumentTreeState } from "./native-document-tree.js"; +import { DraftGeometryTask, DraftGeometryView } from "./draft-geometry-task.js"; +import { draftPrimitiveCommands, draftPrimitiveTransientKeys, primitivePlane, primitiveDefaults } from "./draft-primitive-geometry.js"; +import { DraftWorkflowTask } from "./draft-workflow-task.js"; +import { DRAFT_WORKFLOW_COMMANDS } from "./draft-desktop-adapter.js"; +import { saveDraftDocument } from "./draft-desktop-adapter.js"; +import { TemplatePyModDesktopTask } from "./templatepymod-desktop-task.js"; +import { applyTemplatePyModResult, type TemplatePyModState } from "./templatepymod-desktop-adapter.js"; +import { SceneViewport } from "./scene-viewport.js"; +import type { SceneDocument } from "./scene-document.js"; +import { BimFrameTask } from "./bim-frame-task.js"; +import { BimImagePlaneTask } from "./bim-image-plane-task.js"; +import { BimFrameView } from "./bim-frame-view.js"; +import { BimWindowsTask } from "./bim-windows-task.js"; +import { BimRelationshipTask } from "./bim-relationship-task.js"; +import { BimNativeEntryButtons } from "./bim-native-entry-buttons.js"; +import { BimIfcOpenShellUpdateTask } from "./bim-ifcopenshell-update-task.js"; +import { bimFrameCommands } from "./bim-desktop-adapter.js"; +import { BimLibraryTask } from "./bim-library-task.js"; +import { saveBimFrameDocument, bimExternalUrl } from "./bim-desktop-adapter.js"; +import { createRoot } from "react-dom/client"; +import { prepareBimDesktopArgs, bimNudgeSetting, orderBimAddSelection } from "./bim-desktop-adapter.js"; +import { BimSelectedTask } from "./bim-selected-task.js"; +import { ASSEMBLY_FIXTURE } from "./assembly-facade.js"; +import { ASSEMBLY_INSPECT_FIXTURE } from "./assembly-inspect-facade.js"; +import { ASSEMBLY_PYTHON_FIXTURE } from "./assembly-python-facade.js"; +import { ASSEMBLY_PERSISTENCE_FIXTURE } from "./assembly-persistence-facade.js"; +import { ASSEMBLY_NATIVE_FIXTURE } from "./assembly-native-facade.js"; +import { CAM_FIXTURE } from "./cam-facade.js"; +import { CamDesktopTask } from "./cam-desktop-task.js"; +import { CamTeachingTask } from "./cam-teaching-task.js"; +import { applyCamDesktopResult, camTaskSelection } from "./cam-desktop-adapter.js"; +import { CAM_IMPORT_EXPORT_FIXTURE } from "./cam-import-export-facade.js"; +import { CAM_INSPECT_FIXTURE } from "./cam-inspect-facade.js"; +import { CAM_PYTHON_FIXTURE } from "./cam-python-facade.js"; +import { CAM_PERSISTENCE_FIXTURE } from "./cam-persistence-facade.js"; +import { CLOUD_FIXTURE, createCloudTransferRequest } from "./cloud-facade.js"; +import { CLOUD_INSPECT_FIXTURE } from "./cloud-inspect-facade.js"; +import { CLOUD_PYTHON_FIXTURE } from "./cloud-python-facade.js"; +import { createCloudPythonFamilyRequest } from "./cloud-python-family-facade.js"; +import { CLOUD_PERSISTENCE_FIXTURE } from "./cloud-persistence-facade.js"; +import { createCloudTestRequest } from "./cloud-diagnostic-facade.js"; +import { DRAFT_FIXTURE } from "./draft-facade.js"; +import { createDraftPythonFamilyRequest, createDraftFormatRequest } from "./draft-python-family-facade.js"; +import { draftGroupState, DRAFT_GROUP_COMMANDS, type DraftGroupState, draftSnapState, draftSnapKey, DRAFT_SNAP_MODES, executeDraftDesktop, type DraftSnapState } from "./draft-desktop-adapter.js"; +import { FEM_FIXTURE } from "./fem-facade.js"; +import { FemDesktopTask } from "./fem-desktop-task.js"; +import { FemWorkbenchView } from "./fem-workbench-view.js"; +import { INSPECTION_FIXTURE } from "./inspection-facade.js"; +import { POINTS_FIXTURE } from "./points-facade.js"; +import { POINTS_INSPECT_FIXTURE } from "./points-inspect-facade.js"; +import { POINTS_PYTHON_FIXTURE } from "./points-python-facade.js"; +import { POINTS_PERSISTENCE_FIXTURE } from "./points-persistence-facade.js"; +import { ROBOT_CREATE_FIXTURE } from "./robot-create-facade.js"; +import { ROBOT_INSPECT_FIXTURE } from "./robot-inspect-facade.js"; +import { ROBOT_PYTHON_FIXTURE } from "./robot-python-facade.js"; +import { ROBOT_SAVE_FIXTURE } from "./robot-save-facade.js"; +import { SANDBOX_FIXTURE } from "./sandbox-facade.js"; +import { SANDBOX_INSPECT_FIXTURE } from "./sandbox-inspect-facade.js"; +import { SANDBOX_PYTHON_FIXTURE } from "./sandbox-python-facade.js"; +import { SANDBOX_SAVE_FIXTURE } from "./sandbox-save-facade.js"; +import { SURFACE_FIXTURE } from "./surface-facade.js"; +import { SURFACE_INSPECT_FIXTURE } from "./surface-inspect-facade.js"; +import { SURFACE_PY_FIXTURE } from "./surface-python-facade.js"; +import { SURFACE_SAVE_FIXTURE } from "./surface-save-facade.js"; +import { SPREADSHEET_CREATE_FIXTURE } from "./spreadsheet-facade.js"; +import { SPREADSHEET_INSPECT_FIXTURE } from "./spreadsheet-inspect-facade.js"; +import { SPREADSHEET_PYTHON_FIXTURE } from "./spreadsheet-python-facade.js"; +import { SPREADSHEET_SAVE_FIXTURE } from "./spreadsheet-save-facade.js"; +import { REVERSEENGINEERING_CREATE_FIXTURE } from "./reverseengineering-create-facade.js"; +import { REVERSEENGINEERING_INSPECT_FIXTURE } from "./reverseengineering-inspect-facade.js"; +import { REVERSEENGINEERING_PYTHON_FIXTURE } from "./reverseengineering-python-facade.js"; +import { REVERSEENGINEERING_SAVE_FIXTURE } from "./reverseengineering-save-facade.js"; +import { BIM_INSPECT_FIXTURE } from "./bim-inspect-facade.js"; +import { BIM_PYTHON_FIXTURE } from "./bim-python-facade.js"; +import { BIM_AXIS_FIXTURE } from "./bim-axis-facade.js"; +import { BIM_EXTRUSION_FIXTURE } from "./bim-extrusion-facade.js"; +import { HELP_INSPECT_FIXTURE } from "./help-inspect-facade.js"; +import { HELP_PYTHON_FIXTURE } from "./help-python-facade.js"; +import { START_FIXTURE } from "./start-facade.js"; +import { START_INVENTORY_FIXTURE } from "./start-inventory-facade.js"; +import { START_PY_FIXTURE } from "./start-python-facade.js"; +import { SHOW_INSPECT_FIXTURE } from "./show-inspect-facade.js"; +import { SHOW_PYTHON_FIXTURE } from "./show-python-facade.js"; +import { TUX_FIXTURE } from "./tux-facade.js"; +import { WEB_FIXTURE } from "./web-facade.js"; +import { WEB_FIXTURE as WEB_PERSISTENCE_FIXTURE } from "./web-persistence-facade.js"; +import { TEST_FIXTURE } from "./test-facade.js"; +import { TestDesktopOutput } from "./test-desktop-output.js"; +import { TestSceneWorkspace } from "./test-scene-workspace.js"; +import { TestMdiViewHost } from "./test-mdi-host.js"; +import { DockOverlayHost } from "./dock-overlay-host.js"; +import { executeTestDesktopWithHost, type TestWorkbenchHost } from "./test-desktop-adapter.js"; +import { JTREADER_FIXTURE } from "./jtreader-facade.js"; +import { JTREADER_INSPECT_FIXTURE } from "./jtreader-inspect-facade.js"; +import { JTREADER_PERSISTENCE_FIXTURE } from "./jtreader-persistence-facade.js"; +import { PLOT_PYTHON_FIXTURE } from "./plot-python-facade.js"; +import { TPM_FIXTURE } from "./templatepymod-facade.js"; +import { TPM_PY_FIXTURE } from "./templatepymod-python-facade.js"; +import { IMPORT_CREATE_RECOMPUTE_FIXTURE, IMPORT_FIXTURE, IMPORT_SAVE_REOPEN_FIXTURE } from "./import-facade.js"; +import { MESH_FIXTURE } from "./mesh-facade.js"; +import { MESH_IO_FIXTURE } from "./mesh-io-facade.js"; +import { MEASURE_PYTHON_FIXTURE } from "./measure-python-facade.js"; +import { MEASUREMENT_API_FIXTURE } from "./measure-measurement-facade.js"; +import { MESHPART_FIXTURE } from "./meshpart-facade.js"; +import { MSP_INSPECT_FIXTURE } from "./meshpart-inspect-facade.js"; +import { MSP_PYTHON_FIXTURE } from "./meshpart-python-facade.js"; +import { MATERIAL_FIXTURE } from "./material-facade.js"; +import { MATERIAL_INSPECT_FIXTURE } from "./material-inspect-facade.js"; +import { MATERIAL_PYTHON_FIXTURE } from "./material-python-facade.js"; +import { MATERIAL_PERSISTENCE_FIXTURE } from "./material-persistence-facade.js"; +import { writeDocumentFile, writeRawStep } from "./storage.js"; +import { PARTDESIGN_FIXTURE } from "./partdesign-facade.js"; +import { PART_FIXTURE } from "./part-facade.js"; +import { PART_IO_FIXTURE } from "./part-io-facade.js"; +import { PART_SAVE_FIXTURE } from "./part-save-facade.js"; +import { PART_PYTHON_FIXTURE } from "./part-python-facade.js"; +import { createPartPythonMethodRequest } from "./part-python-method-facade.js"; +import { PARTDESIGN_PYTHON_FIXTURE } from "./partdesign-python-facade.js"; +import { SKETCHER_FIXTURE } from "./sketcher-facade.js"; +import { TECHDRAW_NATIVE_FIXTURE } from "./techdraw-native-facade.js"; +import { TECHDRAW_COMMAND, TECHDRAW_FIXTURE, type TechDrawResult } from "./techdraw-facade.js"; +import { TECHDRAW_PY_FIXTURE } from "./techdraw-python-facade.js"; +import { IMPORT_PYTHON_FIXTURE } from "./import-python-facade.js"; +import { WEB_MODULE_REGISTRY } from "./module-registry.generated.js"; +import { WebModuleRouter } from "./module-router.js"; +import { createCancel, createFailure, createSuccess, type FacadeResponse } from "./facade-envelope.js"; +import { PythonFamilyDispatcher } from "./python-family-dispatcher.js"; +import { listWebCommands, WebCommandRuntime, type WebCommandDescriptor } from "./command-runtime.js"; +import { nativeSourceDecision } from "./native-source-policy.js"; +import { PythonApiCallDispatcher } from "./python-api-call.js"; +import { installNavigation, readNavigationContext, updateNavigationContext } from "./navigation.js"; +import { installUiAccessibility } from "./ui-accessibility.js"; +import { PluginRegistry } from "./plugin-registry.js"; +import { createWorkbenchCommandRequest, type WorkbenchCommandRecord } from "./workbench-command-facade.js"; +import { DesktopCommandDispatcher } from "./desktop-command-dispatcher.js"; + +interface WorkbenchCommandMatrix { + records: WorkbenchCommandRecord[]; + dispositionCounts: { native_handler: number; restricted: number; not_implemented: number }; + modules: Array<{ module: string; desktopCommandCount: number; webCommandCount: number; taskPanelFileCount: number; resourceFileCount: number }>; +} + +type WorkbenchStage = "ready" | "running" | "success" | "expected-error" | "cancelled" | "reset"; + +declare global { + interface Window { + __freecadWorkbenchState?: { + stage: WorkbenchStage; + status: string; + response: FacadeResponse | null; + matrix: { records: number; nativeHandlers: number; restricted: number } | null; + selected: WorkbenchCommandRecord | null; + }; + } +} + +const PAYLOADS: Record = { + "Assembly:assembly.createRecompute": ASSEMBLY_FIXTURE, + "Assembly:assembly.inspectSourceInventory": ASSEMBLY_INSPECT_FIXTURE, + "Assembly:assembly.inspectPythonApi": ASSEMBLY_PYTHON_FIXTURE, + "Assembly:assembly.saveReopen": ASSEMBLY_PERSISTENCE_FIXTURE, + "Assembly:assembly.nativeTypeProbe": ASSEMBLY_NATIVE_FIXTURE, + "CAM:cam.createRecompute": CAM_FIXTURE, + "CAM:cam.import": CAM_IMPORT_EXPORT_FIXTURE, + "CAM:cam.export": CAM_IMPORT_EXPORT_FIXTURE, + "CAM:cam.inspectSourceInventory": CAM_INSPECT_FIXTURE, + "CAM:cam.inspectPythonApi": CAM_PYTHON_FIXTURE, + "CAM:cam.saveReopen": CAM_PERSISTENCE_FIXTURE, + "Fem:fem.action": FEM_FIXTURE, + "Draft:draft.action": DRAFT_FIXTURE, + "Draft:draft.pythonFamilyBatch": createDraftPythonFamilyRequest("workbench-draft-python-family", [{ apiId: "py:Draft:class:Arc", name: "Arc", family: "generic-object" }]).payload, + "Draft:draft.formatBatch": createDraftFormatRequest("workbench-draft-format", [{ format: "svg", direction: "export", documentId: "draft-document", payload: "" }]).payload, + "Inspection:inspection.createRecompute": INSPECTION_FIXTURE, + "Points:points.createRecompute": POINTS_FIXTURE, + "Points:points.inspectSource": POINTS_INSPECT_FIXTURE, + "Points:points.pythonApi": POINTS_PYTHON_FIXTURE, + "Points:points.saveReopen": POINTS_PERSISTENCE_FIXTURE, + "Robot:robot.createRecompute": ROBOT_CREATE_FIXTURE, + "Robot:robot.inspectSourceInventory": ROBOT_INSPECT_FIXTURE, + "Robot:robot.pythonApi": ROBOT_PYTHON_FIXTURE, + "Robot:robot.saveReopen": ROBOT_SAVE_FIXTURE, + "Sandbox:sandbox.createRecompute": SANDBOX_FIXTURE, + "Sandbox:sandbox.inspectSourceInventory": SANDBOX_INSPECT_FIXTURE, + "Sandbox:sandbox.pythonApi": SANDBOX_PYTHON_FIXTURE, + "Sandbox:sandbox.saveReopen": SANDBOX_SAVE_FIXTURE, + "Surface:surface.createRecompute": SURFACE_FIXTURE, + "Surface:surface.inspectSourceInventory": SURFACE_INSPECT_FIXTURE, + "Surface:surface.pythonApi": SURFACE_PY_FIXTURE, + "Surface:surface.saveReopen": SURFACE_SAVE_FIXTURE, + "Spreadsheet:spreadsheet.createRecompute": SPREADSHEET_CREATE_FIXTURE, + "Spreadsheet:spreadsheet.inspectSourceInventory": SPREADSHEET_INSPECT_FIXTURE, + "Spreadsheet:spreadsheet.pythonApi": SPREADSHEET_PYTHON_FIXTURE, + "Spreadsheet:spreadsheet.saveReopen": SPREADSHEET_SAVE_FIXTURE, + "ReverseEngineering:reverseengineering.createRecompute": REVERSEENGINEERING_CREATE_FIXTURE, + "ReverseEngineering:reverseengineering.inspectSourceInventory": REVERSEENGINEERING_INSPECT_FIXTURE, + "ReverseEngineering:reverseengineering.pythonApi": REVERSEENGINEERING_PYTHON_FIXTURE, + "ReverseEngineering:reverseengineering.saveReopen": REVERSEENGINEERING_SAVE_FIXTURE, + "Part:part.createRecompute": PART_FIXTURE, + "Part:part.importExport": PART_IO_FIXTURE, + "Part:part.saveReopen": PART_SAVE_FIXTURE, + "Part:part.pythonApi": PART_PYTHON_FIXTURE, + "Part:part.pythonMethod": createPartPythonMethodRequest("workbench-part-method", { outerRadius: 5, innerRadius: 2, height: 10 }).payload, + "PartDesign:partdesign.createRecompute": PARTDESIGN_FIXTURE, + "PartDesign:partdesign.pythonApi": PARTDESIGN_PYTHON_FIXTURE, + "Sketcher:sketcher.createRecompute": SKETCHER_FIXTURE, + "TechDraw:techdraw.nativeImportExport": TECHDRAW_NATIVE_FIXTURE, + "TechDraw:techdraw.createRecompute": TECHDRAW_FIXTURE, + "TechDraw:techdraw.pythonApi": TECHDRAW_PY_FIXTURE, + "Import:import.step": IMPORT_FIXTURE, + "Import:import.pythonApi": IMPORT_PYTHON_FIXTURE, + "Import:import.createRecompute": IMPORT_CREATE_RECOMPUTE_FIXTURE, + "Import:import.saveReopen": IMPORT_SAVE_REOPEN_FIXTURE, + "Mesh:mesh.createRecompute": MESH_FIXTURE, + "Mesh:mesh.importExport": MESH_IO_FIXTURE, + "Measure:measure.pythonApi": MEASURE_PYTHON_FIXTURE, + "Measure:measure.measurementApi": MEASUREMENT_API_FIXTURE, + "Material:material.createRecompute": MATERIAL_FIXTURE, + "Material:material.inspectSourceInventory": MATERIAL_INSPECT_FIXTURE, + "Material:material.pythonApi": MATERIAL_PYTHON_FIXTURE, + "Material:material.saveReopen": MATERIAL_PERSISTENCE_FIXTURE, + "Cloud:cloud.configureRecompute": CLOUD_FIXTURE, + "Cloud:cloud.inspectSourceInventory": CLOUD_INSPECT_FIXTURE, + "Cloud:cloud.inspectPythonApi": CLOUD_PYTHON_FIXTURE, + "Cloud:cloud.saveReopen": CLOUD_PERSISTENCE_FIXTURE, + "Cloud:cloud.save": createCloudTransferRequest("workbench-cloud-save", "save", "document.fcstd").payload, + "Cloud:cloud.restore": createCloudTransferRequest("workbench-cloud-restore", "restore", "document.fcstd").payload, + "Cloud:cloud.pythonFamilyBatch": createCloudPythonFamilyRequest("workbench-cloud-python-family", [{ apiId: "py:Cloud:class:CloudWorkbench", name: "CloudWorkbench", family: "generic-object" }]).payload, + "Cloud:Cloud_Test": createCloudTestRequest("workbench-cloud-test").payload, + "MeshPart:meshpart.createRecompute": MESHPART_FIXTURE, + "MeshPart:meshpart.inspectSourceInventory": MSP_INSPECT_FIXTURE, + "MeshPart:meshpart.pythonApi": MSP_PYTHON_FIXTURE, + "BIM:bim.inspectSourceInventory": BIM_INSPECT_FIXTURE, + "BIM:bim.inspectPythonApi": BIM_PYTHON_FIXTURE, + "BIM:bim.createAxis": BIM_AXIS_FIXTURE, + "BIM:bim.extrusionData": BIM_EXTRUSION_FIXTURE, + "Help:help.inspectSourceInventory": HELP_INSPECT_FIXTURE, + "Help:help.pythonApi": HELP_PYTHON_FIXTURE, + "Start:start.moduleImport": START_FIXTURE, + "Start:start.inspectSourceInventory": START_INVENTORY_FIXTURE, + "Start:start.pythonApi": START_PY_FIXTURE, + "Show:show.inspectSourceInventory": SHOW_INSPECT_FIXTURE, + "Show:show.pythonApi": SHOW_PYTHON_FIXTURE, + "Tux:tux.navigationBoundary": TUX_FIXTURE, + "Web:web.serverContract": WEB_FIXTURE, + "Web:web.saveReopenBoundary": WEB_PERSISTENCE_FIXTURE, + "Test:test.inspectRegistry": TEST_FIXTURE, + "JtReader:jtreader.createRecompute": JTREADER_FIXTURE, + "JtReader:jtreader.inspectSourceInventory": JTREADER_INSPECT_FIXTURE, + "JtReader:jtreader.saveReopen": JTREADER_PERSISTENCE_FIXTURE, + "Plot:plot.pythonApi": PLOT_PYTHON_FIXTURE, + "TemplatePyMod:templatepymod.inspectSourceInventory": TPM_FIXTURE, + "TemplatePyMod:templatepymod.pythonApi": TPM_PY_FIXTURE, +}; + +const css = `:root{color-scheme:dark;font-family:Inter,system-ui,sans-serif;background:#10161d;color:#e7edf3}*{box-sizing:border-box}html{overflow-x:hidden}body{margin:0;min-width:320px;overflow-x:hidden}.top{align-items:center;background:#17212b;border-bottom:1px solid #2c3b48;display:flex;gap:14px;padding:14px 20px}.brand{background:#3b9db0;border-radius:5px;color:#071219;font-weight:800;padding:7px}.title{margin-left:auto}.layout{display:grid;grid-template-columns:260px 340px minmax(0,1fr);min-height:calc(100vh - 56px);min-width:0}aside{background:#17212b;padding:16px;overflow:auto;min-width:0}aside:first-child{border-right:1px solid #2c3b48}aside:nth-child(2){border-right:1px solid #2c3b48}.stage{background:#0d1319;padding:24px;min-width:0;overflow-x:hidden}.search,.payload-editor{background:#10161d;border:1px solid #435464;border-radius:5px;color:#e7edf3;font:inherit;padding:8px;width:100%;max-width:100%}.payload-editor{font-family:ui-monospace,monospace;font-size:12px;line-height:1.45;min-height:132px;resize:vertical}.module,.command{background:transparent;border:0;border-bottom:1px solid #2c3b48;color:#d9e4e8;cursor:pointer;display:block;font:inherit;padding:10px 6px;text-align:left;width:100%;min-width:0;overflow-wrap:anywhere}.module:hover,.command:hover{background:color-mix(in srgb,#575757 70%,#66c7d5 30%)}.module.selected,.command.selected{background:#304b52;border-left:3px solid #66c7d5}.module:focus-visible,.command:focus-visible{outline:1px solid #66c7d5;outline-offset:-1px}.module:disabled,.command:disabled{color:#858585;cursor:default}.module small,.command small{color:#8ea2ae;display:block;font-size:11px;margin-top:3px}.heading{color:#9cb6c2;font-size:11px;letter-spacing:.08em;margin:0 0 12px;text-transform:uppercase}.status{color:#9cb6c2;line-height:1.5;overflow-wrap:anywhere}.status.ok{color:#9ce0bd}.status.error{color:#ff9e9e}.run{background:#1d2a35;border:1px solid #66b7c8;border-radius:5px;color:#e7edf3;cursor:pointer;font:inherit;margin:8px 0;padding:9px 12px;width:100%}.run:disabled{opacity:.45}.secondary{border-color:#61717d}.result{font-family:ui-monospace,monospace;font-size:12px;line-height:1.5;max-height:52vh;overflow:auto;white-space:pre-wrap;word-break:break-word}.stat{border-bottom:1px solid #2c3b48;padding:9px 0}.stat small{color:#8ea2ae;display:block;margin-top:3px;overflow-wrap:anywhere}.matrix-list{border-top:1px solid #2c3b48;margin-top:18px;max-height:240px;overflow:auto}.matrix-list .command{font-size:12px}.workbench-status-mirror{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}.workbench-status-bar{position:fixed;left:0;right:0;bottom:0;z-index:20;display:flex;align-items:center;min-height:22px;padding:0 8px;background:#191919;border:0}.workbench-status-bar .status{flex:1;min-width:0;margin:0;padding:2px 0;line-height:1.35;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}@media(max-width:920px){.layout{grid-template-columns:220px minmax(0,300px) minmax(0,1fr)}}.fem-split{display:grid;grid-template-columns:minmax(220px,300px) minmax(0,1fr);gap:12px;align-items:start}@media(max-width:720px){.layout{grid-template-columns:1fr}.layout>aside{max-height:none}.stage{min-height:55vh;padding:16px}aside:nth-child(2){border-top:1px solid #2c3b48;border-right:0}.fem-split{grid-template-columns:1fr}}`; + +const desktopParityCss = `button,input,select,textarea{border-radius:3px}.search,.payload-editor,.run{border-radius:3px}#app textarea{box-sizing:border-box;min-height:22px;padding:2px 4px;background:#191919;color:#fff;border:1px solid #3f3f3f;border-radius:3px;color-scheme:dark}#app textarea:focus{border-color:#66c7d5;outline:none}#app textarea::selection{background:#575757;color:#fff}#app textarea:disabled{background:#0f0f0f;color:#858585;opacity:.65}[role="toolbar"] [role="separator"][aria-orientation="vertical"]{display:inline-block;width:1px;height:18px;flex:0 0 1px;margin:5px;background:#3f3f3f}[role="toolbar"] [role="separator"][aria-orientation="horizontal"]{display:block;width:18px;height:1px;flex:0 0 1px;margin:5px;background:#3f3f3f}.dock-workbench table{box-sizing:border-box;border:1px solid transparent;border-collapse:collapse;color:#fff;background:#191919}.dock-workbench table:hover{border-color:#66c7d5}.dock-workbench table thead th{background:linear-gradient(to bottom,#2b2b2b,#191919);padding:4px;border-top:1px solid #3f3f3f;border-right:1px solid #3f3f3f;border-bottom:1px solid #3f3f3f;border-left:1px solid transparent;text-align:left;font-weight:600}.dock-workbench table thead th:first-child{border-left-color:#3f3f3f}.dock-workbench table thead th:hover{background:#575757}.dock-workbench table thead th:disabled{color:#858585}.dock-workbench table tbody td{border-right:1px solid #3f3f3f;border-bottom:1px solid #3f3f3f;padding:4px;vertical-align:top}.dock-workbench table tbody td:first-child{border-left:1px solid #3f3f3f}.dock-workbench table tbody tr:nth-child(even){background:#2b2b2b}.dock-workbench table tbody tr:hover{background:color-mix(in srgb,#575757 70%,#66c7d5 30%)}.dock-workbench table tbody tr:has(input[type=checkbox]:checked){background:#304b52}.dock-workbench table tbody tr:focus-within{outline:1px solid #66c7d5;outline-offset:-1px}section[aria-label="Appearance task"] input[type=color],section[aria-label="Custom appearance"] input[type=color]{width:32px;height:22px;min-height:22px;padding:3px;border:1px solid #3f3f3f;border-radius:3px;background:linear-gradient(to bottom,#2b2b2b,#191919);cursor:pointer}section[aria-label="Appearance task"] input[type=color]:hover,section[aria-label="Custom appearance"] input[type=color]:hover{border-color:#575757}section[aria-label="Appearance task"] input[type=color]:focus-visible,section[aria-label="Custom appearance"] input[type=color]:focus-visible{outline:1px solid #66c7d5;outline-offset:1px}section[aria-label="Appearance task"] input[type=number],section[aria-label="Custom appearance"] input[type=number]{box-sizing:border-box;min-height:22px;padding:2px 4px;background:#191919;color:#fff;border:1px solid #3f3f3f;border-radius:3px;color-scheme:dark}section[aria-label="Appearance task"] input[type=number]:focus,section[aria-label="Custom appearance"] input[type=number]:focus{border-color:#66c7d5;outline:none}section[aria-label="Appearance task"] input[type=number]::-webkit-inner-spin-button,section[aria-label="Appearance task"] input[type=number]::-webkit-outer-spin-button{opacity:1;filter:grayscale(1) brightness(1.35)}section[aria-label="Appearance task"] input[type=number]::-webkit-outer-spin-button{opacity:1;filter:grayscale(1) brightness(1.35)}section[aria-label="Appearance task"] input[type=number]:hover::-webkit-inner-spin-button,section[aria-label="Custom appearance"] input[type=number]:hover::-webkit-outer-spin-button{filter:grayscale(1) brightness(1.7)}section[aria-label="Appearance task"] input[type=number]:disabled,section[aria-label="Custom appearance"] input[type=number]:disabled{opacity:.45}`; + +const tableButtonParityCss = `#app table button:not([class]):not([role=tab]){padding:2px}#app table button:not([class]):not([role=tab]):hover:not(:disabled){background:#575757;border:1px solid #3f3f3f}`; +const materialParityCss = `section[aria-label="Material resource preferences"] input:not([type=checkbox]),section[aria-label="Material resource preferences"] select{box-sizing:border-box;min-height:22px;padding:2px 4px;background:#191919;color:#fff;border:1px solid #3f3f3f;border-radius:3px;color-scheme:dark}section[aria-label="Material resource preferences"] input:not([type=checkbox]):focus,section[aria-label="Material resource preferences"] select:focus{border-color:#66c7d5;outline:none}section[aria-label="Material resource preferences"] input:not([type=checkbox]):disabled,section[aria-label="Material resource preferences"] select:disabled{opacity:.45}`; +const radioParityCss = `#app input[type=radio]{appearance:none;box-sizing:border-box;width:12px;height:12px;margin:2px 8px 0 0;padding:0;border:1px solid #3f3f3f;border-radius:50%;background:#191919;color-scheme:dark;vertical-align:top}#app input[type=radio]:hover{background:#575757;border-color:#575757}#app input[type=radio]:focus-visible{outline:1px solid #66c7d5;outline-offset:1px}#app input[type=radio]:checked{background:radial-gradient(circle,#fff 0 3px,transparent 3.5px),#191919}#app input[type=radio]:checked:hover{background:radial-gradient(circle,#fff 0 3px,transparent 3.5px),#575757}#app input[type=radio]:disabled{background:#0f0f0f;border-color:#3f3f3f;opacity:.45}#app input[type=radio]:checked:disabled{background:radial-gradient(circle,#858585 0 3px,transparent 3.5px),#0f0f0f}`; +const checkboxParityCss = `#app input[type=checkbox]{appearance:none;box-sizing:border-box;width:12px;height:12px;margin:2px 8px 0 0;padding:0;border:1px solid #3f3f3f;border-radius:3px;background:#191919;color-scheme:dark;vertical-align:top;flex:0 0 12px}#app input[type=checkbox]:hover{background:#191919;border-color:#575757}#app input[type=checkbox]:focus-visible{outline:1px solid #66c7d5;outline-offset:1px}#app input[type=checkbox]:checked{background:linear-gradient(135deg,transparent 42%,#fff 42% 56%,transparent 56%) 0 4px/6px 6px no-repeat,linear-gradient(45deg,transparent 41%,#fff 41% 56%,transparent 56%) 5px 1px/6px 8px no-repeat,#191919}#app input[type=checkbox]:checked:hover{background:linear-gradient(135deg,transparent 42%,#fff 42% 56%,transparent 56%) 0 4px/6px 6px no-repeat,linear-gradient(45deg,transparent 41%,#fff 41% 56%,transparent 56%) 5px 1px/6px 8px no-repeat,#191919;border-color:#575757}#app input[type=checkbox]:indeterminate{background:linear-gradient(#fff,#fff) center/7px 2px no-repeat,#191919}#app input[type=checkbox]:disabled{background:#0f0f0f;border-color:#3f3f3f;opacity:.65}#app input[type=checkbox]:checked:disabled{background:linear-gradient(135deg,transparent 42%,#858585 42% 56%,transparent 56%) 0 4px/6px 6px no-repeat,linear-gradient(45deg,transparent 41%,#858585 41% 56%,transparent 56%) 5px 1px/6px 8px no-repeat,#0f0f0f}`; +const spinBoxParityCss = `#app input[type=number]{appearance:auto;box-sizing:border-box;min-width:10px;min-height:22px;padding:2px 4px;background:#191919;color:#fff;border:1px solid #3f3f3f;border-radius:3px;color-scheme:dark}#app input[type=number]:hover{border-color:#575757}#app input[type=number]:focus{border-color:#66c7d5;outline:none}#app input[type=number]:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:.65}#app input[type=number]::-webkit-inner-spin-button,#app input[type=number]::-webkit-outer-spin-button{opacity:1;filter:grayscale(1) brightness(1.35)}#app input[type=number]:hover::-webkit-inner-spin-button,#app input[type=number]:hover::-webkit-outer-spin-button{filter:grayscale(1) brightness(1.7)}#app input[type=number]:disabled::-webkit-inner-spin-button,#app input[type=number]:disabled::-webkit-outer-spin-button{filter:grayscale(1) brightness(.7)}`; +const lineEditParityCss = `#app input[type=text]:not(.search):not(.payload-editor),#app input:not([type]):not(.search):not(.payload-editor){box-sizing:border-box;min-width:10px;min-height:22px;padding:2px 4px;background:#191919;color:#fff;border:1px solid #3f3f3f;border-radius:3px;color-scheme:dark}#app input[type=text]:not(.search):not(.payload-editor):hover,#app input:not([type]):not(.search):not(.payload-editor):hover{border-color:#575757}#app input[type=text]:not(.search):not(.payload-editor):focus,#app input:not([type]):not(.search):not(.payload-editor):focus{border-color:#66c7d5;outline:none}#app input[type=text]:not(.search):not(.payload-editor)::selection,#app input:not([type]):not(.search):not(.payload-editor)::selection{background:#575757;color:#fff}#app input[type=text]:not(.search):not(.payload-editor):disabled,#app input:not([type]):not(.search):not(.payload-editor):disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:.65}`; +const groupBoxParityCss = `#app fieldset{box-sizing:border-box;min-width:0;margin:18px 0 2px;padding:6px 8px 8px;border:1px solid #575757;border-radius:5px;background:#2b2b2b;color:#fff}#app fieldset>legend{padding:0 4px;color:#fff;font-weight:600}#app fieldset:disabled{color:#858585}#app fieldset:disabled>legend{color:#858585}`; +const sliderParityCss = `#app input[type=range]{appearance:none;width:100%;height:8px;margin:4px 0;padding:0;background:transparent;color-scheme:dark;vertical-align:middle}#app input[type=range]::-webkit-slider-runnable-track{height:4px;border:1px solid #3f3f3f;border-radius:3px;background:#191919}#app input[type=range]::-webkit-slider-thumb{appearance:none;width:10px;height:8px;margin:-3px 0;border:1px solid #3f3f3f;border-radius:6px;background:#66c7d5}#app input[type=range]:hover::-webkit-slider-thumb{border-color:#575757;background:#575757}#app input[type=range]:focus-visible{outline:1px solid #66c7d5;outline-offset:1px}#app input[type=range]:disabled{opacity:.45}#app input[type=range]:disabled::-webkit-slider-thumb{background:#3f3f3f}#app input[type=range]::-moz-range-track{height:4px;border:1px solid #3f3f3f;border-radius:3px;background:#191919}#app input[type=range]::-moz-range-progress{height:4px;border:1px solid #3f3f3f;border-radius:3px;background:#66c7d5}#app input[type=range]::-moz-range-thumb{width:10px;height:8px;border:1px solid #3f3f3f;border-radius:6px;background:#66c7d5}`; +const progressParityCss = `#app progress{appearance:none;box-sizing:border-box;width:100%;height:16px;border:1px solid #3f3f3f;border-radius:3px;background:#191919;color:#66c7d5;vertical-align:middle}#app progress::-webkit-progress-bar{border-radius:3px;background:#191919}#app progress::-webkit-progress-value{border-radius:3px;background:#66c7d5}#app progress::-moz-progress-bar{border-radius:3px;background:#66c7d5}#app progress:disabled,#app progress[disabled]{background:#0f0f0f;color:#858585;opacity:.65}#app progress:disabled::-webkit-progress-value,#app progress[disabled]::-webkit-progress-value{background:#3f3f3f}#app progress:disabled::-moz-progress-bar,#app progress[disabled]::-moz-progress-bar{background:#3f3f3f}`; +const dialogParityCss = `#app dialog{box-sizing:border-box;min-width:280px;max-width:calc(100vw - 24px);padding:12px;background:#2b2b2b;color:#fff;border:1px solid #3f3f3f;border-radius:3px}#app dialog::backdrop{background:#0008}`; +const tabWidgetParityCss = `#app .draft-style-tabs{display:flex;align-items:flex-end;justify-content:center;gap:0;padding:2px 2px 0;background:transparent}#app .draft-style-tabs [role=tab]{min-width:5px;margin:0;padding:4px;background:#171717;color:#fff;border:1px solid #3f3f3f;border-radius:3px 3px 0 0;font:inherit;cursor:pointer}#app .draft-style-tabs [role=tab][aria-selected=true]{background:#191919;border-bottom-color:#191919;font-weight:700}#app .draft-style-tabs [role=tab]:not([aria-selected=true]):hover,#app .draft-style-tabs [role=tab]:focus-visible{background:#575757;border-color:#3f3f3f;outline:1px solid #66c7d5;outline-offset:-1px}#app .draft-style-tab-panel{margin-top:-1px;border:1px solid #3f3f3f;border-radius:3px;padding:8px;background:#191919}#app .draft-style-tab-panel>legend{color:#fff;font-weight:600}`; +const dateEditParityCss = `#app input[type=date],#app input[type=datetime-local]{box-sizing:border-box;min-width:10px;min-height:22px;padding:2px 4px;background:#191919;color:#fff;border:1px solid #3f3f3f;border-radius:3px;color-scheme:dark}#app input[type=date]:focus,#app input[type=datetime-local]:focus{border-color:#66c7d5;outline:none}#app input[type=date]::-webkit-calendar-picker-indicator,#app input[type=datetime-local]::-webkit-calendar-picker-indicator{width:12px;height:12px;padding:0;filter:grayscale(1) brightness(1.35);cursor:pointer}#app input[type=date]:hover,#app input[type=datetime-local]:hover{border-color:#575757}#app input[type=date]:disabled,#app input[type=datetime-local]:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;opacity:.65}`; +const comboPopupParityCss = `#app select{appearance:none;box-sizing:border-box;padding-right:18px;background-color:#191919;background-image:linear-gradient(45deg,transparent 50%,#d3d3d3 50%),linear-gradient(135deg,#d3d3d3 50%,transparent 50%),linear-gradient(to bottom,#2b2b2b,#191919);background-position:calc(100% - 9px) 50%,calc(100% - 5px) 50%,0 0;background-repeat:no-repeat;background-size:4px 4px,4px 4px,100% 100%}#app select:hover{background-image:linear-gradient(45deg,transparent 50%,#fff 50%),linear-gradient(135deg,#fff 50%,transparent 50%),linear-gradient(to bottom,#575757,#191919)}#app select:focus{background-image:linear-gradient(45deg,transparent 50%,#fff 50%),linear-gradient(135deg,#fff 50%,transparent 50%),linear-gradient(to bottom,#2b2b2b,#191919)}#app select:disabled{background-image:linear-gradient(45deg,transparent 50%,#858585 50%),linear-gradient(135deg,#858585 50%,transparent 50%),linear-gradient(to bottom,#0f0f0f,#0f0f0f)}#app select option{background:#191919;color:#fff}#app select option:nth-child(even){background:#2b2b2b}#app select option:checked{background:#575757;color:#fff}#app select option:disabled{background:#0f0f0f;color:#858585}`; +const nativeTreeParityCss = `#app .native-tree-list,#app .native-tree-children{list-style:none;margin:0;padding:0}#app .native-tree-children{padding-left:12px}#app .native-tree-item{margin:0;padding:0}#app .native-tree-row{display:block;box-sizing:border-box;width:100%;min-width:0;margin:0;padding:4px 6px;border:0;border-bottom:1px solid #2c3b48;border-radius:0;background:transparent;color:#fff;font:inherit;text-align:left;overflow-wrap:anywhere;cursor:pointer}#app .native-tree-item[aria-selected=true]>.native-tree-row{background:#304b52;color:#fff}#app .native-tree-row:hover:not(:disabled){background:color-mix(in srgb,#575757 70%,#66c7d5 30%)}#app .native-tree-row:focus-visible{outline:1px solid #66c7d5;outline-offset:-1px}#app .native-tree-row:disabled{color:#858585;cursor:default}#app .native-tree-meta{padding:0 6px 3px;color:#8ea2ae;font-size:11px}`; +const pushButtonParityCss = `#app button:not([class]):not([role=tab]){box-sizing:border-box;min-width:80px;padding:3px 12px;border:1px solid #3f3f3f;border-radius:3px;background:linear-gradient(to bottom,#2b2b2b,#191919);color:#fff;cursor:pointer}#app button:not([class]):not([role=tab]):hover:not(:disabled){background:#575757}#app button:not([class]):not([role=tab]):focus-visible{border-color:#66c7d5;outline:none}#app button:not([class]):not([role=tab]):active:not(:disabled){background:linear-gradient(to bottom,#191919,#2b2b2b);border-color:#575757}#app button:not([class]):not([role=tab]):disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f;cursor:default}#app button:not([class]):not([role=tab])[aria-pressed=true]{background:linear-gradient(to bottom,#242424,#191919);border-color:#575757}#app button:not([class]):not([role=tab])[aria-pressed=true]:hover:not(:disabled){background:#575757;border-color:#66c7d5}#app button:not([class]):not([role=tab])[aria-pressed=true]:active:not(:disabled){background:#2b2b2b;border-color:#3f3f3f}#app button:not([class]):not([role=tab])[aria-pressed=true]:disabled{background:#0f0f0f;color:#858585;border-color:#3f3f3f}#app button:not([class]):not([role=tab]):default{background:linear-gradient(to bottom,#394649,#253638);border-color:#536b6e}`; +const toolButtonParityCss = `#app [data-desktop-toolbar]>.command,#app [data-desktop-commandbar]>.command{box-sizing:border-box;min-width:30px;min-height:22px;padding:2px 6px;border:1px solid transparent;border-radius:3px;background:transparent;color:#fff;cursor:pointer}#app [data-desktop-toolbar]>.command:hover:not(:disabled),#app [data-desktop-commandbar]>.command:hover:not(:disabled){background:#575757;border-color:#3f3f3f}#app [data-desktop-toolbar]>.command:focus-visible,#app [data-desktop-commandbar]>.command:focus-visible{border-color:#3f3f3f;outline:1px solid #66c7d5;outline-offset:-1px}#app [data-desktop-toolbar]>.command:active:not(:disabled),#app [data-desktop-commandbar]>.command:active:not(:disabled){background:#2b2b2b;border-color:#3f3f3f}#app [data-desktop-toolbar]>.command.selected,#app [data-desktop-commandbar]>.command.selected{background:transparent;border:1px solid #575757;border-left:1px solid #575757;color:#fff}#app [data-desktop-toolbar]>.command:disabled,#app [data-desktop-commandbar]>.command:disabled{background:transparent;border-color:transparent;color:#858585;opacity:1;cursor:default}`; +const listBoxParityCss = `#app [role="listbox"]{box-sizing:border-box;background:#191919;color:#fff;border:1px solid #3f3f3f}#app [role="listbox"] button[role="option"],#app [role="listbox"] [role="option"]{box-sizing:border-box;display:block;min-width:0;min-height:22px;width:100%;margin:0;padding:4px 6px;border:0;border-radius:0;background:transparent;color:#fff;font:inherit;text-align:left;cursor:pointer}#app [role="listbox"] button[role="option"][aria-selected="true"],#app [role="listbox"] [role="option"][aria-selected="true"]{background:#304b52;color:#fff}#app [role="listbox"] button[role="option"]:hover:not(:disabled),#app [role="listbox"] [role="option"]:hover:not(:disabled){background:#575757}#app [role="listbox"] button[role="option"]:focus-visible,#app [role="listbox"] [role="option"]:focus-visible{outline:1px solid #66c7d5;outline-offset:-1px}#app [role="listbox"] button[role="option"]:disabled,#app [role="listbox"] [role="option"][aria-disabled="true"]{background:transparent;color:#858585;cursor:default;opacity:1}`; +const sketcherStatefulCss = `#app .sketcher-stateful-label{display:block;margin:6px 0;font-weight:400}#app .sketcher-stateful-label.fully-constrained{color:#8cff5b;font-weight:700}#app .sketcher-stateful-label.solver-failed{color:#ff9090;font-weight:700}`; +const notificationLabelParityCss = `#app [role=alert]{box-sizing:border-box;display:block;min-width:0;padding:4px 6px;background:#191919;color:#ff9090;border:1px solid #3f3f3f;border-radius:3px;overflow-wrap:anywhere}`; +const validationStateParityCss = `#app input[aria-invalid=true],#app select[aria-invalid=true],#app textarea[aria-invalid=true]{border:1px solid #d93025!important;border-image:none!important}#app input[aria-invalid=true]:focus,#app select[aria-invalid=true]:focus,#app textarea[aria-invalid=true]:focus{border-color:#ff3b30!important;outline:none}`; +const urlLabelParityCss = `#app a[href]{color:#0095ff;text-decoration:underline;text-underline-offset:2px}#app a[href]:hover,#app a[href]:focus-visible{color:#66c7d5}#app a[href]:focus-visible{outline:1px solid #66c7d5;outline-offset:2px}`; + +function commandPayload(module: string, command: string | null): string { + const payload = command ? PAYLOADS[`${module}:${command}`] : undefined; + return JSON.stringify(payload ?? {}, null, 2); +} + +function KeyboardShortcutEditor({ busy, run, initial }: { busy: boolean; run: (event?: unknown, args?: Record) => void; initial?: Record }) { + const [category, setCategory] = useState(""); + const [search, setSearch] = useState(""); + const [command, setCommand] = useState(""); + const [shortcut, setShortcut] = useState(""); + const [timeout, setTimeoutValue] = useState(""); + const result = initial?.commands ?? initial?.categories; + return
+ Keyboard shortcuts + + + + {Array.isArray(result) &&
    {result.map((item, index) =>
  • {typeof item === "string" ? item : JSON.stringify(item)}
  • )}
} + + + + + + + + + +
; +} + +function App() { + const router = useMemo(() => new WebModuleRouter(), []); + const showClippingRequest = useRef | null>(null); + const navigationContext = useMemo(() => readNavigationContext(), []); + const initialModule = WEB_MODULE_REGISTRY.some((item) => item.module === navigationContext.module) ? navigationContext.module! : "Part"; + const [module, setModule] = useState(initialModule); + const workbenchSwitch = useRef<{ cancelled: boolean } | null>(null); + const [switchingWorkbenches, setSwitchingWorkbenches] = useState(false); + const switchDialog = useRef(null); + useEffect(() => { + if (switchingWorkbenches) switchDialog.current?.showModal(); + else switchDialog.current?.close(); + }, [switchingWorkbenches]); + useEffect(() => () => { if (workbenchSwitch.current) workbenchSwitch.current.cancelled = true; }, []); + const [query, setQuery] = useState(""); + const [WebViewTask, setWebViewTask] = useState(); + useEffect(() => { + void import("./web-view-task.js").then(module => setWebViewTask(() => module.WebViewTask)); + }, []); + const [command, setCommand] = useState(navigationContext.command ?? null); + const [payloadText, setPayloadText] = useState(() => commandPayload(initialModule, navigationContext.command ?? null)); + const [response, setResponse] = useState(null); + const [status, setStatus] = useState("选择模块和命令"); + const [busy, setBusy] = useState(false); + const [draftNativePreview, setDraftNativePreview] = useState<{ paths: number[][][]; points: number[][] } | null>(); + const draftPrimitiveOwner = useRef(""); + const [draftHoverPoint, setDraftHoverPoint] = useState(null); + const [linkChildCommand, setLinkChildCommand] = useState("Std_LinkMake"); + const [robotCreateFiles, setRobotCreateFiles] = useState<{ vrml?: { name: string; data: string }; kinematic?: { name: string; data: string } }>({}); + const [robotModifyRevision, setRobotModifyRevision] = useState(0); + const [sessionClosed, setSessionClosed] = useState(false); + useEffect(() => { + const close = () => { + setSessionClosed(true); + setDocumentSelection({ documentId: "", selection: [] }); + }; + window.addEventListener("freecad-session-closed", close); + return () => window.removeEventListener("freecad-session-closed", close); + }, []); + const [commandRuntime] = useState(() => new WebCommandRuntime(router)); + useEffect(() => { + let chooser: HTMLDialogElement | undefined; + let cancelSelection: (() => void) | undefined; + const receive = (event: Event) => { + const detail = (event as CustomEvent<{ + workbenches: string[]; active: unknown; handled: boolean; + select: (workbench: string | undefined) => void; + }>).detail; + if (!detail || sessionClosed) return; + detail.handled = true; + cancelSelection?.(); + chooser = document.createElement("dialog"); + chooser.setAttribute("aria-label", "Workbench"); + const select = document.createElement("select"); + select.setAttribute("aria-label", "Workbench"); + for (const name of detail.workbenches) { + const option = document.createElement("option"); + option.value = name; option.textContent = name; + option.selected = name === detail.active; + select.append(option); + } + const activate = document.createElement("button"); + activate.textContent = "Activate"; + activate.onclick = () => { + chooser?.remove(); + cancelSelection = undefined; + detail.select(select.value); + }; + const cancel = document.createElement("button"); + cancel.textContent = "Cancel"; + const cancelled = () => { chooser?.remove(); cancelSelection = undefined; detail.select(undefined); }; + cancelSelection = cancelled; + cancel.onclick = cancelled; + chooser.addEventListener("cancel", cancelled); + chooser.append(select, activate, cancel); + document.body.append(chooser); + chooser.showModal(); + }; + window.addEventListener("freecad-native-workbench-picker", receive); + const receiveMacroFolder = (event: Event) => { + const value = (event as CustomEvent).detail; + if (Array.isArray(value?.files)) setMacroFiles(value.files.filter((file: unknown): file is string => typeof file === "string")); + if (typeof value?.directory === "string") setStatus(`Macro folder: ${value.directory}`); + }; + window.addEventListener("freecad-macro-folder", receiveMacroFolder); + return () => { + cancelSelection?.(); + window.removeEventListener("freecad-native-workbench-picker", receive); + window.removeEventListener("freecad-macro-folder", receiveMacroFolder); + }; + }, [sessionClosed]); + const [desktopCommands] = useState(() => new DesktopCommandDispatcher(router)); + useEffect(() => { + const receive = (event: Event) => { + const detail = (event as CustomEvent).detail; + detail.handled = true; + void requestOwnerParameters(router, "PartBox", "workbench-document", { + path: "User parameter:BaseApp/Preferences/View", operation: "read", ...detail.args, + }).then(detail.resolve, detail.reject); + }; + window.addEventListener("freecad-inspection-view-preferences", receive); + return () => window.removeEventListener("freecad-inspection-view-preferences", receive); + }, [router]); + + const [sketchInteraction, setSketchInteraction] = useState(null); + const [sketchElementHover, setSketchElementHover] = useState(null); + const [sketchConstraints, setSketchConstraints] = useState(null); + const [sketchView, setSketchView] = useState(null); + const [nativeDocuments, setNativeDocuments] = useState>({}); + const sketchCamera = useRef(); + const [documentSelection, setDocumentSelection] = useState<{ documentId: string; selection: Array<{ documentId: string; object: string; subelements?: string[] }> }>({ documentId: navigationContext.documentId ?? "workbench-document", selection: [] }); + const [detailTaskClosed, setDetailTaskClosed] = useState(false); + useEffect(() => { setDetailTaskClosed(false); }, [module, command, documentSelection.documentId]); + useEffect(() => { + if (module !== "TechDraw" || command !== "TechDraw_DetailView" || detailTaskClosed) return; + const onKeyDown = (event: KeyboardEvent) => { + if (event.key !== "Escape" || busy) return; + event.preventDefault(); event.stopPropagation(); setDetailTaskClosed(true); void run("cancel"); + }; + window.addEventListener("keydown", onKeyDown); + return () => window.removeEventListener("keydown", onKeyDown); + }, [module, command, detailTaskClosed, busy]); + useEffect(() => { + if (module !== "Assembly" || command !== "Assembly_ToggleGrounded") return; + const assembly = desktopCommands.getActiveAssembly(documentSelection.documentId); + setPayloadText(JSON.stringify({ documentId: documentSelection.documentId, assembly, + selection: documentSelection.selection }, null, 2)); + }, [module, command, documentSelection.documentId, documentSelection.selection]); + const sketchSessionRef = useRef(null); + const sketchWorkbenchHost = useRef({ module, documentId: "", mounted: true }); + sketchWorkbenchHost.current.module = module; + sketchWorkbenchHost.current.documentId = documentSelection.documentId; + const [sketchSession, setSketchSession] = useState(null); + const closeSketchSession = () => sketchSessionRef.current?.close().catch(error => { + setStatus(error instanceof Error ? error.message : String(error)); + }); + useEffect(() => { + const session = sketchSessionRef.current; + if (session && (module !== session.workbench || session.documentId !== documentSelection.documentId)) + void session.close(false).catch(error => setStatus(String(error))); + }, [module, documentSelection.documentId, sketchSession]); + useEffect(() => { + sketchWorkbenchHost.current.mounted = true; + const escape = (event: KeyboardEvent) => { + if (event.key === "Escape" && sketchSessionRef.current && !sketchSessionRef.current.closing) { + event.preventDefault(); event.stopPropagation(); void closeSketchSession(); + } + }; + window.addEventListener("keydown", escape, true); + return () => { + sketchWorkbenchHost.current.mounted = false; + window.removeEventListener("keydown", escape, true); + void sketchSessionRef.current?.close(false).catch(error => console.error(error)); + }; + }, []); + const executeSketchCommand = async (record: Parameters[0], + args: Record, documentId: string) => { + if (record.command === "Sketcher_EditSketch") { + await sketchSessionRef.current?.close(); + const selection = args.selection as Array<{ documentId: string; object: string; subElement?: string }>; + if (!Array.isArray(selection) || selection.length !== 1) throw new Error("Select one sketch to edit"); + const session: SketcherEditSession = new SketcherEditSession(documentId, selection.map(item => ({ ...item })), record, + desktopCommands, router, () => { + if (sketchSessionRef.current !== session) return; + sketchSessionRef.current = null; + if (!sketchWorkbenchHost.current.mounted) return; + setSketchSession(null); setSketchInteraction(null); setSketchConstraints(null); setSketchView(null); + setDocumentSelection(current => current.documentId === session.documentId + ? { ...current, selection: session.selection } : current); + }, { + current: () => sketchWorkbenchHost.current.module, + isCurrent: () => sketchWorkbenchHost.current.mounted + && sketchSessionRef.current === session + && sketchWorkbenchHost.current.documentId === session.documentId, + activate: next => activateModule(next), + }); + sketchSessionRef.current = session; setDocumentSelection(current => ({ ...current, documentId })); setSketchSession(session); + } + const session = sketchSessionRef.current; + if (session && !session.closing && session.documentId === documentId) + return session.execute(record, args); + return desktopCommands.execute(record, args, documentId); + }; + + const [techDrawPage, setTechDrawPage] = useState(""); + const [balloonPlacement, setBalloonPlacement] = useState(null); + const [balloonPagePoint, setBalloonPagePoint] = useState(null); + const [centerLineTaskActive, setCenterLineTaskActive] = useState(false); + const [hatchTaskActive, setHatchTaskActive] = useState(false); + const [weldTaskActive, setWeldTaskActive] = useState(false); + const [balloonTaskActive, setBalloonTaskActive] = useState(false); + const [techDrawClip, setTechDrawClip] = useState(null); + const [sectionCutOpen, setSectionCutOpen] = useState(false); + const [sliceFilesOpen, setSliceFilesOpen] = useState(false); + useEffect(() => { + if (module === "Part" && command === "Part_SectionCut") setSectionCutOpen(true); + }, [module, command]); + const [macroFiles, setMacroFiles] = useState([]); + const [macroRecording, setMacroRecording] = useState(false); + useEffect(() => { + const receive = (event: Event) => { + const value = (event as CustomEvent).detail; + if (typeof value?.recording === "boolean") setMacroRecording(value.recording); + if (Array.isArray(value?.files)) setMacroFiles(value.files.filter((file: unknown): file is string => typeof file === "string")); + if (typeof value?.source === "string" && typeof value?.filename === "string") { + setPayloadText(previous => { + try { + const payload = JSON.parse(previous); + if (!payload || typeof payload !== "object" || Array.isArray(payload)) return previous; + return JSON.stringify({ ...payload, filename: value.filename, source: value.source }, null, 2); + } catch { return previous; } + }); + } + }; + window.addEventListener("freecad-macro-result", receive); + return () => window.removeEventListener("freecad-macro-result", receive); + }, []); + const [bimBottomPanels, setBimBottomPanels] = useState([ + { name: "Report view", visible: true }, { name: "Selection view", visible: true }, + ]); + const [startWorkspaceMounted, setStartWorkspaceMounted] = useState(() => new URLSearchParams(window.location.search).has("start")); + const [startWorkspaceVisible, setStartWorkspaceVisible] = useState(() => new URLSearchParams(window.location.search).has("start")); + const startWorkspaceFrame = useRef(null); + useEffect(() => { + const forwardSheetOutput = (event: Event) => { + const frame = startWorkspaceFrame.current; + if (!frame || !startWorkspaceVisible || !frame.contentWindow) return; + // The mounted same-origin project view owns the active retained sheet. + // Share the request object so identity/lifetime checks stay with that view. + frame.contentWindow.dispatchEvent(new CustomEvent("freecad-sheet-print-capture", { detail: (event as CustomEvent).detail })); + }; + window.addEventListener("freecad-sheet-print-capture", forwardSheetOutput); + return () => window.removeEventListener("freecad-sheet-print-capture", forwardSheetOutput); + }, [startWorkspaceVisible]); + + const projectWorkspaceReady = useRef(false); + const pendingProjectNativeSelection = useRef<{ documentId: string; object?: string } | null>(null); + const spreadsheetOwners = useRef(new Map()); + const projectDocumentOwners = useRef(router.modelingDocumentOwners); + const sheetWorkspaceRequest = useRef<{ requestId: string; send(): void; reject(error: Error): void } | null>(null); + useEffect(() => { + const unsubscribeOwners = router.onRequestCompleted((module, command, payload, documentId, response) => { + if ((command !== "part.document" && command !== "partdesign.document") || response.kind !== "result") return; + const result = response.result as { document?: string; closed?: boolean; objects?: Array<{ name: string; type: string; label?: string }> }; + if (!result.document) return; + setNativeDocuments(previous => { + const tree = previous[result.document!]; + if (!tree || !["DocumentProbe", "PartDesign"].includes(tree.owner)) return previous; + if (result.closed) { const next = { ...previous }; delete next[result.document!]; return next; } + if (!result.objects) return previous; + return { ...previous, [result.document!]: { ...tree, objects: result.objects.map(object => ({ ...object, typeId: object.type })) } }; + }); + if (result.closed) { + for (const [key, owner] of projectDocumentOwners.current) if (owner.document === result.document) projectDocumentOwners.current.delete(key); + } else { + const owner = { document: result.document, module: command === "partdesign.document" ? "PartDesign" as const : "Part" as const }; + projectDocumentOwners.current.set(documentId, owner); projectDocumentOwners.current.set(result.document, owner); + } + }); + const ready = (event: MessageEvent) => { + if (event.origin === location.origin && event.source === startWorkspaceFrame.current?.contentWindow + && event.data?.type === "freecad-project-ready") { + projectWorkspaceReady.current = true; sheetWorkspaceRequest.current?.send(); + const pendingSelection = pendingProjectNativeSelection.current; + if (pendingSelection && startWorkspaceFrame.current?.contentWindow) { + pendingProjectNativeSelection.current = null; + startWorkspaceFrame.current.contentWindow.postMessage({ type: "freecad-project-select-native-object", ...pendingSelection }, location.origin); + } + if (showClippingRequest.current) { + startWorkspaceFrame.current?.contentWindow?.postMessage(showClippingRequest.current, location.origin); + showClippingRequest.current = null; + } + } + }; + const forward = (event: MessageEvent) => { + if (event.origin !== location.origin || event.source !== startWorkspaceFrame.current?.contentWindow + || event.data?.type !== "freecad-project-native-request") return; + const { requestId, document: nativeDocument, action, details } = event.data; + const retainedOwner = projectDocumentOwners.current.get(nativeDocument); + const owner = spreadsheetOwners.current.get(nativeDocument) ?? retainedOwner?.module; + const reply = (result: Record) => event.source?.postMessage({ + type: "freecad-project-native-response", requestId, ...result, + }, { targetOrigin: location.origin }); + if (!owner) { + reply({ error: `The native document owner for ${nativeDocument} is unavailable. Reopen the document from its workbench.` }); + return; + } + const ownerDocument = retainedOwner?.document ?? nativeDocument; + const command = owner === "PartDesign" ? "partdesign.document" : "part.document"; + const payload = { ...details, document: ownerDocument, action, module: owner, + schema: owner === "PartDesign" ? "freecad-web-partdesign/document/v1" : "freecad-web-part/document/v1" }; + void router.request(owner, command, payload, ownerDocument).then(response => { + if (response.kind === "result" && (response.result as { closed?: boolean }).closed) { + spreadsheetOwners.current.delete(nativeDocument); + spreadsheetOwners.current.delete(ownerDocument); + } + reply({ response }); + }).catch(error => { + reply({ error: String(error) }); + }); + }; + window.addEventListener("message", ready); + window.addEventListener("message", forward); + desktopCommands.setSpreadsheetHost((documentId, args) => new Promise((resolve, reject) => { + if (sheetWorkspaceRequest.current) { reject(new Error("A sheet command is already pending")); return; } + const requestId = crypto.randomUUID(); + const knownOwner = projectDocumentOwners.current.get(documentId); + const owner = args.command === "Test_InsertFeature" ? knownOwner?.module : args.runtimeOwner === "DocumentProbe" ? "Part" : args.runtimeOwner === "PartDesign" ? "PartDesign" : knownOwner?.module; + if (args.command === "Test_InsertFeature" && !knownOwner) { reject(new Error("The selected document owner is closed or unsupported")); return; } + const nativeDocument = knownOwner?.document ?? documentId; + if (owner) spreadsheetOwners.current.set(nativeDocument, owner); + const receive = (event: MessageEvent) => { + if (event.origin !== location.origin || event.source !== startWorkspaceFrame.current?.contentWindow + || event.data?.type !== "freecad-sheet-created" || event.data.requestId !== requestId) return; + window.removeEventListener("message", receive); sheetWorkspaceRequest.current = null; + if (event.data.error) reject(new Error(event.data.error)); + else resolve(spreadsheetSuccess(requestId, event.data.result)); + }; + let sent = false; + sheetWorkspaceRequest.current = { requestId, reject, send() { + if (sent || !projectWorkspaceReady.current || !startWorkspaceFrame.current?.contentWindow) return; + sent = true; + startWorkspaceFrame.current.contentWindow.postMessage({ type: "freecad-create-sheet", requestId, documentId: nativeDocument, owner, command: args.command, object: args.object ?? args.sheet, ranges: args.ranges ?? (args.range ? [args.range] : undefined), cancelled: args.cancelled, materialAssignment: args.materialAssignment, cellProperties: args.cellProperties ?? (typeof args.alias === "string" ? { alias: args.alias } : undefined) }, location.origin); + } }; + window.addEventListener("message", receive); + setStartWorkspaceMounted(true); setStartWorkspaceVisible(true); + sheetWorkspaceRequest.current.send(); + })); + return () => { unsubscribeOwners(); window.removeEventListener("message", ready); window.removeEventListener("message", forward); desktopCommands.setSpreadsheetHost(); sheetWorkspaceRequest.current?.reject(new Error("Workspace closed")); }; + }, [desktopCommands]); + const [standardCommandView, setStandardCommandView] = useState<{ + command: string; documentId: string; runtimeOwner?: "PartBox" | "DocumentProbe" | "Fem" | "Assembly"; object?: string; text?: string; + title?: string; details?: Record; url?: string; + path?: string; groups?: string[]; parameters?: Array<[string, string, unknown]>; + } | null>(null); + const [consoleResponse, setConsoleResponse] = useState(null); + const [consoleActivation, setConsoleActivation] = useState(0); + const [consoleMounted, setConsoleMounted] = useState(false); + const consoleIdentity = useRef({ router, documentId: documentSelection.documentId, module, + owner: Object.values(nativeDocuments).find(tree => tree.document === documentSelection.documentId)?.owner ?? ("PartBox" as const) }); + consoleIdentity.current = { router, documentId: documentSelection.documentId, module, + owner: Object.values(nativeDocuments).find(tree => tree.document === documentSelection.documentId)?.owner ?? ("PartBox" as const) }; + useEffect(() => { + const activate = (event: Event) => { + const detail = (event as CustomEvent<{ router: typeof router; documentId: string; + runtimeOwner: string; response: FacadeResponse; handled: boolean }>).detail; + const identity = consoleIdentity.current; + if (!detail || detail.router !== identity.router || detail.documentId !== identity.documentId + || detail.runtimeOwner !== identity.owner || !["Web", "Std"].includes(identity.module)) return; + detail.handled = true; + setConsoleMounted(true); + setConsoleResponse(detail.response); + setSelectedMatrixId(null); + setCommand("Std_CommandLine"); + setConsoleActivation(value => value + 1); + }; + window.addEventListener("freecad-python-console-activate", activate); + return () => window.removeEventListener("freecad-python-console-activate", activate); + }, []); + useEffect(() => { + if ((module === "Web" || module === "Std") && command?.replace(/^(Web|Std):desktop:/, "") === "Std_CommandLine") + setConsoleMounted(true); + }, [module, command]); + useEffect(() => { + if (response?.kind !== "result") return; + const batch = response.result as { owner?: string; documentId?: string; records?: Array<{ name?: string }> }; + if (batch.owner === consoleIdentity.current.owner && batch.documentId === documentSelection.documentId + && batch.records?.some(record => record.name === "Std_CommandLine")) setConsoleResponse(response); + }, [response, documentSelection.documentId]); + const [parameterName, setParameterName] = useState(""); + const [parameterType, setParameterType] = useState("String"); + const [parameterValue, setParameterValue] = useState(""); + const [macroName, setMacroName] = useState(""); + const [macroMenu, setMacroMenu] = useState(""); + const [macroTooltip, setMacroTooltip] = useState(""); + const [macroShortcut, setMacroShortcut] = useState(""); + const [macroIcon, setMacroIcon] = useState(""); + const [testMenus, setTestMenus] = useState>({}); + useEffect(() => { + const onMenus = (event: Event) => setTestMenus((event as CustomEvent>).detail); + window.addEventListener("freecad-test-menus", onMenus); + return () => window.removeEventListener("freecad-test-menus", onMenus); + }, []); + useEffect(() => { + const onStdCommand = (event: Event) => { + const detail = (event as CustomEvent<{ command?: string; action?: string }>).detail ?? {}; + if (detail.command) setStatus(`${detail.command}${detail.action ? `: ${detail.action}` : ""}`); + }; + window.addEventListener("freecad-std-command", onStdCommand); + return () => window.removeEventListener("freecad-std-command", onStdCommand); + }, []); + const [BimPanelStructureTask, setBimPanelStructureTask] = useState(); + useEffect(() => { + void import("./bim-panel-structure-task.js").then(module => setBimPanelStructureTask(() => module.BimPanelStructureTask)); + }, []); + const [DraftStretchControls, setDraftStretchControls] = useState(); + useEffect(() => { + void import("./draft-stretch-controls.js").then(module => setDraftStretchControls(() => module.DraftStretchControls)); + }, []); + const [BimAxisMaterialTask, setBimAxisMaterialTask] = useState(); + useEffect(() => { + void import("./bim-axis-material-task.js").then(module => setBimAxisMaterialTask(() => module.BimAxisMaterialTask)); + }, []); + const [BimPanelIfcTask, setBimPanelIfcTask] = useState(); + useEffect(() => { + void import("./bim-panel-ifc-task.js").then(module => setBimPanelIfcTask(() => module.BimPanelIfcTask)); + }, []); + const [TestSuiteChooser, setTestSuiteChooser] = useState< typeof import("./test-desktop-output.js").TestSuiteChooser>(); + useEffect(() => { + void import("./test-desktop-output.js").then(module => setTestSuiteChooser(() => module.TestSuiteChooser)); + }, []); + const [templatePyModState, setTemplatePyModState] = useState(); + const [renderAreaState, setRenderAreaState] = useState(); + useEffect(() => { setRenderAreaState(undefined); }, [module, command]); + const [pythonQtActive, setPythonQtActive] = useState(false); + const pythonQtRoute = useRef({ module, command }); + pythonQtRoute.current = { module, command }; + useEffect(() => { setPythonQtActive(false); }, [module, command]); + useEffect(() => { + if (!pythonQtActive) return; + const priorTitle = document.title; + document.title = "FreeCAD -- PythonQt"; + return () => { document.title = priorTitle; }; + }, [pythonQtActive]); + const [techDrawCreated, setTechDrawCreated] = useState(); + const [draftGroups, setDraftGroups] = useState(); + const [bimNudge, setBimNudge] = useState(); + const [bimDocument, setBimDocument] = useState(); + const [sceneDocument, setSceneDocument] = useState(null); + const [draftSnaps, setDraftSnaps] = useState(); + const [techDrawViews, setTechDrawViews] = useState>([]); + const [techDrawImages, setTechDrawImages] = useState>([]); + const assemblyNavigationOrigin = useRef<{ documentId: string; selection: Array<{ documentId: string; object: string; subelements?: string[] }> } | null>(null); + useEffect(() => { + const restore = (event: Event) => { + const detail = (event as CustomEvent<{ owner?: string; documents?: string[] }>).detail; + const origin = assemblyNavigationOrigin.current; + if (!origin || detail?.owner !== "Assembly" || !detail.documents?.includes(documentSelection.documentId)) return; + setDocumentSelection(origin); + assemblyNavigationOrigin.current = null; + }; + window.addEventListener("freecad-documents-closed", restore); + return () => window.removeEventListener("freecad-documents-closed", restore); + }, [documentSelection.documentId]); + const [graphicsView, setGraphicsView] = useState(); + const [plugins] = useState(() => new PluginRegistry(router)); + // Shared activation owner for the module buttons and the desktop workbench command. + // Do not reset workers: they own the current documents and editing history. + const activateModule = (next: string) => { + if (next !== "None" && !plugins.enable(next).enabled) throw new Error(`Workbench unavailable: ${next}`); + sketchWorkbenchHost.current.module = next; + setModule(next); + setCommand(null); + setPayloadText(commandPayload(next, null)); + setSelectedMatrixId(null); + }; + const startActivationPending = useRef(false); + useEffect(() => { + const receive = (event: MessageEvent) => { + if (event.origin !== location.origin || event.source !== startWorkspaceFrame.current?.contentWindow) return; + if (event.data?.type === "freecad-start-launch-complete") { + if (event.data.closeStart === true) setStartWorkspaceVisible(false); + return; + } + if (event.data?.type !== "freecad-start-activate-workbench") return; + const { requestId, document: documentId, module: next } = event.data; + const reply = (error?: string) => event.source?.postMessage({ + type: "freecad-start-workbench-activated", requestId, error, + }, { targetOrigin: location.origin }); + if (startActivationPending.current) { reply("A workbench activation is already pending"); return; } + startActivationPending.current = true; + void (async () => { + if (sessionClosed || busy || workbenchSwitch.current || sketchSessionRef.current + || document.querySelector("dialog[open]")) throw new Error("Finish the active task before switching workbenches"); + if (typeof next !== "string" || !next) throw new Error("Select a workbench"); + const owner = projectDocumentOwners.current.get(documentId); + if (!owner) throw new Error("The document is not retained by this workbench host"); + const response = await router.request(owner.module, + owner.module === "PartDesign" ? "partdesign.document" : "part.document", { + schema: owner.module === "PartDesign" ? "freecad-web-partdesign/document/v1" : "freecad-web-part/document/v1", + module: owner.module, document: owner.document, action: "snapshot", includeMesh: false, + }, owner.document); + if (response.kind === "error") throw new Error(response.error.message); + const snapshot = response.result as { document: string; objects?: Array<{ name: string; type: string; label?: string }> }; + if (snapshot.document !== owner.document) throw new Error("The workbench returned a different document"); + activateModule(next); + setNativeDocuments(previous => ({ ...previous, [owner.document]: { + document: owner.document, owner: owner.module === "PartDesign" ? "PartDesign" : "DocumentProbe", + objects: (snapshot.objects ?? []).map(object => ({ ...object, typeId: object.type })), + } })); + setDocumentSelection(previous => previous.documentId === owner.document + ? previous : { documentId: owner.document, selection: [] }); + reply(); + })().catch(error => reply(String(error))).finally(() => { startActivationPending.current = false; }); + }; + window.addEventListener("message", receive); + return () => window.removeEventListener("message", receive); + }, [busy, sessionClosed, plugins, router]); + const testWorkbenchHost: TestWorkbenchHost = { + prepare() { + if (workbenchSwitch.current || busy) throw new Error("Workbench is busy"); + if (sessionClosed || sketchInteraction?.editMode || sectionCutOpen || sliceFilesOpen + || startWorkspaceVisible || document.querySelector("dialog[open]")) + throw new Error("Finish the active task before switching workbenches"); + const run = { cancelled: false }; + workbenchSwitch.current = run; + setSwitchingWorkbenches(true); + const cancel = () => { run.cancelled = true; }; + window.addEventListener("freecad-test-workbench-cancel", cancel); + window.addEventListener("pagehide", cancel); + return { + get cancelled() { return run.cancelled; }, + async activate(workbench: string) { + const next = ({ MeshWorkbench: "Mesh", NoneWorkbench: "None", PartWorkbench: "Part", TestWorkbench: "Test" } as Record)[workbench]; + if (!next) throw new Error(`Unknown workbench: ${workbench}`); + // Commit the real mounted owner first, then yield for GUI painting and cancellation. + flushSync(() => { + activateModule(next); + if (next === "Test") { setCommand(command); setPayloadText(payloadText); setSelectedMatrixId(selectedMatrixId); } + }); + await new Promise(resolve => setTimeout(resolve, 32)); + }, + dispose() { + window.removeEventListener("freecad-test-workbench-cancel", cancel); + window.removeEventListener("pagehide", cancel); + workbenchSwitch.current = null; + setSwitchingWorkbenches(false); + updateNavigationContext({ documentId: documentSelection.documentId, module: "Test", command: command ?? undefined }); + }, + }; + }, + }; + const [sandboxMeshOwner, setSandboxMeshOwner] = useState<"DocumentProbe" | "Sandbox">("DocumentProbe"); + const [taskPanelGeneration, setTaskPanelGeneration] = useState(0); + const [apiId, setApiId] = useState("py:Measure:method:Measurement.volume"); + const [matrixSummary, setMatrixSummary] = useState<{ records: number; nativeHandlers: number; restricted: number } | null>(null); + const [matrix, setMatrix] = useState(null); + const [selectedMatrixId, setSelectedMatrixId] = useState(initialModule === "Part" + && ["Part_Slice", "Part_SliceApart"].includes(navigationContext.command ?? "") ? `Part:desktop:${navigationContext.command}` : null); + const [stage, setStage] = useState("ready"); + useEffect(() => { + if (!workbenchSwitch.current) updateNavigationContext({ documentId: documentSelection.documentId, module, command: command ?? undefined }); + }, [documentSelection.documentId, module, command]); + useEffect(() => () => { plugins.dispose(); router.dispose(); }, [plugins, router]); + useEffect(() => { + const params = new URLSearchParams(window.location.search); + const manifestUrl = params.get("moduleManifest"); + if (!manifestUrl) return; + let cancelled = false; + const preload = (params.get("preload") ?? "").split(",").map((item) => item.trim()).filter(Boolean); + setStatus("正在加载模块 manifest..."); + void router.loadManifest(manifestUrl).then(async (modules) => { + const selected = preload.filter((moduleName) => modules.includes(moduleName)); + await Promise.all(selected.map((moduleName) => router.preload(moduleName))); + if (!cancelled) setStatus(selected.length ? `模块 manifest 已加载,已预热 ${selected.join(", ")}` : `模块 manifest 已加载:${modules.length} 个模块按需待命`); + }).catch((error: unknown) => { + if (!cancelled) setStatus(error instanceof Error ? error.message : String(error)); + }); + return () => { cancelled = true; }; + }, [router]); + useEffect(() => { + let cancelled = false; + void fetch("/api/workbench-command-matrix.json").then(async (response) => { + if (!response.ok) throw new Error(`Workbench command matrix failed: HTTP ${response.status}`); + const loaded = await response.json() as WorkbenchCommandMatrix; + if (!cancelled) setMatrix(loaded); + }).catch(() => undefined); + return () => { cancelled = true; }; + }, []); + const route = WEB_MODULE_REGISTRY.find((item) => item.module === module) ?? { commands: [], primaryWorker: null }; + const modules = WEB_MODULE_REGISTRY.filter((item) => item.module.toLowerCase().includes(query.toLowerCase())); + const commands = route.commands; + const commandDescriptors = listWebCommands(query).filter((item) => item.module === module); + const allMatrixRecords = matrix?.records ?? []; + const moduleMatrixRecords = matrix?.records.filter((item) => item.module === module) ?? []; + const selectedMatrixRecord = moduleMatrixRecords.find((item) => item.id === selectedMatrixId) + ?? moduleMatrixRecords.find(item => item.command === command) ?? moduleMatrixRecords[0] ?? null; + const moduleMatrixSummary = matrix?.modules.find((item) => item.module === module) ?? null; + useEffect(() => { + if (module !== "Draft") return; + const snapCommand = command?.startsWith("Draft_Snap_") ? command : "Draft_ShowSnapBar"; + let cancelled = false; + setDraftSnaps(undefined); + void executeDraftDesktop(router, { + id: `Draft:desktop:${snapCommand}`, command: snapCommand, + sourcePath: "freecad-source/src/Mod/Draft/draftguitools/gui_snaps.py", + }, { action: "read" }, documentSelection.documentId)?.then(result => { + if (cancelled) return; + const state = draftSnapState(result); + if (state) setDraftSnaps(state); + else setStatus(result.kind === "error" ? result.error.message : "Draft snap state is missing"); + }).catch((error: unknown) => { + if (!cancelled) setStatus(error instanceof Error ? error.message : String(error)); + }); + return () => { cancelled = true; }; + }, [module, command, router, documentSelection.documentId]); + const setDraftSnap = async (mode: typeof DRAFT_SNAP_MODES[number], checked?: boolean, + args: Record = {}) => { + setBusy(true); + try { + const snapCommand = `Draft_Snap_${mode}`; + const result = await executeDraftDesktop(router, { + id: `Draft:desktop:${snapCommand}`, command: snapCommand, + sourcePath: "freecad-source/src/Mod/Draft/draftguitools/gui_snaps.py", + }, checked === undefined ? { ...args, action: "read" } : { ...args, status: checked }, documentSelection.documentId); + if (!result) throw new Error("Draft snap command is unavailable"); + setResponse(result); + const state = draftSnapState(result); + if (state) setDraftSnaps(state); + setStatus(result.kind === "error" ? result.error.message + : checked === undefined ? "Draft snap preferences loaded" : "Draft snap preferences updated"); + } catch (error) { + setStatus(error instanceof Error ? error.message : String(error)); + } finally { setBusy(false); } + }; + useEffect(() => { + window.__freecadWorkbenchState = { stage, status, response, matrix: matrixSummary, selected: selectedMatrixRecord }; + }, [matrixSummary, response, selectedMatrixRecord, stage, status]); + const editSketchInteraction = async (name: string, args: Record = {}) => { + if (name === "Sketcher_LeaveSketch") { await closeSketchSession(); return; } + if (["Sketcher_SetGeometryLayer", "Sketcher_DeleteElements", "Sketcher_ConvertToGeometries"].includes(name)) { + const operation = name === "Sketcher_SetGeometryLayer" ? "setGeometryLayer" + : name === "Sketcher_DeleteElements" ? "deleteElements" : "convertToGeometries"; + name = "Sketcher_RenderingOrder"; + args = { ...args, operation }; + } + if (busy || !sketchInteraction || sketchSessionRef.current?.closing) return; + const record = moduleMatrixRecords.find(item => item.kind === "desktop-gui" && item.command === name); + if (!record) { setStatus(`Sketch command unavailable: ${name}`); return; } + setBusy(true); + try { + const documentId = sketchInteraction.documentHandle; + const session = sketchSessionRef.current; + const result = await executeSketchCommand(record, { ...args, documentId }, documentId); + if (session?.closing || session !== sketchSessionRef.current) return; + setResponse(result); + if (name === "Sketcher_SelectElementsAssociatedWithConstraints" && result.kind === "result") { + const native = (result.result as { records?: Array<{ result?: { selection?: Array<{ subElement: string }> } }> }) + .records?.find(entry => entry.result?.selection)?.result; + if (native?.selection) setDocumentSelection({ documentId, selection: [{ documentId, + object: sketchInteraction.objectHandle, subelements: native.selection.map(item => item.subElement) }] }); + } + const state = sketcherInteractionState(result); + const validation = name === "Sketcher_ValidateSketch" ? (result.kind === "result" ? (result.result as any)?.records?.find((r: any) => r.status === "exposed" && r.result?.validation)?.result : undefined) : undefined; + if (state?.interaction.clearSelection) setDocumentSelection(current => ({ ...current, selection: [] })); + if (state?.interaction.selectedSubelements) setDocumentSelection({ documentId, + selection: state.interaction.selectedSubelements.length ? [{ documentId, object: state.objectHandle, + subelements: state.interaction.selectedSubelements }] : [] }); + if (state?.editMode === false) { + setSketchInteraction(null); setSketchConstraints(null); setSketchView(null); + } else if (state) setSketchInteraction(state); + if (state?.interaction.committed && sketchConstraints) { + const constraintRecord = moduleMatrixRecords.find(item => item.kind === "desktop-gui" && item.command === "Sketcher_SwitchVirtualSpace"); + if (constraintRecord) { + const refreshed = await executeSketchCommand(constraintRecord, { action: "read", selection: [], documentId }, documentId); + if (session?.closing || session !== sketchSessionRef.current) return; + setSketchConstraints(sketcherConstraintState(refreshed) ?? null); + } + } + const constraints = sketcherConstraintState(result); + if (constraints) { + setSketchConstraints(constraints); + if (constraints.constraintTools.clearSelection) setDocumentSelection(current => ({ ...current, selection: [] })); + setSketchInteraction(current => current && current.documentHandle === constraints.documentHandle + ? { ...current, geometryCount: constraints.geometryCount, constraintCount: constraints.constraintCount, + interaction: { ...current.interaction, edges: constraints.constraintTools.edges } } : current); + if (constraints.constraintTools.changed.length) { + const snapRecord = moduleMatrixRecords.find(item => item.kind === "desktop-gui" && item.command === "Sketcher_Snap"); + if (snapRecord) { + const refreshed = await executeSketchCommand(snapRecord, { action: "read", selection: [], documentId }, documentId); + if (session?.closing || session !== sketchSessionRef.current) return; + setSketchInteraction(sketcherInteractionState(refreshed) ?? null); + } + } + } + setStatus(result.kind === "error" ? result.error.message : state?.interaction.warning || `${name} complete`); + } catch (error) { setStatus(error instanceof Error ? error.message : String(error)); } + finally { setBusy(false); } + }; + const saveSketchDocument = async () => { + if (busy || !sketchInteraction) return; + setBusy(true); + try { + const documentId = sketchInteraction.documentHandle; + const objectName = sketchInteraction.objectHandle; + if (sketchSessionRef.current) await closeSketchSession(); + const result = await router.request("Sketcher", "sketcher.saveReopen", { + ...SKETCHER_PERSISTENCE_FIXTURE, documentId, objectName, + }, documentId); + setResponse(result); + if (result.kind !== "result") throw new Error(result.kind === "error" ? result.error.message : "Sketch save cancelled"); + const saved = result.result as SketcherPersistenceResult; + const bytes = Uint8Array.from(atob(saved.fileData), c => c.charCodeAt(0)); + await writeDocumentFile(`${documentId}.FCStd`, bytes.buffer); + setSketchInteraction(saved.after as unknown as SketcherInteractionState); + setSketchConstraints(null); setSketchView(null); + setStatus(`Saved ${documentId}.FCStd to OPFS and reopened for editing`); + } catch (error) { setStatus(error instanceof Error ? error.message : String(error)); } + finally { setBusy(false); } + }; + useEffect(() => router.onRequestCompleted((owner, operation, _payload, _document, reply) => { + if (owner !== "Points" || reply.kind !== "result" || !["points.createRecompute", "points.saveReopen"].includes(operation)) return; + const native = reply.result as { document?: string; objectName?: string; objects?: Array<{ objectName: string }> }; + if (!native.document) return; + const documentId = native.document; + setDocumentSelection(current => ({ documentId, selection: native.objectName + ? [{ documentId, object: native.objectName }] + : current.selection.filter(item => native.objects?.some(object => object.objectName === item.object)).map(item => ({ ...item, documentId })) })); + }), [router]); + const draftEditSelection = useRef(documentSelection); + draftEditSelection.current = documentSelection; + const [measureTaskEpoch, setMeasureTaskEpoch] = useState(0); + const openGraphicsView = () => { + if (!selectedMatrixRecord || busy) return; + try { + const identity = documentSelection.documentId; + const owner = Object.values(nativeDocuments).find(tree => tree.document === identity)?.owner; + setGraphicsView(bindGraphicsDocument(router, selectedMatrixRecord, identity, owner)); + setResponse(null); setStatus("Opening Graphics scene…"); + } catch (error) { setResponse(createFailure("graphics-scene", "document_required", String(error))); setStatus(String(error)); } + }; + const applyAssemblyNavigation = (result: FacadeResponse) => { + if (result.kind === "result") { + const records = (result.result as { records?: Array<{ status: string; result?: { documentId?: string; document?: string; selection?: Array<{ documentId: string; object: string; subelements?: string[] }>; objects?: Array<{ name: string; label?: string; typeId?: string; type?: string }> ; owner?: NativeDocumentTreeState["owner"]; reopenedDocumentName?: string } }> }).records; + const native = records?.find(item => item.status === "exposed")?.result; + if (native?.documentId && native.documentId !== documentSelection.documentId) { + const origin = { documentId: documentSelection.documentId, selection: documentSelection.selection }; + assemblyNavigationOrigin.current = origin; + const target = native.documentId; + if (native.objects) { + setNativeDocuments(previous => ({ ...previous, [target]: { + document: target, owner: native.owner ?? "Assembly", + objects: native.objects!.map(object => ({ ...object, typeId: object.typeId ?? object.type ?? "" })), + } })); + } + // Let the mounted document host/view owners activate the target tab and renderer. + window.dispatchEvent(new CustomEvent("freecad-document-activate", { detail: { documentId: target, owner: native.owner ?? "Assembly", sourceDocumentId: origin.documentId, reason: "Assembly_LinkSelectLinked" } })); + setDocumentSelection({ documentId: native.documentId, selection: native.selection ?? [] }); + } + } + }; + const assemblyContextBlocked = busy || (module === "Assembly" && !!command && + /Assembly_(ActivateAssembly|Insert|CreateJoint|CreateSimulation|CreateView|CreateBom)/.test(command)); + const activateAssemblyObject = async (documentId: string, object: string, linked?: boolean) => { + if (assemblyContextBlocked) { setStatus("Finish or close the active task first"); return; } + setBusy(true); + try { + const activationRecord: WorkbenchCommandRecord = { + id: "Assembly:desktop:Assembly_ActivateAssembly", module: "Assembly", + command: "Assembly_ActivateAssembly", kind: "desktop-gui", + sourcePath: "src/Mod/Assembly/Gui/ViewProviderAssembly.cpp", + }; + let isAssembly = false; + if (!linked) { + const choices = await desktopCommands.execute(activationRecord, { documentId, action: "read" }, documentId); + if (choices.kind === "error") { setResponse(choices); setStatus(choices.error.message); return; } + const native = (choices.result as { records?: Array<{ result?: { assemblies?: Array<{ name: string }>; links?: string[] } }> }).records?.[0]?.result; + isAssembly = !!native?.assemblies?.some(item => item.name === object); + if (!isAssembly && !native?.links?.includes(object)) { setStatus("This object has no Assembly edit or linked-object entry"); return; } + } + const record = isAssembly ? activationRecord : { ...activationRecord, + id: "Assembly:desktop:Assembly_LinkSelectLinked", command: "Assembly_LinkSelectLinked" }; + const result = await desktopCommands.execute(record, isAssembly + ? { documentId, assembly: object, action: "toggle" } + : { documentId, selection: [{ documentId, object }] }, documentId); + setResponse(result); + if (result.kind === "error") { setStatus(result.error.message); return; } + applyAssemblyNavigation(result); + const native = (result.result as { records?: Array<{ result?: { action?: string; documentId?: string; selection?: Array<{ documentId: string; object: string }> } }> }).records?.[0]?.result; + if (native?.selection) setDocumentSelection({ documentId: native.documentId ?? documentId, selection: native.selection }); + setStatus(isAssembly ? (native?.action === "deactivated" ? "Assembly deactivated" : `Assembly active: ${object}`) : "Linked object selected"); + } catch (error) { setStatus(String(error)); } + finally { setBusy(false); } + }; + const selectedRunCommand = command; + const run = async (action?: "read" | "accept" | "apply" | "cancel" | "preview" | "cameraRefresh" | "undo" | "redo", values?: Record, activationCommand?: string) => { + const command = activationCommand ?? selectedRunCommand; + if (!command || busy) return; + if (module === "Assembly" && command.replace(/^Assembly:desktop:/, "") === "Assembly_ActivateAssembly") { + setStatus("Choose an assembly in the Activate Assembly task"); return; + } + if (module === "Sandbox" && command === "Std_TestGraphicsView") { openGraphicsView(); return; } + if (module === "Sandbox" && command === "Std_GrabWidget" && action === "cancel") { + setResponse(null); setStatus("Widget capture cancelled"); return; + } + if (module === "Measure" && command === "Std_MassProperties") { setMeasureTaskEpoch(value => value + 1); setStatus("Choose solids in the Mass properties task"); return; } + if (module === "Measure" && command === "Std_Measure") { setMeasureTaskEpoch(value => value + 1); setStatus("Choose two sources in the Measure distance task"); return; } + if (module === "Part" && command === "Part_SectionCut") setSectionCutOpen(true); + setBusy(true); setStatus(`正在执行 ${module} / ${command}`); setResponse(null); + let payload: unknown; + try { payload = activationCommand ? {} : JSON.parse(payloadText); } + catch (error) { + const result = createFailure(`workbench-${module.toLowerCase()}`, "invalid_request", "命令参数不是有效 JSON", { module, command, error: error instanceof Error ? error.message : String(error) }); + setResponse(result); setStatus(`${result.error.code}: ${result.error.message}`); setBusy(false); return; + } + const snapMode = module === "Draft" ? DRAFT_SNAP_MODES.find(mode => command === `Draft_Snap_${mode}`) : undefined; + if (snapMode && payload && typeof payload === "object" && !Array.isArray(payload)) { + const args = payload as Record; + if (action === "read" || args.action === "read") { + await setDraftSnap(snapMode, undefined, args); + return; + } + if (args.action === undefined && args.status === undefined) { + if (!draftSnaps) { + setStatus("Draft snap state is not loaded"); + setBusy(false); + return; + } + await setDraftSnap(snapMode, !draftSnaps[draftSnapKey(snapMode)], args); + return; + } + } + const desktopRecord = moduleMatrixRecords.find((item) => item.kind === "desktop-gui" && item.command === command + && (activationCommand !== undefined || item.id === selectedMatrixId || selectedMatrixId === null)) + ?? (module === "ReverseEngineering" && ["Mesh_RemeshGmsh", "Mesh_VertexCurvature", "Mesh_CurvatureInfo"].includes(command ?? "") + ? allMatrixRecords.find(item => item.kind === "desktop-gui" && item.module === "Mesh" && item.command === command) : undefined) + ?? ((module === "Web" || module === "Std") && (isStructureCommand(command ?? "") || command === "Std_Group") + ? { id: `${module}:desktop:${command}`, module, command, kind: "desktop-gui", disposition: "exposed", sourcePath: "src/Gui/CommandStructure.cpp", sourceLine: command === "Std_Group" ? 116 : 192 } + : undefined); + if (desktopRecord) { + if (!payload || typeof payload !== "object" || Array.isArray(payload)) { + const result = createFailure(`desktop-${module.toLowerCase()}`, "invalid_request", "桌面命令参数必须是 JSON object", { module, command }); + setResponse(result); setStatus(`${result.error.code}: ${result.error.message}`); setBusy(false); return; + } + const desktopArgs = { ...payload as Record, ...values }; + if (desktopRecord.command === "Sketcher_NewSketch" && desktopArgs.mapMode === "Deactivated") desktopArgs.selection = []; + if (action) desktopArgs.action = action; + const primitiveRequest = desktopRecord.module === "Draft" && draftPrimitiveCommands.includes(desktopRecord.command); + const primitiveOwner = draftPrimitiveOwner.current; + if (primitiveRequest) Object.assign(desktopArgs, primitiveDefaults(desktopArgs, + draftGroups?.documentId === documentSelection.documentId ? draftGroups.workingPlane : undefined)); + if (["MeshPart_Mesher", "MeshPart_TrimByPlane", "MeshPart_CurveOnMesh", "Surface_CurveOnMesh"].includes(desktopRecord.command) && !desktopArgs.runtimeOwner) { + desktopArgs.runtimeOwner = Object.values(nativeDocuments).find(tree => tree.document === documentSelection.documentId)?.owner + ?? (projectDocumentOwners.current.get(documentSelection.documentId)?.module === "Part" ? "DocumentProbe" : undefined); + } + if (desktopRecord.command === "TemplatePyMod_Cmd4" && !values && !action) desktopArgs.action = "read"; + const nativeDocument = desktopRecord.module === "PartDesign" + ? desktopArgs.document ?? desktopArgs.documentHandle + : desktopRecord.module === "Part" ? desktopArgs.document : undefined; + const documentId = typeof nativeDocument === "string" ? nativeDocument + : typeof desktopArgs.documentId === "string" ? desktopArgs.documentId : documentSelection.documentId; + if (desktopRecord.command === "Sketcher_LeaveSketch" && sketchSessionRef.current) { + await closeSketchSession(); setBusy(false); return; + } + try { + const preparedDesktopArgs = desktopRecord.module === "Material" + ? prepareMaterialDesktopArgs(desktopRecord.command, desktopArgs, documentId) + : prepareBimDesktopArgs(desktopRecord, desktopArgs, bimNudge); + if (desktopRecord.module === "BIM" && ["IFC_Save", "IFC_SaveAs"].includes(desktopRecord.command)) { + const { restoreBimIfcSaveArgs } = await import("./bim-desktop-adapter.js"); + Object.assign(preparedDesktopArgs, await restoreBimIfcSaveArgs(documentId, preparedDesktopArgs)); + } + if (desktopRecord.module === "TechDraw" && desktopRecord.command === "TechDraw_ActiveView" + && preparedDesktopArgs.action !== "cancel" && preparedDesktopArgs.action !== "read") { + const { captureTechDrawActiveView } = await import("./techdraw-desktop-adapter.js"); + Object.assign(preparedDesktopArgs, captureTechDrawActiveView(documentId, preparedDesktopArgs)); + } + if (desktopRecord.module === "BIM" && desktopRecord.command === "BIM_Views" + && ["activate", "saveView"].includes(String(preparedDesktopArgs.action))) { + const { captureBimViewCamera } = await import("./bim-desktop-adapter.js"); + preparedDesktopArgs.camera = captureBimViewCamera(documentId); + } + let result = await executeTestDesktopWithHost(desktopRecord, preparedDesktopArgs, documentId, + async args => { + if (desktopRecord.module === "Draft") { + const { executeDraftSelectedTransform } = await import("./draft-desktop-adapter.js"); + const selectedResult = await executeDraftSelectedTransform(desktopRecord.command, { + ...args, selection: preparedDesktopArgs.selection ?? (documentId === documentSelection.documentId ? documentSelection.selection : []), + }, documentId, payload => router.request("Draft", "draft.pythonFamilyBatch", payload, documentId), + (activeDocument, selection) => setDocumentSelection({ documentId: activeDocument, selection })); + if (selectedResult) return selectedResult; + } + if (desktopRecord.module === "Draft") { + const workflowResult = await (await import("./draft-desktop-adapter.js")).executeDraftProjectionSlopeSplit(desktopRecord.command, { + ...args, selection: preparedDesktopArgs.selection ?? (documentId === documentSelection.documentId ? documentSelection.selection : []), + }, documentId, payload => router.request("Draft", "draft.pythonFamilyBatch", payload, documentId), + (activeDocument, selection) => setDocumentSelection({ documentId: activeDocument, selection })); + if (workflowResult) return workflowResult; + } + if (desktopRecord.module === "BIM" && desktopRecord.command === "BIM_TogglePanels") + preparedDesktopArgs.bottomPanels = bimBottomPanels; + if (desktopRecord.module === "Sketcher") { + const { prepareSketcherDesktopArgs } = await import("./sketcher-desktop-adapter.js"); + Object.assign(preparedDesktopArgs, prepareSketcherDesktopArgs(desktopRecord, args, documentId, + documentId === documentSelection.documentId ? documentSelection.selection : [])); + if (["Sketcher_ViewSketch", "Sketcher_ViewSection"].includes(desktopRecord.command) + && sketchView?.documentHandle === documentId && sketchCamera.current) + preparedDesktopArgs.cameraRotation = sketchCamera.current; + if (desktopRecord.command === "Sketcher_ViewSection" && action === "cameraRefresh") + { preparedDesktopArgs.refreshCamera = true; preparedDesktopArgs.cameraRotation = values?.cameraRotation ?? sketchCamera.current; } + } + if (desktopRecord.module === "Sketcher") return executeSketchCommand(desktopRecord, { + ...args, ...preparedDesktopArgs, activeTask: preparedDesktopArgs.activeTask ?? false, + selection: desktopRecord.command === "Sketcher_NewSketch" && preparedDesktopArgs.mapMode === "Deactivated" ? [] : preparedDesktopArgs.selection ?? (documentId === documentSelection.documentId ? documentSelection.selection : []), + }, documentId); + return desktopCommands.execute(desktopRecord, { ...args, + ...(["Material", "BIM", "Sketcher", "TechDraw", "CAM"].includes(desktopRecord.module) ? preparedDesktopArgs : {}), + activeTask: preparedDesktopArgs.activeTask ?? false, + selection: preparedDesktopArgs.selection ?? (documentId === documentSelection.documentId ? documentSelection.selection : []) }, documentId, + (activeDocument, selection) => setDocumentSelection({ documentId: activeDocument, selection })); + }, testWorkbenchHost); + if (desktopRecord.module === "Sketcher" && sketchSessionRef.current?.closing) return; + if (["Reen_SegmentationFromComponents", "Reen_ApproxPlane", "Reen_ApproxCylinder", "Reen_ApproxSphere", "Reen_ApproxPolynomial"].includes(desktopRecord.command) && result.kind === "result") { + const native = (result.result as { records?: Array<{ status: string; result?: SceneDocument }> }).records?.[0]; + if (native?.status === "exposed" && native.result?.objects) { + setSceneDocument(native.result); + setNativeDocuments(previous => ({ ...previous, [documentId]: { + document: documentId, owner: "Inspection", objects: native.result!.objects, + } })); + } + } + if (desktopRecord.module === "Start" && desktopRecord.command === "Start_Start" && result.kind === "result" + && (result.result as { view?: string; active?: boolean }).view === "StartView" + && (result.result as { active?: boolean }).active) { + setStartWorkspaceMounted(true); setStartWorkspaceVisible(true); + startWorkspaceFrame.current?.contentWindow?.postMessage({ type: "freecad-show-start" }, window.location.origin); + startWorkspaceFrame.current?.focus(); + } + if (desktopRecord.module === "Assembly") applyAssemblyNavigation(result); + if (desktopRecord.module === "Web" && result.kind === "result" + && ["Std_LinkSelectActions", "Std_LinkSelectAllLinks", "Std_LinkSelectLinked", "Std_LinkSelectLinkedFinal"].includes(desktopRecord.command)) { + const records = (result.result as { records?: Array<{ result?: { activeDocument?: string; selection?: Array<{ documentId: string; object: string; subelements?: string[] }> } }> }).records; + const native = records?.[0]?.result; + const target = native?.activeDocument; + if (target && target !== documentSelection.documentId) + window.dispatchEvent(new CustomEvent("freecad-document-activate", { detail: { + documentId: target, owner: "PartBox", sourceDocumentId: documentSelection.documentId, + reason: desktopRecord.command, + } })); + if (native?.selection) setDocumentSelection({ documentId: target ?? documentSelection.documentId, selection: native.selection }); + } + if (desktopRecord.module === "Material") { + result = await persistMaterialDesktopResult(result, desktopRecord.command, preparedDesktopArgs); + } + if (desktopRecord.module === "Sketcher") { + const constraints = sketcherConstraintState(result); + if (constraints) { + setSketchConstraints(constraints); + if (constraints.constraintTools.clearSelection) setDocumentSelection(current => ({ ...current, selection: [] })); + setSketchInteraction(current => current && current.documentHandle === constraints.documentHandle + ? { ...current, geometryCount: constraints.geometryCount, constraintCount: constraints.constraintCount, + interaction: { ...current.interaction, edges: constraints.constraintTools.edges } } : current); + } else if (result.kind === "result" && ["Sketcher_EditSketch", "Sketcher_NewSketch", "Sketcher_ReorientSketch"].includes(desktopRecord.command)) { + setSketchConstraints(null); + if (desktopRecord.command === "Sketcher_EditSketch") setDocumentSelection(current => ({ ...current, selection: [] })); + } + const { sketcherCreatedSelection } = await import("./sketcher-desktop-adapter.js"); + const selection = sketcherCreatedSelection(desktopRecord, result, documentId); + if (selection) { + setDocumentSelection({ documentId, selection }); + setPayloadText(JSON.stringify({ ...desktopArgs, documentId, selection }, null, 2)); + } + } + if (desktopRecord.module === "Part" && partDesktopMenu(desktopRecord.command) && result.kind === "result") { + const child = (result.result as { childCommand?: string }).childCommand; + if (child && partDesktopMenu(desktopRecord.command)?.includes(child)) { + setCommand(child); + setSelectedMatrixId(`Part:desktop:${child}`); + setPayloadText(JSON.stringify({ documentId, selection: preparedDesktopArgs.selection ?? documentSelection.selection }, null, 2)); + } + } + if (["Web", "Std"].includes(desktopRecord.module) && result.kind === "result" + && ["Std_About", "Std_AboutQt", "Std_TextDocument", "Std_DevHandbook", "Std_ReportBug", + "Std_FreeCADDonation", "Std_FreeCADForum", "Std_FreeCADUserHub", "Std_FreeCADWebsite", + "Std_DlgParameter", "Std_DlgPreferences", "Std_DlgCustomize"].includes(desktopRecord.command)) { + const batch = result.result as { records?: Array<{ name?: string; status?: string; + result?: { documentId?: string; object?: string; text?: string; title?: string; + details?: Record; url?: string; path?: string; + groups?: string[]; parameters?: Array<[string, string, unknown]> } }> }; + const native = batch.records?.find(item => item.name === desktopRecord.command); + if (native?.status === "success" && native.result) { + const value = native.result; + setStandardCommandView({ ...value, command: desktopRecord.command, + runtimeOwner: preparedDesktopArgs.runtimeOwner === "Assembly" ? "Assembly" : preparedDesktopArgs.runtimeOwner === "Fem" ? "Fem" : preparedDesktopArgs.runtimeOwner === "DocumentProbe" ? "DocumentProbe" : "PartBox", + documentId: value.documentId ?? documentId }); + if (desktopRecord.command === "Std_TextDocument" && typeof value.object === "string" + && typeof value.text === "string") { + setPayloadText(JSON.stringify({ documentId: value.documentId ?? documentId, + operation: "save", object: value.object, text: value.text }, null, 2)); + } + } + } + if (desktopRecord.command === "Test_InsertFeature" && result.kind === "result") { + const snapshot = result.result as { document: string; objects: any[]; owner?: string }; + if (snapshot.document && snapshot.objects) { + const owner = projectDocumentOwners.current.get(documentId)?.module === "PartDesign" ? "PartDesign" : "DocumentProbe"; + setNativeDocuments(previous => ({ ...previous, [snapshot.document]: { document: snapshot.document, owner, objects: snapshot.objects.map(object => ({ ...object, typeId: object.type })) } })); + setDocumentSelection(previous => ({ ...previous, selection: previous.selection.filter(item => + previous.documentId !== documentId || snapshot.objects.some(object => object.name === item.object)) })); + } + } + if (desktopRecord.module === "Mesh" && desktopRecord.command === "Mesh_Import" && result.kind === "result") { + const native = result.result as { document?: string; objects?: Array<{ name?: string; type?: string; typeId?: string; label?: string }> }; + if (typeof native.document === "string" && Array.isArray(native.objects)) { + const objects = native.objects.filter(object => typeof object.name === "string" && typeof (object.typeId ?? object.type) === "string") + .map(object => ({ name: object.name!, label: object.label, typeId: object.typeId ?? object.type! })); + setNativeDocuments(previous => ({ ...previous, [native.document!]: { document: native.document!, owner: "DocumentProbe", objects } })); + const imported = objects.find(object => object.typeId === "Mesh::Feature") ?? objects.at(-1); + if (imported) { + setDocumentSelection({ documentId: native.document, selection: [{ documentId: native.document, object: imported.name }] }); + setPayloadText(JSON.stringify({ ...desktopArgs, documentId: native.document, selection: [{ documentId: native.document, object: imported.name }] }, null, 2)); + } + } + } + if (desktopRecord.module === "Part") { + if (desktopRecord.command === "Part_NewDoc" && result.kind === "result") { + const created = result.result as { document?: string; objects?: unknown[]; objectCount?: number }; + if (typeof created.document === "string" && created.objectCount === 0 && created.objects?.length === 0) + setPayloadText(JSON.stringify({ documentId: created.document }, null, 2)); + } + const tree = partDocumentTreeState(result); + if (tree) { + setNativeDocuments(previous => ({ ...previous, [tree.document]: tree })); + setDocumentSelection({ documentId: tree.document, selection: [] }); + } + } + if (desktopRecord.module === "TemplatePyMod") { + if (desktopRecord.command === "TemplatePyGroup" && result.kind === "result") { + const created = (result.result as { records?: Array<{ name?: string; status?: string; result?: { documentId?: string; activeDocument?: string } }> }).records?.[0]; + const identity = created?.result?.documentId; + if (created?.name === "Std_New" && created.status === "success" && identity && created.result?.activeDocument === identity) { + setNativeDocuments(previous => ({ ...previous, [`PartBox:${identity}`]: { document: identity, owner: "PartBox", objects: [] } })); + setDocumentSelection({ documentId: identity, selection: [] }); + setPayloadText(JSON.stringify({ documentId: identity, runtimeOwner: "PartBox", selection: [] }, null, 2)); + } + } + result = await applyTemplatePyModResult(result, desktopRecord.command, state => { + if (state.renderArea) { + if (pythonQtRoute.current.module === "TemplatePyMod" && pythonQtRoute.current.command === "TemplatePyMod_Cmd5") + setRenderAreaState(previous => previous ?? state); + return; + } + if (state.hostUi) { + if (pythonQtRoute.current.module === "TemplatePyMod" && pythonQtRoute.current.command === "TemplatePyMod_Cmd3") + setPythonQtActive(state.hostUi.active); + return; + } + if (["TemplatePyMod_Cmd1", "TemplatePyGrp_1", "TemplatePyGrp_2", "TemplatePyGrp_3"].includes(state.name)) { + setTemplatePyModState({ name: state.name, status: state.status, consoleOutput: state.consoleOutput, taskState: state.taskState }); + return; + } + setTemplatePyModState(previous => ["TemplatePyMod_Cmd2", "TemplatePyMod_Cmd4"].includes(state.name) ? state : ({ ...previous, ...state })); + if (state.documentId && state.selection && !(state.name === "TemplatePyMod_Cmd6" && state.action === "cancel")) { + setDocumentSelection({ documentId: state.documentId, selection: state.selection }); + const boxDimensions = state.name === "TemplatePyMod_Cmd6" && state.dimensions + ? { length: state.dimensions[0], width: state.dimensions[1], height: state.dimensions[2], objectName: state.documentObject } + : {}; + const { file: _openedFile, ...rest } = desktopArgs; + setPayloadText(JSON.stringify({ ...rest, documentId: state.documentId, selection: state.selection, ...boxDimensions }, null, 2)); + } + }); + } + if (desktopRecord.module === "CAM") { + result = await applyCamDesktopResult(result, (activeDocument, selection) => { + setDocumentSelection({ documentId: activeDocument, selection }); + setPayloadText(JSON.stringify({ ...desktopArgs, documentId: activeDocument, + selection: camTaskSelection(desktopRecord.command, + preparedDesktopArgs.selection ?? (documentId === documentSelection.documentId ? documentSelection.selection : []), + selection) }, null, 2)); + }, preparedDesktopArgs.overwrite === true); + if (["CAM_Array", "CAM_Simulator", "CAM_SimulatorGL", "CAM_DressupAxisMap", "CAM_DressupDogbone", "CAM_DressupArray", "CAM_DressupPathBoundary", "CAM_DressupDragKnife", "CAM_DressupLeadInOut", "CAM_DressupRampEntry", "CAM_DressupTag", "CAM_DressupZCorrect", "CAM_Job", "CAM_Compound", "CAM_Area", "CAM_Area_Workplane"].includes(desktopRecord.command) && result.kind === "result") { + const native = (result.result as { records?: Array<{ status: string; result?: Record }> }) + .records?.find(record => record.status === "exposed")?.result; + if (native && ["CAM_Array", "CAM_Job", "CAM_DressupAxisMap", "CAM_DressupDogbone", "CAM_DressupArray", "CAM_DressupPathBoundary", "CAM_DressupDragKnife", "CAM_DressupLeadInOut", "CAM_DressupRampEntry", "CAM_DressupTag", "CAM_DressupZCorrect"].includes(desktopRecord.command) && Array.isArray(native.objects)) { + const identity = String(native.documentId); + setNativeDocuments(previous => ({ ...previous, [`CAM:${identity}`]: { + document: identity, owner: "CAM", objects: native.objects as NativeDocumentTreeState["objects"], + } })); + } + if (native && desktopRecord.command === "CAM_Area_Workplane") { + setPayloadText(JSON.stringify({ ...desktopArgs, ...native, action: "read", contentBase64: undefined, + files: undefined, saveDocument: false, + selection: native.cancelled || preparedDesktopArgs.action === "reopen" + ? native.selection : preparedDesktopArgs.selection ?? documentSelection.selection }, null, 2)); + } else if (native) setPayloadText(JSON.stringify(native.cancelled + ? { documentId, selection: native.selection ?? documentSelection.selection, overwrite: desktopArgs.overwrite } + : { ...desktopArgs, ...native, action: "read", contentBase64: undefined, files: undefined, + saveDocument: false, selection: native.selection ?? preparedDesktopArgs.selection ?? documentSelection.selection }, null, 2)); + } + } + if (desktopRecord.module === "Draft") { + if (primitiveRequest && primitiveOwner !== draftPrimitiveOwner.current) { setBusy(false); return result; } + const groups = draftGroupState(result); + if (groups) { + setDraftGroups(groups); + if (primitiveRequest && desktopArgs.primitivePreview) setDraftNativePreview(groups.primitivePreview); + await saveDraftDocument(groups); + if (primitiveRequest && primitiveOwner !== draftPrimitiveOwner.current) { setBusy(false); return result; } + if (primitiveRequest && groups.taskStatus === "committed") { + setDraftHoverPoint(null); setDraftNativePreview(undefined); + const next = { ...desktopArgs }; + for (const key of draftPrimitiveTransientKeys) delete next[key]; + setPayloadText(JSON.stringify({ ...next, documentId: groups.documentId, action: "apply" }, null, 2)); + if (!desktopArgs.continueMode) setCommand(null); + } + if (groups.selection !== null && (desktopRecord.command !== "Draft_Edit" + || JSON.stringify(draftEditSelection.current) === JSON.stringify(documentSelection))) setDocumentSelection({ documentId: groups.documentId, + selection: groups.extendedSelection?.length + ? groups.extendedSelection.map(entry => ({ documentId: groups.documentId, ...entry })) + : groups.selection.map(object => ({ documentId: groups.documentId, object })) }); + } + const snapState = draftSnapState(result); + if (snapState) setDraftSnaps(snapState); + if (desktopRecord.command === "Draft_Text" && result.kind === "result") { + const nativeText = (result.result as { records?: Array<{ result?: Record }> }).records?.find(record => record.result)?.result; + if (nativeText && nativeText.action !== "apply" && nativeText.action !== "cancel") { + setPayloadText(JSON.stringify({ ...desktopArgs, ...nativeText, action: "read", + selection: documentSelection.selection }, null, 2)); + } + } + } + const nextNudge = bimNudgeSetting(desktopRecord, result); + if (desktopRecord.module === "BIM") { + const { bimDocumentState, reconcileBimDesktopPayload, bimBottomPanelState } = await import("./bim-desktop-adapter.js"); + const panels = bimBottomPanelState(desktopRecord, result); + if (panels) setBimBottomPanels(panels); + const nextDocument = bimDocumentState(desktopRecord, result); + if (nextDocument) { + setBimDocument(nextDocument); + setPayloadText((current) => reconcileBimDesktopPayload(desktopRecord, current, payloadText, nextDocument)); + await saveBimFrameDocument(desktopRecord, result); + } + } + if (nextNudge !== undefined) { + setBimNudge(nextNudge); + setPayloadText((current) => { + try { + const payload = JSON.parse(current); + return payload && typeof payload === "object" && !Array.isArray(payload) + ? JSON.stringify({ ...payload, nudge: nextNudge }, null, 2) : current; + } catch { return current; } + }); + } + if (desktopRecord.module === "Sketcher") { + const interaction = sketcherInteractionState(result); + if (interaction?.interaction.clearSelection) setDocumentSelection(current => ({ ...current, selection: [] })); + if (interaction?.interaction.selectedSubelements) setDocumentSelection({ documentId, + selection: interaction.interaction.selectedSubelements.length ? [{ documentId, object: interaction.objectHandle, + subelements: interaction.interaction.selectedSubelements }] : [] }); + if (interaction?.editMode === false) { + setSketchInteraction(null); setSketchConstraints(null); setSketchView(null); + } else if (interaction) setSketchInteraction(interaction); + else if (result.kind === "result" && ["Sketcher_EditSketch", "Sketcher_ReorientSketch"].includes(desktopRecord.command)) { + const snapRecord = moduleMatrixRecords.find(item => item.command === "Sketcher_Snap" && item.kind === "desktop-gui"); + if (snapRecord) { + const state = sketcherInteractionState(await executeSketchCommand(snapRecord, { documentId, action: "read" }, documentId)); + if (sketchSessionRef.current?.closing) return; + setSketchInteraction(state ?? null); + } + } else if (result.kind === "result" && desktopRecord.command === "Sketcher_NewSketch") setSketchInteraction(null); + const view = sketcherViewState(desktopRecord, result); + if (view) setSketchView(view); + else if (result.kind === "result" && ["Sketcher_EditSketch", "Sketcher_ReorientSketch", "Sketcher_NewSketch"].includes(desktopRecord.command)) + setSketchView(null); + if (desktopRecord.command === "Sketcher_EditSketch" && sketchSessionRef.current && !sketchSessionRef.current.closing) { + const viewRecord = moduleMatrixRecords.find(item => item.command === "Sketcher_ViewSketch" && item.kind === "desktop-gui"); + if (viewRecord) { + const reply = await executeSketchCommand(viewRecord, { documentId }, documentId); + if (sketchSessionRef.current?.closing) return; + setSketchView(sketcherViewState(viewRecord, reply) ?? null); + } + } + } + let nativeStatus = "native desktop command complete"; + if (desktopRecord.command === "FEM_ResultsPurge" && result.kind === "result") { + const batch = result.result as { records?: Array<{ apiId: string; + result?: { operation?: string; analysis?: string; removed?: string[]; members?: string[]; savedFile?: string } }> }; + const cleanup = batch.records?.find(item => item.apiId === desktopRecord.id)?.result; + if (cleanup?.operation === "ResultsPurge") { + nativeStatus = `FEM ${cleanup.analysis}: 已清理 ${cleanup.removed?.length ?? 0} 个结果对象;剩余 ${cleanup.members?.length ?? 0} 个分析成员` + + (cleanup.savedFile ? `;OPFS: ${cleanup.savedFile}` : ""); + } + } + let techDrawSaveStatus = ""; + if (desktopRecord.module === "TechDraw") { + const { techDrawCreatedView, saveTechDrawViewSvg, techDrawClipGroupState } = await import("./techdraw-desktop-adapter.js"); + if (desktopRecord.command === "TechDraw_ClipGroup") { + const clip = techDrawClipGroupState(result, documentId); + if (clip) { + setTechDrawClip(clip); + setDocumentSelection({ documentId, selection: [{ documentId, object: clip.object }] }); + } + } + const created = techDrawCreatedView(desktopRecord, result, documentId); + if (created) setTechDrawCreated(created); + if (created) setDocumentSelection({ documentId: created.document, + selection: created.views.map(view => ({ documentId: created.document, object: view.view })) }); + if (created && ["TechDraw_ActiveView", "TechDraw_ArchView", "TechDraw_BrokenView", "TechDraw_DraftView"].includes(desktopRecord.command)) { + try { + const paths: string[] = []; + for (const view of created.views) paths.push(await saveTechDrawViewSvg(created.document, view)); + techDrawSaveStatus = `; OPFS: ${paths.join(", ")}`; + } catch (error) { + // The native transaction is already committed; retain the views for a save retry. + techDrawSaveStatus = `; SVG 保存失败: ${error instanceof Error ? error.message : String(error)}`; + } + } + } + if (desktopRecord.module === "TechDraw" && result.kind === "result" + && ["TechDraw_ActiveView", "TechDraw_ArchView", "TechDraw_BrokenView", "TechDraw_DraftView", + "TechDraw_DecorateLine", "TechDraw_FaceCenterLine", "TechDraw_ShowAll", + "TechDraw_SurfaceFinishSymbols", "TechDraw_WeldSymbol", "TechDraw_StackBottom", + "TechDraw_StackDown", "TechDraw_StackGroup"].includes(desktopRecord.command)) { + const batch = result.result as { records?: Array<{ apiId: string; status: string; code?: string; message?: string }> }; + const native = batch?.records?.find((item) => item.apiId === desktopRecord.id); + nativeStatus = native ? `${native.status}: ${native.message ?? native.code ?? ""}` + : "native_protocol_error: TechDraw command result is missing"; + } + if (desktopRecord.module === "TechDraw" && result.kind === "result" + && ["TechDraw_ExtensionCircleCenterLinesGroup", "TechDraw_ExtensionThreadHoleSide", + "TechDraw_ExtensionThreadBoltSide", "TechDraw_ExtensionThreadsGroup"].includes(desktopRecord.command)) { + const batch = result.result as { records?: Array<{ apiId: string; status: string; code?: string }> }; + const native = batch?.records?.find((item) => item.apiId === desktopRecord.id); + if (native?.status === "exposed" && native.code === "native_desktop_command") + setDocumentSelection({ documentId, selection: [] }); + } + if (desktopRecord.module === "Material" && result.kind === "result") { + const batch = result.result as + { schema?: string; records?: Array<{ apiId: string; status: string; code?: string; message?: string; action?: string; document?: string; object?: string }> }; + if (batch?.schema !== "freecad-web-material/python-family-batch/v1") { + nativeStatus = "native_protocol_error: Material batch schema is invalid"; + } + const native = batch?.records?.find((item) => item.apiId === desktopRecord.id); + if (batch?.schema === "freecad-web-material/python-family-batch/v1") { + nativeStatus = native ? `${native.status}: ${native.action ? `${native.action} - ` : ""}${native.message ?? native.code ?? ""}` + : "native_protocol_error: Material command result is missing"; + if (native?.status === "exposed" && typeof native.document === "string") { + const selectedObject = typeof native.object === "string" ? native.object : undefined; + setDocumentSelection({ documentId: native.document, selection: selectedObject + ? [{ documentId: native.document, object: selectedObject }] : [] }); + } + if (native?.status === "exposed") { + const payload = native as typeof native & { file?: { name?: string; base64?: string }; documentFile?: { name?: string; base64?: string } }; + const decode = (encoded: string) => Uint8Array.from(atob(encoded), char => char.charCodeAt(0)).buffer; + if (payload.file?.name && payload.file.base64) await writeRawStep(payload.file.name, decode(payload.file.base64)); + if (payload.documentFile?.name && payload.documentFile.base64) await writeDocumentFile(payload.documentFile.name, decode(payload.documentFile.base64)); + } + } + } + if ((desktopRecord.module === "Web" || desktopRecord.module === "Std") + && ["Std_OnlineHelp", "Std_OnlineHelpWebsite", "Std_DevHandbook", "Std_ReportBug", + "Std_FreeCADDonation", "Std_FreeCADForum", "Std_FreeCADUserHub", "Std_FreeCADWebsite"].includes(desktopRecord.command) + && result.kind === "result") { + const native = result.result as { command?: string; documentId?: string; url?: string }; + if (native.command === desktopRecord.command && native.documentId === documentId + && typeof native.url === "string" && /^https?:\/\//i.test(native.url)) { + setStandardCommandView({ command: native.command, documentId, url: native.url }); + } + } + if (desktopRecord.command === "Std_UserInterface" && result.kind === "result") { + const native = result.result as { status?: string; command?: string }; + if (native.status === "exposed" && native.command === "Std_UserInterface") { + nativeStatus = "exposed: docked user interface"; + } + } + if (desktopRecord.command === "Std_Open" && result.kind === "result") { + const batch = result.result as { + owner?: string; + records?: Array<{ + name?: string; + status?: string; + result?: { + activeDocument?: string; + opened?: Array<{ documents?: Array<{ name?: string }> }>; + scene?: { selection?: Array<{ documentId: string; object: string; subelements?: string[] }> }; + }; + }>; + }; + const opened = batch.records?.find(row => row.name === "Std_Open")?.result; + const document = opened?.activeDocument; + const openedDocument = opened?.opened?.flatMap(file => file.documents ?? []).find(item => item.name === document); + if (batch.owner === "DocumentProbe" && document && openedDocument) { + const snapshotResponse = await router.request("Part", "part.document", { + schema: "freecad-web-part/document/v1", module: "Part", document, + action: "snapshot", includeMesh: false, builderInfo: false, + }, document); + if (snapshotResponse.kind === "error") throw new Error(`Opened document tree unavailable: ${snapshotResponse.error.message}`); + const snapshot = snapshotResponse.result as { document?: string; objects?: Array<{ name: string; label?: string; type: string }> }; + if (snapshot.document !== document || !Array.isArray(snapshot.objects)) + throw new Error("Opened document tree response has a different native document identity"); + projectDocumentOwners.current.set(document, { document, module: "Part" }); + setNativeDocuments(previous => ({ ...previous, [document]: { + document, owner: "DocumentProbe", objects: snapshot.objects!.map(object => ({ ...object, typeId: object.type })), + } })); + const selection = opened.scene?.selection?.map(item => ({ ...item })) ?? []; + setDocumentSelection({ documentId: document, selection }); + setPayloadText(JSON.stringify({ documentId: document, runtimeOwner: "DocumentProbe", selection }, null, 2)); + } + } + const snapState = draftSnapState(result); + if (snapState) setDraftSnaps(snapState); + if (desktopRecord.command === "TechDraw_BrokenView") { + const batch = Object.values(result).find((value) => value && typeof value === "object" + && "schema" in value && value.schema === "freecad-web-techdraw/python-family-batch/v1") as + { records?: Array<{ status: string; result?: { document: string; page: string; view: string; svg: string; nativeOperationCompleted?: boolean } }> } | undefined; + for (const native of batch?.records ?? []) { + const view = native.result; + if (native.status === "exposed" && view?.nativeOperationCompleted === true + && typeof view.document === "string" && typeof view.page === "string" + && typeof view.view === "string" && typeof view.svg === "string" && view.svg.length > 0) { + setTechDrawViews((current) => [...current.filter((item) => item.document !== view.document + || item.page !== view.page || item.view !== view.view), view]); + } + } + } + // Native view creation can commit before a remaining workflow boundary + // is reported. Only display partial results that confirm that commit. + const committedProjection = desktopRecord.module === "TechDraw" + && ["TechDraw_View", "TechDraw_ProjectionGroup", "TechDraw_BrokenView", + "TechDraw_DraftView", "TechDraw_SectionView", "TechDraw_SectionGroup"].includes(desktopRecord.command) + && result.kind === "error" ? result.error.diagnostic?.response : undefined; + const nativeResponse = result.kind === "result" ? result : committedProjection; + if (desktopRecord.module === "TechDraw" && nativeResponse && typeof nativeResponse === "object") { + const batch = Object.values(nativeResponse).find((value) => value && typeof value === "object" + && "schema" in value && value.schema === "freecad-web-techdraw/python-family-batch/v1") as + { records?: Array<{ apiId: string; status: string; code?: string; message?: string; result?: Record }> } | undefined; + const native = batch?.records?.find((item) => item.apiId === desktopRecord.id); + nativeStatus = native ? `${native.status}: ${native.message ?? native.code ?? ""}` : "native_protocol_error: TechDraw command result is missing"; + const state = native?.result; + if (desktopRecord.command === "TechDraw_FillTemplateFields" + && desktopArgs.action !== "accept" && desktopArgs.action !== "cancel" + && result.kind === "result" && native?.status === "success" && state?.document === documentId) { + window.dispatchEvent(new CustomEvent("freecad-techdraw-template-edit", { detail: { document: documentId } })); + } + if (desktopRecord.command === "TechDraw_ProjectShape" && result.kind === "result" + && native?.status === "exposed" && state?.document === documentId + && state.nativeOperationCompleted === true && Array.isArray(state.objects)) { + if (!state.objects.length || state.objects.some((object) => typeof object !== "string" || !object)) { + throw new Error("Native projection returned invalid object handles"); + } + setDocumentSelection({ documentId, selection: state.objects.map((object: string) => ({ documentId, object })) }); + } + if (state && (desktopRecord.command !== "TechDraw_ProjectionGroup" || state.action === "accept") + && state.document === documentId && typeof state.page === "string" + && (result.kind === "result" || (native?.status === "partial" && state.nativeOperationCompleted === true)) + && (native?.status === "exposed" || native?.status === "partial" + || native?.status === "success")) { + if (desktopRecord.command === "TechDraw_Image" && typeof state.object === "string" + && typeof state.imageBase64 === "string") { + const bytes = atob(state.imageBase64); + const mime = bytes.startsWith("\x89PNG\r\n\x1a\n") ? "image/png" + : bytes.startsWith("\xff\xd8\xff") ? "image/jpeg" + : bytes.startsWith("BM") ? "image/bmp" : undefined; + if (!mime) throw new Error("Native document returned an unsupported image format"); + const image = { document: documentId, page: state.page, object: state.object, + url: `data:${mime};base64,${state.imageBase64}` }; + setTechDrawImages((previous) => [...previous.filter((item) => item.document !== documentId + || item.object !== image.object), image]); + setDocumentSelection({ documentId, selection: [{ documentId, object: image.object }] }); + } + const views: Array<{ document: string; page: string; view: string; svg: string }> = []; + if (typeof state.baseView === "string" && typeof state.baseSvg === "string" && state.baseSvg.trim()) { + views.push({ document: documentId, page: state.page, view: state.baseView, svg: state.baseSvg }); + } + if (typeof state.view === "string" && typeof state.svg === "string" && state.svg.trim()) { + views.push({ document: documentId, page: state.page, view: state.view, svg: state.svg }); + setDocumentSelection({ documentId, selection: [{ documentId, object: state.view }] }); + } + if (["TechDraw_LeaderLine", "TechDraw_Balloon", "TechDraw_WeldSymbol"].includes(desktopRecord.command) && state.action === "accept" && state.drawing + && typeof state.drawing === "object" && "view" in state.drawing && "svg" in state.drawing + && typeof state.drawing.view === "string" && typeof state.drawing.svg === "string") { + views.push({ document: documentId, page: state.page, view: state.drawing.view, svg: state.drawing.svg }); + } + if (["TechDraw_ProjectionGroup", "TechDraw_DraftView", "TechDraw_SectionView", + "TechDraw_SectionGroup"].includes(desktopRecord.command) && Array.isArray(state.views)) { + for (const projected of state.views) { + // Some native results also enumerate page members as handles. + if (typeof projected === "string") continue; + if (!projected || typeof projected !== "object" || typeof projected.view !== "string" + || !projected.view || typeof projected.svg !== "string" || !projected.svg.trim()) { + throw new Error("Native command returned an invalid rendered view"); + } + const view = { document: documentId, page: state.page, view: projected.view, svg: projected.svg }; + const index = views.findIndex((existing) => existing.view === view.view); + if (index < 0) views.push(view); + else views[index] = view; + } + } + if (!["TechDraw_LeaderLine", "TechDraw_Balloon", "TechDraw_WeldSymbol"].includes(desktopRecord.command) || state.action === "accept") setTechDrawViews((previous) => [ + ...previous.filter((existing) => existing.document !== documentId + || !views.some((view) => view.page === existing.page && view.view === existing.view)), + ...views, + ]); + if (desktopRecord.command === "TechDraw_DraftView" && state.nativeOperationCompleted === true + && views.length > 0) { + setDocumentSelection({ documentId, + selection: views.map((view) => ({ documentId, object: view.view })) }); + } + if (desktopRecord.command === "TechDraw_DetailView") { + const parameters = { ...desktopArgs }; + delete parameters.action; + for (const key of ["baseView", "view", "anchorX", "anchorY", "radius", "scaleType", "scale", "x", "y", "reference"]) { + if (typeof state[key] === "string" || typeof state[key] === "number") parameters[key] = state[key]; + } + setPayloadText(JSON.stringify(parameters, null, 2)); + } + } + } + if (desktopRecord.command === "Mesh_Merge") { + const merged = selectedMeshState(result, "Mesh_Merge"); + if (merged?.documentChanged && merged.selection?.length) + setDocumentSelection({ documentId, selection: merged.selection }); + } + setResponse(result); setStatus(result.kind === "result" ? nativeStatus + techDrawSaveStatus : `${result.error.code}: ${result.error.message}`); setBusy(false); return result; + } catch (error) { + if (desktopRecord.module === "Sketcher" && command === "Sketcher_EditSketch") await closeSketchSession(); + const result = createFailure(`desktop-${module.toLowerCase()}`, "native_dispatch_failed", error instanceof Error ? error.message : String(error), { module, command }); + setResponse(result); setStatus(`${result.error.code}: ${result.error.message}`); + } finally { setBusy(false); } + return; + } + const descriptor = commandRuntime.commands.find((item) => item.id === `${module}:${command}`) as WebCommandDescriptor; + if (!descriptor?.runnable) { const decision = nativeSourceDecision(module, command); const result = createFailure(`workbench-${module.toLowerCase()}`, decision?.code ?? (module === "Fem" ? "blocked_native_dependency" : "restricted"), (decision?.message ?? descriptor?.reason) || "command is not runnable", decision?.diagnostic ?? { module, command }); setResponse(result); setStatus(`${result.error.code}: ${result.error.message}`); setBusy(false); return; } + let activeDocumentId = module === "Assembly" || module === "Part" || module === "TechDraw" || module === "Points" ? documentSelection.documentId : "workbench-document"; + if (module === "TechDraw" && payload && typeof payload === "object" && !Array.isArray(payload) + && "documentId" in payload && typeof payload.documentId === "string") { + activeDocumentId = payload.documentId; + } + if (module === "TechDraw" && payload && typeof payload === "object" && !Array.isArray(payload) + && !("documentId" in payload) && (documentSelection.documentId !== "workbench-document" || command === "techdraw.nativeSaveReopen")) { + payload = { ...payload, documentId: activeDocumentId }; + } + if (module === "TechDraw" && command === "techdraw.nativeImportExport" + && payload && typeof payload === "object" && !Array.isArray(payload)) { + const selected = techDrawViews.filter((view) => view.document === activeDocumentId); + const current = selected.find((view) => documentSelection.selection.some((item) => + item.documentId === activeDocumentId && item.object === view.view)) + ?? (selected.length === 1 ? selected[0] : undefined); + payload = { ...payload, documentId: activeDocumentId, + ...(!("page" in payload) && current ? { page: current.page } : {}), + ...(!("view" in payload) && current ? { view: current.view } : {}) }; + } + try { + if (module === "Assembly" && command === "assembly.saveReopen" && payload && typeof payload === "object") { + payload = { ...payload, documentName: activeDocumentId }; + } + const result = await plugins.execute(module, command, payload, activeDocumentId); + if (module === "Assembly" && command === "assembly.createRecompute" && result.kind === "result") { + const native = result.result as { document?: { name?: string } }; + if (typeof native.document?.name === "string" && native.document.name.trim()) { + setDocumentSelection({ documentId: native.document.name, selection: [] }); + setPayloadText(JSON.stringify({ documentId: native.document.name, selection: [] }, null, 2)); + } + } + if (module === "Points" && command === "points.saveReopen" && result.kind === "result") { + const saved = result.result as { content?: string; sourceDocument: string }; + if (saved.content) { + const bytes = Uint8Array.from(atob(saved.content), c => c.charCodeAt(0)); + const url = URL.createObjectURL(new Blob([bytes], { type: "application/octet-stream" })); + const link = document.createElement("a"); link.href = url; link.download = `${saved.sourceDocument}.FCStd`; link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + } + } + if (module === "Assembly" && command === "assembly.saveReopen" && result.kind === "result") { + const reopened = (result.result as { reopenedDocumentName?: string }).reopenedDocumentName; + if (reopened) setDocumentSelection({ documentId: reopened, selection: [] }); + } + if (module === "TechDraw" && command === TECHDRAW_COMMAND && result.kind === "result") { + const drawing = result.result as TechDrawResult; + setTechDrawViews((views) => [...views.filter((view) => + view.document !== drawing.document.name || view.view !== drawing.view), + { document: drawing.document.name, page: drawing.page, view: drawing.view, svg: drawing.svg }]); + setDocumentSelection({ documentId: drawing.document.name, selection: drawing.selection ?? [{ documentId: drawing.document.name, object: drawing.view }] }); + } + setResponse(result); setStatus(result.kind === "result" ? "native command complete" : `${result.error.code}: ${result.error.message}`); setBusy(false); + } catch (error) { + const result = createFailure(`workbench-${module.toLowerCase()}`, "native_dispatch_failed", error instanceof Error ? error.message : String(error), { module, command }); + setResponse(result); setStatus(`${result.error.code}: ${result.error.message}`); + } finally { setBusy(false); } + }; + const warmTier2 = async () => { + if (module !== "Part" && module !== "PartDesign") { setStatus("当前模块没有专用 Tier-2 adapter 入口"); return; } + setBusy(true); setStatus(`正在预热 ${module} Tier-2 family adapter...`); setResponse(null); + try { + const response = await fetch("/api/python-api-index.json"); + if (!response.ok) throw new Error(`Python API index failed: HTTP ${response.status}`); + const index = await response.json(); + const apiIds = index.records + .filter((row: [string, number, number, string, number, number, number]) => index.fields.modules[row[1]] === module && index.fields.tiers[row[5]] === "tier-2-pure") + .map((row: [string]) => row[0]); + const result = await new PythonFamilyDispatcher(router, index).dispatchBatch(apiIds, "workbench-document", { includePlanned: true }); + setResponse({ schema: "freecad-web-facade/v1", version: 1, kind: "result", requestId: `${module.toLowerCase()}-tier2-${Date.now()}`, result }); + setStatus(`${module} Tier-2 family adapter 预热完成:${result.count} API ID,方法级 disposition 保留 planned`); + } catch (error) { setStatus(error instanceof Error ? error.message : String(error)); } + finally { setBusy(false); } + }; + const callApi = async () => { + setBusy(true); setStatus(`正在调用 API ID ${apiId}...`); setResponse(null); + try { + const response = await fetch("/api/python-api-index.json"); + if (!response.ok) throw new Error(`Python API index failed: HTTP ${response.status}`); + const result = await new PythonApiCallDispatcher(router, await response.json()).call(apiId); + setResponse(result); setStatus(result.kind === "result" ? "Python API adapter complete" : `${result.error.code}: ${result.error.message}`); + } catch (error) { setStatus(error instanceof Error ? error.message : String(error)); } + finally { setBusy(false); } + }; + const validateCommandMatrix = async (mode: "normal" | "error" | "cancel" = "normal") => { + setBusy(true); setStage("running"); setStatus(mode === "cancel" ? "正在取消命令矩阵核验..." : mode === "error" ? "正在回放无效输入..." : "正在核验工作台命令矩阵..."); setResponse(null); + let worker: Worker | undefined; + try { + const loaded = await fetch("/api/workbench-command-matrix.json").then(async (result) => { + if (!result.ok) throw new Error(`Workbench command matrix failed: HTTP ${result.status}`); + return result.json() as Promise; + }); + setMatrix(loaded); + setSelectedMatrixId((current) => current ?? loaded.records.find((item) => item.module === module)?.id ?? loaded.records[0]?.id ?? null); + worker = new Worker(new URL("./workbench-command.worker.ts", import.meta.url), { type: "module" }); + const records = mode === "error" ? [{ ...loaded.records[0], sourcePath: "" }, ...loaded.records.slice(1)] : loaded.records; + const request = createWorkbenchCommandRequest(mode === "cancel" ? "workbench-command-cancel" : `workbench-command-${mode}-${Date.now()}`, records, { + documentId: "workbench-document", + selection: [selectedMatrixRecord?.id ?? `${module}:active-document`], + propertyMode: "read-only", + }); + const result = await new Promise((resolve, reject) => { + worker!.onerror = () => reject(new Error("workbench command Worker failed")); + worker!.onmessage = (event: MessageEvent) => { + if (event.data.kind === "ready") { + worker!.postMessage(request); + if (mode === "cancel") worker!.postMessage(createCancel("workbench-command-cancel-control", request.requestId, request.documentId)); + return; + } + resolve(event.data as FacadeResponse); + }; + }); + setResponse(result); + setMatrixSummary({ records: loaded.records.length, nativeHandlers: loaded.dispositionCounts.native_handler, restricted: loaded.dispositionCounts.restricted }); + const expectedStage = mode === "cancel" + ? result.kind === "error" && result.error.code === "cancelled" ? "cancelled" : "expected-error" + : mode === "error" + ? result.kind === "error" && result.error.code === "invalid_request" ? "expected-error" : "expected-error" + : result.kind === "result" ? "success" : "expected-error"; + setStage(expectedStage); + setStatus(result.kind === "result" ? "native command matrix complete" : `${result.error.code}: ${result.error.message}`); + } catch (error) { setStage("expected-error"); setStatus(error instanceof Error ? error.message : String(error)); } + finally { worker?.terminate(); setBusy(false); } + }; + const resetCommandMatrix = async () => { + setBusy(true); setStatus("正在重置命令 Worker..."); setResponse(null); + const worker = new Worker(new URL("./workbench-command.worker.ts", import.meta.url), { type: "module" }); + try { + await new Promise((resolve, reject) => { + worker.onerror = () => reject(new Error("workbench command Worker failed")); + worker.onmessage = (event: MessageEvent<{ kind: string }>) => { + if (event.data.kind === "ready") { worker.postMessage({ kind: "reset", requestId: "workbench-command-reset" }); return; } + if (event.data.kind === "reset") resolve(); + }; + }); + setStage("reset"); setStatus("command Worker reset complete"); + } catch (error) { setStage("expected-error"); setStatus(error instanceof Error ? error.message : String(error)); } + finally { worker.terminate(); setBusy(false); } + }; + let detailParameters: Record | null = null; + let jointParameters: Record | null = null; + if (module === "Assembly" && ["Assembly_CreateJointAngle", "Assembly_CreateJointBall", + "Assembly_CreateJointBelt", "Assembly_CreateJointCylindrical", + "Assembly_CreateJointDistance", "Assembly_CreateJointFixed", "Assembly_CreateJointGears", + "Assembly_CreateJointParallel", "Assembly_CreateJointPerpendicular", "Assembly_CreateJointRackPinion", + "Assembly_CreateJointRevolute", "Assembly_CreateJointScrew", "Assembly_CreateJointSlider"].includes(command ?? "")) { + try { + const parsed: unknown = JSON.parse(payloadText); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) jointParameters = parsed as Record; + } catch { /* Preserve malformed input in the JSON editor. */ } + } + const editJointParameter = (key: string, value: unknown) => { + if (!jointParameters) return; + const parameters = { ...jointParameters }; + if (value === undefined) delete parameters[key]; + else parameters[key] = value; + setPayloadText(JSON.stringify(parameters, null, 2)); + setResponse(null); + }; + let projectionParameters: Record | null = null; + const brokenViewParameters = module === "TechDraw" && command === "TechDraw_BrokenView"; + const draftViewParameters = module === "TechDraw" && command === "TechDraw_DraftView"; + const projectShapeParameters = module === "TechDraw" && command === "TechDraw_ProjectShape"; + const sectionViewParameters = module === "TechDraw" && command === "TechDraw_SectionGroup"; + const selectedViewParameters = sectionViewParameters || brokenViewParameters || projectShapeParameters || draftViewParameters + || command === "TechDraw_ArchView" || command === "TechDraw_ActiveView"; + if (module === "TechDraw" && (["TechDraw_View", "TechDraw_ArchView", "TechDraw_ActiveView"].includes(command ?? "") || selectedViewParameters)) { + try { + const parsed: unknown = JSON.parse(payloadText); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) projectionParameters = parsed as Record; + } catch { /* Keep malformed JSON available for correction. */ } + } + const editProjectionParameter = (key: string, value: unknown) => { + if (!projectionParameters) return; + const parameters = { ...projectionParameters }; + if (value === undefined) delete parameters[key]; + else parameters[key] = value; + setPayloadText(JSON.stringify(parameters, null, 2)); + }; + if (module === "TechDraw" && command === "TechDraw_DetailView") { + try { + const parsed: unknown = JSON.parse(payloadText); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) detailParameters = parsed as Record; + } catch { /* The JSON editor retains invalid input until corrected. */ } + } + const editDetailParameter = (key: string, value: string, numeric: boolean) => { + if (!detailParameters) return; + const parameters = { ...detailParameters }; + if (!value) delete parameters[key]; + else if (numeric) { + const number = Number(value); + if (!Number.isFinite(number)) return; + parameters[key] = number; + } else parameters[key] = value; + setPayloadText(JSON.stringify(parameters, null, 2)); + }; + const partDesignChildren = module === "PartDesign" && command ? partDesignCommandGroups[command] : undefined; + let partDesignGroupArgs: Record | undefined; + if (partDesignChildren) { + try { + const parsed: unknown = JSON.parse(payloadText); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) partDesignGroupArgs = parsed as Record; + } catch { /* Retain invalid input in the JSON editor. */ } + } + const techDrawStackGroup = module === "TechDraw" + && (command === "TechDraw_StackGroup" || command === "TechDraw:desktop:TechDraw_StackGroup"); + let techDrawStackArgs: Record | undefined; + if (techDrawStackGroup) { + try { + const parsed: unknown = JSON.parse(payloadText); + if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) + techDrawStackArgs = parsed as Record; + } catch { /* Preserve incomplete input in the JSON editor. */ } + } + const draftArrayCommand = module === "Draft" && /^Draft_(Path|PathLink|PathTwisted|PathTwistedLink|Point|PointLink)Array$/.test((command ?? "").replace("Draft:desktop:", "")); + const draftGroupCommand = module === "Draft" && DRAFT_GROUP_COMMANDS.includes((command ?? "").replace("Draft:desktop:", "")); + const draftModeCommand = module === "Draft" && ["Draft_ToggleConstructionMode", "Draft_ToggleDisplayMode"].includes((command ?? "").replace("Draft:desktop:", "")); + const draftGeometryCommand = module === "Draft" && ["Draft_Arc", "Draft_Arc_3Points", "Draft_Line", "Draft_Wire", "Draft_BezCurve", "Draft_CubicBezCurve", "Draft_Text"].includes((command ?? "").replace("Draft:desktop:", "")); + let draftGroupArgs: Record = {}; + const draftWorkflowCommand = module === "Draft" && DRAFT_WORKFLOW_COMMANDS.includes((command ?? "").replace("Draft:desktop:", "")); + const draftTransformCommand = module === "Draft" && ["Draft_Rotate", "Draft_Scale"].includes((command ?? "").replace("Draft:desktop:", "")); + const draftProjectionCommand = module === "Draft" && ["Draft_Shape2DView", "Draft_Slope", "Draft_Split"].includes((command ?? "").replace("Draft:desktop:", "")); + const draftTrimConvertCommand = module === "Draft" && /Draft_(Trimex|WireToBSpline)$/.test(command ?? ""); + if (draftGroupCommand || draftArrayCommand || draftGeometryCommand || draftModeCommand || draftWorkflowCommand || draftTransformCommand || draftProjectionCommand || draftTrimConvertCommand) { + try { const value = JSON.parse(payloadText); if (value && typeof value === "object" && !Array.isArray(value)) draftGroupArgs = value; } + catch { /* Keep incomplete JSON editable. */ } + } + const draftViewportCommand = (command ?? "").replace(/^Draft:desktop:/, ""); + const draftSplit = module === "Draft" && draftViewportCommand === "Draft_Split"; + const [draftSplitHover, setDraftSplitHover] = useState<{ documentId: string; object: string; subElement: string }>(); + const draftSplitKey = draftSplit ? `${documentSelection.documentId}/Draft_Split` : ""; + const clearDraftSplit = () => { + setDraftHoverPoint(null); setDraftSplitHover(undefined); setDraftNativePreview(undefined); + setPayloadText(current => { + try { + const args = JSON.parse(current); + for (const key of ["point", "edgeIndex", "selection", "snapReference"]) delete args[key]; + return JSON.stringify({ ...args, documentId: documentSelection.documentId, action: "apply" }, null, 2); + } catch { return current; } + }); + }; + useEffect(() => { if (draftSplitKey) clearDraftSplit(); }, [draftSplitKey]); + const draftPrimitive = module === "Draft" && draftPrimitiveCommands.includes(draftViewportCommand); + const draftPrimitiveKey = draftPrimitive ? `${documentSelection.documentId}/${draftViewportCommand}` : ""; + const draftTransformKey = draftTransformCommand ? `${documentSelection.documentId}/${draftViewportCommand}` : ""; + useEffect(() => { + if (!draftTransformKey) return; + setDraftHoverPoint(null); + setDraftNativePreview(undefined); + setPayloadText(current => { + try { + const args = JSON.parse(current); + delete args.transformReference; + delete args.selection; + return JSON.stringify({ ...args, documentId: documentSelection.documentId, + transformStage: 0, angle: 0, scale: [1, 1, 1], action: "apply" }, null, 2); + } catch { return current; } + }); + }, [draftTransformKey]); + draftPrimitiveOwner.current = draftPrimitiveKey; + useEffect(() => { + setDraftHoverPoint(null); setDraftNativePreview(undefined); + if (!draftPrimitiveKey) return; + setPayloadText(current => { + try { + const args = JSON.parse(current); + for (const key of draftPrimitiveTransientKeys) delete args[key]; + return JSON.stringify({ ...args, documentId: documentSelection.documentId, action: "apply" }, null, 2); + } catch { return current; } + }); + }, [draftPrimitiveKey]); + const currentDraftPlane = draftGroups?.documentId === documentSelection.documentId ? draftGroups.workingPlane : undefined; + const updateDraftGroupArgs = (values: Record) => { + setPayloadText(JSON.stringify({ ...draftGroupArgs, + ...(draftPrimitive ? primitiveDefaults(draftGroupArgs, currentDraftPlane) : {}), ...values }, null, 2)); + setDraftNativePreview(undefined); + setResponse(null); + }; + const draftStretchCommand = module === "Draft" && draftViewportCommand === "Draft_Stretch"; + const draftViewportActive = module === "Draft" && (draftPrimitive || draftTransformCommand || draftStretchCommand || ["Draft_Line", "Draft_Wire", "Draft_Move", "Draft_Mirror", "Draft_Offset", "Draft_Text"].includes(draftViewportCommand)); + const primitiveFrame = primitivePlane(draftGroupArgs, currentDraftPlane); + const primitiveX = primitiveFrame.u, primitiveY = primitiveFrame.v; + const primitiveBase = (draftGroupArgs.base ?? primitiveFrame.position) as number[]; + const primitiveAt = (x: number, y: number) => primitiveBase.map((value, axis) => Number(value) + primitiveX[axis] * x + primitiveY[axis] * y); + const primitiveDimensions = (point: number[]) => { + const delta = point.map((value, axis) => value - Number(primitiveBase[axis])); + const x = delta.reduce((sum, value, axis) => sum + value * primitiveX[axis], 0); + const y = delta.reduce((sum, value, axis) => sum + value * primitiveY[axis], 0); + return { length: x, height: y, radius: Math.hypot(x, y), rotation: draftGroupArgs.rotation ?? 0 }; + }; + const draftPoints = Array.isArray(draftGroupArgs.points) ? draftGroupArgs.points as number[][] : []; + const draftStart = Array.isArray(draftGroupArgs.startPoint) ? draftGroupArgs.startPoint as number[] : null; + const draftMirrorStart = Array.isArray(draftGroupArgs.p1) ? draftGroupArgs.p1 as number[] : null; + const draftSelectedNames = ((Array.isArray(draftGroupArgs.selection) ? draftGroupArgs.selection : documentSelection.selection) as Array<{ documentId: string; object: string; subElement?: string; subelements?: string[]; subElementNames?: string[] }>) + .filter(entry => entry.documentId === documentSelection.documentId) + .map(({ subElementNames, ...entry }) => ({ ...entry, subelements: entry.subelements ?? subElementNames })); + const draftPreviewSelection = draftTransformCommand && draftGroupArgs.subelements === true + ? draftSelectedNames.flatMap(entry => { + const names = entry.subElement ? [entry.subElement] : entry.subelements ?? []; + return names.flatMap(name => { + const path = name.split("."); + const element = path.pop()!; + if (!/^(Edge|Vertex)[1-9][0-9]*$/.test(element)) return []; + const prefix = path.length ? `${path.join(".")}.` : ""; + const instance = draftGroups?.subelementGeometry?.find(item => item.object === entry.object && item.prefix === prefix); + if (instance) return [{ ...entry, object: `${entry.object}/${prefix}`, subElement: element, subelements: [element] }]; + let owner = draftGroups?.objects.find(object => object.name === entry.object); + for (const child of path) { + // Only follow document group membership here. Link instances require + // native instance geometry; their source object's placement is different. + if (!owner?.isGroup || !owner.members.includes(child)) return []; + owner = draftGroups?.objects.find(object => object.name === child); + } + return owner ? [{ ...entry, object: owner.name, subElement: element, subelements: [element] }] : []; + }); + }) : draftSelectedNames; + const draftSelectedGeometry = (draftGroups?.documentId === documentSelection.documentId + ? [...draftGroups.geometry ?? [], ...(draftTransformCommand && draftGroupArgs.subelements === true + ? (draftGroups.subelementGeometry ?? []).map(item => ({ ...item, object: `${item.object}/${item.prefix}` })) : [])] : []) + .filter(item => draftPreviewSelection.some(selected => selected.object === item.object)); + const draftTangentOptions = draftSelectedGeometry.flatMap(item => item.edges.flatMap((_, index) => { + const subElement = `Edge${index + 1}`; + const permitted = draftSelectedNames.some(entry => entry.object === item.object + && (!entry.subElement && !entry.subelements?.length || entry.subElement === subElement || entry.subelements?.includes(subElement))); + return permitted ? [{ value: `${item.object}:${subElement}`, label: `${item.object} · ${subElement}` }] : []; + })); + const draftOffsetDelta = (point: number[]): number[] | undefined => { + let nearest: { distance: number; delta: number[] } | undefined; + for (const item of draftSelectedGeometry) for (const edge of item.edges) for (let index = 1; index < edge.length; index++) { + const a = edge[index - 1], b = edge[index]; + const direction = [b[0] - a[0], b[1] - a[1]]; + const length = direction[0] ** 2 + direction[1] ** 2; + if (length < 1e-12) continue; + const parameter = Math.max(0, Math.min(1, ((point[0] - a[0]) * direction[0] + (point[1] - a[1]) * direction[1]) / length)); + const dx = point[0] - a[0] - parameter * direction[0], dy = point[1] - a[1] - parameter * direction[1]; + const signed = (direction[0] * dy - direction[1] * dx) / Math.sqrt(length); + const candidate = { distance: Math.hypot(dx, dy), delta: [-direction[1] / Math.sqrt(length) * signed, direction[0] / Math.sqrt(length) * signed, 0] }; + if (!nearest || candidate.distance < nearest.distance) nearest = candidate; + } + return nearest?.delta; + }; + const draftOffsetPath = (edge: number[][], delta: number[]): number[][] => { + if (edge.length < 2) return edge; + const closed = edge.length > 2 && Math.hypot(edge[0][0] - edge[edge.length - 1][0], edge[0][1] - edge[edge.length - 1][1]) < 1e-7; + const vertices = closed ? edge.slice(0, -1) : edge; + const segments = vertices.map((point, index) => { + const next = vertices[index + 1] ?? (closed ? vertices[0] : undefined); + if (!next) return null; + const dx = next[0] - point[0], dy = next[1] - point[1]; + const length = Math.hypot(dx, dy); + return length > 1e-9 ? [-dy / length, dx / length] : null; + }); + const distance = Math.hypot(delta[0], delta[1]); + const reference = segments.find(normal => normal !== null); + const signedDistance = reference && reference[0] * delta[0] + reference[1] * delta[1] < 0 ? -distance : distance; + const offset = vertices.map((point, index) => { + const previous = segments[(index - 1 + segments.length) % segments.length]; + const next = segments[index]; + const normal = next ?? previous; + if (!normal) return point; + let scale = signedDistance; + if (previous && next && (closed || index > 0)) { + const dot = previous[0] * next[0] + previous[1] * next[1]; + if (dot > -0.9) scale /= Math.max((1 + dot) / 2, 0.1); + } + const bisector = previous && next && (closed || index > 0) + ? [(previous[0] + next[0]) / 2, (previous[1] + next[1]) / 2] : normal; + return [point[0] + bisector[0] * scale, point[1] + bisector[1] * scale, point[2]]; + }); + return closed ? [...offset, offset[0]] : offset; + }; + const draftPreviewPaths: number[][][] = []; + const draftTangentMode = String(draftGroupArgs.tangentMode ?? "radius"); + const draftTangentEdgeCount = ({ "radius": 0, "center-edge": 1, "two-edges-point": 2, "edge-two-points": 1, + "three-edges": 3, "two-edges-radius": 2, "edge-point-radius": 1 } as Record)[draftTangentMode] ?? 0; + const draftTangentPointCount = draftTangentMode === "edge-two-points" ? 2 : ["two-edges-point", "edge-point-radius"].includes(draftTangentMode) ? 1 : 0; + const draftTangentReferences = (draftGroupArgs.tangentReferences ?? []) as string[]; + const draftTangentPoints = (draftGroupArgs.tangentPoints ?? []) as number[][]; + const draftPrimitiveReady = draftTangentMode !== "radius" + ? draftTangentReferences.length === draftTangentEdgeCount && draftTangentReferences.every(value => draftTangentOptions.some(option => option.value === value)) + && new Set(draftTangentReferences).size === draftTangentEdgeCount && draftTangentPoints.length === draftTangentPointCount + : draftGroupArgs.primitiveStage !== 1; + useEffect(() => { + if (!draftPrimitive && !draftTransformCommand && !draftSplit) return; + const keydown = (event: KeyboardEvent) => { + if (event.key === "Escape" && !busy) { event.preventDefault(); if (draftSplit) clearDraftSplit(); setDraftHoverPoint(null); setDraftNativePreview(undefined); setCommand(null); } + }; + window.addEventListener("keydown", keydown); + return () => window.removeEventListener("keydown", keydown); + }, [draftPrimitiveKey, draftTransformCommand, draftSplitKey, busy]); + useEffect(() => { + if (module !== "BIM" || busy) return; + const keydown = (event: KeyboardEvent) => { + if (!event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return; + const target = event.target as HTMLElement | null; + if (target?.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(target?.tagName ?? "")) return; + const commandByKey: Record = { + ArrowUp: "BIM_Nudge_Up", ArrowDown: "BIM_Nudge_Down", + ArrowLeft: "BIM_Nudge_Left", ArrowRight: "BIM_Nudge_Right", + ",": "BIM_Nudge_RotateLeft", ".": "BIM_Nudge_RotateRight", + PageUp: "BIM_Nudge_Extend", PageDown: "BIM_Nudge_Shrink", "/": "BIM_Nudge_Switch", + }; + const next = commandByKey[event.key]; + if (!next || documentSelection.selection.length === 0) return; + event.preventDefault(); + setCommand(next); + void run(undefined, { nudge: bimNudge ?? "" }, next); + setStatus(`BIM shortcut: ${next}`); + }; + window.addEventListener("keydown", keydown, true); + return () => window.removeEventListener("keydown", keydown, true); + }, [bimNudge, busy, documentSelection.selection.length, module, run]); + if (draftTransformCommand) { + const center = (draftGroupArgs.center ?? [0, 0, 0]) as number[]; + const factors = (draftGroupArgs.scale ?? [1, 1, 1]) as number[]; + const axis = (draftGroupArgs.axis ?? currentDraftPlane?.normal ?? [0, 0, 1]) as number[]; + const length = Math.hypot(...axis); + let angle = Number(draftGroupArgs.angle ?? 0) * Math.PI / 180; + const normal = axis.map(value => value / length); + const reference = draftGroupArgs.transformReference as number[] | undefined; + if (draftViewportCommand === "Draft_Rotate" && draftGroupArgs.transformStage === 2 + && reference?.length === 3 && draftHoverPoint && length > 0 && Number.isFinite(length)) { + const project = (point: number[]) => { + const delta = point.map((value, index) => value - center[index]); + const axial = delta.reduce((sum, value, index) => sum + value * normal[index], 0); + return delta.map((value, index) => value - axial * normal[index]); + }; + const from = project(reference), to = project(draftHoverPoint); + if (Math.hypot(...from) > 1e-9 && Math.hypot(...to) > 1e-9) { + const cross = [from[1] * to[2] - from[2] * to[1], + from[2] * to[0] - from[0] * to[2], from[0] * to[1] - from[1] * to[0]]; + angle = Math.atan2(cross.reduce((sum, value, index) => sum + value * normal[index], 0), + from.reduce((sum, value, index) => sum + value * to[index], 0)); + } + } + const cosine = Math.cos(angle), sine = Math.sin(angle); + if (center.length === 3 && center.every(Number.isFinite) + && (draftViewportCommand === "Draft_Scale" + ? factors.length === 3 && factors.every(value => Number.isFinite(value) && value !== 0) + : length > 0 && Number.isFinite(length) && Number.isFinite(angle))) { + for (const item of draftSelectedGeometry) { + const entries = draftPreviewSelection.filter(entry => entry.object === item.object); + const names = [...new Set(entries.flatMap(entry => entry.subElement ? [entry.subElement] : entry.subelements ?? []))]; + const paths = draftGroupArgs.subelements === true + ? names.flatMap(name => { + const match = /^(Edge|Vertex)([1-9][0-9]*)$/.exec(name); + if (!match) return []; + const index = Number(match[2]) - 1; + const path = match[1] === "Edge" ? item.edges[index] + : item.vertices?.[index] ? [item.vertices[index]] : undefined; + return path ? [path] : []; + }) : item.edges; + for (const edge of paths) { + draftPreviewPaths.push(edge.map(point => { + const delta = point.map((value, index) => value - center[index]); + if (draftViewportCommand === "Draft_Scale") + return delta.map((value, index) => center[index] + value * factors[index]); + const dot = delta.reduce((sum, value, index) => sum + value * normal[index], 0); + const cross = [normal[1] * delta[2] - normal[2] * delta[1], + normal[2] * delta[0] - normal[0] * delta[2], normal[0] * delta[1] - normal[1] * delta[0]]; + return delta.map((value, index) => center[index] + value * cosine + + cross[index] * sine + normal[index] * dot * (1 - cosine)); + })); + } + } + } + if (reference?.length === 3) draftPreviewPaths.push([center, reference]); + if (draftHoverPoint) draftPreviewPaths.push([center, draftHoverPoint]); + } + if (draftPrimitive && draftViewportCommand !== "Draft_Point" && draftTangentMode === "radius") { + const dimensions = draftGroupArgs.primitiveStage === 1 && draftHoverPoint ? primitiveDimensions(draftHoverPoint) : draftGroupArgs; + if (draftViewportCommand === "Draft_Rectangle") { + const x = Number(dimensions.length ?? 1), y = Number(dimensions.height ?? 1); + draftPreviewPaths.push([primitiveAt(0, 0), primitiveAt(x, 0), primitiveAt(x, y), primitiveAt(0, y), primitiveAt(0, 0)]); + } else { + const sides = Number(draftGroupArgs.sides ?? draftGroupArgs.faces ?? 3); + let radius = Number(dimensions.radius ?? 1) / (draftGroupArgs.inscribed === false ? Math.cos(Math.PI / sides) : 1); + let angle = Number(dimensions.rotation ?? 0) * Math.PI / 180; + if (Number.isInteger(sides) && sides >= 3 && sides <= 10000 && Number.isFinite(radius)) + draftPreviewPaths.push(Array.from({ length: sides + 1 }, (_, index) => primitiveAt(radius * Math.cos(angle + index * 2 * Math.PI / sides), radius * Math.sin(angle + index * 2 * Math.PI / sides)))); + } + } + if (["Draft_Line", "Draft_Wire"].includes(draftViewportCommand)) { + if (draftPoints.length > 1) draftPreviewPaths.push([...draftPoints, ...(draftGroupArgs.closed === true ? [draftPoints[0]] : [])]); + if (draftHoverPoint && draftPoints.length && draftGroupArgs.closed !== true && (draftViewportCommand === "Draft_Wire" || draftPoints.length < 2)) + draftPreviewPaths.push([draftPoints[draftPoints.length - 1], draftHoverPoint]); + } + if (draftViewportCommand === "Draft_Mirror" && draftMirrorStart && draftHoverPoint) + draftPreviewPaths.push([draftMirrorStart, draftHoverPoint]); + if (["Draft_Move", "Draft_Offset", "Draft_Mirror"].includes(draftViewportCommand)) { + const delta = draftViewportCommand === "Draft_Move" + ? (draftStart && draftHoverPoint ? draftHoverPoint.map((value, index) => value - draftStart[index]) : draftGroupArgs.delta as number[] | undefined) + : draftViewportCommand === "Draft_Offset" ? (draftHoverPoint && draftOffsetDelta(draftHoverPoint)) ?? draftGroupArgs.delta as number[] | undefined : undefined; + for (const item of draftSelectedGeometry) for (const edge of item.edges) { + if (draftViewportCommand === "Draft_Mirror" && draftMirrorStart && draftHoverPoint) { + const axis = [draftHoverPoint[0] - draftMirrorStart[0], draftHoverPoint[1] - draftMirrorStart[1]]; + const length = axis[0] ** 2 + axis[1] ** 2; + if (length > 1e-12) draftPreviewPaths.push(edge.map(point => { + const x = point[0] - draftMirrorStart[0], y = point[1] - draftMirrorStart[1]; + const projection = (x * axis[0] + y * axis[1]) / length; + return [draftMirrorStart[0] + 2 * projection * axis[0] - x, draftMirrorStart[1] + 2 * projection * axis[1] - y, point[2]]; + })); + } else if (delta?.length === 3) draftPreviewPaths.push(draftViewportCommand === "Draft_Offset" + ? draftOffsetPath(edge, delta) : edge.map(point => point.map((value, index) => value + delta[index]))); + } + } + const editStandardParameters = async (args: Record) => { + if (!standardCommandView || busy) return; + const view = standardCommandView; + setBusy(true); + try { + const result = ["Std_DlgParameter", "Std_DlgPreferences", "Std_DlgCustomize"].includes(view.command) + ? await executeOwnerStandard(router, view.command, { path: view.path, ...args, + runtimeOwner: view.runtimeOwner ?? "PartBox" }, view.documentId) + : await router.request("Web", "web.standardCommand", { + schema: "freecad-web/standard-command/v1", module, + command: view.command, args: { path: view.path, ...args }, + }, view.documentId); + if (!result) throw new Error("The parameter editor has no connected route"); + setResponse(result); + if (result.kind === "result") { + const batch = result.result as { records?: Array<{ name?: string; status?: string; + message?: string; result?: { path: string; groups: string[]; + parameters: Array<[string, string, unknown]>; fileName?: string; fileData?: string } }> }; + const record = batch.records?.find(item => item.name === view.command); + if (record?.status === "success" && record.result) { + setStandardCommandView({ ...view, ...record.result }); + if (typeof record.result.fileData === "string") { + const bytes = Uint8Array.from(atob(record.result.fileData), character => character.charCodeAt(0)); + const root = await navigator.storage.getDirectory(); + const directory = await root.getDirectoryHandle("freecad-parameters", { create: true }); + const fileName = `${view.command}${view.command === "Std_DlgParameter" ? `-${isFemParameterPath(view.path) ? "Fem-export" : view.runtimeOwner ?? "PartBox"}` : ""}.FCParam`; + const file = await directory.getFileHandle(fileName, { create: true }); + const writable = await file.createWritable(); + try { + await writable.write(bytes); + await writable.close(); + } catch (error) { + await writable.abort().catch(() => {}); + throw error; + } + const url = URL.createObjectURL(new Blob([bytes], { type: "application/xml" })); + const link = document.createElement("a"); + link.href = url; link.download = fileName; link.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); + setStatus(`Saved freecad-parameters/${fileName}`); + } else setStatus("Parameters updated"); + } else setStatus(record?.message ?? "Parameter operation failed"); + } else setStatus(JSON.stringify(result)); + } catch (error) { + setStatus(error instanceof Error ? error.message : String(error)); + } finally { setBusy(false); } + }; + const importStandardParameters = async (file: File) => { + try { + if (!file.size || file.size > 16 * 1024 * 1024) throw new Error("Parameter file must be between 1 byte and 16 MiB"); + const bytes = new Uint8Array(await file.arrayBuffer()); + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 8192) + binary += String.fromCharCode(...bytes.subarray(offset, offset + 8192)); + await editStandardParameters({ operation: "import", fileData: btoa(binary) }); + } catch (error) { setStatus(error instanceof Error ? error.message : String(error)); } + }; + if (sessionClosed) return
+

Workspace closed

+

Saved documents remain available in OPFS.

+ +
; + const structureCommand = command?.replace(/^(Web|Std):desktop:/, ""); + return
+ + + { + event.preventDefault(); if (workbenchSwitch.current) workbenchSwitch.current.cancelled = true; + }}> +

Switching workbenches · {module}

+ +
+ {startWorkspaceMounted &&