diff --git a/CHANGELOG.md b/CHANGELOG.md index 5e16f692..63c97138 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,7 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [2.0.0] - 2026-11-09 +## [2.0.0] - 2026-11-12 ### Added @@ -136,6 +136,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 reply carries a `warning` naming everything else it deleted (a sketch takes the features built from it). +- **The experimental tools' faults** (item 8 in the work queue): + - `pack_and_go_assembly` no longer closes every open document without + saving when the assembly can't be opened (it packs the open copy, or + fails and closes nothing), and no longer deletes everything already + in `target_dir`: with `overwrite` it replaces only the files it + writes, and `copied_files` lists only those. A preview that can't be + written gives a `warning`. On SolidWorks 2026, SolidWorks' own Pack and + Go listed and copied only the assembly, not its parts, and reported + success; the tool now copies the saved files `GetDependencies2` lists, + under their own names, and its `warning` names open files whose unsaved + changes aren't in the copy. The reply's `save_statuses` and + `all_files_saved` are replaced by `unsaved_changes`. + - `get_dimension` reports an angle in degrees (`units: "deg"`) and a + count with no unit; it used to multiply every value by 1000 and call + it mm. + - `open_model`, `load_part`, `load_assembly` and `list_configurations` + read the configuration's `Name`; they called a `GetName` method + SolidWorks doesn't have, so they always reported an assumed + "Default". A missing file is `not_found` before SolidWorks is asked. + - `generate_vba_code` writes a valid Sub name (returned as `sub_name`), + checks the active document's type, and prints with `Debug.Print` + instead of a `MsgBox` that blocked SolidWorks when the macro ran. + - `classify_feature_tree` fails when it can't read the model, instead + of classifying an empty one. On a part it no longer answers + "assembly" ("Material" contains "mate") or "sheet metal" (the tree's + folders contain "fold"); a known document type decides, and folders + aren't counted as features. + - `close_model` closes the document SolidWorks made active after the + last close; a second close in a row used to fail with "No active + model to close" while documents were still open. + - **`create_extrusion`'s reply says what was built** (#209): the end condition SolidWorks used (`MidPlane` for `both_directions`), and the thin wall. It used to echo `direction: blind`, so an agent concluded @@ -196,6 +227,26 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 inertia from `calculate_mass_properties` are a million times larger than before, because they are now in the kg·mm² their label always said. +- **BREAKING: more inputs that did nothing are refused** (item 8): + `compare_templates`' `comparison_type`, `comparison_depth`, + `include_properties`, `include_dimensions`, `include_materials` and + `generate_report` (it compares the two files only), and + `generate_vba_code`'s `parameters` and `code_style` (its reply loses + `style`). `pack_and_go_assembly` requires `source_path` and + `target_dir`, and `export_preview` is off by default, as its + description always said. `compare_drawing_versions` takes a typed + input. `get_dimension`'s angles and counts change value (see Fixed), + and `load_part` / `load_assembly` report `configuration: null` when + SolidWorks doesn't say. + +- **`generate_vba_code`'s macro opens with a `Sub main()`** that calls the + named Sub (`sub_name`). SolidWorks runs a `.swb` macro only through + `main`, so `execute_macro` runs it with no `proc_name`. +- **`comtypes` is no longer a dependency.** Pack and Go was its only user, + and it now copies the files `GetDependencies2` lists. +- **No tool is experimental any more**: the ten from item 8 passed live + tests on SolidWorks 2026 and are stable. + - **Building the API index needs SolidWorks installed, not running**, and never starts or calls SolidWorks. The lookups build the index themselves, and an index written by an older version is rebuilt automatically. Without diff --git a/docs/assets/progress/progress.json b/docs/assets/progress/progress.json index 3348beda..2bacb41f 100644 --- a/docs/assets/progress/progress.json +++ b/docs/assets/progress/progress.json @@ -2,9 +2,9 @@ "tools": { "total": 156, "by_level": { - "stable": 106, + "stable": 116, "beta": 0, - "experimental": 10, + "experimental": 0, "planned": 40 }, "list": [ @@ -305,8 +305,8 @@ { "name": "classify_feature_tree", "family": "file_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Classify the active model's kind (part, sheet metal, assembly, drawing and so on) from its feature tree, and suggest how to work on it." }, { @@ -319,15 +319,15 @@ { "name": "compare_drawing_versions", "family": "drawing_analysis", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Compare two drawing files on disk: whether they are byte-identical, and how their sizes differ." }, { "name": "compare_templates", "family": "template_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Compare two template files on disk: whether they are byte-identical, and how their sizes differ." }, { @@ -599,9 +599,9 @@ { "name": "generate_vba_code", "family": "automation", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", - "summary": "Write a VBA macro skeleton for an operation you describe: the SolidWorks connection, the active document and optional error handling, with the operation itself left as a TODO." + "level": "stable", + "reason": "", + "summary": "Write a VBA macro skeleton for an operation you describe: the SolidWorks connection, a check of the active document's type and optional error handling, with the operation itself left as a TODO." }, { "name": "generate_vba_drawing_dimensions", @@ -662,15 +662,15 @@ { "name": "get_dimension", "family": "modeling", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Read one dimension of the active model by its full name, e.g. \"D1@Sketch1\"." }, { "name": "get_file_properties", "family": "file_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes." }, { @@ -746,8 +746,8 @@ { "name": "list_configurations", "family": "file_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "List the names of the active model's configurations." }, { @@ -788,15 +788,15 @@ { "name": "load_assembly", "family": "file_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Open an assembly (.sldasm) from disk and make it the active document." }, { "name": "load_part", "family": "file_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", + "level": "stable", + "reason": "", "summary": "Open a part (.sldprt) from disk and make it the active document." }, { @@ -865,9 +865,9 @@ { "name": "pack_and_go_assembly", "family": "file_management", - "level": "experimental", - "reason": "not yet checked by a live test on real SolidWorks.", - "summary": "Copy an assembly and every part it references into one folder, with the references updated (SolidWorks Pack and Go)." + "level": "stable", + "reason": "", + "summary": "Copy an assembly and every file it uses into one folder that opens on its own." }, { "name": "pattern_circular", @@ -1105,11 +1105,11 @@ "com": { "type_library": "83A33D31-27C5-11CE-BFD4-00400513BB57x0x34x0", "core": { - "covered": 215, + "covered": 213, "total": 2838 }, "api": { - "covered": 238, + "covered": 233, "total": 5985 }, "interfaces": [ @@ -1117,7 +1117,6 @@ "name": "ISldWorks", "covered": [ "ActivateDoc3", - "CloseAllDocuments", "CloseDoc", "Frame", "GetConfigurationNames", @@ -1173,6 +1172,7 @@ "GetActiveConfiguration", "GetActiveSketch2", "GetConfigurationNames", + "GetDependencies2", "GetFeatureCount", "GetLineCount", "GetMassProperties", @@ -1222,7 +1222,6 @@ "DeleteSelection2", "GetAnnotations", "GetMassProperties", - "GetPackAndGo", "GetUserPreferenceInteger", "GetUserPreferenceToggle", "GetWhatsWrong", @@ -1231,7 +1230,6 @@ "SaveAs", "SaveAs2", "SaveAs3", - "SavePackAndGo", "SelectByID2", "SetUserPreferenceInteger", "SetUserPreferenceToggle" diff --git a/docs/assets/progress/progress.svg b/docs/assets/progress/progress.svg index 719305c0..12787b25 100644 --- a/docs/assets/progress/progress.svg +++ b/docs/assets/progress/progress.svg @@ -22,32 +22,32 @@ MCP tools: 156 -68% work on SolidWorks today +74% work on SolidWorks today - - - + + + -stable 106 +stable 116 beta 0 -experimental 10 - -planned 40 +experimental 0 + +planned 40 Core SolidWorks COM API (12 interfaces) -215 of 2,838 methods · 7.6% +213 of 2,838 methods · 7.5% - - - + + + -Whole API: 238 of 5,985 method names (4.0%), counted by a text scan of the adapters. +Whole API: 233 of 5,985 method names (3.9%), counted by a text scan of the adapters. diff --git a/docs/assets/progress/tables.html b/docs/assets/progress/tables.html index 054950f4..c1edd96d 100644 --- a/docs/assets/progress/tables.html +++ b/docs/assets/progress/tables.html @@ -44,10 +44,10 @@ check_drawing_standardsdrawingplanned
no adapter implements it yet.Check the active drawing against a drafting standard and score it. check_interferenceanalysisstableFind where the components of the active assembly overlap (Tools > Interference Detection). check_sketch_fully_definedsketchingstableCheck whether a sketch is fully defined, under-defined or over-defined. -classify_feature_treefile_managementexperimental
not yet checked by a live test on real SolidWorks.Classify the active model's kind (part, sheet metal, assembly, drawing and so on) from its feature tree, and suggest how to work on it. +classify_feature_treefile_managementstableClassify the active model's kind (part, sheet metal, assembly, drawing and so on) from its feature tree, and suggest how to work on it. close_modelmodelingstableClose the active document, saving it first only if asked. -compare_drawing_versionsdrawing_analysisexperimental
not yet checked by a live test on real SolidWorks.Compare two drawing files on disk: whether they are byte-identical, and how their sizes differ. -compare_templatestemplate_managementexperimental
not yet checked by a live test on real SolidWorks.Compare two template files on disk: whether they are byte-identical, and how their sizes differ. +compare_drawing_versionsdrawing_analysisstableCompare two drawing files on disk: whether they are byte-identical, and how their sizes differ. +compare_templatestemplate_managementstableCompare two template files on disk: whether they are byte-identical, and how their sizes differ. convert_file_formatfile_managementplanned
no adapter implements it yet.Convert a SolidWorks file on disk to another format without opening it first. create_assemblymodelingstableCreate a new, empty assembly document and make it active, ready for `insert_component`. create_axismodelingstableAdd a reference axis along the model's x, y or z direction, through the origin. @@ -86,7 +86,7 @@ generate_vba_assembly_insertvba_generationstableWrite a VBA macro that inserts a component into the active assembly at a point. generate_vba_assembly_matesvba_generationstableWrite a VBA macro that adds a concentric, distance, parallel, perpendicular or coincident mate between two selected faces or edges. generate_vba_batch_exportvba_generationstableWrite a VBA macro that opens every matching file in a folder and saves a STEP copy of each to another folder. -generate_vba_codeautomationexperimental
not yet checked by a live test on real SolidWorks.Write a VBA macro skeleton for an operation you describe: the SolidWorks connection, the active document and optional error handling, with the operation itself left as a TODO. +generate_vba_codeautomationstableWrite a VBA macro skeleton for an operation you describe: the SolidWorks connection, a check of the active document's type and optional error handling, with the operation itself left as a TODO. generate_vba_drawing_dimensionsvba_generationstableWrite a VBA macro that adds a dimension to the selected drawing entities and sets its precision. generate_vba_drawing_viewsvba_generationstableWrite a VBA macro that places a model's standard views (front, top, right) on the active drawing. generate_vba_extrusionvba_generationstableWrite a VBA macro that makes an extrusion with the full FeatureExtrusion options: both directions, draft, thin wall, end conditions. @@ -95,8 +95,8 @@ generate_vba_part_modelingvba_generationstableWrite a VBA macro for a shell or a fillet on the active part. generate_vba_revolvevba_generationstableWrite a VBA macro that revolves the selected sketch, with both-direction and thin-wall options. get_custom_propertiesengineering_datastableRead the active document's custom properties, such as PartNo, Description or Revision. -get_dimensionmodelingexperimental
not yet checked by a live test on real SolidWorks.Read one dimension of the active model by its full name, e.g. "D1@Sketch1". -get_file_propertiesfile_managementexperimental
not yet checked by a live test on real SolidWorks.Report the active document's file details: name, path, size, dates, type, configuration and unsaved changes. +get_dimensionmodelingstableRead one dimension of the active model by its full name, e.g. "D1@Sketch1". +get_file_propertiesfile_managementstableReport the active document's file details: name, path, size, dates, type, configuration and unsaved changes. get_mass_propertiesanalysisstableMeasure the active part or assembly's mass properties: volume, surface area, mass, centre of mass and moments of inertia. get_materialengineering_datastableReport the material assigned to the active part. get_material_propertiesanalysisplanned
no adapter implements it yet.Report the physical properties of the active part's material: density, modulus, Poisson's ratio, strength. @@ -107,14 +107,14 @@ insert_model_dimensionsdrawing_automationstableBring the model's dimensions into the active drawing's views, each dimension shown once. list_available_materialsengineering_datastableList the materials in the installed SolidWorks material libraries. list_componentsmodelingstableList the top-level components of the active assembly by instance name, e.g. "bracket-1". -list_configurationsfile_managementexperimental
not yet checked by a live test on real SolidWorks.List the names of the active model's configurations. +list_configurationsfile_managementstableList the names of the active model's configurations. list_drawing_viewsdrawingstableList the views on the active drawing, by name. list_featuresfile_managementstableList the feature tree of the active part or assembly, in order. list_model_dimensionsengineering_datastableList every dimension in the active part or assembly with its full name and value. list_open_documentsfile_managementstableList every document open in SolidWorks and say which one is active. list_template_librarytemplate_managementplanned
no adapter implements it yet.List the templates in the shared template library. -load_assemblyfile_managementexperimental
not yet checked by a live test on real SolidWorks.Open an assembly (.sldasm) from disk and make it the active document. -load_partfile_managementexperimental
not yet checked by a live test on real SolidWorks.Open a part (.sldprt) from disk and make it the active document. +load_assemblyfile_managementstableOpen an assembly (.sldasm) from disk and make it the active document. +load_partfile_managementstableOpen a part (.sldprt) from disk and make it the active document. lookup_api_interfacedocs_discoverystableList every method and property of a SolidWorks COM interface. lookup_api_methoddocs_discoverystableLook up one SolidWorks API method or property: parameters, return type, description. manage_design_tableautomationplanned
no adapter implements it yet.Create, read or update a design table (an Excel sheet that drives a model's configurations). @@ -124,7 +124,7 @@ open_modelmodelingstableOpen a part, assembly or drawing from disk and make it the active document. optimize_macromacro_recordingplanned
no adapter implements it yet.Suggest improvements to a macro's code for speed and reliability. optimize_performanceautomationplanned
no adapter implements it yet.Review SolidWorks' performance settings and apply faster ones. -pack_and_go_assemblyfile_managementexperimental
not yet checked by a live test on real SolidWorks.Copy an assembly and every part it references into one folder, with the references updated (SolidWorks Pack and Go). +pack_and_go_assemblyfile_managementstableCopy an assembly and every file it uses into one folder that opens on its own. pattern_circularmodelingstableRepeat features of the active part around an axis, e.g. a ring of bosses or ribs. rebuild_modelmodelingstableRebuild the active model and report each feature that fails, with the reason and a fix. rename_featuremodelingstableRename a feature in the active model's feature tree. @@ -166,9 +166,9 @@ - - - + + + diff --git a/docs/user-guide/tool-catalog/file-management.md b/docs/user-guide/tool-catalog/file-management.md index 4aa3d03d..073feb3d 100644 --- a/docs/user-guide/tool-catalog/file-management.md +++ b/docs/user-guide/tool-catalog/file-management.md @@ -301,28 +301,39 @@ Save the active assembly in place, or as a new .sldasm, optionally copying the p ### `pack_and_go_assembly` -Copy an assembly and every part it references into one folder, with the references updated (SolidWorks Pack and Go). +Copy an assembly and every file it uses into one folder that opens on its own. -The active assembly (or `source_path`) is opened, every referenced component is enumerated via the native SolidWorks IPackAndGo COM API, and all files are written into `target_dir` with internal paths rewritten so the copy opens without any dependency on the original file locations. +SolidWorks lists the files the assembly uses (`GetDependencies2`), and each is +copied into `target_dir` under its own name. The copy opens with its own parts, +because SolidWorks looks for a referenced file in the assembly's folder before +the path stored in the assembly. The files are copied as saved on disk: save +first, or the reply's `warning` names each open file whose unsaved changes the +copy doesn't have. No document is closed or changed. -**Prerequisite:** SolidWorks running with the assembly loaded (or openable). `target_dir` must be writable. +The call fails, and copies nothing, when a file the assembly uses is missing, +when two files share a name (renaming one would break the reference), or when +`target_dir` holds the originals. + +(SolidWorks' own Pack and Go, `IPackAndGo`, listed only the assembly on +SolidWorks 2026, so the tool no longer uses it.) + +**Prerequisite:** SolidWorks running, and the `.sldasm` on disk. **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| -| `source_path` | `str` | ✅ | | Absolute path to the source `.sldasm` file | -| `target_dir` | `str` | ✅ | | Directory where the assembly and all referenced parts will be copied | -| `export_preview` | `bool` | — | `True` | Export an isometric PNG preview next to the copied files | -| `overwrite` | `bool` | — | `False` | Overwrite files that already exist in `target_dir` | +| `source_path` | `str` | ✅ | | The source `.sldasm` file | +| `target_dir` | `str` | ✅ | | The folder to copy into; created if needed | +| `export_preview` | `bool` | — | `False` | Write an isometric PNG preview next to the copies | +| `overwrite` | `bool` | — | `False` | Allow a folder that already has files; only the copied files are replaced | **Sample call:** ```json { "source_path": "C:\\Projects\\robot_arm.sldasm", - "target_dir": "C:\\Exports\\robot_arm_pkg", - "export_preview": true + "target_dir": "C:\\Exports\\robot_arm_pkg" } ``` @@ -331,22 +342,14 @@ The active assembly (or `source_path`) is opened, every referenced component is | Field | Type | Description | |-------|------|-------------| | `status` | `str` | `"success"` or `"error"` | -| `file_path` | `str` | Path to the copied root assembly file | -| `copied_file_count` | `int` | Total number of files written | -| `copied_files` | `list[str]` | Absolute paths of every copied file | -| `all_files_saved` | `bool` | `true` when every per-file save status is `swPackAndGoSaveStatus_Ok` (0) | -| `save_status_warnings` | `list[str]` | Human-readable description of any non-zero per-file statuses (empty list on full success) | -| `preview_image` | `str?` | Path to the isometric PNG preview, or `null` if export was skipped or failed | - -**`swPackAndGoSaveStatus_e` reference** (values reported in `save_status_warnings`): - -| Code | Name | Meaning | -|------|------|---------| -| `0` | `Ok` | File was written successfully | -| `2` | `FileAlreadyExist` | Target file already existed and was not overwritten | -| `3` | `MissingSource` | Source reference file could not be found | - -All zeros in the per-file status array (`all_files_saved: true`) means SolidWorks confirmed every file was written successfully via its native Pack-and-Go engine. +| `method` | `str` | `"dependency_copy"` | +| `source_assembly` | `str` | The assembly packed | +| `target_dir` | `str` | The folder written | +| `copied_files` | `list[str]` | The files copied | +| `source_files` | `list[str]` | The assembly, then each file it uses | +| `unsaved_changes` | `list[str]` | Open files whose unsaved changes are not in the copy | +| `preview_image` | `str?` | The PNG preview, or `null` if it couldn't be written | +| `warning` | `str?` | Unsaved changes left out, or a preview that couldn't be written | --- diff --git a/openspec/changes/beta-tool-faults/.openspec.yaml b/openspec/changes/archive/2026-11-09-beta-tool-faults/.openspec.yaml similarity index 100% rename from openspec/changes/beta-tool-faults/.openspec.yaml rename to openspec/changes/archive/2026-11-09-beta-tool-faults/.openspec.yaml diff --git a/openspec/changes/beta-tool-faults/design.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/design.md similarity index 100% rename from openspec/changes/beta-tool-faults/design.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/design.md diff --git a/openspec/changes/beta-tool-faults/proposal.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/proposal.md similarity index 100% rename from openspec/changes/beta-tool-faults/proposal.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/proposal.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/document-creation/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/document-creation/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/document-creation/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/document-creation/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/extrusion/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/extrusion/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/extrusion/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/extrusion/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/feature-deletion/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/feature-deletion/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/feature-deletion/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/feature-deletion/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/feature-patterns/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/feature-patterns/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/feature-patterns/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/feature-patterns/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/file-saving/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/file-saving/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/file-saving/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/file-saving/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/input-contract/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/input-contract/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/input-contract/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/input-contract/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/macro-execution/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/macro-execution/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/macro-execution/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/macro-execution/spec.md diff --git a/openspec/changes/beta-tool-faults/specs/tools/mass-properties/spec.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/mass-properties/spec.md similarity index 100% rename from openspec/changes/beta-tool-faults/specs/tools/mass-properties/spec.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/specs/tools/mass-properties/spec.md diff --git a/openspec/changes/beta-tool-faults/tasks.md b/openspec/changes/archive/2026-11-09-beta-tool-faults/tasks.md similarity index 100% rename from openspec/changes/beta-tool-faults/tasks.md rename to openspec/changes/archive/2026-11-09-beta-tool-faults/tasks.md diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/.openspec.yaml b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/.openspec.yaml new file mode 100644 index 00000000..2b638f83 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/.openspec.yaml @@ -0,0 +1,2 @@ +schema: spec-driven +created: 2026-11-10 diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/design.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/design.md new file mode 100644 index 00000000..341d6e0d --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/design.md @@ -0,0 +1,183 @@ +## Context + +`support_levels.py` rates ten tools `experimental` ("not yet checked by a +live test on real SolidWorks"). Item 7 (`beta-tool-faults`, archived +2026-11-09) set the pattern this change follows: honour or refuse every +advertised input, prove each tool with a live test in `tests/live/`, then +promote it. That change also showed the live runs find faults the mock +can't: three of its fixes (renaming an open sketch, deleting a used sketch, +the inertia fallback) came from them. + +What reading the ten found, tool by tool: + +| Tool | Calls SolidWorks | Found by reading | +| --- | --- | --- | +| `pack_and_go_assembly` | yes (comtypes vtable) | `CloseAllDocuments(False)` when `OpenDoc6` fails; deletes all of `target_dir` before copying; input optional, so omitting it gives "not found: ."; preview failure is a silent `null` | +| `get_dimension` | yes | every value is `SystemValue × 1000` labelled mm, so an angle (radians) is wrong; the `GetValue3` fallback is in document units, also × 1000 | +| `generate_vba_code` | no | `parameters` and `code_style` do nothing; Sub name is the description with spaces replaced, so punctuation gives invalid VBA; `MsgBox` blocks SolidWorks when run; its description says `execute_macro` runs only `.swp`, untrue since 2.0.0; an `adapter.generate_vba_code` branch no adapter implements | +| `compare_templates` | no | six comparison switches do nothing; an `adapter.compare_templates` branch no adapter implements | +| `compare_drawing_versions` | no | takes a bare `dict`, not a typed input model | +| `classify_feature_tree` | yes (reads) | a failed `get_model_info` is ignored and an empty model is classified; `hasattr` branches every adapter satisfies | +| `load_part`, `load_assembly` | yes | the reply's `configuration` falls back to an assumed "Default" | +| `get_file_properties`, `list_configurations` | yes (reads) | nothing | + +## Goals / Non-Goals + +**Goals:** + +- Every one of the ten has a live test that proves what its description + says, and is `stable` when it passes. +- No tool can lose the user's work: Pack and Go never closes documents or + deletes files it didn't write. +- Every input is honoured or refused (the input contract from item 7). + +**Non-Goals:** + +- Comparing SolidWorks content (views, dimensions, template settings) in the + two compare tools. They compare files; a content diff is new work. +- Merging `load_part` / `load_assembly` into `open_model`. That is #174's job + (item 11); this change only makes them correct. +- The 40 `planned` tools (item 10). + +## Decisions + +### 1. Pack and Go uses the open document instead of closing everything + +When `OpenDoc6` returns no model, the adapter today calls +`CloseAllDocuments(False)` and retries, which throws away unsaved work in +every open document. Instead, the adapter first looks for the assembly +among the open documents (`ISldWorks.GetOpenDocumentByName` with the path) +and packs that. If it is neither openable nor open, the call fails with the +`OpenDoc6` error codes and closes nothing. Alternative considered: close +only the source assembly. Rejected: it still discards unsaved changes, and +the user didn't ask for anything to close. + +### 2. Overwrite replaces files, never the folder + +The adapter renames `target_dir` aside and deletes it before packing, so +`overwrite: true` on a folder holding anything else deletes it. The rename +and delete go. Pack and Go writes into the existing folder, and +`SavePackAndGo` replaces the files it writes. The tool keeps refusing a +non-empty folder without `overwrite`. Risk (batch 2): `SavePackAndGo` may +refuse to replace a file SolidWorks still holds open from an earlier pack; +the per-file save statuses already in the reply show it, and the live test +packs twice into one folder to find out. + +### 2a. Pack and Go copies the dependencies; SolidWorks' Pack and Go is dropped + +Live batch 2 on SolidWorks 2026: `IPackAndGo.GetDocumentNames` listed only +the assembly, not its two parts, and `SavePackAndGo` wrote only the +assembly while reporting every file saved; on a second pack it refused the +file already there (`swPackAndGoSaveStatus_FileAlreadyExist`). The project +had already removed `save_assembly`'s native Pack and Go for never working +on 2026 (dead-code item 13); its dependency copy is proven live. So the +adapter asks the open assembly for `GetDependencies2(True, True, False)` +and copies the assembly and each listed file into `target_dir` under its +own name. SolidWorks looks for a referenced file in the assembly's own +folder before the stored path, so the copy opens with its own parts (demo +7 proves it). The copy is of the saved files: an open dependency with +unsaved changes is named in a `warning`. A file-name clash between two +dependencies fails the call, since renaming one would break the reference. +The comtypes vtable bridge, used only by Pack and Go, goes. The dependency +parsing moves to `utils/sw_dependencies.py`, shared with `save_assembly`. +Alternative considered: probe why `GetDocumentNames` misses the parts. +Rejected: the outcome was unknown, and overwrite would still need us to +delete the old copies. + +### 3. A dimension's unit comes from its type + +The adapter reads `IDimension.GetType()` (`swDimensionParamType_e`, read +from swconst.tlb on 2026: 0 linear, 1 angular, 2 integer, -1 unknown) and +`SystemValue` (metres, radians, or a count). It returns `{value, units}`: +mm (× 1000), deg (radians to degrees), or the count with `units: None`. An +unknown type returns the system value with `units: None` rather than a +guess. The `GetValue3` fallback goes: it returns document units, which the +adapter can't convert without reading the document's unit system, and +`SystemValue` worked on every version measured. `base.py`'s `get_dimension` +return type changes from `float` to a dict; the tool already reads `value` +and `units` from a dict, so its reply shape is unchanged. + +### 4. Inputs that do nothing are refused, as in item 7 + +`compare_templates`' six switches and `generate_vba_code`'s `parameters` +and `code_style` go into `input_compat.REMOVED_INPUTS`, each with a pointer +sentence. The tool boundary refuses them with `invalid_input`. This is +breaking, so it goes in the CHANGELOG under **Changed**. + +### 5. The VBA skeleton is checked by running it + +`generate_vba_code` never calls SolidWorks, so a unit test can only check +the text. The live test saves the macro as a `.swb` file and runs it with +`execute_macro` (which runs text macros since 2.0.0): the run completing +proves the VBA parses and that nothing blocks. The Sub name keeps letters, +digits and underscores, starts with a letter (prefix `Macro_` otherwise) +and is cut to VBA's 255-character limit. A `Sub main()` calls it: on +SolidWorks 2026 a `.swb` macro runs only through `main` (live batch 3), and +`main` is `execute_macro`'s default. `MsgBox` becomes `Debug.Print`. +The type check compares `swModel.GetType` with `swDocPART` (1), +`swDocASSEMBLY` (2) or `swDocDRAWING` (3) as literal numbers, so the macro +needs no type-library reference. + +### 6. The compare tools stay file comparisons, said plainly + +They never call SolidWorks, and a content diff is a different tool. Each +gets a typed input model (`compare_drawing_versions` from its bare dict), a +`not_found` for a missing path, and its existing `note` saying only the +files were compared. The live test uses files SolidWorks wrote: its own +templates, and a drawing saved twice. The dead `adapter.compare_templates` +branch is deleted. + +### 7. Reads fail instead of guessing + +`classify_feature_tree` raises when it has to read the model and +`get_model_info` fails, the same way it already does for `list_features`. +`load_part` and `load_assembly` report the configuration from the adapter, +or `null`, never an assumed "Default". The `hasattr` checks every adapter +satisfies are deleted (coverage is honest, so dead branches go). + +### 8. Live batches + +One live test file, `tests/live/test_live_sw_experimental_tools.py`, run +one test per process with the user's permission: + +1. Reading: `get_file_properties`, `list_configurations` (a second + configuration added in the test through COM, as item 7's hidden-component + test did), `get_dimension` (a length and a revolve's angle), + `classify_feature_tree` (a part and an assembly). +2. Files: `load_part` and `load_assembly` (save, close, reload, wrong type + refused), `pack_and_go_assembly` (a two-part assembly, an unrelated file + kept, a second pack into the same folder, a part left dirty stays dirty). +3. Off-line tools on SolidWorks files: `compare_templates` (the installed + part and assembly templates), `compare_drawing_versions` (a drawing saved + before and after adding a view), `generate_vba_code` (generated, saved as + `.swb`, run on a part, then run on a drawing and stopping). + +## Risks / Trade-offs + +- [**The copy holds the saved files, not unsaved changes.**] Unlike + Pack and Go in the SolidWorks UI. The reply's `warning` names each open + dependency with unsaved changes, and the description says to save first. +- [**The copy's references still store the original paths.**] SolidWorks + finds the same-named file in the assembly's folder first, so it opens + from the copy (demo 7); a file-name clash fails instead of renaming. +- [**A saved drawing may differ byte-for-byte even when nothing changed**] + (SolidWorks stamps save times). The compare tools would then call two + equal drawings different. The live test records whether an unchanged + re-save is identical; if not, the description says a re-save alone makes + files differ. +- [**Breaking input removals right after 2.0.0.**] See Open Questions. + +## Migration Plan + +Removed inputs are listed in the CHANGELOG with what to use instead. No data +migration. Rollback is reverting the PR. + +## Open Questions + +None. **Version, settled 2026-11-10:** `v2.0.0` is not tagged (the last +release is `v1.5.0`), so this ships in 2.0.0 with item 7, and its breaking +items join the 2.0.0 CHANGELOG section under **Changed**. The maintainer +accepted the three refusals (`compare_templates`' switches, +`generate_vba_code`'s `parameters` and `code_style`, and +`classify_feature_tree` failing on an unreadable model) because none of them +worked before. `v2.0.0` is tagged after this merges. diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/proposal.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/proposal.md new file mode 100644 index 00000000..50d2c42b --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/proposal.md @@ -0,0 +1,101 @@ +## Why + +Ten of the 156 tools are rated experimental: they are implemented but have +never been run against real SolidWorks. Item 7 (`beta-tool-faults`, 2.0.0) +showed that a tool which passes in the mock can still be wrong on SolidWorks; +three of its fixes were found only by the live runs. Reading these ten for +this proposal found two faults of that kind before any live run: +`pack_and_go_assembly` can close every open document without saving and +delete the contents of the folder it writes to, and `get_dimension` reports +an angle as a length. Item 8 in `openspec/queue.md` (reliability before new +features, 2026-11-09) is to check each of the ten live and promote it, or +fix it, or record why it stays where it is. + +## What Changes + +The ten tools fall into four groups. + +**Faults found by reading the code (2 tools)** + +- `pack_and_go_assembly`: never closes the user's documents. When the + assembly is already open, Pack and Go uses the open copy instead of + `CloseAllDocuments(False)`, which discarded unsaved work. With + `overwrite`, it replaces only the files Pack and Go writes; it no longer + deletes everything already in `target_dir`. On SolidWorks 2026 the native + Pack and Go copied only the assembly (live batch 2), so the tool copies + the saved files `GetDependencies2` lists instead, and warns about unsaved + changes it can't copy. `source_path` and + `target_dir` become required (the input could be omitted, which turned + into a "not found: ." error). A preview that can't be written gives a + `warning` instead of a silent `null`. +- `get_dimension`: an angle dimension is reported in degrees with + `units: "deg"`, a length in mm, and a count with no unit, from the + dimension's own type (`IDimension.GetType`). The fallback that multiplied + a document-unit value by 1000 is removed. + +**Inputs that do nothing (2 tools)** + +- **BREAKING** `compare_templates`: its six comparison switches + (`comparison_type`, `comparison_depth`, `include_properties`, + `include_dimensions`, `include_materials`, `generate_report`) are refused, + as item 7 did for unused inputs; it compares the files, and says so. +- **BREAKING** `generate_vba_code`: `parameters` and `code_style` are + refused (neither shapes the code). `target_document` is honoured: the + macro stops when the active document is another type. The Sub name is + made a valid VBA name, and the macro reports through `Debug.Print` + instead of `MsgBox`, which would block SolidWorks when the macro runs. + +**Smaller corrections (4 tools)** + +- `compare_drawing_versions`: takes a typed input model like every other + tool, instead of a bare mapping. +- `classify_feature_tree`: fails when the model can't be read, instead of + classifying an empty model; dead `hasattr` branches go. +- `load_part` and `load_assembly`: report the configuration SolidWorks + opened, or `null`, instead of assuming "Default"; a missing file is + `not_found`. + +**Checked live and promoted as they are (2 tools)** + +- `get_file_properties` and `list_configurations`: no fault found in the + code; the live test decides. + +Each tool gets a live test in `tests/live/test_live_sw_experimental_tools.py`. +A tool that passes moves to `stable` in `support_levels.py`; one that fails +and can't be fixed in this change is recorded with its fault, at `beta`. + +## Capabilities + +### New Capabilities + +- `tools/pack-and-go`: copying an assembly with its parts, without closing + documents or deleting files that were already there. +- `tools/dimension-reading`: reading one dimension with the unit its type + gives it. +- `tools/file-comparison`: comparing two drawing or template files on disk, + and saying it compares the files only. +- `tools/vba-skeleton`: a macro skeleton that is valid VBA and runs without + blocking SolidWorks. +- `tools/document-inspection`: file properties, configurations, feature-tree + classification, and opening a part or assembly by type. + +### Modified Capabilities + +None. The input contract (refusing removed inputs) and the support levels +are reused unchanged. + +## Impact + +- **Tools:** `file_management.py`, `modeling.py` (`get_dimension`), + `template_management.py`, `drawing_analysis.py`, `automation.py`, and + `input_compat.REMOVED_INPUTS`. +- **COM and adapter code:** `adapters/solidworks/io.py` (Pack and Go and + `get_dimension`), `adapters/base.py` (the `get_dimension` return shape), + and `mock_adapter.py`. Pack and Go drops its comtypes vtable path for + `GetDependencies2` and a file copy, on the connect thread; `get_dimension` adds one late-bound call + (`IDimension.GetType`, flagged as a method). +- **Clients:** two breaking input removals (above). `get_dimension` replies + gain a real `units`, which is "deg" for an angle. +- **Docs:** each tool's description, the skill's errors-and-limits page if a + fault is recorded, the CHANGELOG, and the progress page. +- **Issue:** none filed; this is item 8 in `openspec/queue.md`. diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/dimension-reading/spec.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/dimension-reading/spec.md new file mode 100644 index 00000000..4156b5c8 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/dimension-reading/spec.md @@ -0,0 +1,22 @@ +## ADDED Requirements + +### Requirement: A dimension is read in the unit its type gives it + +`get_dimension` SHALL report a length dimension in millimetres with +`units: "mm"`, an angle dimension in degrees with `units: "deg"`, and a +count (such as a pattern's instance count) as a plain number with +`units: null`. The unit SHALL come from the dimension's own type, never be +assumed. A dimension whose value can't be read SHALL fail rather than return +a guessed number. + +#### Scenario: A length +- **WHEN** a part has a 10 mm extrusion and an agent reads `D1@Boss-Extrude1` +- **THEN** the reply's `dimension` is `value: 10.0`, `units: "mm"` + +#### Scenario: An angle +- **WHEN** a part has a revolve of 270° and an agent reads its angle dimension +- **THEN** the reply's `dimension` is `value: 270.0`, `units: "deg"` + +#### Scenario: A name that doesn't exist +- **WHEN** an agent reads `D9@Sketch1` on a part that has no such dimension +- **THEN** the call fails with `not_found`, and the message points to `list_model_dimensions` diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/document-inspection/spec.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/document-inspection/spec.md new file mode 100644 index 00000000..6564ba85 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/document-inspection/spec.md @@ -0,0 +1,50 @@ +## ADDED Requirements + +### Requirement: File properties describe the active document's file + +`get_file_properties` SHALL report the active document's file name, path, +size in bytes, created and modified times, type, active configuration and +whether it has unsaved changes. For a document never saved, the size and +times SHALL be `null`. + +#### Scenario: A saved part, then edited +- **WHEN** a part is saved and an agent reads its properties, then adds a feature and reads them again +- **THEN** the first reply has the saved path, a size above 0 and `is_dirty: false`, and the second has `is_dirty: true` + +### Requirement: Every configuration is listed + +`list_configurations` SHALL list the name of every configuration of the +active part or assembly. + +#### Scenario: A part with two configurations +- **WHEN** a part has the configurations "Default" and "Long" +- **THEN** the reply's `configurations` holds both names and `count` is 2 + +### Requirement: Classification fails when the model can't be read + +`classify_feature_tree` SHALL classify the model it reads, or the +`model_info` and `features` passed to it. When it must read the model and +can't, it SHALL fail, not classify an empty model. + +#### Scenario: A part and an assembly +- **WHEN** an agent classifies a plain extruded part, then an assembly +- **THEN** the first `family` is a part family and the second is the assembly family + +#### Scenario: Nothing is open +- **WHEN** no document is open and an agent classifies without passing `model_info` and `features` +- **THEN** the call fails with `no_active_document` + +### Requirement: Opening a part or assembly reports what SolidWorks opened + +`load_part` and `load_assembly` SHALL open the file, refusing a path of the +wrong type before calling SolidWorks, and SHALL report the configuration +SolidWorks opened, or `null` when it can't be read, never an assumed +"Default". A path that does not exist SHALL fail with `not_found`. + +#### Scenario: A saved part reopened +- **WHEN** a part is saved, closed, and loaded with `load_part` +- **THEN** it is the active document, and the reply's `path` is the file and `configuration` is the one SolidWorks reports + +#### Scenario: The wrong file type +- **WHEN** an agent calls `load_assembly` with a `.sldprt` path +- **THEN** the call fails with `invalid_input`, and nothing is opened diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/file-comparison/spec.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/file-comparison/spec.md new file mode 100644 index 00000000..8fd84cd8 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/file-comparison/spec.md @@ -0,0 +1,32 @@ +## ADDED Requirements + +### Requirement: Two files on disk are compared, and the reply says that is all + +`compare_drawing_versions` and `compare_templates` SHALL compare two files on +disk by content hash and size, and SHALL say in the reply that no SolidWorks +content (views, dimensions, properties) was compared. Each SHALL take a typed +input with both paths required. A path that does not exist SHALL fail with +`not_found`, naming it. + +#### Scenario: The same template twice +- **WHEN** an agent compares a SolidWorks part template with a copy of itself +- **THEN** `identical` is true and `size_delta_bytes` is 0 + +#### Scenario: Two different templates +- **WHEN** an agent compares the default part template with the default assembly template +- **THEN** `identical` is false, and `size_delta_bytes` is the second file's size minus the first's + +#### Scenario: Two saved versions of a drawing +- **WHEN** a drawing is saved, a view is added, and it is saved under a second name +- **THEN** `compare_drawing_versions` reports `identical: false` + +### Requirement: Comparison switches that did nothing are refused + +`compare_templates` SHALL refuse `comparison_type`, `comparison_depth`, +`include_properties`, `include_dimensions`, `include_materials` and +`generate_report` with `invalid_input`, as the input contract does for every +removed input. + +#### Scenario: An old caller sends a switch +- **WHEN** an agent calls `compare_templates` with `include_properties: true` +- **THEN** the call fails with `invalid_input`, and the message says the tool compares the files only diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/pack-and-go/spec.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/pack-and-go/spec.md new file mode 100644 index 00000000..92dea15c --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/pack-and-go/spec.md @@ -0,0 +1,68 @@ +## ADDED Requirements + +### Requirement: Pack and Go never closes the user's documents + +`pack_and_go_assembly` SHALL NOT close any open document. When the source +assembly is already open, it SHALL pack the open copy. Documents that were +open before the call SHALL still be open afterwards, with their unsaved +changes. + +#### Scenario: The assembly is already open with unsaved changes +- **WHEN** an assembly is open, a part it uses has unsaved changes, and an agent packs the assembly +- **THEN** the call succeeds, the part is still open and still shows unsaved changes, and every document open before the call is open after it + +### Requirement: Pack and Go copies the saved files SolidWorks lists + +`pack_and_go_assembly` SHALL copy the assembly and every file SolidWorks +lists as its dependency (`GetDependencies2`) into `target_dir`, each under +its own file name. It copies the files as saved on disk: when an open +document among them has unsaved changes, the reply SHALL carry a `warning` +naming it. Two dependencies with the same file name from different folders, +or a dependency missing on disk, SHALL fail the call before anything is +copied, naming the files. + +#### Scenario: A part has unsaved changes +- **WHEN** a part of the assembly has unsaved changes and an agent packs the assembly +- **THEN** the saved part is copied and the reply's `warning` names the part, saying its unsaved changes are not in the copy + +#### Scenario: A dependency is missing +- **WHEN** a file the assembly uses is not on disk +- **THEN** the call fails naming the file, and nothing is copied + +### Requirement: Pack and Go leaves other files in the target folder alone + +Without `overwrite`, a `target_dir` that already holds files SHALL be refused +before anything is written. With `overwrite`, only the files Pack and Go +writes SHALL be replaced; any other file in `target_dir` SHALL be left as it +was. + +#### Scenario: A folder with an unrelated file +- **WHEN** `target_dir` holds `notes.txt` and an agent packs an assembly into it with `overwrite: true` +- **THEN** the assembly and its parts are written, and `notes.txt` is unchanged + +#### Scenario: Packing twice into one folder +- **WHEN** an agent packs the same assembly into the same folder again, with `overwrite: true` +- **THEN** the call succeeds and replaces the files it wrote the first time + +#### Scenario: A folder with files, without overwrite +- **WHEN** `target_dir` holds any file and `overwrite` is off +- **THEN** the call fails with `invalid_input`, and nothing in the folder changes + +### Requirement: The packed assembly opens from its new folder + +The reply SHALL list `copied_files`, and every component of the packed +assembly SHALL resolve to a file inside `target_dir`. + +#### Scenario: A two-part assembly +- **WHEN** an assembly of two saved parts is packed into an empty folder +- **THEN** `copied_files` names the assembly and both parts, and opening the copied assembly loads both components from `target_dir` + +### Requirement: Pack and Go's inputs are required and its preview is reported + +`source_path` and `target_dir` SHALL be required. A `source_path` that does +not exist SHALL fail with `not_found`. When `export_preview` is on and the +preview can't be written, the reply SHALL carry a `warning` saying so. + +#### Scenario: The input is left out +- **WHEN** an agent calls `pack_and_go_assembly` with no input +- **THEN** the call fails with `invalid_input` naming `source_path` and `target_dir` diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/vba-skeleton/spec.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/vba-skeleton/spec.md new file mode 100644 index 00000000..6d74c766 --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/specs/tools/vba-skeleton/spec.md @@ -0,0 +1,35 @@ +## ADDED Requirements + +### Requirement: The generated macro is valid VBA that runs without blocking + +`generate_vba_code` SHALL return a macro whose Sub name is a valid VBA +identifier whatever `operation_description` says, and which reports through +`Debug.Print`, never a dialog. Run by `execute_macro` on the document type +`target_document` names, it SHALL complete without error and without +waiting on the user. + +#### Scenario: A description with punctuation +- **WHEN** an agent asks for a macro described as "Add 3 holes (M6), then save" +- **THEN** the Sub name contains only letters, digits and underscores and starts with a letter, and saved as a `.swb` file, `execute_macro` runs it on an open part and returns success + +#### Scenario: Run with execute_macro's default procedure +- **WHEN** the macro is saved as a `.swb` file and `execute_macro` is called with no `proc_name` +- **THEN** its `Sub main()` calls the named Sub, because SolidWorks runs a `.swb` macro only through `main`, and the run returns success + +### Requirement: The macro checks the document type it was written for + +The macro SHALL stop, printing why, when the active document is not the type +`target_document` names (Part, Assembly or Drawing). + +#### Scenario: A part macro run on a drawing +- **WHEN** a macro generated for `target_document: "Part"` runs while a drawing is active +- **THEN** it ends without changing the drawing + +### Requirement: Inputs that did nothing are refused + +`generate_vba_code` SHALL refuse `parameters` and `code_style` with +`invalid_input`. + +#### Scenario: An old caller sends a code style +- **WHEN** an agent calls `generate_vba_code` with `code_style: "advanced"` +- **THEN** the call fails with `invalid_input`, naming the `generate_vba_*` tools that write complete macros diff --git a/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/tasks.md b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/tasks.md new file mode 100644 index 00000000..1cb4cffe --- /dev/null +++ b/openspec/changes/archive/2026-11-12-experimental-tools-to-stable/tasks.md @@ -0,0 +1,85 @@ +## 1. Shared pieces + +- [x] 1.1 `input_compat.REMOVED_INPUTS`: `TemplateComparisonInput` (six switches) and `GenerateVBAInput` (`parameters`, `code_style`), each with a pointer sentence; tests that each is refused and that `operation_type` (an alias that is used) is still accepted +- [x] 1.2 `tests/live/test_live_sw_experimental_tools.py`: the tool registry helper and the scratch fixture, reused from `test_live_sw_beta_tools.py` where they fit + +## 2. Reading (live batch 1) + +- [x] 2.1 `get_dimension`: adapter returns `{value, units}` from `IDimension.GetType` (mm, deg, or `None` for a count or unknown type); remove the `GetValue3` fallback; `base.py` and the mock match; tests for a length, an angle, a count, an unknown type and an unreadable value +- [x] 2.2 `classify_feature_tree`: raise when `get_model_info` fails and the model must be read; delete the `hasattr` branches; tests +- [x] 2.3 `get_file_properties` and `list_configurations`: no code change expected; tests stay as they are +- [x] 2.4 Live batch 1: file properties (saved, then edited), two configurations, a length and a 270° revolve angle, a part and an assembly classified; run with the user's permission + +## 3. Files (live batch 2) + +- [x] 3.1 `load_part` and `load_assembly`: report the adapter's configuration or `null`; a missing file is `not_found`; tests +- [x] 3.2 `pack_and_go_assembly` adapter: use the open document when `OpenDoc6` returns none, never `CloseAllDocuments`; no rename-and-delete of `target_dir`; tests with a stubbed comtypes path +- [x] 3.3 `pack_and_go_assembly` tool: `PackAndGoInput` required; missing source `not_found`; a failed preview gives a `warning`; description says the copy holds what is open, saved or not; tests +- [x] 3.5 `pack_and_go_assembly` copies the saved files `GetDependencies2` lists (design 2a): shared parsing in `utils/sw_dependencies.py`, a `warning` for unsaved changes, a name clash or missing file fails; the comtypes bridge goes; tests +- [x] 3.4 Live batch 2: save, close and reload a part and an assembly, wrong types refused; pack a two-part assembly into a folder holding `notes.txt` (kept), pack again into the same folder, and pack while a part is dirty (still dirty after) + +## 4. Off-line tools on SolidWorks files (live batch 3) + +- [x] 4.1 `compare_templates`: delete the `adapter.compare_templates` branch; missing path `not_found`; description; tests +- [x] 4.2 `compare_drawing_versions`: a typed input model with both paths required; missing path `not_found`; tests +- [x] 4.3 `generate_vba_code`: valid Sub name, `Debug.Print` for `MsgBox`, the `target_document` type check, delete the adapter branch, fix the `.swp`-only sentence; tests for the name rules and each document type +- [x] 4.4 Live batch 3: the installed part template against itself and against the assembly template; a drawing saved before and after adding a view, and an unchanged re-save (record whether it is byte-identical); a generated macro run on a part, then on a drawing + +## 5. Promote and document + +- [x] 5.1 `support_levels.py`: each tool whose batch passed moves to `stable`; any that can't be fixed here goes to `beta` with its fault as the reason; `python -m solidworks_mcp.progress.generate` +- [x] 5.2 Each tool's description matches what it now does; the skill's `errors-and-limits.md` gains a row for any fault recorded +- [x] 5.3 CHANGELOG: **Fixed** (Pack and Go, angles), **Changed** (the removed inputs; `get_dimension` units) +- [x] 5.4 Full mock suite at 100% coverage, ruff, `mkdocs build --strict` +- [x] 5.5 Live-demo sign-off with the user before the PR; settle the version question in design.md + +## Notes from the implementation + +- `open_model` (stable) and `list_configurations` had the same fault as the + load tools: they called `IConfiguration.GetName()`, which doesn't exist + (the type library has only the `Name` property), so on SolidWorks the + call always failed and the reply fell back to "Default". Both now read + `Name`. `open_model` also checks the file exists before `OpenDoc6`, so a + missing file is `not_found` for all three open tools. +- `OpenDoc6`'s error 65536 is `swFileWithSameTitleAlreadyOpen`: another + document with the same file name is open. Pack and Go now says so and + closes nothing, where it used to close every document. +- `pack_and_go_assembly`'s `export_preview` defaulted to on, though its + description said off; it is now off. +- `classify_feature_tree` keeps `require_capability` for an adapter without + `get_model_info` or `list_features` (the house pattern), replacing the + `hasattr` branches. +- `generate_vba_code`'s macro is late-bound (`As Object`), so it runs as a + `.swb` text macro without a type-library reference; its reply gains + `sub_name`, the Sub that `Sub main()` calls. +- Live batch 1: `classify_feature_tree` called a plain extruded part an + assembly. Its assembly check matched "mate" anywhere in a feature name, + and every real part's tree has "Material ". The mock's + parts have no Material entry, so no unit test saw it. Now a known + document type (part, assembly, drawing) decides, feature names only + count when the type is unknown, and the mate check skips "material". +- The rerun then called the same part sheet metal: every real tree has + folders ("HistoryFolder", "SensorFolder", ...), and the sheet-metal word + "fold" is inside "folder". The classifier now skips rows whose type ends + in "Folder", and the live test expects `extrude`. +- Live batch 2: `close_model` (stable) only closed the document the + adapter tracked, and forgot it after closing. SolidWorks makes another + open document active, so a second close in a row failed with "No active + model to close". It now reads `ActiveDoc` first, as `list_features` does. +- Live batch 3: a drawing saved again with no change is not byte-identical + to the earlier save (SolidWorks 2026). `compare_drawing_versions` now says + that identical files mean nothing changed, but different files may not. +- Live batch 3: the generated macro failed on SolidWorks: `RunMacro2` + returned false with error 0 (no reason), on the part and the drawing. A + `.swb` macro ran in the beta batch, so `test_which_macro_text_runs_from_a_swb` + runs one-change variants of it to find the construct the `.swb` runner + rejects. Until that passes, `generate_vba_code` stays experimental; the + other nine tools are stable (5.1), and the skill's limits page has rows + for Pack and Go's saved files and drawing re-saves (5.2). +- The diagnostic answered it: every construct ran, but a `.swb` runs only + through a Sub named `main` (a lone `Sub Add_3_holes` failed; the generated + macro ran once its Sub was renamed `main`). The macro now opens with + `Sub main()` calling the named Sub, so `execute_macro` runs it with no + `proc_name`. +- Demo 10 rerun passed: the macro ran on the part and on the drawing, + which it left unchanged. `generate_vba_code` is stable. diff --git a/openspec/queue.md b/openspec/queue.md index c0c1c737..3b08306c 100644 --- a/openspec/queue.md +++ b/openspec/queue.md @@ -6,7 +6,7 @@ reviewed, then implemented, signed off live where it touches SolidWorks, and archived after its PR merges. Update this file when an item is done or the order changes. -Last updated 2026-11-09. +Last updated 2026-11-12. | # | Item | Issue | OpenSpec change | State | | --- | --- | --- | --- | --- | @@ -17,8 +17,8 @@ Last updated 2026-11-09. | 4 | Support levels for every tool, and COM coverage progress bars at the top of the README with an interactive docs page | #79 (coverage half) | `tool-support-levels-and-progress` (archived) | Done 2026-11-06 (#214). #79's licence-tier half is item 13 | | 5 | Tool gaps found building the U-joint: face mates, fixed parts and flexible sub-assemblies, angled planes, angled chamfers, `both_directions`, a stale interference result, thin extrudes | #209 | `ujoint-tool-gaps` (archived) | Done 2026-11-07 (#216), signed off live | | 6 | `--selftest` command and a compatibility-report issue template | #179 | `selftest-and-compatibility-report` (archived) | Done 2026-11-09 (#217), signed off live | -| 7 | Beta tools to stable: fix each beta tool's known fault (the small faults listed below), prove it live, and move it up a level | not filed yet | `beta-tool-faults` | Next, by request 2026-11-09: reliability before new features, moving up the support levels one at a time | -| 8 | Experimental tools to stable: a live test for each of the 10, then promote it or record its fault | not filed yet | not yet written | | +| 7 | Beta tools to stable: fix each beta tool's known fault (the small faults listed below), prove it live, and move it up a level | not filed yet | `beta-tool-faults` (archived) | Done 2026-11-09 (#219, 2.0.0): 23 tools promoted, signed off live | +| 8 | Experimental tools to stable: a live test for each of the 10, then promote it or record its fault | not filed yet | `experimental-tools-to-stable` (archived) | Done 2026-11-12 (2.0.0, tagged `v2.0.0`): all 10 promoted, signed off live. Pack and Go now copies the files `GetDependencies2` lists (SolidWorks 2026's own Pack and Go copied only the assembly); `comtypes` dropped | | 9 | Monitor stand demo follow-ups | #206 | not yet written | | | 10 | The 40 planned tools: implement each one or take it out of the tool list (listed below). A registered tool that can't run is a promise the server doesn't keep | not filed yet | not yet written | Check against #174 first, which may retire some as duplicates | | 11 | Clear out duplicate and overlapping tools: compare each cluster, keep one, settle a verb list, deprecate old names for one release | #174 | not yet written | | diff --git a/openspec/specs/tools/dimension-reading/spec.md b/openspec/specs/tools/dimension-reading/spec.md new file mode 100644 index 00000000..172fac8f --- /dev/null +++ b/openspec/specs/tools/dimension-reading/spec.md @@ -0,0 +1,27 @@ +# tools/dimension-reading Specification + +## Purpose +`get_dimension` reads a dimension's value in the unit its type gives it: millimetres for a length, degrees for an angle, and no unit for a count. + +## Requirements +### Requirement: A dimension is read in the unit its type gives it + +`get_dimension` SHALL report a length dimension in millimetres with +`units: "mm"`, an angle dimension in degrees with `units: "deg"`, and a +count (such as a pattern's instance count) as a plain number with +`units: null`. The unit SHALL come from the dimension's own type, never be +assumed. A dimension whose value can't be read SHALL fail rather than return +a guessed number. + +#### Scenario: A length +- **WHEN** a part has a 10 mm extrusion and an agent reads `D1@Boss-Extrude1` +- **THEN** the reply's `dimension` is `value: 10.0`, `units: "mm"` + +#### Scenario: An angle +- **WHEN** a part has a revolve of 270° and an agent reads its angle dimension +- **THEN** the reply's `dimension` is `value: 270.0`, `units: "deg"` + +#### Scenario: A name that doesn't exist +- **WHEN** an agent reads `D9@Sketch1` on a part that has no such dimension +- **THEN** the call fails with `not_found`, and the message points to `list_model_dimensions` + diff --git a/openspec/specs/tools/document-creation/spec.md b/openspec/specs/tools/document-creation/spec.md new file mode 100644 index 00000000..9e70a3d4 --- /dev/null +++ b/openspec/specs/tools/document-creation/spec.md @@ -0,0 +1,36 @@ +# tools/document-creation Specification + +## Purpose +What the document and sketch creation tools apply from their inputs, and the +names they report back. +## Requirements +### Requirement: A new part gets the material asked for + +`create_part` with `material` SHALL assign that material to the new part. When +the material isn't found, the part SHALL still be created, and the reply SHALL +say the material wasn't applied and which library was searched. + +#### Scenario: A known material +- **WHEN** an agent creates a part with `material: "AISI 304"` +- **THEN** reading the part's material afterwards returns AISI 304 + +#### Scenario: An unknown material +- **WHEN** an agent creates a part with `material: "Unobtainium"` +- **THEN** the part is created, and the reply carries a `warning` that the material wasn't found + +### Requirement: A new sketch has the name asked for + +`create_sketch` with `sketch_name` SHALL give the new sketch that name in the +feature tree when `exit_sketch` closes it, because SolidWorks won't rename an +open sketch. Every reply's sketch name SHALL be the name the feature tree shows +at that moment: `create_sketch` gives SolidWorks' name and the wanted one as +`name_on_exit`, and `exit_sketch` gives the final name. + +#### Scenario: A named sketch +- **WHEN** an agent creates a sketch with `sketch_name: "HoleProfile"`, draws in it and closes it with `exit_sketch` +- **THEN** the feature tree shows `HoleProfile`, `exit_sketch` replies with that name, and `create_cut_extrude` with `sketch_name: "HoleProfile"` uses it + +#### Scenario: A name already taken +- **WHEN** the requested name is already in the tree +- **THEN** the sketch keeps SolidWorks' own name, and `exit_sketch` replies with that name and a `warning` saying why + diff --git a/openspec/specs/tools/document-inspection/spec.md b/openspec/specs/tools/document-inspection/spec.md new file mode 100644 index 00000000..eaddb6c0 --- /dev/null +++ b/openspec/specs/tools/document-inspection/spec.md @@ -0,0 +1,55 @@ +# tools/document-inspection Specification + +## Purpose +The tools that read the active document (`get_file_properties`, `list_configurations`, `classify_feature_tree`, `load_part`, `load_assembly`) report what SolidWorks says, and fail plainly when they can't read it. + +## Requirements +### Requirement: File properties describe the active document's file + +`get_file_properties` SHALL report the active document's file name, path, +size in bytes, created and modified times, type, active configuration and +whether it has unsaved changes. For a document never saved, the size and +times SHALL be `null`. + +#### Scenario: A saved part, then edited +- **WHEN** a part is saved and an agent reads its properties, then adds a feature and reads them again +- **THEN** the first reply has the saved path, a size above 0 and `is_dirty: false`, and the second has `is_dirty: true` + +### Requirement: Every configuration is listed + +`list_configurations` SHALL list the name of every configuration of the +active part or assembly. + +#### Scenario: A part with two configurations +- **WHEN** a part has the configurations "Default" and "Long" +- **THEN** the reply's `configurations` holds both names and `count` is 2 + +### Requirement: Classification fails when the model can't be read + +`classify_feature_tree` SHALL classify the model it reads, or the +`model_info` and `features` passed to it. When it must read the model and +can't, it SHALL fail, not classify an empty model. + +#### Scenario: A part and an assembly +- **WHEN** an agent classifies a plain extruded part, then an assembly +- **THEN** the first `family` is a part family and the second is the assembly family + +#### Scenario: Nothing is open +- **WHEN** no document is open and an agent classifies without passing `model_info` and `features` +- **THEN** the call fails with `no_active_document` + +### Requirement: Opening a part or assembly reports what SolidWorks opened + +`load_part` and `load_assembly` SHALL open the file, refusing a path of the +wrong type before calling SolidWorks, and SHALL report the configuration +SolidWorks opened, or `null` when it can't be read, never an assumed +"Default". A path that does not exist SHALL fail with `not_found`. + +#### Scenario: A saved part reopened +- **WHEN** a part is saved, closed, and loaded with `load_part` +- **THEN** it is the active document, and the reply's `path` is the file and `configuration` is the one SolidWorks reports + +#### Scenario: The wrong file type +- **WHEN** an agent calls `load_assembly` with a `.sldprt` path +- **THEN** the call fails with `invalid_input`, and nothing is opened + diff --git a/openspec/specs/tools/extrusion/spec.md b/openspec/specs/tools/extrusion/spec.md index c1520898..ada5a7a3 100644 --- a/openspec/specs/tools/extrusion/spec.md +++ b/openspec/specs/tools/extrusion/spec.md @@ -19,3 +19,29 @@ TBD - created by archiving change ujoint-tool-gaps. Update Purpose after archive - **WHEN** an agent extrudes an open L-shaped chain 38.1 mm with a 6.35 mm thin wall - **THEN** one solid body is made whose volume is the chain's length times 6.35 times 38.1 mm, within 1 % +### Requirement: The named sketch is the one used + +`create_extrusion` and `create_revolve` SHALL use the sketch `sketch_name` +names, found in the feature tree without regard to case. When the name matches +no sketch, the call SHALL fail before anything is built, and the message SHALL +list the sketches that exist. When `sketch_name` is empty, they SHALL use the +sketch the session closed last, as `create_cut_extrude` does. + +#### Scenario: Extruding an earlier sketch +- **WHEN** a part has `Sketch1` (a 20 mm square) and `Sketch2` (a Ø10 circle), both closed, and an agent extrudes `sketch_name: "Sketch1"` 5 mm +- **THEN** the new body is 20 × 20 × 5 mm, 2,000 mm³ + +#### Scenario: A sketch that doesn't exist +- **WHEN** an agent extrudes `sketch_name: "Sketch9"` +- **THEN** the call fails, naming `Sketch1` and `Sketch2`, and the feature tree is unchanged + +### Requirement: The revolve axis can be a reference axis + +`create_revolve` with `axis_entity` naming a reference axis SHALL revolve about +that axis. Without `axis_entity`, it SHALL revolve about the centreline drawn +in the sketch. + +#### Scenario: Revolving about Axis1 +- **WHEN** a sketch holds a 10 × 20 mm rectangle 5 mm from `Axis1`, with no centreline, and an agent revolves it 360° about `axis_entity: "Axis1"` +- **THEN** the body is a tube with volume π·(15² − 5²)·20 = 12,566.4 mm³ within 0.1 % + diff --git a/openspec/specs/tools/feature-deletion/spec.md b/openspec/specs/tools/feature-deletion/spec.md new file mode 100644 index 00000000..3b096a3a --- /dev/null +++ b/openspec/specs/tools/feature-deletion/spec.md @@ -0,0 +1,16 @@ +# tools/feature-deletion Specification + +## Purpose +What `delete_feature` reports, so an agent knows every feature that went, +including the dependent features SolidWorks removed along with the named one. +## Requirements +### Requirement: The reply names every feature removed + +`delete_feature` SHALL return `removed_features`, the names of every feature +that was in the tree before the call and isn't after it. Its message SHALL +name the dependent features too. + +#### Scenario: Deleting a sketch that a feature uses +- **WHEN** an agent deletes `Sketch2`, which `Cut-Extrude1` was built from +- **THEN** `removed_features` lists both `Sketch2` and `Cut-Extrude1`, and the message says the cut went with it + diff --git a/openspec/specs/tools/feature-patterns/spec.md b/openspec/specs/tools/feature-patterns/spec.md new file mode 100644 index 00000000..39eccff0 --- /dev/null +++ b/openspec/specs/tools/feature-patterns/spec.md @@ -0,0 +1,24 @@ +# tools/feature-patterns Specification + +## Purpose +When `pattern_circular` and `mirror_feature` count as having worked, for +features that add material and features that remove it. +## Requirements +### Requirement: A pattern or mirror succeeds when the volume changes + +`pattern_circular` and `mirror_feature` SHALL succeed when the part's volume +changes, up or down, and SHALL fail when it doesn't change. The reply SHALL +include the volume before and after. + +#### Scenario: A ring of holes +- **WHEN** an agent patterns a Ø6 mm through-hole in a 10 mm plate 6 times around an axis, with every instance on the plate +- **THEN** the call succeeds and the volume falls by 5 × π·3²·10 = 1,413.7 mm³ within 0.1 % + +#### Scenario: A mirrored cut +- **WHEN** an agent mirrors a cut about a plane, and the mirrored cut lands on the body +- **THEN** the call succeeds and the volume falls by the cut's volume + +#### Scenario: Nothing patterned +- **WHEN** a pattern's instances all land off the body, so the volume is unchanged +- **THEN** the call fails and says the pattern produced no geometry + diff --git a/openspec/specs/tools/file-comparison/spec.md b/openspec/specs/tools/file-comparison/spec.md new file mode 100644 index 00000000..3cecafda --- /dev/null +++ b/openspec/specs/tools/file-comparison/spec.md @@ -0,0 +1,37 @@ +# tools/file-comparison Specification + +## Purpose +`compare_templates` and `compare_drawing_versions` compare two files on disk, and their replies say that a byte comparison is all they do. + +## Requirements +### Requirement: Two files on disk are compared, and the reply says that is all + +`compare_drawing_versions` and `compare_templates` SHALL compare two files on +disk by content hash and size, and SHALL say in the reply that no SolidWorks +content (views, dimensions, properties) was compared. Each SHALL take a typed +input with both paths required. A path that does not exist SHALL fail with +`not_found`, naming it. + +#### Scenario: The same template twice +- **WHEN** an agent compares a SolidWorks part template with a copy of itself +- **THEN** `identical` is true and `size_delta_bytes` is 0 + +#### Scenario: Two different templates +- **WHEN** an agent compares the default part template with the default assembly template +- **THEN** `identical` is false, and `size_delta_bytes` is the second file's size minus the first's + +#### Scenario: Two saved versions of a drawing +- **WHEN** a drawing is saved, a view is added, and it is saved under a second name +- **THEN** `compare_drawing_versions` reports `identical: false` + +### Requirement: Comparison switches that did nothing are refused + +`compare_templates` SHALL refuse `comparison_type`, `comparison_depth`, +`include_properties`, `include_dimensions`, `include_materials` and +`generate_report` with `invalid_input`, as the input contract does for every +removed input. + +#### Scenario: An old caller sends a switch +- **WHEN** an agent calls `compare_templates` with `include_properties: true` +- **THEN** the call fails with `invalid_input`, and the message says the tool compares the files only + diff --git a/openspec/specs/tools/file-saving/spec.md b/openspec/specs/tools/file-saving/spec.md new file mode 100644 index 00000000..e8d29fd4 --- /dev/null +++ b/openspec/specs/tools/file-saving/spec.md @@ -0,0 +1,19 @@ +# tools/file-saving Specification + +## Purpose +How `save_as` treats a file that already exists at the target path. +## Requirements +### Requirement: save_as keeps an existing file unless told to overwrite + +`save_as` SHALL refuse to write when a file already exists at `file_path` and +`overwrite` is off, and SHALL leave that file untouched. With `overwrite` on, it +SHALL replace the file. + +#### Scenario: The file exists and overwrite is off +- **WHEN** an agent saves the active part as a path that already holds a file +- **THEN** the reply is an `invalid_input` error naming the path and `overwrite`, and the file's contents and modified time are unchanged + +#### Scenario: Overwrite is on +- **WHEN** the same call has `overwrite: true` +- **THEN** the file is replaced and the call succeeds + diff --git a/openspec/specs/tools/input-contract/spec.md b/openspec/specs/tools/input-contract/spec.md new file mode 100644 index 00000000..b5c8495b --- /dev/null +++ b/openspec/specs/tools/input-contract/spec.md @@ -0,0 +1,77 @@ +# tools/input-contract Specification + +## Purpose +A tool's input schema is a promise: every field it advertises changes what the +tool does, and an input the tool no longer takes is refused, not ignored. +## Requirements +### Requirement: Advertised inputs are honoured + +Every field in a stable tool's input schema SHALL change what the tool does or +what it reports. A tool SHALL NOT echo back an input it didn't apply. + +#### Scenario: An input the tool applies +- **WHEN** an agent calls `create_part` with `material: "AISI 304"` +- **THEN** the new part's material is AISI 304, and the reply says so + +#### Scenario: No echo of an unapplied input +- **WHEN** a tool's reply names a value the agent passed +- **THEN** that value is what SolidWorks now holds, not only what was asked for + +### Requirement: Removed inputs are refused with a pointer + +When a call sends an input the tool no longer takes, the tool SHALL return +`status: "error"` with `error_type: "invalid_input"` before anything changes in +SolidWorks. The message SHALL name the input and say which tool or input to use +instead. The removed inputs are: + +- `create_extrusion.direction` → `end_condition` +- `create_revolve.direction` → `both_directions` +- `create_assembly.components` → `insert_component` +- `create_drawing.model_path` and `create_drawing.sheet_format` → + `create_drawing_view` or `generate_drawing_package` +- `create_technical_drawing.template`, `.sheet_size`, `.title` and + `.output_path` → `generate_drawing_package` +- `save_file.force_save` → none: the tool always saves +- `check_interference.tolerance` and `.check_all_components` → none: the + check has no tolerance and always covers the whole assembly, or the + `components` given +- `export_step.options`, `export_iges.options`, `export_stl.options`, + `export_pdf.options` and `export_dwg.options` → the file extension +- `calculate_mass_properties.model_path`, `.units`, `.include_hidden` and + `.reference_coordinate_system` → open and activate the model first + +#### Scenario: A removed input is sent +- **WHEN** an agent calls `create_assembly` with `components: ["a.sldprt"]` +- **THEN** the reply is an `invalid_input` error naming `components` and `insert_component`, and no assembly is created + +#### Scenario: An operation the tool doesn't do +- **WHEN** an agent calls `add_drawing_view` with `operation: "remove"` +- **THEN** the reply is an `invalid_input` error saying the tool only adds views, and the drawing is unchanged + +### Requirement: Interference checks follow include_hidden + +`check_interference` SHALL leave hidden components out of the check unless +`include_hidden` is on. + +#### Scenario: A hidden component overlaps +- **WHEN** two components overlap and one is hidden +- **THEN** the check finds no interference by default, and finds one with `include_hidden: true` + +### Requirement: get_material reports the density + +`get_material` SHALL return the active part's material density in kg/m³ beside +its name and library, or `null` when no material is assigned. + +#### Scenario: A steel part +- **WHEN** an agent reads the material of a part assigned AISI 304 +- **THEN** the reply gives the name AISI 304 and the density SolidWorks holds for it, 8,000 kg/m³ + +### Requirement: The hole tutorial teaches the cut tool + +`sketch_tutorial_simple_hole` SHALL tell the agent to make the hole with +`create_cut_extrude`, never with a negative-depth extrusion. + +#### Scenario: Reading the tutorial +- **WHEN** an agent calls `sketch_tutorial_simple_hole` +- **THEN** its steps call `create_cut_extrude` for the hole and none passes a negative `depth` + diff --git a/openspec/specs/tools/macro-execution/spec.md b/openspec/specs/tools/macro-execution/spec.md new file mode 100644 index 00000000..0c9d77d9 --- /dev/null +++ b/openspec/specs/tools/macro-execution/spec.md @@ -0,0 +1,21 @@ +# tools/macro-execution Specification + +## Purpose +How many times `execute_macro` runs a macro, and what its reply says about the +runs. +## Requirements +### Requirement: A macro runs repeat_count times + +`execute_macro` SHALL run the macro `repeat_count` times, waiting +`pause_between_runs` seconds between runs. It SHALL stop at the first run that +fails. The reply SHALL give the number of runs that completed, and the message +SHALL state that number, not the number asked for. + +#### Scenario: Three runs +- **WHEN** an agent runs a macro that adds one feature with `repeat_count: 3` +- **THEN** three features are added and the reply says 3 runs completed + +#### Scenario: A run fails part way +- **WHEN** the second of three runs fails +- **THEN** the reply is an error saying 1 run completed and the second failed, and no third run is attempted + diff --git a/openspec/specs/tools/mass-properties/spec.md b/openspec/specs/tools/mass-properties/spec.md new file mode 100644 index 00000000..1c82d7bd --- /dev/null +++ b/openspec/specs/tools/mass-properties/spec.md @@ -0,0 +1,16 @@ +# tools/mass-properties Specification + +## Purpose +The units and values `calculate_mass_properties` and `get_mass_properties` +report, so every number matches the unit printed beside it. +## Requirements +### Requirement: Moments of inertia in kg·mm² + +`calculate_mass_properties` SHALL report the moments and products of inertia +in kg·mm², labelled `kg·mm²`, matching the millimetres used for the centre of +mass. + +#### Scenario: A steel block +- **WHEN** an agent measures a 100 × 50 × 20 mm block of material with density 7,800 kg/m³ (mass 0.78 kg), about its centre of mass +- **THEN** `Ixx`, `Iyy` and `Izz` match m·(b² + c²)/12 for each axis in kg·mm² within 0.1 %, for example m·(50² + 20²)/12 = 188.5 kg·mm² about the 100 mm axis + diff --git a/openspec/specs/tools/pack-and-go/spec.md b/openspec/specs/tools/pack-and-go/spec.md new file mode 100644 index 00000000..84b0a063 --- /dev/null +++ b/openspec/specs/tools/pack-and-go/spec.md @@ -0,0 +1,73 @@ +# tools/pack-and-go Specification + +## Purpose +`pack_and_go_assembly` copies an assembly and every file it uses into one folder that opens on its own, without closing or changing the user's documents, and says when the copy leaves out unsaved changes. + +## Requirements +### Requirement: Pack and Go never closes the user's documents + +`pack_and_go_assembly` SHALL NOT close any open document. When the source +assembly is already open, it SHALL pack the open copy. Documents that were +open before the call SHALL still be open afterwards, with their unsaved +changes. + +#### Scenario: The assembly is already open with unsaved changes +- **WHEN** an assembly is open, a part it uses has unsaved changes, and an agent packs the assembly +- **THEN** the call succeeds, the part is still open and still shows unsaved changes, and every document open before the call is open after it + +### Requirement: Pack and Go copies the saved files SolidWorks lists + +`pack_and_go_assembly` SHALL copy the assembly and every file SolidWorks +lists as its dependency (`GetDependencies2`) into `target_dir`, each under +its own file name. It copies the files as saved on disk: when an open +document among them has unsaved changes, the reply SHALL carry a `warning` +naming it. Two dependencies with the same file name from different folders, +or a dependency missing on disk, SHALL fail the call before anything is +copied, naming the files. + +#### Scenario: A part has unsaved changes +- **WHEN** a part of the assembly has unsaved changes and an agent packs the assembly +- **THEN** the saved part is copied and the reply's `warning` names the part, saying its unsaved changes are not in the copy + +#### Scenario: A dependency is missing +- **WHEN** a file the assembly uses is not on disk +- **THEN** the call fails naming the file, and nothing is copied + +### Requirement: Pack and Go leaves other files in the target folder alone + +Without `overwrite`, a `target_dir` that already holds files SHALL be refused +before anything is written. With `overwrite`, only the files Pack and Go +writes SHALL be replaced; any other file in `target_dir` SHALL be left as it +was. + +#### Scenario: A folder with an unrelated file +- **WHEN** `target_dir` holds `notes.txt` and an agent packs an assembly into it with `overwrite: true` +- **THEN** the assembly and its parts are written, and `notes.txt` is unchanged + +#### Scenario: Packing twice into one folder +- **WHEN** an agent packs the same assembly into the same folder again, with `overwrite: true` +- **THEN** the call succeeds and replaces the files it wrote the first time + +#### Scenario: A folder with files, without overwrite +- **WHEN** `target_dir` holds any file and `overwrite` is off +- **THEN** the call fails with `invalid_input`, and nothing in the folder changes + +### Requirement: The packed assembly opens from its new folder + +The reply SHALL list `copied_files`, and every component of the packed +assembly SHALL resolve to a file inside `target_dir`. + +#### Scenario: A two-part assembly +- **WHEN** an assembly of two saved parts is packed into an empty folder +- **THEN** `copied_files` names the assembly and both parts, and opening the copied assembly loads both components from `target_dir` + +### Requirement: Pack and Go's inputs are required and its preview is reported + +`source_path` and `target_dir` SHALL be required. A `source_path` that does +not exist SHALL fail with `not_found`. When `export_preview` is on and the +preview can't be written, the reply SHALL carry a `warning` saying so. + +#### Scenario: The input is left out +- **WHEN** an agent calls `pack_and_go_assembly` with no input +- **THEN** the call fails with `invalid_input` naming `source_path` and `target_dir` + diff --git a/openspec/specs/tools/vba-skeleton/spec.md b/openspec/specs/tools/vba-skeleton/spec.md new file mode 100644 index 00000000..a6d81a87 --- /dev/null +++ b/openspec/specs/tools/vba-skeleton/spec.md @@ -0,0 +1,40 @@ +# tools/vba-skeleton Specification + +## Purpose +`generate_vba_code` writes a macro skeleton that is valid VBA, runs through `execute_macro` without waiting on a dialog, and stops on a document of the wrong type. + +## Requirements +### Requirement: The generated macro is valid VBA that runs without blocking + +`generate_vba_code` SHALL return a macro whose Sub name is a valid VBA +identifier whatever `operation_description` says, and which reports through +`Debug.Print`, never a dialog. Run by `execute_macro` on the document type +`target_document` names, it SHALL complete without error and without +waiting on the user. + +#### Scenario: A description with punctuation +- **WHEN** an agent asks for a macro described as "Add 3 holes (M6), then save" +- **THEN** the Sub name contains only letters, digits and underscores and starts with a letter, and saved as a `.swb` file, `execute_macro` runs it on an open part and returns success + +#### Scenario: Run with execute_macro's default procedure +- **WHEN** the macro is saved as a `.swb` file and `execute_macro` is called with no `proc_name` +- **THEN** its `Sub main()` calls the named Sub, because SolidWorks runs a `.swb` macro only through `main`, and the run returns success + +### Requirement: The macro checks the document type it was written for + +The macro SHALL stop, printing why, when the active document is not the type +`target_document` names (Part, Assembly or Drawing). + +#### Scenario: A part macro run on a drawing +- **WHEN** a macro generated for `target_document: "Part"` runs while a drawing is active +- **THEN** it ends without changing the drawing + +### Requirement: Inputs that did nothing are refused + +`generate_vba_code` SHALL refuse `parameters` and `code_style` with +`invalid_input`. + +#### Scenario: An old caller sends a code style +- **WHEN** an agent calls `generate_vba_code` with `code_style: "advanced"` +- **THEN** the call fails with `invalid_input`, naming the `generate_vba_*` tools that write complete macros + diff --git a/pyproject.toml b/pyproject.toml index 8bc0c9c7..9d5006b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -38,7 +38,6 @@ dependencies = [ "chardet<6", "pywin32>=306; platform_system=='Windows'", "pywin32-ctypes>=0.2.0; platform_system=='Windows'", - "comtypes>=1.4.0; platform_system=='Windows'", "loguru>=0.7.0", "typing-extensions>=4.8.0", "httpx>=0.24.0", diff --git a/solidworks_mcp.yml b/solidworks_mcp.yml index a402a029..d188fbcd 100644 --- a/solidworks_mcp.yml +++ b/solidworks_mcp.yml @@ -16,7 +16,6 @@ dependencies: - typing-extensions>=4.8.0 # SolidWorks COM interface (Windows only) - - comtypes>=1.4.0 ; sys_platform=="win32" - pywin32>=306 ; sys_platform=="win32" # Development dependencies diff --git a/src/solidworks_mcp/adapters/base.py b/src/solidworks_mcp/adapters/base.py index e3b0ae0b..594d5b1f 100644 --- a/src/solidworks_mcp/adapters/base.py +++ b/src/solidworks_mcp/adapters/base.py @@ -1661,14 +1661,14 @@ async def export_file( # Dimension Operations @abstractmethod - async def get_dimension(self, name: str) -> AdapterResult[float]: + async def get_dimension(self, name: str) -> AdapterResult[dict[str, Any]]: """Get the value of a dimension. Args: name (str): The name value. Returns: - AdapterResult[float]: The result produced by the operation. + AdapterResult[dict[str, Any]]: ``value`` and ``units`` (mm, deg or None). """ pass diff --git a/src/solidworks_mcp/adapters/circuit_breaker.py b/src/solidworks_mcp/adapters/circuit_breaker.py index e286005e..0a6d3de8 100644 --- a/src/solidworks_mcp/adapters/circuit_breaker.py +++ b/src/solidworks_mcp/adapters/circuit_breaker.py @@ -1325,14 +1325,14 @@ async def export_file( # Dimension operations - async def get_dimension(self, name: str) -> AdapterResult[float]: + async def get_dimension(self, name: str) -> AdapterResult[dict[str, Any]]: """Get dimension through circuit breaker. Args: name (str): The name value. Returns: - AdapterResult[float]: The result produced by the operation. + AdapterResult[dict[str, Any]]: ``value`` and ``units`` (mm, deg or None). """ return await self._execute_with_circuit_breaker( "get_dimension", diff --git a/src/solidworks_mcp/adapters/connection_pool.py b/src/solidworks_mcp/adapters/connection_pool.py index 1a97d06e..4d8b9793 100644 --- a/src/solidworks_mcp/adapters/connection_pool.py +++ b/src/solidworks_mcp/adapters/connection_pool.py @@ -1245,14 +1245,14 @@ async def export_file( # Dimension operations - async def get_dimension(self, name: str) -> AdapterResult[float]: + async def get_dimension(self, name: str) -> AdapterResult[dict[str, Any]]: """Get dimension using pool. Args: name (str): The name value. Returns: - AdapterResult[float]: The result produced by the operation. + AdapterResult[dict[str, Any]]: ``value`` and ``units`` (mm, deg or None). """ return await self._execute_with_pool( "get_dimension", lambda adapter: adapter.get_dimension(name) diff --git a/src/solidworks_mcp/adapters/mock_adapter.py b/src/solidworks_mcp/adapters/mock_adapter.py index f3749db9..bea80829 100644 --- a/src/solidworks_mcp/adapters/mock_adapter.py +++ b/src/solidworks_mcp/adapters/mock_adapter.py @@ -2301,8 +2301,7 @@ async def pack_and_go_assembly( "target_dir": str(out_dir), "copied_files": copied_files, "source_files": source_files, - "save_statuses": [0] * (len(mock_parts) + 1), - "all_files_saved": True, + "unsaved_changes": [], }, execution_time=0.05, metadata={"mock": True}, @@ -2376,14 +2375,14 @@ async def export_file( metadata={"exported_format": format_type, "file_path": file_path}, ) - async def get_dimension(self, name: str) -> AdapterResult[float]: - """Mock getting a dimension value. + async def get_dimension(self, name: str) -> AdapterResult[dict[str, Any]]: + """Mock getting a dimension value; the mock's dimensions are lengths. Args: name (str): The name value. Returns: - AdapterResult[float]: The result produced by the operation. + AdapterResult[dict[str, Any]]: ``value`` in mm and ``units: "mm"``. """ await asyncio.sleep(0.05) # Very fast operation self._operation_count += 1 @@ -2391,12 +2390,16 @@ async def get_dimension(self, name: str) -> AdapterResult[float]: if name in self._dimensions: return AdapterResult( status=AdapterResultStatus.SUCCESS, - data=self._dimensions[name], + data={"value": self._dimensions[name], "units": "mm"}, execution_time=0.05, ) else: return AdapterResult( - status=AdapterResultStatus.ERROR, error=f"Dimension '{name}' not found" + status=AdapterResultStatus.ERROR, + error=( + f"Dimension '{name}' not found; list the names with " + "list_model_dimensions" + ), ) async def set_dimension(self, name: str, value: float) -> AdapterResult[None]: diff --git a/src/solidworks_mcp/adapters/solidworks/io.py b/src/solidworks_mcp/adapters/solidworks/io.py index 634b56dd..ee448f70 100644 --- a/src/solidworks_mcp/adapters/solidworks/io.py +++ b/src/solidworks_mcp/adapters/solidworks/io.py @@ -2,16 +2,15 @@ from __future__ import annotations -import ctypes +import math import os -import re import shutil -import uuid from datetime import datetime from pathlib import Path from types import SimpleNamespace from typing import Any, cast +from ...utils.sw_dependencies import dependency_paths from .. import sw_type_info as _sw_type_info from ..base import AdapterResult, AdapterResultStatus, MassProperties, SolidWorksModel from .face_selection import mate_entity_label @@ -25,59 +24,6 @@ win32com = SimpleNamespace(client=SimpleNamespace()) _dynamic = SimpleNamespace(Dispatch=lambda *_a, **_kw: None) -try: - import comtypes # type: ignore[import-untyped] - import comtypes.client as _comtypes_client # type: ignore[import-untyped] - - _COMTYPES_AVAILABLE = True -except ImportError: - _COMTYPES_AVAILABLE = False - -# SolidWorks type library GUID (stable across SW versions) -_SW_TLB_GUID = "{83A33D31-27C5-11CE-BFD4-00400513BB57}" -# Cached comtypes wrapper module (loaded once per process) -_sw_comtypes_lib: Any = None - - -def _get_sw_comtypes_lib() -> Any: - """Return the comtypes wrapper for the SolidWorks type library. - - Tries SW version numbers 35..30 (newest to oldest). Returns ``None`` when - comtypes is unavailable or the TLB cannot be found in the registry. - """ - global _sw_comtypes_lib - if _sw_comtypes_lib is not None: - return _sw_comtypes_lib - if not _COMTYPES_AVAILABLE: - return None - for major in (35, 34, 33, 32, 31, 30): - try: - _sw_comtypes_lib = _comtypes_client.GetModule( - (comtypes.GUID(_SW_TLB_GUID), major, 0) - ) - return _sw_comtypes_lib - except Exception: - continue - return None - - -def _bridge_com_to_comtypes(pywin32_obj: Any, iface: Any) -> Any: - """Bridge a pywin32 CDispatch/COM object to a comtypes interface pointer. - - Extracts the raw IUnknown pointer from pywin32's repr string, then - QueryInterface-es for *iface* via comtypes. The AddRef keeps the object - alive through the Python reference. - """ - unk = pywin32_obj._oleobj_.QueryInterface(pythoncom.IID_IUnknown) - m = re.search(r"obj at (0x[0-9a-fA-F]+)", repr(unk)) - if not m: - raise RuntimeError(f"Could not extract COM pointer from {repr(unk)!r}") - ptr_int = int(m.group(1), 16) - ct_unk = ctypes.cast(ptr_int, ctypes.POINTER(comtypes.IUnknown)) - ct_unk.AddRef() - return ct_unk.QueryInterface(iface) - - _MATE_TYPES: dict[str, int] = { "coincident": 0, "concentric": 1, @@ -239,6 +185,117 @@ def _component_transforms(adapter: Any, assembly: Any) -> dict[str, tuple[float, return snapshot +#: ``swFileLoadError_e.swFileWithSameTitleAlreadyOpen``: a document with the +#: same file name, from another folder, is already open. +_SAME_TITLE_ALREADY_OPEN = 65536 + + +def _files_to_pack(source: Path, dependencies: list[Path], out_dir: Path) -> list[Path]: + """The assembly and each file it uses, checked before anything is copied. + + Args: + source: The assembly. + dependencies: The files ``GetDependencies2`` listed. + out_dir: The folder they are copied into, under their own names. + + Returns: + list[Path]: The assembly first, then each dependency once. + + Raises: + FileNotFoundError: A file is not on disk. + ValueError: Two files share a name (renaming one would break the + reference to it), or ``out_dir`` is a folder they are in. + """ + files = [source] + keys = {os.path.normcase(str(source))} + for path in dependencies: + if os.path.normcase(str(path)) not in keys: + keys.add(os.path.normcase(str(path))) + files.append(path) + missing = [str(f) for f in files if not f.is_file()] + if missing: + raise FileNotFoundError( + f"Files the assembly uses were not found on disk: {', '.join(missing)}. " + "Nothing was copied." + ) + by_name: dict[str, list[str]] = {} + for f in files: + by_name.setdefault(f.name.casefold(), []).append(str(f)) + clashes = [path for group in by_name.values() if len(group) > 1 for path in group] + if clashes: + raise ValueError( + f"These files share a name and can't go in one folder: {', '.join(clashes)}. " + "Nothing was copied." + ) + target = os.path.normcase(str(out_dir.resolve())) + if any(os.path.normcase(str(f.parent.resolve())) == target for f in files): + raise ValueError( + "target_dir holds the files being packed; choose another folder. " + "Nothing was copied." + ) + return files + + +def _open_or_find_assembly(adapter: Any, source: Path) -> Any: + """Open the assembly, or use it when it is already open; never close anything. + + ``OpenDoc6`` returns nothing for a file that can't be opened, including + when a document with the same file name is already open. The assembly + itself, if open, is found by its path (``ISldWorks.GetOpenDocumentByName``) + and used as it is, unsaved changes included. + + Args: + adapter: A connected adapter. + source: The assembly file. + + Returns: + Any: The assembly's ``IModelDoc2``. + + Raises: + RuntimeError: When it can neither be opened nor found open. + """ + err, warn = _byref_int(), _byref_int() + model = adapter.swApp.OpenDoc6(str(source), 2, 1, "", err, warn) + if model is not None: + return model + model = adapter._attempt( + lambda: adapter.swApp.GetOpenDocumentByName(str(source)), default=None + ) + if model is not None: + return model + if err.value == _SAME_TITLE_ALREADY_OPEN: + raise RuntimeError( + f"another document named {source.name} is already open; close it, " + "then pack again (nothing was closed)" + ) + raise RuntimeError(f"OpenDoc6 failed err={err.value} warn={warn.value}") + + +#: ``swDimensionParamType_e`` (read from swconst.tlb, 2026): what +#: ``IDimension.GetType`` returns for a length and an angle. 2 is an integer +#: (a count); -1 unknown. +_DIMENSION_LINEAR = 0 +_DIMENSION_ANGULAR = 1 + + +def _dimension_reading(kind: Any, system_value: float) -> dict[str, Any]: + """A dimension's value in the unit its type gives it. + + Args: + kind: ``IDimension.GetType``'s value, or ``None`` when unreadable. + system_value: ``IDimension.SystemValue``: metres, radians or a count. + + Returns: + dict[str, Any]: ``value`` and ``units``: mm for a length, degrees for + an angle, and the number with ``units: None`` for anything else. + """ + if kind == _DIMENSION_LINEAR: + return {"value": system_value * 1000.0, "units": "mm"} + if kind == _DIMENSION_ANGULAR: + return {"value": math.degrees(system_value), "units": "deg"} + return {"value": system_value, "units": None} + + class _ByrefFallback: """Stand-in for a byref VARIANT when pywin32 is unavailable. @@ -1391,6 +1448,8 @@ def _open() -> SolidWorksModel: model_type = "Drawing" else: raise ValueError(f"Unsupported file type: {resolved_path}") + if not os.path.isfile(resolved_path): + raise FileNotFoundError(f"File not found: {resolved_path}") app = adapter.swApp variant_ctor = getattr(getattr(win32com, "client", None), "VARIANT", None) @@ -1428,11 +1487,16 @@ def _open() -> SolidWorksModel: default=0, ) adapter.currentModel = activated + # The configuration SolidWorks opened, or None: never an assumed + # "Default". IConfiguration.Name is a property, not a method. active_config = adapter._attempt(lambda: model.GetActiveConfiguration()) config = ( - adapter._attempt(lambda: active_config.GetName(), default="Default") + adapter._attempt( + lambda: adapter._get_attr_or_call(active_config, "Name"), + default=None, + ) if active_config - else "Default" + else None ) return SolidWorksModel( @@ -1465,6 +1529,11 @@ async def close_model(self, save: bool = False) -> AdapterResult[None]: AdapterResult[None]: Result of the close operation. """ adapter = self._adapter(self) + # After a close, SolidWorks activates another open document; close that + # one, as the tool promises, rather than the document already closed. + active = getattr(adapter.swApp, "ActiveDoc", None) if adapter.swApp else None + if active is not None: + adapter.currentModel = active if not adapter.currentModel: return AdapterResult( status=AdapterResultStatus.WARNING, error="No active model to close" @@ -1747,14 +1816,21 @@ def _create() -> SolidWorksModel: adapter._handle_com_operation("create_drawing", _create), ) - async def get_dimension(self, name: str) -> AdapterResult[float]: - """Read a named model dimension in millimetres. + async def get_dimension(self, name: str) -> AdapterResult[dict[str, Any]]: + """Read a named model dimension in the unit its type gives it. + + ``IDimension.SystemValue`` is metres for a length, radians for an + angle and the number itself for a count; ``IDimension.GetType`` says + which (:func:`_dimension_reading`). ``GetValue3`` is not used: it is + in the document's units, which this can't convert without reading + the document's unit system. Args: - name: Fully-qualified dimension name. + name: Fully-qualified dimension name, e.g. ``"D1@Boss-Extrude1"``. Returns: - AdapterResult[float]: Dimension value in millimetres. + AdapterResult[dict[str, Any]]: ``value`` and ``units`` ("mm", + "deg", or ``None`` for a count or a dimension of unknown type). """ adapter = self._adapter(self) if not adapter.currentModel: @@ -1762,24 +1838,23 @@ async def get_dimension(self, name: str) -> AdapterResult[float]: status=AdapterResultStatus.ERROR, error="No active model" ) - def _get() -> float: - """Get the dimension value.""" + def _get() -> dict[str, Any]: + """Get the dimension value and its unit.""" dimension = adapter.currentModel.Parameter(name) if not dimension: - raise Exception(f"Dimension '{name}' not found") - # SystemValue is reliable on SW 2025 (in meters, convert to mm) - value = adapter._attempt(lambda: dimension.SystemValue, default=None) - if value is None: - # Fall back to GetValue3 for older SW versions - value = adapter._attempt( - lambda: dimension.GetValue3(0, 0), default=None + raise Exception( + f"Dimension '{name}' not found; list the names with " + "list_model_dimensions" ) + dimension = _sw_type_info.flagged(dimension, "IDimension") + value = adapter._attempt(lambda: dimension.SystemValue, default=None) if value is None: raise Exception(f"Failed to read dimension '{name}'") - return float(value) * 1000 + kind = adapter._attempt(lambda: dimension.GetType(), default=None) + return _dimension_reading(kind, float(value)) return cast( - AdapterResult[float], + AdapterResult[dict[str, Any]], adapter._handle_com_operation("get_dimension", _get), ) @@ -2301,8 +2376,9 @@ def _list() -> list[str]: active_config = adapter._attempt( lambda: adapter.currentModel.GetActiveConfiguration(), default=None ) + # IConfiguration.Name is a property; it has no GetName method. active_name = adapter._attempt( - lambda: active_config.GetName(), default=None + lambda: adapter._get_attr_or_call(active_config, "Name"), default=None ) if active_name: return [str(active_name)] @@ -2521,103 +2597,59 @@ async def pack_and_go_assembly( source_path: str, target_dir: str, ) -> AdapterResult[dict[str, Any]]: - """Copy an assembly and all its referenced components to a self-contained folder. + """Copy an assembly and every file it uses into one folder. - Uses ``IModelDocExtension.GetPackAndGo()`` → ``IPackAndGo`` via the - comtypes vtable interface (bypassing the broken IDispatch path present - in SolidWorks 2026's late-binding layer), then calls - ``IModelDocExtension.SavePackAndGo()`` to execute the copy. All file - paths inside the copied assembly are automatically updated by - SolidWorks — this is the native Pack-and-Go mechanism. + SolidWorks lists the files (``IModelDoc2.GetDependencies2``) and each + is copied, as saved on disk, into ``target_dir`` under its own name. + The copy opens with its own parts: SolidWorks looks for a referenced + file in the assembly's folder before the stored path. (SolidWorks' + own Pack and Go, ``IPackAndGo``, listed only the assembly on + SolidWorks 2026.) No document is closed or changed. Args: - source_path: Absolute path to the source ``.sldasm`` file. - target_dir: Directory where the assembly and parts will be copied. - Created if it does not exist. + source_path: The ``.sldasm`` file. + target_dir: The folder to copy into; created if needed. A file + already there with a copied file's name is replaced. Returns: - AdapterResult[dict]: On success, ``data`` is a dict with keys: - ``source_assembly``, ``target_dir``, ``copied_files``, - ``source_files``, ``save_statuses``, and ``all_files_saved``. + AdapterResult[dict]: ``source_assembly``, ``target_dir``, + ``copied_files``, ``source_files`` and ``unsaved_changes`` (the + files open with changes the copy doesn't have). """ adapter = self._adapter(self) source = Path(source_path) out_dir = Path(target_dir) - def _do_pack_and_go() -> dict[str, Any]: - # Load comtypes TLB (cached after first call) - sw_lib = _get_sw_comtypes_lib() - if sw_lib is None: - raise RuntimeError( - "comtypes SolidWorks type library not available. " - "Ensure comtypes is installed and SolidWorks is registered." - ) - - # Prepare a clean target directory. SW holds file locks on previously - # opened assemblies so rmtree raises WinError 32. We rename the old - # dir aside (Windows allows rename with open handles) and delete the - # backup afterwards; if rename also fails we just proceed and let SW - # overwrite existing files. - if out_dir.exists(): - backup = out_dir.parent / f"{out_dir.name}_bak_{uuid.uuid4().hex[:8]}" - try: - os.rename(out_dir, backup) - try: - shutil.rmtree(backup) - except Exception: - pass # best-effort cleanup; stale backup is harmless - except OSError: - pass # rename also failed — proceed; SW will overwrite files - out_dir.mkdir(parents=True, exist_ok=True) - - # Open the source assembly - err, warn = _byref_int(), _byref_int() - model = adapter.swApp.OpenDoc6(str(source), 2, 1, "", err, warn) - if model is None and err.value == 65536: - adapter.swApp.CloseAllDocuments(False) - err, warn = _byref_int(), _byref_int() - model = adapter.swApp.OpenDoc6(str(source), 2, 1, "", err, warn) - if model is None: - raise RuntimeError(f"OpenDoc6 failed err={err.value} warn={warn.value}") + def _pack() -> dict[str, Any]: + model = _open_or_find_assembly(adapter, source) _sw_type_info.flag_doc(model, 2) adapter.currentModel = model - - # Bridge model.Extension → IModelDocExtension via comtypes vtable - ext_ct = _bridge_com_to_comtypes(model.Extension, sw_lib.IModelDocExtension) - - # GetPackAndGo() via vtable (IDispatch path broken in SW 2026) - pg = ext_ct.GetPackAndGo() - - # Configure: flatten all files to root of target directory - pg.FlattenToSingleFolder = True - pg.SetSaveToName(True, str(out_dir) + "\\") - - # Record what files will be packed - names_result = pg.GetDocumentNames() - source_files: list[str] = list(names_result[0]) if names_result[0] else [] - - # Execute Pack and Go — SavePackAndGo returns a tuple of per-file status codes - ext_ct2 = _bridge_com_to_comtypes( - model.Extension, sw_lib.IModelDocExtension - ) - status_arr = ext_ct2.SavePackAndGo(pg) - save_statuses: list[int] = list(status_arr) if status_arr else [] - - copied_files = sorted( - str(p) - for p in out_dir.rglob("*") - if p.is_file() and p.suffix.lower() in {".sldasm", ".sldprt", ".slddrw"} - ) + listed = dependency_paths(model.GetDependencies2(True, True, False)) + files = _files_to_pack(source, listed, out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + copied = [str(shutil.copy2(f, out_dir / f.name)) for f in files] + unsaved = [ + f.name + for f in files + if adapter._attempt( + lambda f=f: bool( + adapter._get_attr_or_call( + adapter.swApp.GetOpenDocumentByName(str(f)), + "GetSaveFlag", + ) + ), + default=False, + ) + ] return { "source_assembly": str(source), "target_dir": str(out_dir), - "copied_files": copied_files, - "source_files": source_files, - "save_statuses": save_statuses, - "all_files_saved": all(s == 0 for s in save_statuses), + "copied_files": sorted(copied), + "source_files": [str(f) for f in files], + "unsaved_changes": unsaved, } - result = adapter._handle_com_operation("pack_and_go_assembly", _do_pack_and_go) + result = adapter._handle_com_operation("pack_and_go_assembly", _pack) if not result.is_success: return AdapterResult( status=AdapterResultStatus.ERROR, diff --git a/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md b/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md index 6ef6f7cd..9a86f8ed 100644 --- a/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md +++ b/src/solidworks_mcp/skills/solidworks-mcp/references/errors-and-limits.md @@ -48,3 +48,5 @@ mostly batch, template, macro-recording and drawing-analysis tools, plus | Fault | Workaround | | --- | --- | | `add_mate` can't mate edges or vertices, only planes, axes and faces. | Mate the faces that meet at the edge. | +| `pack_and_go_assembly` copies the files as saved on disk; unsaved changes in open parts are left out, and its `warning` names those parts. | Save the assembly and its parts first, then pack. | +| `compare_drawing_versions`: SolidWorks writes a different file every time it saves, so two saves of an unchanged drawing still differ. | Treat "identical" as proof nothing changed; treat "different" as "may have changed", and check with `list_drawing_views`. | diff --git a/src/solidworks_mcp/tools/automation.py b/src/solidworks_mcp/tools/automation.py index 0317c4b1..d11bae5b 100644 --- a/src/solidworks_mcp/tools/automation.py +++ b/src/solidworks_mcp/tools/automation.py @@ -7,10 +7,11 @@ create_template for reusable standards, and optimize_performance for tuning. """ -from typing import Any +import re +from typing import Any, Literal from fastmcp import FastMCP -from pydantic import Field +from pydantic import Field, field_validator from ..adapters.base import SolidWorksAdapter from .input_compat import CompatInput @@ -27,32 +28,44 @@ class GenerateVBAInput(CompatInput): """Input schema for generating VBA code. + ``parameters`` and ``code_style`` are refused + (``input_compat.REMOVED_INPUTS``): neither shaped the code. + Attributes: - code_style (str): The code style value. - include_error_handling (bool): The include error handling value. - operation_description (str | None): The operation description value. - operation_type (str | None): The operation type value. - parameters (dict[str, Any]): The parameters value. - target_document (str): The target document value. + include_error_handling (bool): Whether the Sub gets an error handler. + operation_description (str | None): What the macro is for; it also + names the Sub. + operation_type (str | None): An alias for ``operation_description``. + target_document (str): The document type the macro runs on. """ operation_description: str | None = Field( default=None, description="Description of the operation to generate VBA for" ) operation_type: str | None = Field(default=None, description="Operation type alias") - parameters: dict[str, Any] = Field( - default_factory=dict, description="Operation parameters" - ) - target_document: str = Field( - default="Part", description="Target document type (Part, Assembly, Drawing)" + target_document: Literal["Part", "Assembly", "Drawing"] = Field( + default="Part", + description=( + "The document type the macro runs on; it stops, printing why, on any other" + ), ) include_error_handling: bool = Field( default=True, description="Include error handling in generated code" ) - code_style: str = Field( - default="professional", - description="Code style (simple, professional, advanced)", - ) + + @field_validator("target_document", mode="before") + @classmethod + def _document_type(cls, value: Any) -> Any: + """Accept the document type in any case ("part", "PART"). + + Args: + value: The document type as sent. + + Returns: + Any: ``Part``, ``Assembly`` or ``Drawing`` for a string; anything + else unchanged, for the type check to refuse. + """ + return value.strip().capitalize() if isinstance(value, str) else value def model_post_init(self, __context: Any) -> None: """Provide model post init support for the generate vbainput. @@ -269,6 +282,99 @@ class TemplateInput(CompatInput): ) +#: ``swDocumentTypes_e``: the value ``IModelDoc2.GetType`` returns for each +#: document type a macro can be written for. +_VBA_DOC_TYPES = {"Part": 1, "Assembly": 2, "Drawing": 3} +#: VBA's limit on an identifier's length. +_VBA_NAME_LIMIT = 255 + + +def _vba_sub_name(description: str) -> str: + """A valid VBA Sub name made from an operation description. + + Every run of characters other than letters, digits and underscores + becomes one underscore; a name that doesn't start with a letter gets + ``Macro_`` in front; the result is cut to VBA's 255-character limit. + + Args: + description: The operation description, e.g. "Add 3 holes (M6)". + + Returns: + str: The Sub name, e.g. ``Add_3_holes_M6``. + """ + name = re.sub(r"[^A-Za-z0-9_]+", "_", description).strip("_") + if not name[:1].isalpha(): + name = f"Macro_{name}".rstrip("_") + return name[:_VBA_NAME_LIMIT] + + +def _vba_skeleton( + sub_name: str, description: str, target_document: str, error_handling: bool +) -> str: + """The macro text ``generate_vba_code`` returns. + + Late-bound (``As Object``), so it needs no type-library reference when + run as a text macro; ``Debug.Print`` instead of ``MsgBox``, so a run never + waits on a dialog. A ``Sub main()`` calls the named Sub: SolidWorks runs + a ``.swb`` macro only through ``main`` (live batch 3), and ``main`` is + ``execute_macro``'s default procedure. + + Args: + sub_name: The Sub's name, from :func:`_vba_sub_name`. + description: The operation description, for the header comment. + target_document: Part, Assembly or Drawing. + error_handling: Whether to add an error handler. + + Returns: + str: The macro. + """ + comment = " ".join(description.split()) # one line, whatever was sent + doc_type = _VBA_DOC_TYPES[target_document] + lines = [ + f"' Generated VBA code for: {comment}", + f"' Runs on: {target_document}", + "' Generated by: SolidWorks MCP Server", + "", + "Option Explicit", + "", + ] + if sub_name.lower() != "main": # VBA names ignore case + lines += ["Sub main()", f" {sub_name}", "End Sub", ""] + lines += [ + f"Sub {sub_name}()", + " Dim swApp As Object", + " Dim swModel As Object", + ] + if error_handling: + lines.append(" On Error GoTo ErrorHandler") + lines += [ + "", + " Set swApp = Application.SldWorks", + " Set swModel = swApp.ActiveDoc", + " If swModel Is Nothing Then", + ' Debug.Print "No active document"', + " Exit Sub", + " End If", + f" If swModel.GetType <> {doc_type} Then", + f' Debug.Print "The active document is not a {target_document}"', + " Exit Sub", + " End If", + "", + " ' TODO: the operation itself", + "", + ' Debug.Print "Done"', + " Exit Sub", + ] + if error_handling: + lines += [ + "", + "ErrorHandler:", + ' Debug.Print "Error " & Err.Number & ": " & Err.Description', + ] + lines.append("End Sub") + return "\n".join(lines) + + async def register_automation_tools( mcp: FastMCP, adapter: SolidWorksAdapter, config: dict[str, Any] ) -> int: @@ -290,81 +396,44 @@ async def register_automation_tools( @mcp.tool() async def generate_vba_code(input_data: GenerateVBAInput) -> dict[str, Any]: - """Write a VBA macro skeleton for an operation you describe: the SolidWorks connection, the active document and optional error handling, with the operation itself left as a TODO. + """Write a VBA macro skeleton for an operation you describe: the SolidWorks connection, a check of the active document's type and optional error handling, with the operation itself left as a TODO. - Use it as a starting point for a custom macro. For a working macro for a + Use it as a starting point for a custom macro. For a complete macro for a specific feature, use a `generate_vba_*` tool (extrusion, revolve, mates, - drawing views, batch export). The macro comes back as text for the SolidWorks - VBA editor; `execute_macro` runs only binary .swp files. Read-only. Nothing runs - in SolidWorks. Returns: `vba_code` with `code`, `operation`, `target_document`, - `style`, `lines_of_code` and `includes_error_handling`. + drawing views, batch export). The macro reports through `Debug.Print`, never a + dialog, so it runs without waiting on anyone: save it as a .swb file and run it + with `execute_macro` (its `Sub main()` calls the Sub named `sub_name`; SolidWorks + runs a .swb macro only through `main`). It stops, printing why, + when the active document isn't `target_document`. Read-only. Nothing runs in + SolidWorks. Returns: `vba_code` with `code`, `sub_name`, `operation`, + `target_document`, `lines_of_code` and `includes_error_handling`. Args: input_data: The macro to write. Nothing is required: give `operation_description` (it also names the Sub) and - `target_document`; `include_error_handling` and `code_style` have - defaults. + `target_document` (Part, Assembly or Drawing); + `include_error_handling` is on by default. Returns: dict[str, Any]: The macro text. """ - if hasattr(adapter, "generate_vba_code"): - result = await adapter.generate_vba_code(input_data.model_dump()) - require_success(result, "Failed to generate VBA code") - return { - "status": "success", - "message": f"Generated VBA code for: {input_data.operation_description}", - "data": result.data, - "execution_time": result.execution_time, - } - - # Build a VBA code skeleton from the operation description. This - # is real, usable output (a labelled template), not a stand-in - # for a SolidWorks operation that was supposed to run. - sample_vba = f""" -' Generated VBA code for: {input_data.operation_description} -' Target: {input_data.target_document} -' Generated by: SolidWorks MCP Server - -Option Explicit - -Sub {(input_data.operation_description or "").replace(" ", "_")}() -Dim swApp As SldWorks.SldWorks -Dim swModel As SldWorks.ModelDoc2 - -{("On Error GoTo ErrorHandler" if input_data.include_error_handling else "")} - -' Connect to SolidWorks -Set swApp = Application.SldWorks -Set swModel = swApp.ActiveDoc - -If swModel Is Nothing Then - MsgBox "No active document found" - Exit Sub -End If - -' Main operation code would go here -' TODO: Implement specific operation - -MsgBox "Operation completed successfully" -Exit Sub - -{("ErrorHandler:" if input_data.include_error_handling else "")} -{(' MsgBox "Error: " & Err.Description' if input_data.include_error_handling else "")} -{(" Resume Next" if input_data.include_error_handling else "")} - -End Sub -""" - + description = input_data.operation_description or "" + sub_name = _vba_sub_name(description) + code = _vba_skeleton( + sub_name, + description, + input_data.target_document, + input_data.include_error_handling, + ) return { "status": "success", - "message": f"Generated VBA code for: {input_data.operation_description}", + "message": f"Generated VBA code for: {description}", "vba_code": { - "code": sample_vba.strip(), - "operation": input_data.operation_description, + "code": code, + "sub_name": sub_name, + "operation": description, "target_document": input_data.target_document, - "style": input_data.code_style, - "lines_of_code": len(sample_vba.strip().split("\n")), + "lines_of_code": len(code.split("\n")), "includes_error_handling": input_data.include_error_handling, }, } diff --git a/src/solidworks_mcp/tools/drawing_analysis.py b/src/solidworks_mcp/tools/drawing_analysis.py index f8b8bc6b..f5f99ccf 100644 --- a/src/solidworks_mcp/tools/drawing_analysis.py +++ b/src/solidworks_mcp/tools/drawing_analysis.py @@ -13,9 +13,9 @@ from .file_facts import file_fact_snapshot from .input_compat import CompatInput from .tool_boundary import ( - InvalidInputError, ToolOperationError, UnsupportedOperationError, + normalize_input, require_capability, require_success, with_tool_boundary, @@ -119,6 +119,22 @@ class ComplianceCheckInput(CompatInput): ) +class DrawingVersionsInput(CompatInput): + """Input schema for comparing two saved versions of a drawing. + + Attributes: + drawing_version_1 (str): The first drawing file. + drawing_version_2 (str): The second drawing file. + """ + + drawing_version_1: str = Field( + min_length=1, description="Full path to the first drawing file" + ) + drawing_version_2: str = Field( + min_length=1, description="Full path to the second drawing file" + ) + + async def register_drawing_analysis_tools( mcp: FastMCP, adapter: SolidWorksAdapter, config: Any ) -> int: @@ -339,29 +355,28 @@ async def generate_drawing_report(input_data: dict[str, Any]) -> dict[str, Any]: ) @mcp.tool() - async def compare_drawing_versions(input_data: dict[str, Any]) -> dict[str, Any]: + async def compare_drawing_versions( + input_data: DrawingVersionsInput, + ) -> dict[str, Any]: """Compare two drawing files on disk: whether they are byte-identical, and how their sizes differ. Use it to tell whether a drawing changed between two saved versions. It does not - open SolidWorks, so it can't say which views, dimensions or notes differ. Needs: + open SolidWorks, so it can't say which views, dimensions or notes differ. + Identical files mean nothing changed, but different files may not: SolidWorks + writes a different file each time it saves, even with no change. Needs: both files on disk. Read-only. Returns: `comparison` with `file_1` and `file_2` (size, modified time, SHA-256), `identical` and `size_delta_bytes`. Args: - input_data: A mapping with both full paths, `drawing_version_1` and + input_data: Both full paths, `drawing_version_1` and `drawing_version_2`; both are required. Returns: dict[str, Any]: The comparison. """ - drawing_v1 = input_data.get("drawing_version_1", "") - drawing_v2 = input_data.get("drawing_version_2", "") - - if not drawing_v1 or not drawing_v2: - raise InvalidInputError( - "compare_drawing_versions requires both " - "drawing_version_1 and drawing_version_2 paths." - ) + input_data = normalize_input(input_data, DrawingVersionsInput) + drawing_v1 = input_data.drawing_version_1 + drawing_v2 = input_data.drawing_version_2 file_1 = file_fact_snapshot(drawing_v1) file_2 = file_fact_snapshot(drawing_v2) diff --git a/src/solidworks_mcp/tools/file_management.py b/src/solidworks_mcp/tools/file_management.py index f8f6d5e4..ef454cce 100644 --- a/src/solidworks_mcp/tools/file_management.py +++ b/src/solidworks_mcp/tools/file_management.py @@ -17,11 +17,11 @@ build_component_tree, classify_feature_tree_snapshot, ) +from ..utils.sw_dependencies import dependency_paths from .input_compat import CompatInput from .tool_boundary import ( InvalidInputError, ToolOperationError, - UnsupportedOperationError, require_capability, require_success, with_tool_boundary, @@ -188,12 +188,15 @@ class PackAndGoInput(CompatInput): description="Directory where the assembly and all referenced parts will be copied" ) export_preview: bool = Field( - default=True, + default=False, description="Export an isometric PNG preview next to the copied files", ) overwrite: bool = Field( default=False, - description="Overwrite files that already exist in target_dir", + description=( + "Pack into a target_dir that already holds files, replacing the ones " + "Pack and Go writes; other files there are kept" + ), ) @@ -461,22 +464,6 @@ def _get_attr_or_call(obj: Any, name: str, default: Any = None) -> Any: return default if value is None else value return candidate - def _extract_dependency_paths( - raw_dependencies: Any, - ) -> list[Path]: - """Extract model file paths from SolidWorks GetDependencies2 payloads.""" - if not isinstance(raw_dependencies, (list, tuple)): - return [] - - dependency_paths: list[Path] = [] - for item in raw_dependencies: - if not isinstance(item, str): - continue - lower_item = item.lower() - if lower_item.endswith((".sldprt", ".sldasm", ".slddrw")): - dependency_paths.append(Path(item)) - return dependency_paths - def _copy_with_collision_handling(source_path: Path, target_dir: Path) -> Path: """Copy a source file into target_dir, suffixing when name collisions occur.""" destination = target_dir / source_path.name @@ -537,9 +524,8 @@ def _copy_active_assembly_with_references( f"Failed to enumerate assembly dependencies: {exc}" ) from exc - dependency_paths = _extract_dependency_paths(raw_dependencies) unique_sources: list[Path] = [source_assembly] - for dep in dependency_paths: + for dep in dependency_paths(raw_dependencies): if dep not in unique_sources: unique_sources.append(dep) @@ -829,31 +815,35 @@ async def classify_feature_tree( features = input_data.features execution_time = 0.0 - if model_info is None and hasattr(adapter, "get_model_info"): + # Reading the model can fail (nothing open); classifying an empty + # model instead would give a confident wrong answer. + if model_info is None: + require_capability( + adapter, + "get_model_info", + "Active adapter does not support get_model_info", + ) model_result = await adapter.get_model_info() - if model_result.is_success: - model_info = model_result.data - execution_time = max(execution_time, model_result.execution_time or 0.0) + require_success( + model_result, context="Failed to read the model to classify" + ) + model_info = model_result.data + execution_time = max(execution_time, model_result.execution_time or 0.0) if features is None: - if hasattr(adapter, "list_features"): - feature_result = await adapter.list_features( - include_suppressed=input_data.include_suppressed - ) - if feature_result.is_success: - features = feature_result.data or [] - execution_time = max( - execution_time, feature_result.execution_time or 0.0 - ) - else: - raise ToolOperationError( - feature_result.error - or "Failed to list features for classification" - ) - else: - raise UnsupportedOperationError( - "Active adapter does not support list_features" - ) + require_capability( + adapter, + "list_features", + "Active adapter does not support list_features", + ) + feature_result = await adapter.list_features( + include_suppressed=input_data.include_suppressed + ) + require_success( + feature_result, context="Failed to list features to classify" + ) + features = feature_result.data or [] + execution_time = max(execution_time, feature_result.execution_time or 0.0) classification = classify_feature_tree_snapshot(model_info, features or []) # type: ignore[arg-type] return { @@ -994,7 +984,8 @@ async def load_part(input_data: LoadPartInput) -> dict[str, Any]: `open_model`, and to switch to a document that is already open, use `activate_document`. A path that isn't a .sldprt is refused. Needs: the file on disk. Changes: opens the part (no file is written). Returns: `model` with - `name`, `type`, `path` and `configuration`. + `name`, `type`, `path` and `configuration` (the one SolidWorks opened, or + null when it can't be read). Args: input_data: The part. `file_path` (a .sldprt) is required. @@ -1013,7 +1004,7 @@ async def load_part(input_data: LoadPartInput) -> dict[str, Any]: model = result.data title = _result_value(model, "title", "name", default=file_path) path = _result_value(model, "path", "file_path", default=file_path) - configuration = _result_value(model, "configuration", default="Default") + configuration = _result_value(model, "configuration") return { "status": "success", "message": f"Loaded part: {title}", @@ -1034,7 +1025,8 @@ async def load_assembly(input_data: LoadAssemblyInput) -> dict[str, Any]: `open_model`, and to switch to a document that is already open, use `activate_document`. A path that isn't a .sldasm is refused. Needs: the file on disk. Changes: opens the assembly (no file is written). Returns: `model` with - `name`, `type`, `path` and `configuration`. + `name`, `type`, `path` and `configuration` (the one SolidWorks opened, or + null when it can't be read). Args: input_data: The assembly. `file_path` (a .sldasm) is required. @@ -1055,7 +1047,7 @@ async def load_assembly(input_data: LoadAssemblyInput) -> dict[str, Any]: model = result.data title = _result_value(model, "title", "name", default=file_path) path = _result_value(model, "path", "file_path", default=file_path) - configuration = _result_value(model, "configuration", default="Default") + configuration = _result_value(model, "configuration") return { "status": "success", "message": f"Loaded assembly: {title}", @@ -1175,16 +1167,20 @@ async def save_assembly( } @mcp.tool() - async def pack_and_go_assembly( - input_data: PackAndGoInput | None = None, - ) -> dict[str, Any]: - """Copy an assembly and every part it references into one folder, with the references updated (SolidWorks Pack and Go). - - Use it to hand over or archive an assembly as a self-contained folder. It - refuses a folder that already has files unless `overwrite` is on, and can add an + async def pack_and_go_assembly(input_data: PackAndGoInput) -> dict[str, Any]: + """Copy an assembly and every file it uses into one folder that opens on its own. + + Use it to hand over or archive an assembly. SolidWorks lists the files the + assembly uses; each is copied under its own name, as saved on disk, so save + first: a `warning` names any open file whose unsaved changes the copy doesn't + have. The copy opens with its own parts, since SolidWorks looks in the + assembly's folder first. It fails, copying nothing, when a file is missing, + two files share a name, or `target_dir` holds the originals. It refuses a + folder that already has files unless `overwrite` is on, and then replaces only + the files it copies. It never closes or changes a document. It can add an isometric PNG preview. Needs: the .sldasm on disk. Changes: writes the copies into `target_dir`, creating it if needed. Returns: `source_assembly`, - `target_dir`, `copied_files`, `source_files`, `all_files_saved` and, with a + `target_dir`, `copied_files`, `source_files`, `unsaved_changes` and, with a preview, `preview_image`. Args: @@ -1194,10 +1190,7 @@ async def pack_and_go_assembly( Returns: dict[str, Any]: The files copied. """ - if input_data is None: - input_data = PackAndGoInput(source_path="", target_dir="") - else: - input_data = _coerce_input(PackAndGoInput, input_data) + input_data = _coerce_input(PackAndGoInput, input_data) from pathlib import Path as _Path @@ -1227,10 +1220,17 @@ async def pack_and_go_assembly( report: dict[str, Any] = { "status": "success", - "method": "native_pack_and_go", + "method": "dependency_copy", "execution_time": result.execution_time, **result.data, } + warnings: list[str] = [] + unsaved = result.data.get("unsaved_changes") or [] + if unsaved: + warnings.append( + f"{', '.join(unsaved)} had unsaved changes, which are not in the " + "copy; save, then pack again to include them." + ) if input_data.export_preview: preview_path = out_dir / "assembly_preview.png" @@ -1246,7 +1246,14 @@ async def pack_and_go_assembly( report["preview_image"] = ( str(preview_path) if img_result.is_success else None ) + if not img_result.is_success: + warnings.append( + f"The copy is complete, but the preview couldn't be written: " + f"{img_result.error}" + ) + if warnings: + report["warning"] = " ".join(warnings) return report @mcp.tool() diff --git a/src/solidworks_mcp/tools/input_compat.py b/src/solidworks_mcp/tools/input_compat.py index 03b29a7f..c4694357 100644 --- a/src/solidworks_mcp/tools/input_compat.py +++ b/src/solidworks_mcp/tools/input_compat.py @@ -20,6 +20,11 @@ class CompatInput(BaseModel): _DRAWING_PACKAGE = "use `generate_drawing_package` for a complete drawing" _FILE_EXTENSION = "the file extension sets the format and its options" _ACTIVE_MODEL = "it measures the active model; open and activate the one you want" +_FILES_ONLY = "the tool compares the two files on disk, not their settings" +_WHOLE_MACROS = ( + "it writes a skeleton; for a complete macro use a `generate_vba_*` tool " + "such as `generate_vba_extrusion`" +) #: Inputs a tool used to advertise but never applied, by input model name. #: Each maps to what to use instead. A call that still sends one is refused @@ -57,6 +62,21 @@ class CompatInput(BaseModel): "pause_on_error": "it stops at the first run that fails", "log_execution": "the reply reports every run", }, + "TemplateComparisonInput": dict.fromkeys( + ( + "comparison_type", + "comparison_depth", + "include_properties", + "include_dimensions", + "include_materials", + "generate_report", + ), + _FILES_ONLY, + ), + "GenerateVBAInput": { + "parameters": _WHOLE_MACROS, + "code_style": _WHOLE_MACROS, + }, "MassPropertiesInput": { "model_path": _ACTIVE_MODEL, "units": "volumes are mm³, masses kg and inertia kg·mm²", diff --git a/src/solidworks_mcp/tools/modeling.py b/src/solidworks_mcp/tools/modeling.py index 85fdf6cb..45940e56 100644 --- a/src/solidworks_mcp/tools/modeling.py +++ b/src/solidworks_mcp/tools/modeling.py @@ -1442,8 +1442,9 @@ async def get_dimension(input_data: GetDimensionInput) -> dict[str, Any]: """Read one dimension of the active model by its full name, e.g. "D1@Sketch1". Find names with `list_model_dimensions`. Needs: an open part or assembly. - Read-only. Returns: `dimension` with `name`, `value` and `units` (mm for a - length). + Read-only. Returns: `dimension` with `name`, `value` and `units`: "mm" for a + length, "deg" for an angle, and null for a count (such as a pattern's + instance count). Args: input_data: The dimension. Give `name` (or `dimension_name`), e.g. @@ -1456,12 +1457,13 @@ async def get_dimension(input_data: GetDimensionInput) -> dict[str, Any]: result = await adapter.get_dimension(input_data.name) require_success(result, context="Failed to get dimension") - value = result.data - dimension_value = _result_value(value, "value", default=value) - dimension_units = _result_value(value, "units", default="mm") + reading = result.data or {} + dimension_value = reading.get("value") + dimension_units = reading.get("units") + unit_text = f" {dimension_units}" if dimension_units else "" return { "status": "success", - "message": f"Dimension {input_data.name} = {dimension_value} {dimension_units}", + "message": f"Dimension {input_data.name} = {dimension_value}{unit_text}", "dimension": { "name": input_data.name, "value": dimension_value, diff --git a/src/solidworks_mcp/tools/support_levels.py b/src/solidworks_mcp/tools/support_levels.py index 1cbaeb5a..478d9850 100644 --- a/src/solidworks_mcp/tools/support_levels.py +++ b/src/solidworks_mcp/tools/support_levels.py @@ -72,9 +72,6 @@ def warning(self) -> str | None: OFFLINE_FAMILIES = frozenset({"docs_discovery", "server_admin", "vba_generation"}) _STABLE = Support(SupportLevel.STABLE) -_UNCHECKED = Support( - SupportLevel.EXPERIMENTAL, "not yet checked by a live test on real SolidWorks." -) _PLANNED = Support(SupportLevel.PLANNED, "no adapter implements it yet.") @@ -92,7 +89,7 @@ def warning(self) -> str | None: "batch_process_files": _PLANNED, "create_template": _PLANNED, "execute_workflow": _PLANNED, - "generate_vba_code": _UNCHECKED, + "generate_vba_code": _STABLE, "manage_design_table": _PLANNED, "optimize_performance": _PLANNED, # docs_discovery @@ -122,7 +119,7 @@ def warning(self) -> str | None: "analyze_drawing_dimensions": _PLANNED, "analyze_drawing_views": _PLANNED, "check_drawing_compliance": _PLANNED, - "compare_drawing_versions": _UNCHECKED, + "compare_drawing_versions": _STABLE, "generate_drawing_report": _PLANNED, "validate_drawing_completeness": _PLANNED, # drawing_automation @@ -153,18 +150,18 @@ def warning(self) -> str | None: # file_management "activate_document": _STABLE, "batch_file_operations": _PLANNED, - "classify_feature_tree": _UNCHECKED, + "classify_feature_tree": _STABLE, "convert_file_format": _PLANNED, - "get_file_properties": _UNCHECKED, + "get_file_properties": _STABLE, "get_model_info": _STABLE, "get_selected_entities": _STABLE, - "list_configurations": _UNCHECKED, + "list_configurations": _STABLE, "list_features": _STABLE, "list_open_documents": _STABLE, - "load_assembly": _UNCHECKED, - "load_part": _UNCHECKED, + "load_assembly": _STABLE, + "load_part": _STABLE, "manage_file_properties": _PLANNED, - "pack_and_go_assembly": _UNCHECKED, + "pack_and_go_assembly": _STABLE, "save_as": _STABLE, "save_assembly": _STABLE, "save_body_as_part": _STABLE, @@ -195,7 +192,7 @@ def warning(self) -> str | None: "create_revolve": _STABLE, "create_sweep": _STABLE, "delete_feature": _STABLE, - "get_dimension": _UNCHECKED, + "get_dimension": _STABLE, "insert_component": _STABLE, "list_components": _STABLE, "mirror_feature": _STABLE, @@ -235,7 +232,7 @@ def warning(self) -> str | None: # template_management "apply_template": _PLANNED, "batch_apply_template": _PLANNED, - "compare_templates": _UNCHECKED, + "compare_templates": _STABLE, "extract_template": _PLANNED, "list_template_library": _PLANNED, "save_to_template_library": _PLANNED, diff --git a/src/solidworks_mcp/tools/template_management.py b/src/solidworks_mcp/tools/template_management.py index b655a9f2..b23a48f0 100644 --- a/src/solidworks_mcp/tools/template_management.py +++ b/src/solidworks_mcp/tools/template_management.py @@ -88,29 +88,16 @@ class TemplateBatchInput(BaseModel): class TemplateComparisonInput(CompatInput): """Input schema for comparing templates. + The six comparison switches it used to take are refused + (``input_compat.REMOVED_INPUTS``): it compares the files only. + Attributes: - comparison_depth (str): The comparison depth value. - comparison_type (str): The comparison type value. - generate_report (bool): The generate report value. - include_dimensions (bool): The include dimensions value. - include_materials (bool): The include materials value. - include_properties (bool): The include properties value. - template1_path (str): The template1 path value. - template2_path (str): The template2 path value. + template1_path (str): The first template file. + template2_path (str): The second template file. """ template1_path: str = Field(description="Path to first template") template2_path: str = Field(description="Path to second template") - comparison_type: str = Field( - default="full", description="Comparison type (full, properties, dimensions)" - ) - comparison_depth: str = Field(default="full", description="Comparison depth alias") - include_properties: bool = Field(default=True, description="Include properties") - include_dimensions: bool = Field(default=True, description="Include dimensions") - include_materials: bool = Field(default=True, description="Include materials") - generate_report: bool = Field( - default=True, description="Generate comparison report" - ) async def register_template_management_tools( @@ -239,23 +226,12 @@ async def compare_templates(input_data: TemplateComparisonInput) -> dict[str, An `file_2` (size, modified time, SHA-256), `identical` and `size_delta_bytes`. Args: - input_data: The two templates. `template1_path` and `template2_path` - are required; the comparison switches have defaults and are not used - yet. + input_data: The two templates: `template1_path` and `template2_path`, + both required. Returns: dict[str, Any]: The comparison. """ - if hasattr(adapter, "compare_templates"): - result = await adapter.compare_templates(input_data.model_dump()) - require_success(result, "Failed to compare templates") - return { - "status": "success", - "message": "Template comparison completed", - "data": result.data, - "execution_time": result.execution_time, - } - file_1 = file_fact_snapshot(input_data.template1_path) file_2 = file_fact_snapshot(input_data.template2_path) diff --git a/src/solidworks_mcp/utils/feature_tree_classifier.py b/src/solidworks_mcp/utils/feature_tree_classifier.py index 5d8dc5a1..ecf790f2 100644 --- a/src/solidworks_mcp/utils/feature_tree_classifier.py +++ b/src/solidworks_mcp/utils/feature_tree_classifier.py @@ -2,6 +2,7 @@ from __future__ import annotations +import re from collections.abc import Mapping from typing import Any @@ -49,6 +50,12 @@ ) _ASSEMBLY_TOKENS = ("mate", "component", "subassembly") +#: A mate or the Mates folder (MateGroup), never "Material ", +#: which every real part's tree has. +_ASSEMBLY_PATTERN = re.compile(r"\bmate(?!rial)|\bcomponent|\bsubassembly") +#: Document types get_model_info reports; when one is known, it decides the +#: family, and feature names can't turn a part into an assembly. +_KNOWN_DOCUMENT_TYPES = frozenset({"part", "assembly", "drawing"}) _DRAWING_TOKENS = ( "sheet format", "drawing view", @@ -86,6 +93,24 @@ def _feature_text(feature: Mapping[str, Any]) -> str: return f"{name} {feature_type}".strip() +def _is_tree_folder(feature: Mapping[str, Any]) -> bool: + """Tell whether a tree row is a folder, not a feature. + + Every real tree has folders ("HistoryFolder", "SensorFolder", + "SurfaceBodyFolder", "MaterialFolder", ...). Their names and types would + match feature words: "fold" (sheet metal) is inside "folder", "surface" + (advanced solid) inside "Surface Bodies". + + Args: + feature (Mapping[str, Any]): A ``list_features`` row. + + Returns: + bool: True when the row's type ends with "folder". + """ + + return _as_lower_text(feature.get("type")).endswith("folder") + + def _has_any(texts: list[str], tokens: tuple[str, ...]) -> bool: """Build internal has any. @@ -141,7 +166,11 @@ def classify_feature_tree_snapshot( """ feature_list = list(features or []) - feature_texts = [_feature_text(feature) for feature in feature_list] + feature_texts = [ + _feature_text(feature) + for feature in feature_list + if not _is_tree_folder(feature) + ] document_type = _as_lower_text((model_info or {}).get("type")) or "unknown" evidence: list[str] = [] @@ -153,7 +182,10 @@ def classify_feature_tree_snapshot( confidence = "low" needs_vba = False - if document_type == "assembly" or _has_any(feature_texts, _ASSEMBLY_TOKENS): + unknown_type = document_type not in _KNOWN_DOCUMENT_TYPES + if document_type == "assembly" or ( + unknown_type and any(_ASSEMBLY_PATTERN.search(t) for t in feature_texts) + ): family = "assembly" workflow = "assembly-planning" confidence = "high" if document_type == "assembly" else "medium" @@ -164,7 +196,9 @@ def classify_feature_tree_snapshot( "Delegate part-level reconstruction for each component separately", ] ) - elif document_type == "drawing" or _has_any(feature_texts, _DRAWING_TOKENS): + elif document_type == "drawing" or ( + unknown_type and _has_any(feature_texts, _DRAWING_TOKENS) + ): family = "drawing" workflow = "drawing-review" confidence = "high" if document_type == "drawing" else "medium" diff --git a/src/solidworks_mcp/utils/sw_dependencies.py b/src/solidworks_mcp/utils/sw_dependencies.py new file mode 100644 index 00000000..3fc6a960 --- /dev/null +++ b/src/solidworks_mcp/utils/sw_dependencies.py @@ -0,0 +1,40 @@ +"""Read the file paths out of SolidWorks' ``GetDependencies2`` reply.""" + +from __future__ import annotations + +import os +from pathlib import Path, PureWindowsPath +from typing import Any + +_MODEL_SUFFIXES = (".sldprt", ".sldasm", ".slddrw") + + +def dependency_paths(raw_dependencies: Any) -> list[Path]: + """The model files in a ``GetDependencies2`` reply, each once, in order. + + ``IModelDoc2.GetDependencies2`` returns a flat array that alternates a + document's name and its full path. Only full paths to SolidWorks model + files are kept; a repeated path (compared as Windows does, ignoring case) + is kept once. + + Args: + raw_dependencies: The reply; anything other than a list or tuple + gives no paths. + + Returns: + list[Path]: The absolute model-file paths. + """ + if not isinstance(raw_dependencies, (list, tuple)): + return [] + paths: list[Path] = [] + seen: set[str] = set() + for item in raw_dependencies: + if not isinstance(item, str) or not item.lower().endswith(_MODEL_SUFFIXES): + continue + path = Path(item) + key = os.path.normcase(os.path.normpath(item)) + absolute = path.is_absolute() or PureWindowsPath(item).is_absolute() + if absolute and key not in seen: + seen.add(key) + paths.append(path) + return paths diff --git a/tests/conftest.py b/tests/conftest.py index 09d7092c..f1046295 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -464,7 +464,7 @@ def perf_monitor() -> PerformanceMonitor: def import_without(): """Import a module in a child interpreter with some dependencies blocked. - Used to test the "dependency not installed" fallbacks (pywin32, comtypes, + Used to test the "dependency not installed" fallbacks (pywin32, pydantic-ai, ...). A child process keeps the blocked import out of this test session; coverage measures it via ``patch = subprocess``. diff --git a/tests/live/test_live_sw_experimental_tools.py b/tests/live/test_live_sw_experimental_tools.py new file mode 100644 index 00000000..8901d57f --- /dev/null +++ b/tests/live/test_live_sw_experimental_tools.py @@ -0,0 +1,539 @@ +"""The experimental tools (``experimental-tools-to-stable``), checked on real SolidWorks. + +Every test calls the tools as an agent would, through the MCP tool functions +with plain dicts, and prints its proof as ``[evidence]`` lines. They run in +three batches, one test per process, each with the maintainer's permission: + +1. reading: ``get_file_properties``, ``list_configurations``, + ``get_dimension`` (a length and an angle), ``classify_feature_tree``; +2. files: ``load_part`` and ``load_assembly``, ``pack_and_go_assembly``; +3. tools that never call SolidWorks, on files SolidWorks wrote: + ``compare_templates``, ``compare_drawing_versions``, ``generate_vba_code`` + (its macro run by ``execute_macro``). + +Run one with:: + + powershell -ExecutionPolicy Bypass -File tests\\scripts\\live_demo.ps1 ` + -Test tests/live/test_live_sw_experimental_tools.py::test_file_properties_of_a_saved_then_edited_part + +Collected only with ``SOLIDWORKS_MCP_RUN_REAL_INTEGRATION=1`` on Windows (see +``tests/live/conftest.py``). +""" + +from __future__ import annotations + +import shutil +from pathlib import Path +from typing import Any + +import pytest + +from tests.live.evidence import evidence +from tests.live.test_live_sw_beta_tools import _saved_block, _sketch +from tests.live.test_live_sw_ujoint_tool_gaps import _plate_and_pin + +pytestmark = pytest.mark.asyncio + + +async def _tools(adapter: Any) -> dict[str, Any]: + """Every tool family these tests need, registered on ``adapter``; name -> fn.""" + from fastmcp import FastMCP + + from solidworks_mcp.tools.automation import register_automation_tools + from solidworks_mcp.tools.drawing import register_drawing_tools + from solidworks_mcp.tools.drawing_analysis import register_drawing_analysis_tools + from solidworks_mcp.tools.engineering_data import register_engineering_data_tools + from solidworks_mcp.tools.file_management import register_file_management_tools + from solidworks_mcp.tools.macro_recording import register_macro_recording_tools + from solidworks_mcp.tools.modeling import register_modeling_tools + from solidworks_mcp.tools.server_admin import register_server_admin_tools + from solidworks_mcp.tools.sketching import register_sketching_tools + from solidworks_mcp.tools.template_management import ( + register_template_management_tools, + ) + + mcp = FastMCP("experimental-tools-live") + for register in ( + register_modeling_tools, + register_sketching_tools, + register_drawing_tools, + register_drawing_analysis_tools, + register_engineering_data_tools, + register_file_management_tools, + register_macro_recording_tools, + register_automation_tools, + register_template_management_tools, + register_server_admin_tools, + ): + await register(mcp, adapter, {}) + return {t.name: t.fn for t in await mcp.list_tools()} + + +def _open_doc(adapter: Any, path: str) -> Any: + """An open document by its path, as ``IModelDoc2`` (test-side COM).""" + from solidworks_mcp.adapters import sw_type_info + + doc = adapter.swApp.GetOpenDocumentByName(path) + assert doc is not None, f"{path} is not open" + return sw_type_info.flagged(doc, "IModelDoc2") + + +async def _close_everything(tools: dict[str, Any]) -> None: + """Close the test's documents (all saved) one at a time, without saving.""" + for _ in range(10): # a few documents at most; never loop forever + if not (await tools["list_open_documents"]())["count"]: + return + assert (await tools["close_model"]({"save": False}))["status"] == "success" + raise AssertionError("documents still open after 10 closes") + + +async def _two_part_assembly( + scratch: Any, tools: dict[str, Any], folder: Path, tag: str +) -> tuple[str, str, str]: + """A saved assembly of the plate and the pin; (assembly, plate, pin) paths.""" + adapter = scratch.adapter + plate, pin = await _plate_and_pin(scratch, tools, folder, tag) + assert (await tools["create_assembly"]({"name": tag}))["status"] == "success" + assert (await adapter.insert_component(plate, 0.0, 0.0, 0.0)).is_success + assert (await adapter.insert_component(pin, 40.0, 0.0, 0.0)).is_success + assembly = str(folder / f"{tag}.SLDASM") + saved = await tools["save_file"]({"file_path": assembly}) + scratch.written_files.append(assembly) + assert saved["status"] == "success", saved + return assembly, plate, pin + + +# ---- batch 1: reading ---------------------------------------------------------- + + +async def test_file_properties_of_a_saved_then_edited_part(scratch, tmp_path) -> None: + tools = await _tools(scratch.adapter) + part = tmp_path / "props.SLDPRT" + await _saved_block(scratch, tools, part) + + saved = (await tools["get_file_properties"]())["properties"] + await _sketch(tools, "Front", {"center_x": 0, "center_y": 5, "radius": 2}) + edited = (await tools["get_file_properties"]())["properties"] + evidence( + "file properties of a saved part, then after adding a sketch", + { + "saved": { + k: saved[k] for k in ("file_name", "file_size_bytes", "is_dirty") + }, + "path_matches": Path(saved["file_path"]) == part, + "edited_is_dirty": edited["is_dirty"], + }, + call="get_file_properties()", + ) + assert Path(saved["file_path"]) == part + assert saved["file_size_bytes"] == part.stat().st_size > 0 + assert saved["modified_date"] is not None + assert saved["is_dirty"] is False + assert edited["is_dirty"] is True + + +async def test_two_configurations_are_listed(scratch, tmp_path) -> None: + tools = await _tools(scratch.adapter) + await _saved_block(scratch, tools, tmp_path / "configs.SLDPRT") + # No tool adds a configuration: add one through the API. + manager = scratch.adapter.currentModel.ConfigurationManager + added = manager.AddConfiguration2("Long", "", "", 0, "", "", True) + assert added is not None + + listed = await tools["list_configurations"]() + evidence( + "list_configurations after adding a configuration named Long", + {"configurations": listed["configurations"], "count": listed["count"]}, + call="list_configurations()", + ) + assert sorted(listed["configurations"]) == ["Default", "Long"] + assert listed["count"] == 2 + + +async def test_a_length_and_an_angle_dimension(scratch) -> None: + """A 10 mm extrusion in mm; a 270° revolve in degrees.""" + adapter = scratch.adapter + tools = await _tools(adapter) + assert (await tools["create_part"]({"name": "dims"}))["status"] == "success" + await _sketch(tools, "Top", {"x1": -10, "y1": -10, "x2": 10, "y2": 10}) + boss = await tools["create_extrusion"]({"depth": 10.0}) + assert boss["status"] == "success", boss + length = await tools["get_dimension"]({"name": "D1@Boss-Extrude1"}) + + profile = await _sketch(tools, "Front", {"x1": 20, "y1": 0, "x2": 30, "y2": 10}) + axis = (await adapter.create_axis("y")).data["name"] + revolve = await tools["create_revolve"]( + {"sketch_name": profile, "axis_entity": axis, "angle": 270} + ) + assert revolve["status"] == "success", revolve + feature = revolve["revolve"]["name"] + listed = await tools["list_model_dimensions"]({"feature_name": feature}) + readings = [ + (await tools["get_dimension"]({"name": d["full_name"]}))["dimension"] + for d in listed["data"] + ] + missing = await tools["get_dimension"]({"name": "D9@Sketch1"}) + evidence( + "get_dimension: the extrusion's depth, then each of the revolve's dimensions", + { + "length": length["dimension"], + "revolve": readings, + "missing": missing.get("message"), + }, + call='get_dimension({"name": "D1@Boss-Extrude1"})', + ) + assert length["dimension"]["value"] == pytest.approx(10.0) + assert length["dimension"]["units"] == "mm" + angles = [r for r in readings if r["units"] == "deg"] + assert [a["value"] for a in angles] == [pytest.approx(270.0)] + assert missing["error_type"] == "not_found" + assert "list_model_dimensions" in missing["message"] + + +async def test_a_part_and_an_assembly_are_classified(scratch, tmp_path) -> None: + tools = await _tools(scratch.adapter) + await _two_part_assembly(scratch, tools, tmp_path, "classify") + assembly = await tools["classify_feature_tree"]({}) + assert (await tools["create_part"]({"name": "plain"}))["status"] == "success" + await _sketch(tools, "Top", {"x1": -10, "y1": -10, "x2": 10, "y2": 10}) + assert (await tools["create_extrusion"]({"depth": 10.0}))["status"] == "success" + part = await tools["classify_feature_tree"]({}) + evidence( + "classify_feature_tree on an assembly, then on an extruded part", + { + "assembly": assembly["classification"]["family"], + "part": part["classification"]["family"], + "part_workflow": part["classification"]["recommended_workflow"], + }, + call="classify_feature_tree({})", + ) + assert assembly["classification"]["family"] == "assembly" + assert part["classification"]["family"] == "extrude" + + +# ---- batch 2: files ------------------------------------------------------------ + + +async def test_a_part_and_an_assembly_reload(scratch, tmp_path) -> None: + adapter = scratch.adapter + tools = await _tools(adapter) + assembly, plate, _pin = await _two_part_assembly(scratch, tools, tmp_path, "reload") + await _close_everything(tools) + + part = await tools["load_part"]({"file_path": plate}) + asm = await tools["load_assembly"]({"file_path": assembly}) + wrong = await tools["load_assembly"]({"file_path": plate}) + missing = await tools["load_part"]({"file_path": str(tmp_path / "gone.SLDPRT")}) + evidence( + "load_part and load_assembly after closing, a wrong type, a missing file", + { + "part": part.get("model"), + "assembly": asm.get("model"), + "wrong_type": wrong.get("message"), + "missing": [missing.get("error_type"), missing.get("message")], + }, + call=f'load_part({{"file_path": "{Path(plate).name}"}})', + ) + assert part["status"] == "success", part + assert Path(part["model"]["path"]) == Path(plate) + assert part["model"]["configuration"] == "Default" + assert asm["status"] == "success", asm + assert asm["model"]["type"] == "Assembly" + assert wrong["error_type"] == "invalid_input" + assert missing["error_type"] == "not_found" + + +async def test_pack_and_go_keeps_the_folder_and_the_open_documents( + scratch, tmp_path +) -> None: + """A folder with a note, a part with unsaved changes, two packs into one folder.""" + adapter = scratch.adapter + tools = await _tools(adapter) + assembly, plate, _pin = await _two_part_assembly(scratch, tools, tmp_path, "pack") + target = tmp_path / "packed" + target.mkdir() + (target / "notes.txt").write_text("keep me", encoding="utf-8") + _open_doc(adapter, plate).SetSaveFlag() # unsaved changes in the plate + open_before = (await tools["list_open_documents"]())["count"] + + refused = await tools["pack_and_go_assembly"]( + {"source_path": assembly, "target_dir": str(target)} + ) + first = await tools["pack_and_go_assembly"]( + {"source_path": assembly, "target_dir": str(target), "overwrite": True} + ) + second = await tools["pack_and_go_assembly"]( + {"source_path": assembly, "target_dir": str(target), "overwrite": True} + ) + open_after = (await tools["list_open_documents"]())["count"] + plate_dirty = bool(_open_doc(adapter, plate).GetSaveFlag()) + for name in first.get("copied_files") or []: + scratch.written_files.append(name) + evidence( + "pack_and_go_assembly into a folder holding notes.txt, twice", + { + "without_overwrite": refused.get("message"), + "first_copied": [Path(f).name for f in first.get("copied_files") or []], + "first_warning": first.get("warning"), + "second": second.get("status"), + "folder_after": sorted(p.name for p in target.iterdir()), + "notes_kept": (target / "notes.txt").read_text(encoding="utf-8"), + "open_documents": [open_before, open_after], + "plate_still_unsaved": plate_dirty, + }, + call='pack_and_go_assembly({"source_path": "pack.SLDASM", "overwrite": true})', + ) + assert refused["error_type"] == "invalid_input" + assert first["status"] == "success", first + assert sorted(Path(f).name.lower() for f in first["copied_files"]) == [ + "pack.sldasm", + "pack_pin.sldprt", + "pack_plate.sldprt", + ] + # The plate is named (the assembly may be too, once a part has changed). + assert Path(plate).name.lower() in [n.lower() for n in first["unsaved_changes"]] + assert Path(plate).name.lower() in first["warning"].lower() + assert second["status"] == "success", second + assert (target / "notes.txt").read_text(encoding="utf-8") == "keep me" + assert open_after >= open_before + assert plate_dirty is True + + +async def test_the_packed_assembly_opens_from_its_folder(scratch, tmp_path) -> None: + from solidworks_mcp.adapters import sw_type_info + + adapter = scratch.adapter + tools = await _tools(adapter) + source = tmp_path / "src" + source.mkdir() + assembly, _plate, _pin = await _two_part_assembly(scratch, tools, source, "moved") + target = tmp_path / "moved_copy" + packed = await tools["pack_and_go_assembly"]( + {"source_path": assembly, "target_dir": str(target)} + ) + assert packed["status"] == "success", packed + scratch.written_files.extend(packed["copied_files"]) + # Close the originals, so the copy's same-named files are the ones loaded. + await _close_everything(tools) + + opened = await tools["load_assembly"]({"file_path": str(target / "moved.SLDASM")}) + asm = sw_type_info.flagged(adapter.currentModel, "IAssemblyDoc") + paths = [ + str(sw_type_info.flagged(c, "IComponent2").GetPathName()) + for c in asm.GetComponents(True) + ] + evidence( + "the packed assembly opened from its new folder: where its parts load from", + {"opened": opened.get("model"), "components": paths}, + call='load_assembly({"file_path": "moved_copy/moved.SLDASM"})', + ) + assert opened["status"] == "success", opened + assert len(paths) == 2 + assert all(Path(p).parent == target for p in paths) + + +# ---- batch 3: tools that never call SolidWorks, on SolidWorks' files ------------ + + +async def test_templates_are_compared(scratch) -> None: + adapter = scratch.adapter + tools = await _tools(adapter) + part = adapter._resolve_template_path([8, 0, 1, 2, 3], ".prtdot") + assembly = adapter._resolve_template_path([9, 2, 3, 1, 0], ".asmdot") + assert part and assembly, (part, assembly) + + same = await tools["compare_templates"]( + {"template1_path": part, "template2_path": part} + ) + other = await tools["compare_templates"]( + {"template1_path": part, "template2_path": assembly} + ) + old_switch = await tools["compare_templates"]( + {"template1_path": part, "template2_path": assembly, "include_properties": True} + ) + evidence( + "the installed part template against itself, then against the assembly one", + { + "same": [ + same["comparison"]["identical"], + same["comparison"]["size_delta_bytes"], + ], + "other": [ + other["comparison"]["identical"], + other["comparison"]["size_delta_bytes"], + ], + "include_properties": old_switch.get("message"), + }, + call=f'compare_templates({{"template1_path": "{Path(part).name}", ...}})', + ) + assert same["comparison"]["identical"] is True + assert other["comparison"]["identical"] is False + assert other["comparison"]["size_delta_bytes"] == ( + Path(assembly).stat().st_size - Path(part).stat().st_size + ) + assert old_switch["error_type"] == "invalid_input" + + +async def test_drawing_versions_are_compared(scratch, tmp_path) -> None: + """Saved, re-saved unchanged, and saved again after adding a view.""" + tools = await _tools(scratch.adapter) + part = tmp_path / "drawn.SLDPRT" + await _saved_block(scratch, tools, part) + assert (await tools["create_drawing"]({"name": "versions"}))["status"] == "success" + views = await tools["create_technical_drawing"]({"model_file": str(part)}) + assert views["status"] == "success", views + first = tmp_path / "v1.SLDDRW" + scratch.written_files.append(str(first)) + assert (await tools["save_file"]({"file_path": str(first)}))["status"] == "success" + kept = tmp_path / "v1_copy.SLDDRW" + shutil.copyfile(first, kept) + assert (await tools["save_file"]({}))["status"] == "success" # unchanged + resaved = await tools["compare_drawing_versions"]( + {"drawing_version_1": str(kept), "drawing_version_2": str(first)} + ) + iso = await tools["add_drawing_view"]( + {"model_file": str(part), "view_type": "isometric", "position": [230, 100]} + ) + assert iso["status"] == "success", iso + second = tmp_path / "v2.SLDDRW" + scratch.written_files.append(str(second)) + assert (await tools["save_as"]({"file_path": str(second)}))["status"] == "success" + changed = await tools["compare_drawing_versions"]( + {"drawing_version_1": str(kept), "drawing_version_2": str(second)} + ) + evidence( + "a drawing re-saved unchanged, then saved again with one more view", + { + "unchanged_resave_identical": resaved["comparison"]["identical"], + "with_a_view_identical": changed["comparison"]["identical"], + "size_delta_bytes": changed["comparison"]["size_delta_bytes"], + }, + call='compare_drawing_versions({"drawing_version_1": "v1", ...})', + ) + assert resaved["status"] == "success" # identical or not: recorded above + assert changed["comparison"]["identical"] is False + + +async def test_a_generated_macro_runs(scratch, tmp_path) -> None: + """Generated for a part: it runs on a part, and stops on a drawing.""" + from solidworks_mcp.adapters import sw_type_info + + adapter = scratch.adapter + tools = await _tools(adapter) + generated = await tools["generate_vba_code"]( + { + "operation_description": "Add 3 holes (M6), then save", + "target_document": "Part", + } + ) + vba = generated["vba_code"] + macro = tmp_path / "skeleton.swb" + macro.write_text(vba["code"], encoding="ascii") + part = tmp_path / "macro_part.SLDPRT" + await _saved_block(scratch, tools, part) + + on_part = await tools["execute_macro"]({"macro_path": str(macro)}) + assert (await tools["create_drawing"]({"name": "macro_drawing"}))[ + "status" + ] == "success" + drawing = sw_type_info.flagged(adapter.currentModel, "IModelDoc2") + dirty_before = bool(drawing.GetSaveFlag()) + on_drawing = await tools["execute_macro"]({"macro_path": str(macro)}) + dirty_after = bool(drawing.GetSaveFlag()) + evidence( + "a generated macro run on a part, then on a drawing (it stops there)", + { + "sub_name": vba["sub_name"], + "on_part": on_part.get("message"), + "on_drawing": on_drawing.get("message"), + "drawing_changed": dirty_before != dirty_after, + }, + call='execute_macro({"macro_path": "skeleton.swb"})', + ) + assert vba["sub_name"] == "Add_3_holes_M6_then_save" + assert on_part["status"] == "success", on_part + assert on_drawing["status"] == "success", on_drawing + assert dirty_before == dirty_after + + +#: A macro that ran from a .swb in the beta batch, cut to its first lines. +_CONTROL = ( + "Dim swApp As Object\nSub main()\n Set swApp = Application.SldWorks\nEnd Sub\n" +) + + +def _macro_variants(generated: str, sub_name: str) -> dict[str, tuple[str, str]]: + """Each variant changes one thing from the control; name -> (text, proc). + + The generated macro failed with ``errors=0`` and no reason, so these + find which of its constructs the .swb runner rejects. + """ + body = " Set swApp = Application.SldWorks\n" + + def sub(name: str, inner: str = "", head: str = "") -> str: + return f"{head}Dim swApp As Object\nSub {name}()\n{body}{inner}End Sub\n" + + return { + "control": (_CONTROL, "main"), + "sub_not_named_main": (sub("Add_3_holes"), "Add_3_holes"), + "option_explicit": (sub("main", head="Option Explicit\n\n"), "main"), + "comment_header": (sub("main", head="' a comment\n\n"), "main"), + "dim_inside_sub": ( + "Sub main()\n Dim swApp As Object\n" + body + "End Sub\n", + "main", + ), + "debug_print": (sub("main", ' Debug.Print "Done"\n'), "main"), + "exit_sub": (sub("main", " Exit Sub\n"), "main"), + "get_type_check": ( + sub( + "main", + " Dim swModel As Object\n" + " Set swModel = swApp.ActiveDoc\n" + " If swModel.GetType <> 1 Then\n" + " Exit Sub\n" + " End If\n", + ), + "main", + ), + "generated_sub_renamed_main": ( + generated.replace(f"Sub {sub_name}()", "Sub main()"), + "main", + ), + "generated_as_is": (generated, sub_name), + } + + +async def test_which_macro_text_runs_from_a_swb(scratch, tmp_path) -> None: + """Diagnostic: run each variant on a part and record which run. + + Every variant only reads; none changes the part. The circuit breaker is + reset after each run, so the expected failures can't pause execute_macro. + """ + tools = await _tools(scratch.adapter) + generated = ( + await tools["generate_vba_code"]( + { + "operation_description": "Add 3 holes (M6), then save", + "target_document": "Part", + } + ) + )["vba_code"] + assert (await tools["create_part"]({"name": "macro_probe"}))["status"] == "success" + + ran: dict[str, str] = {} + for name, (text, proc) in _macro_variants( + generated["code"], generated["sub_name"] + ).items(): + macro = tmp_path / f"{name}.swb" + macro.write_text(text, encoding="ascii") + result = await tools["execute_macro"]( + {"macro_path": str(macro), "proc_name": proc} + ) + ran[name] = "ran" if result["status"] == "success" else "failed" + await tools["reset_circuit_breaker"]({}) + evidence( + "each macro variant run from a .swb on a part", + ran, + call='execute_macro({"macro_path": ".swb", "proc_name": ...})', + ) + assert ran["control"] == "ran", ran diff --git a/tests/solidworks_mcp/adapters/solidworks/test_io.py b/tests/solidworks_mcp/adapters/solidworks/test_io.py index f3f7a676..db9a04a7 100644 --- a/tests/solidworks_mcp/adapters/solidworks/test_io.py +++ b/tests/solidworks_mcp/adapters/solidworks/test_io.py @@ -3,14 +3,10 @@ from __future__ import annotations from types import SimpleNamespace -from unittest.mock import patch from solidworks_mcp.adapters.base import AdapterResult, AdapterResultStatus from solidworks_mcp.adapters.solidworks import io as _io_module -from solidworks_mcp.adapters.solidworks.io import ( - SolidWorksIOMixin, - _get_sw_comtypes_lib, -) +from solidworks_mcp.adapters.solidworks.io import SolidWorksIOMixin class _IOHarness(SolidWorksIOMixin): @@ -115,40 +111,14 @@ async def test_get_mass_properties_missing_gmp_fails() -> None: assert "Failed to get mass properties" in (result.error or "") -def test_get_sw_comtypes_lib_returns_cached_value() -> None: - """Second call returns the cached module without re-querying the registry (io.py:46-47).""" - sentinel = object() - with patch.object(_io_module, "_sw_comtypes_lib", sentinel): - result = _get_sw_comtypes_lib() - assert result is sentinel - - -def test_get_sw_comtypes_lib_returns_none_when_comtypes_unavailable() -> None: - """Returns None immediately when comtypes is not installed (io.py:48-49).""" - with ( - patch.object(_io_module, "_sw_comtypes_lib", None), - patch.object(_io_module, "_COMTYPES_AVAILABLE", False), - ): - result = _get_sw_comtypes_lib() - assert result is None - - -def test_io_imports_without_pywin32_or_comtypes(import_without) -> None: - """Mock mode on Linux/macOS: names stay defined, COM bridges report absent.""" +def test_io_imports_without_pywin32(import_without) -> None: + """Mock mode on Linux/macOS: names stay defined.""" attrs = import_without( "solidworks_mcp.adapters.solidworks.io", - [ - "pythoncom", - "win32com", - "win32com.client", - "win32com.client.dynamic", - "comtypes", - "comtypes.client", - ], - ["_COMTYPES_AVAILABLE", "pythoncom"], + ["pythoncom", "win32com", "win32com.client", "win32com.client.dynamic"], + ["pythoncom"], ) - assert attrs["_COMTYPES_AVAILABLE"] is False assert attrs["pythoncom"] == "namespace()" @@ -416,152 +386,30 @@ async def test_save_body_as_part_failures_and_overwrite(tmp_path, monkeypatch) - assert not target.exists() # the stale file was removed before saving -# ---- pack and go: comtypes type library, COM bridge, adapter flow ------------ - - -def test_get_sw_comtypes_lib_tries_newest_version_first(monkeypatch) -> None: - tried: list[int] = [] - lib = object() - - def get_module(spec): - tried.append(spec[1]) - if spec[1] > 33: - raise OSError("type library not registered") - return lib - - monkeypatch.setattr(_io_module, "_sw_comtypes_lib", None) - monkeypatch.setattr(_io_module, "_COMTYPES_AVAILABLE", True) - monkeypatch.setattr( - _io_module, "comtypes", SimpleNamespace(GUID=str), raising=False - ) - monkeypatch.setattr( - _io_module, - "_comtypes_client", - SimpleNamespace(GetModule=get_module), - raising=False, - ) - - assert _get_sw_comtypes_lib() is lib - assert tried == [35, 34, 33] - assert _io_module._sw_comtypes_lib is lib - - -def test_get_sw_comtypes_lib_returns_none_when_no_version_is_registered( - monkeypatch, -) -> None: - def get_module(_spec): - raise OSError("type library not registered") - - monkeypatch.setattr(_io_module, "_sw_comtypes_lib", None) - monkeypatch.setattr(_io_module, "_COMTYPES_AVAILABLE", True) - monkeypatch.setattr( - _io_module, "comtypes", SimpleNamespace(GUID=str), raising=False - ) - monkeypatch.setattr( - _io_module, - "_comtypes_client", - SimpleNamespace(GetModule=get_module), - raising=False, - ) - - assert _get_sw_comtypes_lib() is None - - -class _Unknown: - """pywin32 PyIUnknown stand-in; only its repr carries the raw pointer.""" - - def __init__(self, text: str) -> None: - self._text = text - - def __repr__(self) -> str: - return self._text - - -def _bridge_env(monkeypatch, unk_repr: str) -> tuple[SimpleNamespace, list]: - calls: list = [] - - class _CtUnknown: - def __init__(self, address: int) -> None: - self.address = address - - def AddRef(self) -> None: - calls.append(("AddRef", self.address)) - - def QueryInterface(self, iface): - calls.append(("QueryInterface", iface)) - return f"{iface}@{self.address:#x}" - - def query_interface(iid): - calls.append(("ole", iid)) - return _Unknown(unk_repr) - - monkeypatch.setattr( - _io_module, "pythoncom", SimpleNamespace(IID_IUnknown="IID_IUnknown") - ) - monkeypatch.setattr( - _io_module, "comtypes", SimpleNamespace(IUnknown=object), raising=False - ) - monkeypatch.setattr( - _io_module, - "ctypes", - SimpleNamespace( - POINTER=lambda kind: kind, - cast=lambda address, _kind: _CtUnknown(address), - ), - ) - obj = SimpleNamespace(_oleobj_=SimpleNamespace(QueryInterface=query_interface)) - return obj, calls - - -def test_bridge_com_to_comtypes_reuses_the_raw_pointer(monkeypatch) -> None: - obj, calls = _bridge_env(monkeypatch, "") - - bridged = _io_module._bridge_com_to_comtypes(obj, "IModelDocExtension") - - assert bridged == "IModelDocExtension@0x2a" - assert calls == [ - ("ole", "IID_IUnknown"), - ("AddRef", 0x2A), - ("QueryInterface", "IModelDocExtension"), - ] - - -def test_bridge_com_to_comtypes_rejects_an_unparseable_pointer(monkeypatch) -> None: - obj, _calls = _bridge_env(monkeypatch, "") - - with pytest.raises(RuntimeError, match="Could not extract COM pointer"): - _io_module._bridge_com_to_comtypes(obj, "IModelDocExtension") - - -class _PackAndGo: - """IPackAndGo stand-in that records its configuration.""" - - def __init__(self, names) -> None: - self.names = names - self.FlattenToSingleFolder = False - self.save_to = None - - def SetSaveToName(self, flag, folder) -> None: - self.save_to = (flag, folder) - - def GetDocumentNames(self): - return (self.names,) +# ---- pack and go: the files GetDependencies2 lists, copied ------------------ class _PackApp: - """swApp stand-in: OpenDoc6 answers from a scripted list of (model, err).""" + """swApp stand-in: OpenDoc6 answers from a scripted list of (model, err). - def __init__(self, opens) -> None: + ``open_docs`` maps a path to a document already open. Closing documents + is never allowed: ``CloseAllDocuments`` fails the test. + """ + + def __init__(self, opens, open_docs=None) -> None: self.opens = list(opens) - self.closed_all = False + self.open_docs = dict(open_docs or {}) def OpenDoc6(self, _path, _type, _opts, _cfg, err, _warn): model, code = self.opens.pop(0) err.value = code return model + def GetOpenDocumentByName(self, path): + return self.open_docs.get(path) + def CloseAllDocuments(self, _include_unsaved) -> None: - self.closed_all = True + raise AssertionError("Pack and Go must never close the user's documents") class _PackHarness(_IOHarness): @@ -572,149 +420,198 @@ def __init__(self, app) -> None: def _adapter(self, _owner): return self + @staticmethod + def _get_attr_or_call(obj, name): + value = getattr(obj, name) + return value() if callable(value) else value -def _pack_env(monkeypatch, out_dir, *, names, statuses): - """Fake the comtypes layer; SavePackAndGo writes the packed files.""" - pg = _PackAndGo(names) - class _Ext: - def GetPackAndGo(self): - return pg +def _assembly(tmp_path, *parts: str) -> tuple[Path, SimpleNamespace]: + """An assembly and its parts on disk, and a model listing them.""" + source = tmp_path / "src" + source.mkdir(exist_ok=True) + asm = source / "a.SLDASM" + asm.write_text("asm") + listed: list[str] = [] + for name in parts: + (source / name).write_text(name) + listed += [Path(name).stem, str(source / name)] + model = SimpleNamespace(GetDependencies2=lambda *_a: tuple(listed)) + return asm, model - def SavePackAndGo(self, _pg): - for name in ("asm.SLDASM", "part.sldprt", "notes.txt"): - (out_dir / name).write_text("x") - return statuses +@pytest.fixture +def _no_flagging(monkeypatch) -> None: + """No type flagging, and plain byref stand-ins for OpenDoc6's out codes.""" + monkeypatch.setattr(_io_module._sw_type_info, "flag_doc", lambda _m, _t: None) monkeypatch.setattr( _io_module, "win32com", SimpleNamespace(client=SimpleNamespace()) ) - monkeypatch.setattr( - _io_module, - "_get_sw_comtypes_lib", - lambda: SimpleNamespace(IModelDocExtension="IModelDocExtension"), - ) - monkeypatch.setattr( - _io_module, "_bridge_com_to_comtypes", lambda _obj, _iface: _Ext() - ) - monkeypatch.setattr(_io_module._sw_type_info, "flag_doc", lambda _m, _t: None) - return pg @pytest.mark.asyncio -async def test_pack_and_go_assembly_packs_into_a_fresh_folder( - tmp_path, monkeypatch +async def test_pack_and_go_copies_the_assembly_and_each_file_it_uses( + tmp_path, _no_flagging ) -> None: + asm, model = _assembly(tmp_path, "b.sldprt", "c.SLDPRT") out_dir = tmp_path / "pkg" - pg = _pack_env( - monkeypatch, out_dir, names=["a.sldasm", "b.sldprt"], statuses=(0, 0) - ) - model = SimpleNamespace(Extension=object()) harness = _PackHarness(_PackApp([(model, 0)])) - result = await harness.pack_and_go_assembly( - str(tmp_path / "a.sldasm"), str(out_dir) - ) + result = await harness.pack_and_go_assembly(str(asm), str(out_dir)) - assert result.is_success + assert result.is_success, result.error assert harness.currentModel is model - assert pg.FlattenToSingleFolder is True - assert pg.save_to == (True, str(out_dir) + "\\") - assert result.data["source_files"] == ["a.sldasm", "b.sldprt"] - assert result.data["copied_files"] == sorted( - [str(out_dir / "asm.SLDASM"), str(out_dir / "part.sldprt")] - ) - assert result.data["save_statuses"] == [0, 0] - assert result.data["all_files_saved"] is True + assert sorted(p.name for p in out_dir.iterdir()) == [ + "a.SLDASM", + "b.sldprt", + "c.SLDPRT", + ] + assert (out_dir / "b.sldprt").read_text() == "b.sldprt" + assert result.data["copied_files"] == sorted(str(p) for p in out_dir.iterdir()) + assert [Path(f).name for f in result.data["source_files"]] == [ + "a.SLDASM", + "b.sldprt", + "c.SLDPRT", + ] + assert result.data["unsaved_changes"] == [] @pytest.mark.asyncio -async def test_pack_and_go_assembly_retries_after_closing_documents( - tmp_path, monkeypatch +async def test_pack_and_go_names_open_files_with_unsaved_changes( + tmp_path, _no_flagging ) -> None: - """err 65536 (file already open elsewhere) closes everything and retries once.""" - out_dir = tmp_path / "pkg" - _pack_env(monkeypatch, out_dir, names=None, statuses=(0, 2)) - app = _PackApp([(None, 65536), (SimpleNamespace(Extension=object()), 0)]) - harness = _PackHarness(app) + """The copy is the saved file; an open part with changes is named.""" + asm, model = _assembly(tmp_path, "plate.sldprt", "pin.sldprt") + plate = str(asm.parent / "plate.sldprt") + pin = str(asm.parent / "pin.sldprt") + open_docs = { + str(asm): model, # the assembly, open; it has no save flag to read + plate: SimpleNamespace(GetSaveFlag=lambda: True), + pin: SimpleNamespace(GetSaveFlag=False), + } + harness = _PackHarness(_PackApp([(None, 0)], open_docs=open_docs)) - result = await harness.pack_and_go_assembly( - str(tmp_path / "a.sldasm"), str(out_dir) - ) + result = await harness.pack_and_go_assembly(str(asm), str(tmp_path / "pkg")) - assert app.closed_all is True - assert result.data["source_files"] == [] - assert result.data["all_files_saved"] is False + assert result.is_success, result.error + assert harness.currentModel is model # the open copy; nothing was closed + assert result.data["unsaved_changes"] == ["plate.sldprt"] @pytest.mark.asyncio -async def test_pack_and_go_assembly_moves_an_existing_folder_aside( - tmp_path, monkeypatch +async def test_pack_and_go_keeps_other_files_and_replaces_its_own( + tmp_path, _no_flagging ) -> None: + """The folder is never emptied; packing again replaces the earlier copy.""" + asm, model = _assembly(tmp_path, "b.sldprt") out_dir = tmp_path / "pkg" out_dir.mkdir() - (out_dir / "stale.sldprt").write_text("old") - _pack_env(monkeypatch, out_dir, names=[], statuses=None) - harness = _PackHarness(_PackApp([(SimpleNamespace(Extension=object()), 0)])) + (out_dir / "notes.txt").write_text("mine") + (out_dir / "b.sldprt").write_text("an older copy") + harness = _PackHarness(_PackApp([(model, 0), (model, 0)])) - result = await harness.pack_and_go_assembly( - str(tmp_path / "a.sldasm"), str(out_dir) - ) + first = await harness.pack_and_go_assembly(str(asm), str(out_dir)) + second = await harness.pack_and_go_assembly(str(asm), str(out_dir)) - assert result.is_success - assert result.data["save_statuses"] == [] - assert str(out_dir / "stale.sldprt") not in result.data["copied_files"] - assert [p.name for p in tmp_path.iterdir()] == ["pkg"] + assert first.is_success and second.is_success + assert (out_dir / "notes.txt").read_text() == "mine" + assert (out_dir / "b.sldprt").read_text() == "b.sldprt" + assert str(out_dir / "notes.txt") not in second.data["copied_files"] @pytest.mark.asyncio -async def test_pack_and_go_assembly_keeps_going_when_the_old_folder_is_locked( - tmp_path, monkeypatch +async def test_pack_and_go_copies_nothing_when_a_file_is_missing( + tmp_path, _no_flagging ) -> None: - """SolidWorks file locks: a failed rename or delete must not stop the pack.""" + asm, _model = _assembly(tmp_path, "b.sldprt") + gone = str(asm.parent / "gone.sldprt") + model = SimpleNamespace(GetDependencies2=lambda *_a: ("gone", gone)) out_dir = tmp_path / "pkg" - out_dir.mkdir() - _pack_env(monkeypatch, out_dir, names=[], statuses=(0,)) - harness = _PackHarness(_PackApp([(SimpleNamespace(Extension=object()), 0)] * 2)) + harness = _PackHarness(_PackApp([(model, 0)])) + + result = await harness.pack_and_go_assembly(str(asm), str(out_dir)) + + assert result.status == AdapterResultStatus.ERROR + assert "were not found on disk" in (result.error or "") + assert gone in (result.error or "") + assert not out_dir.exists() + + +@pytest.mark.asyncio +async def test_pack_and_go_copies_nothing_when_two_files_share_a_name( + tmp_path, _no_flagging +) -> None: + """Renaming one would break the assembly's reference to it.""" + asm, model = _assembly(tmp_path, "b.sldprt") + other = tmp_path / "other" + other.mkdir() + (other / "B.SLDPRT").write_text("another b") + listed = model.GetDependencies2() + ("B", str(other / "B.SLDPRT")) + model = SimpleNamespace(GetDependencies2=lambda *_a: listed) + out_dir = tmp_path / "pkg" + harness = _PackHarness(_PackApp([(model, 0)])) + + result = await harness.pack_and_go_assembly(str(asm), str(out_dir)) + + assert "share a name and can't go in one folder" in (result.error or "") + assert str(other / "B.SLDPRT") in (result.error or "") + assert not out_dir.exists() + + +@pytest.mark.asyncio +async def test_pack_and_go_refuses_the_originals_folder(tmp_path, _no_flagging) -> None: + asm, model = _assembly(tmp_path, "b.sldprt") + harness = _PackHarness(_PackApp([(model, 0)])) + + result = await harness.pack_and_go_assembly(str(asm), str(asm.parent)) + + assert "target_dir holds the files being packed" in (result.error or "") + + +@pytest.mark.asyncio +async def test_pack_and_go_lists_each_file_once(tmp_path, _no_flagging) -> None: + """GetDependencies2 can repeat a file, or list the assembly itself.""" + asm, model = _assembly(tmp_path, "b.sldprt") + listed = model.GetDependencies2() + ("a", str(asm)) + model.GetDependencies2() + model = SimpleNamespace(GetDependencies2=lambda *_a: listed) + harness = _PackHarness(_PackApp([(model, 0)])) + + result = await harness.pack_and_go_assembly(str(asm), str(tmp_path / "pkg")) + + assert [Path(f).name for f in result.data["source_files"]] == [ + "a.SLDASM", + "b.sldprt", + ] - def locked(*_args, **_kwargs): - raise OSError("[WinError 32] file in use") - monkeypatch.setattr(_io_module.shutil, "rmtree", locked) - first = await harness.pack_and_go_assembly(str(tmp_path / "a.sldasm"), str(out_dir)) - backups = [p for p in tmp_path.iterdir() if p.name.startswith("pkg_bak_")] +@pytest.mark.asyncio +async def test_pack_and_go_assembly_names_a_same_name_clash( + tmp_path, _no_flagging +) -> None: + """err 65536: another document with the file's name is open; nothing is closed.""" + harness = _PackHarness(_PackApp([(None, 65536)])) - monkeypatch.setattr(_io_module.os, "rename", locked) - second = await harness.pack_and_go_assembly( - str(tmp_path / "a.sldasm"), str(out_dir) + result = await harness.pack_and_go_assembly( + str(tmp_path / "a.sldasm"), str(tmp_path / "pkg") ) - assert first.is_success and second.is_success - assert len(backups) == 1 + assert result.status == AdapterResultStatus.ERROR + assert "another document named a.sldasm is already open" in (result.error or "") + assert "nothing was closed" in (result.error or "") @pytest.mark.asyncio async def test_pack_and_go_assembly_reports_why_it_failed( - tmp_path, monkeypatch + tmp_path, _no_flagging ) -> None: - out_dir = tmp_path / "pkg" - _pack_env(monkeypatch, out_dir, names=[], statuses=()) harness = _PackHarness(_PackApp([(None, 1024)])) opened = await harness.pack_and_go_assembly( - str(tmp_path / "a.sldasm"), str(out_dir) - ) - - monkeypatch.setattr(_io_module, "_get_sw_comtypes_lib", lambda: None) - no_lib = await harness.pack_and_go_assembly( - str(tmp_path / "a.sldasm"), str(out_dir) + str(tmp_path / "a.sldasm"), str(tmp_path / "pkg") ) assert opened.status == AdapterResultStatus.ERROR assert opened.error == "Pack and Go failed: OpenDoc6 failed err=1024 warn=0" - assert no_lib.error.startswith( - "Pack and Go failed: comtypes SolidWorks type library not available" - ) @pytest.mark.asyncio @@ -828,13 +725,13 @@ async def test_open_model_uses_int_errors_when_variant_ctor_missing( self, monkeypatch ) -> None: """open_model should pass integer error/warning refs when VARIANT is unavailable.""" + # The paths are made up; open_model now checks the file exists. + monkeypatch.setattr(_io_module.os.path, "isfile", lambda _p: True) adapter = _build_adapter(monkeypatch) monkeypatch.setattr(adapter, "is_connected", lambda: True) class _Cfg: - @staticmethod - def GetName() -> str: - return "Default" + Name = "Default" # IConfiguration.Name is a property model = MagicMock() model.GetActiveConfiguration.return_value = _Cfg() @@ -1994,14 +1891,17 @@ async def test_save_export_close_and_dimension_error_paths(self, monkeypatch): model.ForceRebuild3 = Mock(return_value=True) model.Parameter = Mock( return_value=SimpleNamespace( - GetValue3=Mock(return_value=0.015), SetValue3=Mock(return_value=True) + SystemValue=0.015, + GetType=Mock(return_value=0), # a length + SetValue3=Mock(return_value=True), ) ) assert (await adapter.save_file()).is_success assert (await adapter.save_file("C:/tmp/new.sldprt")).is_success assert (await adapter.export_file("C:/tmp/out.step", "step")).is_success - assert (await adapter.get_dimension("D1@Sketch1")).data == pytest.approx(15.0) + reading = (await adapter.get_dimension("D1@Sketch1")).data + assert reading == {"value": pytest.approx(15.0), "units": "mm"} assert (await adapter.set_dimension("D1@Sketch1", 20.0)).is_success assert (await adapter.rebuild_model()).is_success @@ -2030,9 +1930,7 @@ async def test_list_configurations_falls_back_to_active_configuration( adapter.currentModel = SimpleNamespace( GetConfigurationNames=Mock(return_value=None), - GetActiveConfiguration=Mock( - return_value=SimpleNamespace(GetName=Mock(return_value="Default")) - ), + GetActiveConfiguration=Mock(return_value=SimpleNamespace(Name="Default")), ) result = await adapter.list_configurations() @@ -2047,6 +1945,8 @@ async def test_list_configurations_falls_back_to_active_configuration( ) async def test_connect_disconnect_and_document_creation_paths(self, monkeypatch): """Test COM connect lifecycle plus model creation/open branches with mocks.""" + # The paths are made up; open_model now checks the file exists. + monkeypatch.setattr(_io_module.os.path, "isfile", lambda _p: True) adapter = self._build_adapter(monkeypatch) co_initialize = Mock() @@ -2118,7 +2018,20 @@ async def test_connect_disconnect_and_document_creation_paths(self, monkeypatch) opened = await adapter.open_model("C:/Models/sample.sldasm") assert opened.is_success assert opened.data.type == "Assembly" - assert opened.data.configuration == "Default" + # No active configuration reported: None, never an assumed "Default". + assert opened.data.configuration is None + + monkeypatch.setattr(_io_module.os.path, "isfile", lambda _p: False) + missing = await adapter.open_model("C:/Models/gone.sldasm") + assert "File not found" in (missing.error or "") + fake_app.OpenDoc6.assert_called_once() # not called for the missing file + monkeypatch.setattr(_io_module.os.path, "isfile", lambda _p: True) + + # The file exists but SolidWorks opens nothing. + fake_app.OpenDoc6.return_value = None + refused = await adapter.open_model("C:/Models/broken.sldasm") + assert "Failed to open model" in (refused.error or "") + fake_app.OpenDoc6.return_value = fake_open_model unsupported = await adapter.open_model("C:/Models/sample.txt") assert unsupported.is_error @@ -2571,6 +2484,31 @@ async def test_close_model_reads_get_title_property_style( close_doc.assert_called_once_with("wifi_box_snapfit") assert adapter.currentModel is None + @pytest.mark.asyncio + async def test_close_model_twice_closes_the_document_solidworks_activated( + self, monkeypatch + ) -> None: + """Seen on SolidWorks 2026: after one close, SolidWorks makes another + open document active. The next close closes that one, instead of + failing with "No active model to close".""" + adapter = self._build_adapter(monkeypatch) + app = SimpleNamespace(CloseDoc=Mock(), ActiveDoc=None) + adapter.swApp = app + adapter.currentModel = SimpleNamespace(GetTitle="asm.SLDASM") + + first = await adapter.close_model(save=False) + app.ActiveDoc = SimpleNamespace(GetTitle="plate.SLDPRT") + second = await adapter.close_model(save=False) + app.ActiveDoc = None + third = await adapter.close_model(save=False) + + assert first.is_success and second.is_success + assert [c.args[0] for c in app.CloseDoc.call_args_list] == [ + "asm.SLDASM", + "plate.SLDPRT", + ] + assert third.status.name == "WARNING" + @pytest.mark.asyncio async def test_close_model_save_reads_save_property_style( self, monkeypatch @@ -2592,6 +2530,8 @@ async def test_open_model_activates_opened_document(self, monkeypatch) -> None: opened document. OpenDoc6 with swOpenDocOptions_Silent opens the file but leaves the previously focused document active, so without this every later tool call targets the wrong document.""" + # The paths are made up; open_model now checks the file exists. + monkeypatch.setattr(_io_module.os.path, "isfile", lambda _p: True) adapter = self._build_adapter(monkeypatch) opened_doc = SimpleNamespace( @@ -4379,3 +4319,45 @@ async def test_export_image_with_an_unreadable_size(monkeypatch, tmp_path) -> No assert result.is_success, result.error assert result.data["dimensions"] == "unknown" + + +@pytest.mark.parametrize( + ("kind", "system_value", "expected"), + [ + (0, 0.01, {"value": 10.0, "units": "mm"}), + (1, 4.71238898038469, {"value": 270.0, "units": "deg"}), + (2, 6.0, {"value": 6.0, "units": None}), # a count + (-1, 0.5, {"value": 0.5, "units": None}), # unknown: never guessed + (None, 0.5, {"value": 0.5, "units": None}), # type unreadable + ], +) +def test_a_dimension_takes_the_unit_its_type_gives_it(kind, system_value, expected): + from solidworks_mcp.adapters.solidworks.io import _dimension_reading + + reading = _dimension_reading(kind, system_value) + + assert reading["units"] == expected["units"] + assert reading["value"] == pytest.approx(expected["value"]) + + +@pytest.mark.asyncio +async def test_a_dimension_whose_value_cant_be_read_fails() -> None: + """No guessed number: an unreadable SystemValue is an error.""" + model = SimpleNamespace(Parameter=lambda _name: SimpleNamespace(GetType=lambda: 0)) + harness = _IOHarness(model) + + result = await harness.get_dimension("D1@Sketch1") + + assert result.status == AdapterResultStatus.ERROR + assert "Failed to read dimension 'D1@Sketch1'" in (result.error or "") + + +@pytest.mark.asyncio +async def test_a_missing_dimension_points_at_the_lister() -> None: + harness = _IOHarness(SimpleNamespace(Parameter=lambda _name: None)) + + result = await harness.get_dimension("D9@Sketch1") + + assert "not found; list the names with list_model_dimensions" in ( + result.error or "" + ) diff --git a/tests/solidworks_mcp/adapters/test_mock_adapter.py b/tests/solidworks_mcp/adapters/test_mock_adapter.py index ec2598df..4717ad59 100644 --- a/tests/solidworks_mcp/adapters/test_mock_adapter.py +++ b/tests/solidworks_mcp/adapters/test_mock_adapter.py @@ -123,7 +123,7 @@ async def test_pack_and_go_assembly_mock(self, mock_adapter, tmp_path) -> None: source_path=str(source), target_dir=str(out_dir) ) assert result.is_success - assert result.data["all_files_saved"] is True + assert result.data["unsaved_changes"] == [] assert len(result.data["copied_files"]) >= 1 @pytest.mark.asyncio diff --git a/tests/solidworks_mcp/tools/test_automation.py b/tests/solidworks_mcp/tools/test_automation.py index 896679d0..4b0d9b15 100644 --- a/tests/solidworks_mcp/tools/test_automation.py +++ b/tests/solidworks_mcp/tools/test_automation.py @@ -43,58 +43,30 @@ async def test_register_automation_tools( async def test_generate_vba_code_success( self, mcp_server, mock_adapter, mock_config ): - """Test successful VBA code generation.""" + """The skeleton names its Sub, checks the document type, never blocks.""" await register_automation_tools(mcp_server, mock_adapter, mock_config) - - mock_adapter.generate_vba_code = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "vba_code": "Sub CreateExtrusion()\n ' Generated VBA code\n swModel.FeatureManager.FeatureExtrusion2(...)\nEnd Sub", - "operation_type": "Extrusion", - "parameter_count": 15, - "estimated_execution_time": 2.1, - "complexity_level": "High", - }, - execution_time=0.8, - ) + tool_func = next( + t.fn for t in await mcp_server.list_tools() if t.name == "generate_vba_code" ) - input_data = VBAGenerationInput( - operation_type="Extrusion", - parameters={ - "sketch_name": "Sketch1", - "depth": 25.0, - "direction": "Blind", - "reverse_direction": False, - "draft_angle": 0.0, - "draft_outward": True, - "thin_feature": False, - "merge_result": True, - "start_condition": "SketchPlane", - "end_condition": "Blind", - "end_condition_reference": None, - "offset_parameters": {}, - "feature_scope": "All bodies", - "auto_select": True, - "assembly_feature_scope": "All components", - }, + result = await tool_func( + input_data=VBAGenerationInput( + operation_type="Add 3 holes (M6), then save", target_document="part" + ) ) - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "generate_vba_code": - tool_func = tool.fn - break - - assert tool_func is not None - result = await tool_func(input_data=input_data) - + vba = result["vba_code"] assert result["status"] == "success" - assert "CreateExtrusion" in result["data"]["vba_code"] - assert result["data"]["parameter_count"] == 15 - assert result["data"]["complexity_level"] == "High" - mock_adapter.generate_vba_code.assert_called_once() + assert vba["sub_name"] == "Add_3_holes_M6_then_save" + assert "Sub Add_3_holes_M6_then_save()" in vba["code"] + # SolidWorks runs a .swb macro only through main, which calls the Sub. + assert "Sub main()\n Add_3_holes_M6_then_save\nEnd Sub" in vba["code"] + assert "If swModel.GetType <> 1 Then" in vba["code"] + assert "MsgBox" not in vba["code"] + assert "On Error GoTo ErrorHandler" in vba["code"] + assert vba["target_document"] == "Part" + assert vba["lines_of_code"] == len(vba["code"].split("\n")) + assert "style" not in vba @pytest.mark.asyncio async def test_start_macro_recording_success( @@ -396,27 +368,17 @@ async def test_automation_error_handling( """Test error handling in automation operations.""" await register_automation_tools(mcp_server, mock_adapter, mock_config) - mock_adapter.generate_vba_code = AsyncMock( - return_value=Mock( - is_success=False, - error="Invalid operation parameters", - execution_time=0.1, - ) + tool_func = next( + t.fn for t in await mcp_server.list_tools() if t.name == "generate_vba_code" ) - input_data = VBAGenerationInput( - operation_type="Invalid Operation", parameters={} + result = await tool_func( + input_data={"operation_type": "Invalid Operation", "parameters": {}} ) - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "generate_vba_code": - tool_func = tool.fn - break - - result = await tool_func(input_data=input_data) assert result["status"] == "error" - assert "Invalid operation parameters" in result["message"] + assert result["error_type"] == "invalid_input" + assert "`parameters` is no longer an input" in result["message"] @pytest.mark.asyncio async def test_automation_fallback_paths_without_adapter_methods( @@ -489,7 +451,6 @@ async def test_automation_exception_paths_from_adapter_methods( """Test exception handlers across automation tools that call adapter methods.""" await register_automation_tools(mcp_server, mock_adapter, mock_config) - mock_adapter.generate_vba_code = AsyncMock(side_effect=RuntimeError("vba boom")) mock_adapter.start_macro_recording = AsyncMock( side_effect=RuntimeError("record boom") ) @@ -534,8 +495,7 @@ async def test_automation_exception_paths_from_adapter_methods( input_data={"optimization_type": "general"} ) - assert vba["status"] == "error" - assert vba["error_type"] == "internal" + assert vba["status"] == "success" # it never calls the adapter assert start["status"] == "error" assert start["error_type"] == "internal" assert batch["status"] == "error" @@ -773,3 +733,52 @@ async def test_manage_design_table_exception(self): fn = await _get_tool(mcp, "manage_design_table") result = await fn(DesignTableInput(table_type="create", excel_file="test.xlsx")) assert result["status"] == "error" + + +@pytest.mark.parametrize( + ("description", "expected"), + [ + ("Add 3 holes (M6), then save", "Add_3_holes_M6_then_save"), + ("3D export", "Macro_3D_export"), + ("___", "Macro"), + ("x" * 300, "x" * 255), + ], +) +def test_the_sub_name_is_a_valid_vba_name(description: str, expected: str) -> None: + from solidworks_mcp.tools.automation import _vba_sub_name + + assert _vba_sub_name(description) == expected + + +@pytest.mark.parametrize( + ("document", "doc_type"), [("Part", 1), ("Assembly", 2), ("Drawing", 3)] +) +def test_the_macro_checks_its_document_type(document: str, doc_type: int) -> None: + from solidworks_mcp.tools.automation import _vba_skeleton + + code = _vba_skeleton("Go", "two\nlines", document, error_handling=False) + + assert f"If swModel.GetType <> {doc_type} Then" in code + assert f"not a {document}" in code + assert "' Generated VBA code for: two lines" in code # one comment line + assert "ErrorHandler" not in code + + +def test_an_unknown_document_type_is_refused() -> None: + from pydantic import ValidationError + + with pytest.raises(ValidationError): + VBAGenerationInput(target_document="Sketch") + with pytest.raises(ValidationError): + VBAGenerationInput(target_document=3) + assert VBAGenerationInput(target_document=" drawing ").target_document == "Drawing" + + +@pytest.mark.parametrize("name", ["main", "Main"]) +def test_a_sub_named_main_is_not_wrapped(name: str) -> None: + """A second main would be a duplicate definition; VBA names ignore case.""" + from solidworks_mcp.tools.automation import _vba_skeleton + + code = _vba_skeleton(name, name, "Part", error_handling=False) + + assert code.lower().count("sub main()") == 1 diff --git a/tests/solidworks_mcp/tools/test_drawing_analysis.py b/tests/solidworks_mcp/tools/test_drawing_analysis.py index 23e0b240..ebd627ad 100644 --- a/tests/solidworks_mcp/tools/test_drawing_analysis.py +++ b/tests/solidworks_mcp/tools/test_drawing_analysis.py @@ -660,7 +660,9 @@ async def test_compare_drawing_versions_reads_real_files( # Missing paths refuse outright. missing_paths = await compare_tool(input_data={}) assert missing_paths["status"] == "error" - assert "requires both" in missing_paths["message"] + assert missing_paths["error_type"] == "invalid_input" + assert "drawing_version_1" in missing_paths["message"] + assert "drawing_version_2" in missing_paths["message"] # Non-existent files refuse with a clear message naming them. rev_a = tmp_path / "rev_a.slddrw" @@ -834,9 +836,10 @@ async def test_drawing_analysis_exception_handlers( assert report_exception["status"] == "error" assert report_exception["error_type"] == "internal" + # A typed input: a list is refused as bad input, not a crash. compare_exception = await compare_tool(input_data=[]) assert compare_exception["status"] == "error" - assert compare_exception["error_type"] == "internal" + assert compare_exception["error_type"] == "invalid_input" completeness_exception = await completeness_tool(input_data=[]) assert completeness_exception["status"] == "error" diff --git a/tests/solidworks_mcp/tools/test_file_management.py b/tests/solidworks_mcp/tools/test_file_management.py index 5bf51273..d41777c8 100644 --- a/tests/solidworks_mcp/tools/test_file_management.py +++ b/tests/solidworks_mcp/tools/test_file_management.py @@ -1124,6 +1124,15 @@ async def test_classify_feature_tree_tool_paths( exception_result = await classify_tool(input_data={}) assert exception_result["status"] == "error" + # Nothing open: fail, never classify an empty model. + mock_adapter.get_model_info = AsyncMock( + return_value=Mock(is_success=False, error="No active model") + ) + nothing_open = await classify_tool(input_data={}) + assert nothing_open["status"] == "error" + assert nothing_open["error_type"] == "no_active_document" + assert "Failed to read the model to classify" in nothing_open["message"] + @pytest.mark.asyncio async def test_load_part_and_load_assembly_paths( self, mcp_server, mock_adapter, mock_config @@ -1563,7 +1572,12 @@ async def test_read_tools_fallback_when_adapter_methods_missing( assert configs_result["status"] == "error" assert "does not support list_configurations" in configs_result["message"] assert classify_result["status"] == "error" - assert "does not support list_features" in classify_result["message"] + assert "does not support get_model_info" in classify_result["message"] + # With model_info passed, it still needs the feature tree. + classify_features = await classify_tool( + input_data={"model_info": {"type": "Part"}} + ) + assert "does not support list_features" in classify_features["message"] @pytest.mark.asyncio async def test_load_tools_result_value_defaults_with_sparse_payloads( @@ -1593,7 +1607,7 @@ async def test_load_tools_result_value_defaults_with_sparse_payloads( assert part_none_data["status"] == "success" assert part_none_data["model"]["name"] == "C:/tmp/a.sldprt" assert part_none_data["model"]["path"] == "C:/tmp/a.sldprt" - assert part_none_data["model"]["configuration"] == "Default" + assert part_none_data["model"]["configuration"] is None # never assumed # Sparse object payload with None values -> _result_value falls through keys/default. sparse_model = Mock() @@ -1612,7 +1626,7 @@ async def test_load_tools_result_value_defaults_with_sparse_payloads( assert asm_sparse["status"] == "success" assert asm_sparse["model"]["name"] == "C:/tmp/a.sldasm" assert asm_sparse["model"]["path"] == "C:/tmp/a.sldasm" - assert asm_sparse["model"]["configuration"] == "Default" + assert asm_sparse["model"]["configuration"] is None # Dict payload with only None fields exercises dict fallback return-default path. mock_adapter.open_model = AsyncMock( @@ -1804,10 +1818,10 @@ async def test_save_assembly_with_references_no_getdeps_method( # ------------------------------------------------------------------ @pytest.mark.asyncio - async def test_pack_and_go_none_input_creates_empty_and_errors( + async def test_pack_and_go_requires_both_paths( self, mcp_server, mock_adapter, mock_config, tmp_path ): - """pack_and_go_assembly with None input falls through to source-not-found error.""" + """No input, or an empty one: invalid_input naming what is missing.""" await register_file_management_tools(mcp_server, mock_adapter, mock_config) pack_tool = None @@ -1817,15 +1831,13 @@ async def test_pack_and_go_none_input_creates_empty_and_errors( assert pack_tool is not None - # None input → PackAndGoInput(source_path="", target_dir=""). - # Path("") resolves to the current directory on Windows (exists=True), - # so the .sldasm extension check fires before the source-not-found check. - result = await pack_tool(input_data=None) - assert result["status"] == "error" - assert ( - "sldasm" in result["message"].lower() - or "not found" in result["message"].lower() - ) + nothing = await pack_tool(input_data=None) + assert nothing["error_type"] == "invalid_input" + + empty = await pack_tool(input_data={}) + assert empty["error_type"] == "invalid_input" + assert "source_path" in empty["message"] + assert "target_dir" in empty["message"] @pytest.mark.asyncio async def test_pack_and_go_source_not_found( @@ -1938,6 +1950,44 @@ async def test_pack_and_go_adapter_error( assert result["status"] == "error" assert "pack failed" in result["message"] + @pytest.mark.asyncio + async def test_pack_and_go_warns_about_unsaved_changes( + self, mcp_server, mock_adapter, mock_config, tmp_path + ): + """The copy is of the saved files: open files with changes are named, + alongside a preview that couldn't be written.""" + await register_file_management_tools(mcp_server, mock_adapter, mock_config) + tools = {t.name: t.fn for t in await mcp_server.list_tools()} + source = tmp_path / "box.sldasm" + source.write_text("asm", encoding="utf-8") + mock_adapter.pack_and_go_assembly = AsyncMock( + return_value=Mock( + is_success=True, + data={"copied_files": [], "unsaved_changes": ["plate.sldprt"]}, + execution_time=0.5, + ) + ) + mock_adapter.export_image = AsyncMock( + return_value=Mock(is_success=False, error="no graphics window") + ) + + result = await tools["pack_and_go_assembly"]( + input_data={ + "source_path": str(source), + "target_dir": str(tmp_path / "out"), + "overwrite": True, + "export_preview": True, + } + ) + + assert result["status"] == "success" + assert result["method"] == "dependency_copy" + assert result["warning"].startswith( + "plate.sldprt had unsaved changes, which are not in the copy; save, " + "then pack again to include them. The copy is complete, but the " + "preview couldn't be written: no graphics window" + ) + @pytest.mark.asyncio async def test_pack_and_go_success_without_preview( self, mcp_server, mock_adapter, mock_config, tmp_path @@ -1972,7 +2022,7 @@ async def test_pack_and_go_success_without_preview( } ) assert result["status"] == "success" - assert result["method"] == "native_pack_and_go" + assert result["method"] == "dependency_copy" assert "preview_image" not in result @pytest.mark.asyncio @@ -2038,7 +2088,9 @@ async def test_pack_and_go_success_preview_fails( execution_time=0.5, ) ) - mock_adapter.export_image = AsyncMock(return_value=Mock(is_success=False)) + mock_adapter.export_image = AsyncMock( + return_value=Mock(is_success=False, error="no graphics window") + ) result = await pack_tool( input_data={ @@ -2050,6 +2102,10 @@ async def test_pack_and_go_success_preview_fails( ) assert result["status"] == "success" assert result["preview_image"] is None + assert result["warning"].startswith( + "The copy is complete, but the preview couldn't be written: " + "no graphics window" + ) @pytest.mark.asyncio async def test_pack_and_go_exception( diff --git a/tests/solidworks_mcp/tools/test_modeling.py b/tests/solidworks_mcp/tools/test_modeling.py index 28feed8d..76870002 100644 --- a/tests/solidworks_mcp/tools/test_modeling.py +++ b/tests/solidworks_mcp/tools/test_modeling.py @@ -440,6 +440,31 @@ async def test_get_dimension_value(self, mcp_server, mock_adapter, mock_config): assert result["status"] == "success" assert result["dimension"]["value"] == 15.5 assert result["dimension"]["units"] == "mm" + assert result["message"] == "Dimension D1@Sketch1 = 15.5 mm" + + @pytest.mark.asyncio + async def test_get_dimension_of_a_count_has_no_unit( + self, mcp_server, mock_adapter, mock_config + ): + """A pattern's instance count: the number, no unit in the reply.""" + await register_modeling_tools(mcp_server, mock_adapter, mock_config) + mock_adapter.get_dimension = AsyncMock( + return_value=Mock( + is_success=True, data={"value": 6.0, "units": None}, execution_time=0.1 + ) + ) + tool_func = next( + t.fn for t in await mcp_server.list_tools() if t.name == "get_dimension" + ) + + result = await tool_func(GetDimensionInput(name="D1@CirPattern1")) + + assert result["dimension"] == { + "name": "D1@CirPattern1", + "value": 6.0, + "units": None, + } + assert result["message"] == "Dimension D1@CirPattern1 = 6.0" @pytest.mark.asyncio async def test_set_dimension_value(self, mcp_server, mock_adapter, mock_config): diff --git a/tests/solidworks_mcp/tools/test_template_management.py b/tests/solidworks_mcp/tools/test_template_management.py index 7febc4c3..b38e1cd1 100644 --- a/tests/solidworks_mcp/tools/test_template_management.py +++ b/tests/solidworks_mcp/tools/test_template_management.py @@ -193,65 +193,56 @@ async def test_batch_apply_template_success( @pytest.mark.asyncio async def test_compare_templates_success( - self, mcp_server, mock_adapter, mock_config + self, mcp_server, mock_adapter, mock_config, tmp_path ): - """Test successful template comparison.""" + """Two files on disk are compared by content and size.""" await register_template_management_tools(mcp_server, mock_adapter, mock_config) + tool_func = next( + t.fn for t in await mcp_server.list_tools() if t.name == "compare_templates" + ) + part = tmp_path / "part.prtdot" + part.write_bytes(b"part template") + copy = tmp_path / "copy.prtdot" + copy.write_bytes(b"part template") + assembly = tmp_path / "assembly.asmdot" + assembly.write_bytes(b"assembly template, longer") - mock_adapter.compare_templates = AsyncMock( - return_value=Mock( - is_success=True, - data={ - "template1": "old_template.prtdot", - "template2": "new_template.prtdot", - "differences_found": 8, - "similarity_percentage": 75.5, - "added_properties": ["MaterialDensity", "CostCenter"], - "removed_properties": ["OldRevision"], - "modified_properties": ["Description", "PartNumber", "Author"], - "identical_properties": [ - "Title", - "Subject", - "Keywords", - "Comments", - ], - "comparison_details": { - "units_different": False, - "dimensions_different": True, - "materials_different": False, - "custom_properties_different": True, - }, - }, - execution_time=0.9, + same = await tool_func( + input_data=TemplateComparisonInput( + template1_path=str(part), template2_path=str(copy) ) ) - - input_data = TemplateComparisonInput( - template1_path="templates/old_template.prtdot", - template2_path="templates/new_template.prtdot", - comparison_depth="Detailed", - include_properties=True, - include_dimensions=True, - include_materials=True, + other = await tool_func( + input_data=TemplateComparisonInput( + template1_path=str(part), template2_path=str(assembly) + ) ) - tool_func = None - for tool in await mcp_server.list_tools(): - if tool.name == "compare_templates": - tool_func = tool.fn - break + assert same["comparison"]["identical"] is True + assert same["comparison"]["size_delta_bytes"] == 0 + assert other["comparison"]["identical"] is False + assert other["comparison"]["size_delta_bytes"] == 12 + assert "only" in other["note"] - assert tool_func is not None - result = await tool_func(input_data=input_data) + @pytest.mark.asyncio + async def test_compare_templates_refuses_its_old_switches( + self, mcp_server, mock_adapter, mock_config + ): + await register_template_management_tools(mcp_server, mock_adapter, mock_config) + tool_func = next( + t.fn for t in await mcp_server.list_tools() if t.name == "compare_templates" + ) - assert result["status"] == "success" - assert result["data"]["differences_found"] == 8 - assert result["data"]["similarity_percentage"] == 75.5 - assert "MaterialDensity" in result["data"]["added_properties"] - assert ( - result["data"]["comparison_details"]["custom_properties_different"] is True + result = await tool_func( + input_data={ + "template1_path": "a.prtdot", + "template2_path": "b.prtdot", + "include_properties": True, + } ) - mock_adapter.compare_templates.assert_called_once() + + assert result["error_type"] == "invalid_input" + assert "compares the two files on disk" in result["message"] @pytest.mark.asyncio async def test_save_to_template_library_success( @@ -484,7 +475,6 @@ async def test_template_management_fallback_paths_refuse( input_data=TemplateComparisonInput( template1_path="templates/a.prtdot", template2_path="templates/b.prtdot", - comparison_type="full", ) ) assert compare_result["status"] == "error" @@ -552,9 +542,6 @@ async def test_template_management_adapter_error_and_exception_paths( mock_adapter.apply_template = AsyncMock( return_value=Mock(is_success=False, error="template apply failed") ) - mock_adapter.compare_templates = AsyncMock( - return_value=Mock(is_success=False, error="template compare failed") - ) mock_adapter.save_to_template_library = AsyncMock( side_effect=RuntimeError("library storage down") ) @@ -589,14 +576,6 @@ async def test_template_management_adapter_error_and_exception_paths( assert apply_error["status"] == "error" assert "template apply failed" in apply_error["message"] - compare_error = await compare_tool( - input_data=TemplateComparisonInput( - template1_path="templates/a.prtdot", template2_path="templates/b.prtdot" - ) - ) - assert compare_error["status"] == "error" - assert "template compare failed" in compare_error["message"] - save_exception = await save_tool(input_data={"template_name": "bad"}) assert save_exception["status"] == "error" assert save_exception["error_type"] == "internal" diff --git a/tests/solidworks_mcp/utils/test_feature_tree_classifier.py b/tests/solidworks_mcp/utils/test_feature_tree_classifier.py index 40bfc9d1..c6540ff2 100644 --- a/tests/solidworks_mcp/utils/test_feature_tree_classifier.py +++ b/tests/solidworks_mcp/utils/test_feature_tree_classifier.py @@ -66,12 +66,63 @@ def test_classify_assembly_by_document_type() -> None: def test_classify_assembly_by_feature_tokens() -> None: + """With no document type, a mate in the tree says assembly.""" features = [{"name": "mate1", "type": ""}] - result = classify_feature_tree_snapshot({"type": "part"}, features) + result = classify_feature_tree_snapshot({}, features) assert result["family"] == "assembly" assert result["confidence"] == "medium" +def test_a_part_is_never_an_assembly_because_of_its_material() -> None: + """Every real part's tree has "Material ": not a mate. + + Seen on SolidWorks 2026: a plain extruded part was classified as an + assembly, because "material" contains "mate". + """ + features = [ + {"name": "Material ", "type": "MaterialFolder"}, + {"name": "Boss-Extrude1", "type": "Extrusion"}, + ] + + as_part = classify_feature_tree_snapshot({"type": "Part"}, features) + untyped = classify_feature_tree_snapshot({}, features) + + assert as_part["family"] != "assembly" + assert untyped["family"] != "assembly" + + +def test_a_real_part_tree_with_its_folders_is_an_extrude() -> None: + """The folders of a real tree don't count as features. + + Seen on SolidWorks 2026: a plain extruded block was classified as sheet + metal, because "fold" is inside "HistoryFolder", and "Surface Bodies" + would look like an advanced solid. + """ + features = [ + {"name": "History", "type": "HistoryFolder"}, + {"name": "Sensors", "type": "SensorFolder"}, + {"name": "Annotations", "type": "DetailCabinet"}, + {"name": "Surface Bodies", "type": "SurfaceBodyFolder"}, + {"name": "Solid Bodies", "type": "SolidBodyFolder"}, + {"name": "Material ", "type": "MaterialFolder"}, + {"name": "Front Plane", "type": "RefPlane"}, + {"name": "Origin", "type": "OriginProfileFeature"}, + {"name": "Boss-Extrude1", "type": "Extrusion"}, + ] + + result = classify_feature_tree_snapshot({"type": "Part"}, features) + + assert result["family"] == "extrude" + + +def test_a_known_part_type_wins_over_drawing_like_names() -> None: + features = [{"name": "Drawing View1 sketch", "type": "ProfileFeature"}] + + result = classify_feature_tree_snapshot({"type": "Part"}, features) + + assert result["family"] != "drawing" + + def test_classify_drawing_by_document_type() -> None: result = classify_feature_tree_snapshot({"type": "drawing"}, []) assert result["family"] == "drawing" @@ -81,7 +132,7 @@ def test_classify_drawing_by_document_type() -> None: def test_classify_drawing_by_feature_tokens() -> None: features = [{"name": "drawing view 1", "type": ""}] - result = classify_feature_tree_snapshot({"type": "part"}, features) + result = classify_feature_tree_snapshot({"type": ""}, features) # unknown assert result["family"] == "drawing" assert result["confidence"] == "medium" @@ -360,7 +411,7 @@ def test_classify_assembly_from_feature_tokens() -> None: """Test classify assembly from feature tokens.""" result = classify_feature_tree_snapshot( - {"type": "Part"}, + None, # no document type: the tree's mates and components decide [ {"name": "Coincident Mate1", "type": "Mate", "suppressed": False}, {"name": "Component1", "type": "Component", "suppressed": False}, diff --git a/tests/solidworks_mcp/utils/test_sw_dependencies.py b/tests/solidworks_mcp/utils/test_sw_dependencies.py new file mode 100644 index 00000000..92ff1ac8 --- /dev/null +++ b/tests/solidworks_mcp/utils/test_sw_dependencies.py @@ -0,0 +1,35 @@ +"""Tests for reading file paths out of GetDependencies2's reply.""" + +from __future__ import annotations + +from pathlib import Path + +from solidworks_mcp.utils.sw_dependencies import dependency_paths + + +def test_names_and_paths_alternate_and_only_paths_are_kept() -> None: + raw = ("plate", r"C:\work\plate.SLDPRT", "pin", r"C:\work\pin.sldprt") + + assert dependency_paths(raw) == [ + Path(r"C:\work\plate.SLDPRT"), + Path(r"C:\work\pin.sldprt"), + ] + + +def test_a_repeated_path_is_kept_once_ignoring_case(tmp_path) -> None: + part = str(tmp_path / "plate.SLDPRT") + raw = [part, str(tmp_path / "sub.sldasm"), part] + + assert dependency_paths(raw) == [Path(part), tmp_path / "sub.sldasm"] + + +def test_other_entries_are_skipped() -> None: + """Bare names, other file types and non-strings give nothing.""" + raw = ("plate.SLDPRT", r"C:\work\notes.txt", 42, None, r"C:\work\d.SLDDRW") + + assert dependency_paths(raw) == [Path(r"C:\work\d.SLDDRW")] + + +def test_a_reply_that_is_not_a_list_gives_nothing() -> None: + assert dependency_paths(None) == [] + assert dependency_paths(r"C:\work\plate.SLDPRT") == [] diff --git a/uv.lock b/uv.lock index 7528723c..de4f0f78 100644 --- a/uv.lock +++ b/uv.lock @@ -1,5 +1,5 @@ version = 1 -revision = 5 +revision = 3 requires-python = ">=3.13" resolution-markers = [ "python_full_version >= '3.15' and sys_platform == 'win32'", @@ -453,15 +453,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] -[[package]] -name = "comtypes" -version = "1.4.17" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/0e/ff/c7836bd0d78fc615281016f154f514e9d523d7cb9ab9e8b4d344adc5f5e7/comtypes-1.4.17.tar.gz", hash = "sha256:3d9c1e92ad8daf7600d371e76ee16161a627a5fb70c3144f6e52e78af6034363", size = 262743, upload-time = "2026-09-21T08:08:07.687Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/89/9c/d0bc1fb69ad22a04bdc01dd9b5613a2ebc4d02ba1ec24b02127dc93791ba/comtypes-1.4.17-py3-none-any.whl", hash = "sha256:4e0a221dde2c589b82977bed802efd71cd5eb67a380347b732e02735e597f586", size = 298743, upload-time = "2026-09-21T08:08:06.461Z" }, -] - [[package]] name = "coverage" version = "7.13.4" @@ -592,7 +583,7 @@ name = "cuda-bindings" version = "13.4.4" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cuda-pathfinder" }, + { name = "cuda-pathfinder", marker = "python_full_version < '3.15' and sys_platform != 'win32'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/a7/97/7d75105a92ee18b7764f5cf60672d6a966842348a2a049e663fe690902ff/cuda_bindings-13.4.4-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0c3f4cc887eac0d5edb5d7396cc78b336bee151a97e2ba7acf59e8b9380132d0", size = 6316532, upload-time = "2026-10-14T12:35:30.291Z" }, @@ -625,43 +616,43 @@ wheels = [ [package.optional-dependencies] cublas = [ - { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, - { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cudart = [ - { name = "nvidia-cuda-runtime", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-runtime", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cufft = [ - { name = "nvidia-cufft", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, - { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cufft", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cufile = [ - { name = "nvidia-cufile", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cufile", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cupti = [ - { name = "nvidia-cuda-cupti", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-cupti", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] curand = [ - { name = "nvidia-curand", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-curand", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cusolver = [ - { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, - { name = "nvidia-cusolver", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, - { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, - { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cublas", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cusolver", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-cusparse", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] cusparse = [ - { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, - { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusparse", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] nvjitlink = [ - { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] nvrtc = [ - { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] nvtx = [ - { name = "nvidia-nvtx", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvtx", marker = "(platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux')" }, ] [[package]] @@ -976,6 +967,34 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] +[[package]] +name = "hatch-fancy-pypi-readme" +version = "25.1.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "hatchling" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f3/0f/aed57c301f339936eb91cb4d8c1e5088a101081854bd3ec18a889df32365/hatch_fancy_pypi_readme-25.1.0.tar.gz", hash = "sha256:9c58ed3dff90d51f43414ce37009ad1d5b0f08ffc9fc216998a06380f01c0045", size = 29701, upload-time = "2025-05-01T10:34:42.989Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/b4/ad71e051b34f1935783de37beffee16e343ff2514b204dc515f9e939d4af/hatch_fancy_pypi_readme-25.1.0-py3-none-any.whl", hash = "sha256:ce0134c40d63d874ac48f48ccc678b8f3b62b8e50e9318520d2bffc752eedaf3", size = 10046, upload-time = "2025-05-01T10:34:41.204Z" }, +] + +[[package]] +name = "hatchling" +version = "1.33.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, + { name = "pathspec" }, + { name = "pluggy" }, + { name = "tomlkit" }, + { name = "trove-classifiers" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/f1/e47b937226ae3b093bbd0132eb0b7ee5bfad12c2b5324afd10ae49946b05/hatchling-1.33.0.tar.gz", hash = "sha256:4c422bd4d554fcff5de5b73e9596f85e41e9f97f7e553d8f7595ecb31a627bef", size = 58079, upload-time = "2026-10-28T02:27:30.694Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/64/4afe5dd77b2939a93e8c9513f8082dbd049ecba9c1484a379a0f6ae29d6b/hatchling-1.33.0-py3-none-any.whl", hash = "sha256:415290b84f464d2884303fca8974d38e7b85579069fab02a15db0828fbb1446d", size = 78750, upload-time = "2026-10-28T02:27:29.033Z" }, +] + [[package]] name = "hf-xet" version = "1.4.2" @@ -1969,7 +1988,7 @@ name = "nvidia-cublas" version = "13.1.1.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cuda-nvrtc" }, + { name = "nvidia-cuda-nvrtc", marker = "sys_platform != 'win32'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, @@ -2008,7 +2027,7 @@ name = "nvidia-cudnn-cu13" version = "9.20.0.48" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas" }, + { name = "nvidia-cublas", marker = "sys_platform != 'win32'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, @@ -2020,7 +2039,7 @@ name = "nvidia-cufft" version = "12.0.0.61" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink" }, + { name = "nvidia-nvjitlink", marker = "sys_platform != 'win32'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, @@ -2050,9 +2069,9 @@ name = "nvidia-cusolver" version = "12.0.4.66" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-cublas" }, - { name = "nvidia-cusparse" }, - { name = "nvidia-nvjitlink" }, + { name = "nvidia-cublas", marker = "sys_platform != 'win32'" }, + { name = "nvidia-cusparse", marker = "sys_platform != 'win32'" }, + { name = "nvidia-nvjitlink", marker = "sys_platform != 'win32'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, @@ -2064,7 +2083,7 @@ name = "nvidia-cusparse" version = "12.6.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "nvidia-nvjitlink" }, + { name = "nvidia-nvjitlink", marker = "sys_platform != 'win32'" }, ] wheels = [ { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, @@ -2589,6 +2608,36 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/bd/c038d7cc38edc1aa5bf91ab8068b63d4308c66c4c8bb3cbba7dfbc049f9c/pyparsing-3.3.2-py3-none-any.whl", hash = "sha256:850ba148bd908d7e2411587e247a1e4f0327839c40e2e5e6d05a007ecc69911d", size = 122781, upload-time = "2026-01-21T03:57:55.912Z" }, ] +[[package]] +name = "pypdfium2" +version = "5.15.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fb/47/8555ff96dd676dd7b2029b8c98a8afd255f5f9eef4a2f4a0445566a323bb/pypdfium2-5.15.2.tar.gz", hash = "sha256:0185193bbdf0cc39f0bf31954c25f12edb81048bcb628ea4fc3dccf8d2ce2aef", size = 696348, upload-time = "2026-11-09T15:33:28.299Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/73/cf/a4adc114427c7e72716aaa487ddff7d085791dbe5ac830f2345f61814f3c/pypdfium2-5.15.2-py3-none-android_23_arm64_v8a.whl", hash = "sha256:fe64472c32d0717669c99758ce234066500b0234730dad0327248f09399e9736", size = 3605158, upload-time = "2026-11-09T15:32:35.375Z" }, + { url = "https://files.pythonhosted.org/packages/05/6f/fae810e1c45427c7b3d229497eca0ff37fd35d6c81d5c1f8f3028251763e/pypdfium2-5.15.2-py3-none-android_23_armeabi_v7a.whl", hash = "sha256:8faaafc2a18b17b3bcfad79b376bb382d536b011cb9e6eee2f4d7e8af0a23167", size = 3023159, upload-time = "2026-11-09T15:32:37.448Z" }, + { url = "https://files.pythonhosted.org/packages/e7/bb/bf88a781a53c905022b25b2d1fb742c908f86b8076403471f626cc41a508/pypdfium2-5.15.2-py3-none-macosx_13_0_arm64.whl", hash = "sha256:e71fe832e94421ac3c28d6a6ed4a9e61f22417089652d339f391c4ffc2a44c35", size = 3710813, upload-time = "2026-11-09T15:32:39.633Z" }, + { url = "https://files.pythonhosted.org/packages/09/de/9e7eda3ee1c00228d72f7fc53a370d76eed51fe5fea25debc428ac684e35/pypdfium2-5.15.2-py3-none-macosx_13_0_x86_64.whl", hash = "sha256:7f296a298074d76fb7c3d1ecb80d7097a96778bf0ad9c5c48a0170e56e2c6821", size = 3940099, upload-time = "2026-11-09T15:32:41.647Z" }, + { url = "https://files.pythonhosted.org/packages/03/1f/7a18e64c50049dce8512239bcdb9f8469d0a0c352dd42ae85b6b01d143f8/pypdfium2-5.15.2-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dd46e93c0c3a73f6cea8489baff6d77a5d0759dd53fbbce0aeb49c91830176fc", size = 3887212, upload-time = "2026-11-09T15:32:43.395Z" }, + { url = "https://files.pythonhosted.org/packages/c6/cf/2ee999eed1ffdd6c4be8fcd824f05acc4d5b47785ba8ca3c80d51aac15cc/pypdfium2-5.15.2-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f4d422d2662bf0be37118abb14dbac6acc3bfbc04a82da92cb200b570ee24da2", size = 3595005, upload-time = "2026-11-09T15:32:45.368Z" }, + { url = "https://files.pythonhosted.org/packages/64/4d/9555e8d15d112ba179895218cc78cc0a2370b71570f918158418b2c8a2bb/pypdfium2-5.15.2-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:397271721330866d1da291042b128595f44cb0314c4675bb439ebaf5c7349b8b", size = 4077462, upload-time = "2026-11-09T15:32:47.108Z" }, + { url = "https://files.pythonhosted.org/packages/95/86/2942d7e6257048abaa12273d9299251861985fcfb422f1f8d5584322c5ad/pypdfium2-5.15.2-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:93e51d8ed458085cf67974834e6888bde0df5581e1212de46da2ff5c07dedfd2", size = 4467118, upload-time = "2026-11-09T15:32:48.806Z" }, + { url = "https://files.pythonhosted.org/packages/c8/e5/2e668bc1bc6fe22f9006694b5571a2dd2c9b874d6a21d16ee839c8f7f6ea/pypdfium2-5.15.2-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc31aea5b0fb9fefc9b537a65f4113980b2c40798445736a7e6565bc85161e37", size = 4020833, upload-time = "2026-11-09T15:32:50.715Z" }, + { url = "https://files.pythonhosted.org/packages/ff/62/c4f6890085a829681ea4bfc7232979742d9dd7a59320f1f26c268f46a699/pypdfium2-5.15.2-py3-none-manylinux_2_27_s390x.manylinux_2_28_s390x.whl", hash = "sha256:fddd832b17f11cae080c395530eed01da0c003c66d6c233ba656e93ddf570ee0", size = 4184727, upload-time = "2026-11-09T15:32:52.592Z" }, + { url = "https://files.pythonhosted.org/packages/af/89/1384feac64c4a60d0a7940e929dd3815195647eefbb250424cb953a2ca2c/pypdfium2-5.15.2-py3-none-manylinux_2_34_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:2dd2ef2e966181b199870e109ae3c17af4415fc012ba12b7f8d7e08d521bd480", size = 4097549, upload-time = "2026-11-09T15:32:54.809Z" }, + { url = "https://files.pythonhosted.org/packages/ef/29/5a68e61d8404047b411219b5d1915692c5daf02326449aed4c75fb3b2809/pypdfium2-5.15.2-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:71ba93a356708cb2a7b1a82dbc2c07ddb62c501e35bb6a67c7323e1da6ae9cb7", size = 5113284, upload-time = "2026-11-09T15:32:56.709Z" }, + { url = "https://files.pythonhosted.org/packages/43/31/5a7a23f299df390269cc4d8c09a61bc2dcea04621b1dafb162527e05eb80/pypdfium2-5.15.2-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:7a8edc5f3a020373ebf839e75db86590c364566b958703e89e5c0c9b4fa5a885", size = 4643080, upload-time = "2026-11-09T15:32:58.726Z" }, + { url = "https://files.pythonhosted.org/packages/43/09/6b9e20130411acfaf5ecbbbdd9e65a84c35860873163fedc152e90e87c6c/pypdfium2-5.15.2-py3-none-musllinux_1_2_i686.whl", hash = "sha256:de2ca1627ad8c08d577f7e17f1ac8b9ff599b26c727ebf687f964ddff8fed78e", size = 5387839, upload-time = "2026-11-09T15:33:11.6Z" }, + { url = "https://files.pythonhosted.org/packages/8c/04/745e3062d97d43c0e4756649883af663b6bf5aef21f606acca635415399b/pypdfium2-5.15.2-py3-none-musllinux_1_2_ppc64le.whl", hash = "sha256:5c4c89468afc3d9498b547becf9732cf710836a5a24f4c18dcf6041a895fcfe5", size = 5296188, upload-time = "2026-11-09T15:33:13.49Z" }, + { url = "https://files.pythonhosted.org/packages/d9/16/ec34d4561835b2f8d099089c1e06756f43bb05db6de313113761f0b550ad/pypdfium2-5.15.2-py3-none-musllinux_1_2_riscv64.whl", hash = "sha256:95aa8134acaeac540bf8cf5b30def149b26df0db6a955f1d0e64b5f633b2721b", size = 4737631, upload-time = "2026-11-09T15:33:15.361Z" }, + { url = "https://files.pythonhosted.org/packages/1a/c2/1563e718832be7dd44d091a0e541f5e0ee0baed7a7892a0736c1cb5b3cf7/pypdfium2-5.15.2-py3-none-musllinux_1_2_s390x.whl", hash = "sha256:c4eee1d6d483783a115953fbf9caae42fead0187ddd2a1178f616d4453afb6a0", size = 5228144, upload-time = "2026-11-09T15:33:17.226Z" }, + { url = "https://files.pythonhosted.org/packages/53/54/2936bc6b2887fd8bba6bfc641448d3820e56469e4a47e3aee8ef212bfc96/pypdfium2-5.15.2-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:ef452a7178744196d4ff97029f46b56a13817346fc7ee0473c75643512276b3a", size = 5193509, upload-time = "2026-11-09T15:33:19.228Z" }, + { url = "https://files.pythonhosted.org/packages/bd/4b/f3425e1f3759d2a6473cddbba5bdcc25ac0c49939921d568331fee16ca03/pypdfium2-5.15.2-py3-none-pyemscripten_2026_0_wasm32.whl", hash = "sha256:51e380faf433899d3b07a40b3f6aa97b9ab61399e732280f4007dc7aa0d0694f", size = 2695471, upload-time = "2026-11-09T15:33:21.089Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3b/37e7bfcb6a51e967e7a4c6e3698c73548f4455176c7e352a31ee7011c2dc/pypdfium2-5.15.2-py3-none-win32.whl", hash = "sha256:4cfc5ae26b600f92c5be0a0dccb949c10bd8bd3c93e440b75a362f9c1453fd93", size = 4015242, upload-time = "2026-11-09T15:33:22.919Z" }, + { url = "https://files.pythonhosted.org/packages/fe/7f/8aa446529fa14523e5c18f89e823afc95526689f76a75efe68a82a10d850/pypdfium2-5.15.2-py3-none-win_amd64.whl", hash = "sha256:74d1bace34fb01c660d0b64344d5a4b7d276942b7c6623c88ab59ea21c5acfbd", size = 4187589, upload-time = "2026-11-09T15:33:24.718Z" }, + { url = "https://files.pythonhosted.org/packages/e7/20/edc21f0b086aba3162a33e5725a4f224dcabb46f67a051e1a1be81e3cbbc/pypdfium2-5.15.2-py3-none-win_arm64.whl", hash = "sha256:a20398367f188eb817be156bfd00077dcb5f8ad06c093849f3fa70b8087b4a87", size = 3907705, upload-time = "2026-11-09T15:33:26.624Z" }, +] + [[package]] name = "pyperclip" version = "1.11.0" @@ -3248,8 +3297,8 @@ name = "secretstorage" version = "3.5.0" source = { registry = "https://pypi.org/simple" } dependencies = [ - { name = "cryptography" }, - { name = "jeepney" }, + { name = "cryptography", marker = "sys_platform != 'win32'" }, + { name = "jeepney", marker = "sys_platform != 'win32'" }, ] sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" } wheels = [ @@ -3323,13 +3372,12 @@ wheels = [ [[package]] name = "solidworks-mcp-python" -version = "1.4.0" +version = "2.0.0" source = { editable = "." } dependencies = [ { name = "aiosqlite" }, { name = "chardet" }, { name = "charset-normalizer" }, - { name = "comtypes", marker = "sys_platform == 'win32'" }, { name = "defusedxml" }, { name = "fastmcp" }, { name = "httpx" }, @@ -3358,10 +3406,12 @@ dev = [ { name = "coverage" }, { name = "doc8" }, { name = "factory-boy" }, + { name = "hatch-fancy-pypi-readme" }, { name = "mypy" }, { name = "numpy" }, { name = "pre-commit" }, { name = "pydocstyle" }, + { name = "pypdfium2" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-benchmark" }, @@ -3397,7 +3447,9 @@ rag = [ test = [ { name = "coverage" }, { name = "fastapi" }, + { name = "hatch-fancy-pypi-readme" }, { name = "numpy" }, + { name = "pypdfium2" }, { name = "pytest" }, { name = "pytest-asyncio" }, { name = "pytest-cov" }, @@ -3421,7 +3473,6 @@ requires-dist = [ { name = "build", marker = "extra == 'dev'", specifier = ">=1.0.0" }, { name = "chardet", specifier = "<6" }, { name = "charset-normalizer", specifier = ">=3.4.0" }, - { name = "comtypes", marker = "sys_platform == 'win32'", specifier = ">=1.4.0" }, { name = "coverage", extras = ["toml"], marker = "extra == 'dev'", specifier = ">=7.3.0" }, { name = "coverage", extras = ["toml"], marker = "extra == 'test'", specifier = ">=7.3.0" }, { name = "defusedxml", specifier = ">=0.7.1" }, @@ -3431,6 +3482,8 @@ requires-dist = [ { name = "fastapi", marker = "extra == 'test'", specifier = ">=0.115.0" }, { name = "fastapi", marker = "extra == 'ui'", specifier = ">=0.115.0" }, { name = "fastmcp", specifier = ">=3.2.2" }, + { name = "hatch-fancy-pypi-readme", marker = "extra == 'dev'", specifier = ">=24" }, + { name = "hatch-fancy-pypi-readme", marker = "extra == 'test'", specifier = ">=24" }, { name = "httpx", specifier = ">=0.24.0" }, { name = "jinja2", specifier = ">=3.1.0" }, { name = "loguru", specifier = ">=0.7.0" }, @@ -3459,6 +3512,8 @@ requires-dist = [ { name = "pydantic-ai-slim", extras = ["openai", "anthropic", "mcp"], specifier = ">=1.107.4,<2" }, { name = "pydocstyle", marker = "extra == 'dev'", specifier = ">=6.3.0" }, { name = "pygments", marker = "extra == 'docs'", specifier = ">=2.16.0" }, + { name = "pypdfium2", marker = "extra == 'dev'", specifier = ">=4.30.0" }, + { name = "pypdfium2", marker = "extra == 'test'", specifier = ">=4.30.0" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=7.4.0" }, { name = "pytest", marker = "extra == 'test'", specifier = ">=7.4.0" }, { name = "pytest-asyncio", marker = "extra == 'dev'", specifier = ">=0.21.0" }, @@ -3813,6 +3868,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/c7/18/c86eb8e0202e32dd3df50d43d7ff9854f8e0603945ff398974c1d91ac1ef/tomli_w-1.2.0-py3-none-any.whl", hash = "sha256:188306098d013b691fcadc011abd66727d3c414c571bb01b1a174ba8c983cf90", size = 6675, upload-time = "2025-01-15T12:07:22.074Z" }, ] +[[package]] +name = "tomlkit" +version = "0.15.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/08/72/fc01563df95c189a9f65850096bdc205bc2fe37da6c740cd64afaf18d07e/tomlkit-0.15.2.tar.gz", hash = "sha256:83e32755ba1d20d9340bd069ee97e9f6232ba2346b63ffcba425de01f7e327a6", size = 190522, upload-time = "2026-10-16T04:07:08.166Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/da/46/7d84138a60a8bd796825b2d38ebe92d0d16501ca57d501b7c5d677401bbc/tomlkit-0.15.2-py3-none-any.whl", hash = "sha256:05562412163a3037b94497385fb7f9204c637bc605af7a48199e41cf2272f437", size = 52225, upload-time = "2026-10-16T04:07:09.216Z" }, +] + [[package]] name = "torch" version = "2.13.0" @@ -3914,6 +3978,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f0/ac/229b7d4589d2e5937310e72c6d46e89599d16a4a12b479ffa1499fee8eb8/triton-3.7.1-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:10ba85fa2cca4a2fbdeb36bf1cb082f2c252bda55bf9fccd74f65ec5bc647e68", size = 197824404, upload-time = "2026-06-17T19:53:42.772Z" }, ] +[[package]] +name = "trove-classifiers" +version = "2026.9.21.13" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/93/af436dfaa845cab5d96f0adbc1e4f3730532d37fa249e4eb796fb1d7fc82/trove_classifiers-2026.9.21.13.tar.gz", hash = "sha256:0a9ebc8d4e2f3e8a22848c5258033035bec17a3012ac3fea16dbaa764489eb71", size = 17085, upload-time = "2026-09-21T13:29:07.301Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/30/81/0da8afb52a71d0a4f2bd3152357b1a441e393b286374802b9d3addab4ab5/trove_classifiers-2026.9.21.13-py3-none-any.whl", hash = "sha256:8b1ff4f9c191b1040b71c37f1e445ab99732911e3cd91de52838453a854d7a17", size = 14232, upload-time = "2026-09-21T13:29:06.123Z" }, +] + [[package]] name = "truststore" version = "0.10.4"
InterfaceMethods calledOfCalled
ISldWorks22330
6.7%ActivateDoc3, CloseAllDocuments, CloseDoc, Frame, GetConfigurationNames, GetCurrentLanguage, GetDocuments, GetExecutablePath, GetExportFileData, GetMassProperties, GetOpenDocumentByName, GetUserPreferenceStringValue, GetUserPreferenceToggle, NewAssembly, NewDocument, NewDrawing2, NewPart, OpenDoc6, RevisionNumber, RunMacro2, SetUserPreferenceIntegerValue, SetUserPreferenceToggle
IModelDoc265758
8.6%AddDiameterDimension2, AddDimension, AddDimension2, AddRadialDimension2, AddRelation, ClearSelection2, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, EditRebuild3, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetFeatureCount, GetLineCount, GetMassProperties, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertGtol, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertSketch, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Select, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, ViewZoomtofit, ViewZoomtofit2
IModelDocExtension20337
5.9%AddDimension, CreateMassProperty, CreateMeasure, CustomPropertyManager, DeleteSelection2, GetAnnotations, GetMassProperties, GetPackAndGo, GetUserPreferenceInteger, GetUserPreferenceToggle, GetWhatsWrong, GetWhatsWrongCount, InsertBomTable4, SaveAs, SaveAs2, SaveAs3, SavePackAndGo, SelectByID2, SetUserPreferenceInteger, SetUserPreferenceToggle
ISldWorks21330
6.4%ActivateDoc3, CloseDoc, Frame, GetConfigurationNames, GetCurrentLanguage, GetDocuments, GetExecutablePath, GetExportFileData, GetMassProperties, GetOpenDocumentByName, GetUserPreferenceStringValue, GetUserPreferenceToggle, NewAssembly, NewDocument, NewDrawing2, NewPart, OpenDoc6, RevisionNumber, RunMacro2, SetUserPreferenceIntegerValue, SetUserPreferenceToggle
IModelDoc266758
8.7%AddDiameterDimension2, AddDimension, AddDimension2, AddRadialDimension2, AddRelation, ClearSelection2, CreateArc, CreateCenterLine, CreateCircleByRadius, CreateCircularSketchStepAndRepeat, CreateEllipse, CreateLine, CreateLinearSketchStepAndRepeat, EditRebuild3, EditSuppress2, EditUndo, EditUndo2, EditUnsuppress2, FeatureByPositionReverse, FeatureChamferType, FeatureCut3, FeatureCut4, FeatureFillet3, FeatureRevolve2, FirstFeature, ForceRebuild3, GetActiveConfiguration, GetActiveSketch2, GetConfigurationNames, GetDependencies2, GetFeatureCount, GetLineCount, GetMassProperties, GetNext, GetPathName, GetSaveFlag, GetTitle, GetType, GetUserPreferenceStringValue, GetUserPreferenceToggle, GraphicsRedraw2, InsertAxis2, InsertDatumTag2, InsertGtol, InsertNote, InsertProtrusionBlend2, InsertProtrusionSwept4, InsertSketch, Lock, Parameter, Save, Save3, SaveAs, SaveAs2, SaveAs3, SaveBMP, Select, SetSaveFlag, SetUserPreferenceIntegerValue, SetUserPreferenceToggle, ShowNamedView2, SketchAddConstraints, SketchMirror, SketchOffset2, ViewZoomtofit, ViewZoomtofit2
IModelDocExtension18337
5.3%AddDimension, CreateMassProperty, CreateMeasure, CustomPropertyManager, DeleteSelection2, GetAnnotations, GetMassProperties, GetUserPreferenceInteger, GetUserPreferenceToggle, GetWhatsWrong, GetWhatsWrongCount, InsertBomTable4, SaveAs, SaveAs2, SaveAs3, SelectByID2, SetUserPreferenceInteger, SetUserPreferenceToggle
IPartDoc12167
7.2%ExportToDWG2, FeatureByName, FeatureExtrusion2, FeatureExtrusion3, FeatureExtrusionThin2, FeatureRevolve2, FirstFeature, GetBodies2, GetMaterialPropertyName2, GetPartBox, InsertMirrorFeature, SetMaterialPropertyName2
IAssemblyDoc11198
5.6%AddComponent4, AddComponent5, AddMate5, CompConfigProperties5, FeatureByName, FixComponent, GetBox, GetComponentByName, GetComponentCount, GetComponents, UnfixComponent
IDrawingDoc13272
4.8%ActivateView, AutoDimension, Create1stAngleViews2, Create3rdAngleViews2, CreateDrawViewFromModelView3, EditSheet, EditTemplate, FeatureByName, GetCurrentSheet, GetFirstView, GetViews, InsertModelAnnotations3, SetupSheet5