Skip to content

armgit / SOMA

Public Imported from GitHub
0

Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice

App: STEP-Dateien im Viewer, CadQuery rein und raus (E99, E100)

Kai-Jungsthoefel7c8bb42c1052
diff --git a/app/README.md b/app/README.md
index 268af4b..4a985d8 100644
--- a/app/README.md
+++ b/app/README.md
@@ -21,6 +21,8 @@ npm run test:smoke # echte App, unsichtbar: Projekt, Viewer, Auswahl, Panel
npm run test:versions # Git-Verlauf, Speichern als .soma, Öffnen von .soma und .zip, Export als ZIP, Vorschau (auch markiert), Wiederherstellen, Störfälle, Öffnen ohne Neubau, Vorschau aus dem Build, Start auf der Startseite, unveränderte Modelle verschwinden, Entfernen (75 Prüfungen)
npm run test:editor # Editor: Höhe und Scrollen, Speichern nur auf Wunsch mit genau einem Build (nur bei Python und inputs/), Änderungen des Agenten, Konflikte mit Sicherung, Nur lesen, CRLF, Rückfragen bei Modellwechsel und Reiter schließen, Markdown als Dokument (37 Prüfungen)
npm run test:measure # Messen: Fläche, Kante, Punkt, Abstand paralleler Ebenen, zweier Bohrungen, zweier Punkte, Punkt zur Ebene, Verdecktes, neuer Build, Vorschau (21 Prüfungen)
+npm run test:stepview # STEP-Datei aus dem Dateibaum im Viewer: Banner, Cache, Build wartet, Messen, Schnitt, Explosion, Neuladen bei Änderung, zurück zum Modell, Versionsvorschau, kaputte und leere Dateien (25 Prüfungen)
+npm run test:cadquery # CadQuery rein und raus: Kompatibilitätsmodus (show_object, ocp_vscode, result), Export als Datei und als Ordner, Lauf ohne soma, Rückweg Zeichen für Zeichen, veränderter Block, nicht exportierbare Imports, in der App „New from CadQuery script“ und „As CadQuery script“, kleiner Knopf auf der Startseite (30 Prüfungen)
npm run test:groups # Gruppen: eigene und importierte (STEP-Baugruppe), Baum, Aus-/Einblenden und Transparenz je Gruppe, Klick durch transparente Teile, Ausgabe-STEP (17 Prüfungen)
npm run test:section # Schnitt: X/Y/Z und an Fläche, Eingabe der Lage, Seite wechseln, gefüllte und schraffierte Schnittfläche, Klicks durch den Schnitt, Wandstärke an der Kontur messen, neuer Build (26 Prüfungen)
npm run test:explode # Explosion: Demontage-Analyse (Richtung je Teil, Schrauben durch ihr Kernloch, Stift schräg aus seiner Bohrung, Baugruppe mit eingeschlossener Mutter, Elternteile), gleiche Lücke, Reihenfolge bei 100 %, Abspielen Schritt für Schritt, Reihenfolge an den Agenten, Auswahl in Einbaulage, Messen setzt zusammen, Schnitt dazu, neuer Build (39 Prüfungen)
@@ -74,17 +76,17 @@ SOMA_TEST_EXE="$LOCALAPPDATA/soma-dev/release/win-unpacked/SOMA.exe" node test/s
| Pfad | Inhalt |
|---|---|
-| `src/main/` | Hauptprozess: `projects.ts` (offenes Projekt, Speichern, Öffnen, Verlauf, Wiederherstellen), `git.ts` (mitgeliefertes Git über dugite), `zip.ts` (Modelldatei .soma oder ZIP schreiben und sicher entpacken), `workspace.ts` (UUID-Arbeitsordner, Projektzustand doppelt, Projekt-Check nur melden), `build.ts` (Build als Einmal-Prozess mit Entprellung, Warteschlange, Zeitlimit, ein vorgewärmter Python-Prozess für alle Aufträge der App, gilt der letzte Build noch), `previews.ts` (Build als Vorschau eines Commits ablegen), `measure.ts` (langlebiger Python-Messdienst, `soma serve`), `skills.ts` (Bibliothek aus mitgelieferten und eigenen Skills, Stufen der Skills: Kopie nach `.soma/skills/`, bei Bedarf mit Hinweis, zwei Listen in `AGENTS.md`, Sicherung abweichender Kopien, Prüfung eines Skill-Texts), `help.ts` (Text und Bilder der Anleitung, Bilder nach `.soma/help/` im Projekt, E83), `skilllibrary.ts` (eigene Skills in den App-Daten für die Einstellungen: anlegen, speichern, zurücksetzen, löschen, importieren, mit Sicherung, E78), `settings.ts` (Einstellungen der App in `settings.json`, Kaputtes gemeldet und vor dem Ersetzen gesichert, E81), `storage.ts` (Größe der App-Daten je Bereich, Vorschau-Cache leeren, E81), `about.ts` (Versionen, Komponenten mit Lizenz, Python-Pakete aus den Metadaten, Text für Fehlermeldungen, E81), `updates.ts` (neueste Version unter GitHub Releases über `net.fetch`, einmal je Sitzung, abschaltbar, E98), `params.ts` (Werte des Nutzers in `parameters.json` lesen, prüfen und schreiben, E74), `dialogs.ts` (native Dialoge, im Test beantwortbar), `watcher.ts`, `terminals.ts` (node-pty, Projektumgebung, `soma` und `git` im PATH, `PIP_PYTHON`), `packages.ts` (Projektumgebung `.soma/env` anlegen lassen, fehlende Pakete aus `requirements.txt` installieren, E67), `files.ts` (Pfadschutz, Dateien nach `inputs/`, Markierungen nach `.soma/feedback/`, Schreiben aus dem Editor mit Konfliktprüfung und Sicherung), `dxf.ts` (DXF für die Ansicht über `soma dxfview`, nur bei geänderter Datei, E80), `agents.ts`, dazu für E58 `bridge.ts` (Verbindung für `soma render`: HTTP auf 127.0.0.1 mit Schlüssel, Adresse und Schlüssel auch in `bridge.json` der App-Daten für Agenten mit fremder Umgebung), `render.ts` (unsichtbares Render-Fenster, Aufträge nacheinander), `animations.ts` (Liste der Animationen und Ergebnisse, Bauen im Hintergrund) |
+| `src/main/` | Hauptprozess: `projects.ts` (offenes Projekt, Speichern, Öffnen, Verlauf, Wiederherstellen), `git.ts` (mitgeliefertes Git über dugite), `zip.ts` (Modelldatei .soma oder ZIP schreiben und sicher entpacken), `workspace.ts` (UUID-Arbeitsordner, Projektzustand doppelt, Projekt-Check nur melden), `build.ts` (Build als Einmal-Prozess mit Entprellung, Warteschlange, Zeitlimit, ein vorgewärmter Python-Prozess für alle Aufträge der App, gilt der letzte Build noch), `previews.ts` (Build als Vorschau eines Commits ablegen, STEP-Dateien des Projekts für den Viewer umwandeln, Cache nach Inhalt), `measure.ts` (langlebiger Python-Messdienst, `soma serve`), `skills.ts` (Bibliothek aus mitgelieferten und eigenen Skills, Stufen der Skills: Kopie nach `.soma/skills/`, bei Bedarf mit Hinweis, zwei Listen in `AGENTS.md`, Sicherung abweichender Kopien, Prüfung eines Skill-Texts), `help.ts` (Text und Bilder der Anleitung, Bilder nach `.soma/help/` im Projekt, E83), `skilllibrary.ts` (eigene Skills in den App-Daten für die Einstellungen: anlegen, speichern, zurücksetzen, löschen, importieren, mit Sicherung, E78), `settings.ts` (Einstellungen der App in `settings.json`, Kaputtes gemeldet und vor dem Ersetzen gesichert, E81), `storage.ts` (Größe der App-Daten je Bereich, Vorschau-Cache leeren, E81), `about.ts` (Versionen, Komponenten mit Lizenz, Python-Pakete aus den Metadaten, Text für Fehlermeldungen, E81), `updates.ts` (neueste Version unter GitHub Releases über `net.fetch`, einmal je Sitzung, abschaltbar, E98), `params.ts` (Werte des Nutzers in `parameters.json` lesen, prüfen und schreiben, E74), `dialogs.ts` (native Dialoge, im Test beantwortbar), `watcher.ts`, `terminals.ts` (node-pty, Projektumgebung, `soma` und `git` im PATH, `PIP_PYTHON`), `packages.ts` (Projektumgebung `.soma/env` anlegen lassen, fehlende Pakete aus `requirements.txt` installieren, E67), `files.ts` (Pfadschutz, Dateien nach `inputs/`, Markierungen nach `.soma/feedback/`, Schreiben aus dem Editor mit Konfliktprüfung und Sicherung), `dxf.ts` (DXF für die Ansicht über `soma dxfview`, nur bei geänderter Datei, E80), `agents.ts`, dazu für E58 `bridge.ts` (Verbindung für `soma render`: HTTP auf 127.0.0.1 mit Schlüssel, Adresse und Schlüssel auch in `bridge.json` der App-Daten für Agenten mit fremder Umgebung), `render.ts` (unsichtbares Render-Fenster, Aufträge nacheinander), `animations.ts` (Liste der Animationen und Ergebnisse, Bauen im Hintergrund) |
| `src/preload/` | Schmale, feste Schnittstelle zum Renderer (kein Node-Zugriff dort), `render-preload.ts` für das Render-Fenster |
-| `src/renderer/` | Oberfläche: `main.ts` (Verdrahtung: Kopfzeile mit Spalten-Schaltern, Seitenleiste und Code-Spalte, Reiter Analysis und Animation mit Punkt für Neues, Werkzeuge neben dem Strukturbaum, Menüs, Auswahl, Export, Übergabe an den Agenten auch per Ziehen ins Terminal, Startseite), `viewer.ts` (three.js, Klick auf Code, Ansichten, Drehpunkt, Mausbelegungen und orthografische Kamera (E81), Schnittebene mit gefüllter Schnittfläche und Kontur, verschobene Bauteile der Explosion mit Wegen, Strahltest der Demontage-Analyse mit BVH aus `three-mesh-bvh`, Vorschaubild, Bild für die Markierung), `viewcube.ts` (Ansichtswürfel in 3D), `sectiontool.ts` (Schnitt: Karte, Ebene, Text für den Agenten), `explodetool.ts` (Explosion: Demontage-Analyse mit Baugruppen und schrägen Richtungen, Elternteile, Lage, Abspielen Schritt für Schritt, Karte, Texte für den Agenten), `busy.ts` (Ladeanzeige über dem Viewer mit Fortschritt und Abbrechen, für die Analyse der Explosion), `skills.ts` (Skills in der Seitenleiste: Zeilen mit Stufen-Schalter, Karte daneben mit Einstellungen), `help.ts` (Hilfe über der App: Abschnitte der Anleitung, E83), `tutorial.ts` (geführte Tour, E94: Karte mit Schritt, Titel und Text, oranger Rahmen um das Element, Abdunklung aus vier Flächen, Klicks gehen durch, ohne Element Karte in der Mitte; die zehn Schritte am Modell „Tutorial“), `settings.ts` (Einstellungen über der App mit Reitern, Reiter „Skills“ mit Liste, Markdown-Editor, Vorschau und Prüfung beim Tippen, E78), `settingspages.ts` (Reiter Viewer, Shortcuts, Storage und About, E81), `params.ts` (Parameter in der Seitenleiste: Felder nach Art, Gruppen, Zurücksetzen auf den Wert aus dem Code, E74), `markup.ts` (Zeichenfläche der Markierung, Formen als bearbeitbare Objekte), `measuretool.ts` (Messen: Ablauf, Karte, Text für den Agenten), `tree.ts` (Strukturbaum oben links im Viewer, E82: ohne Hintergrund, Baumstriche, Gruppen, Auge und Transparenz vor dem Namen, Referenzen als Gruppe am Ende, Suche, F3, Mehrfachauswahl, Ziehen über die Augen), `shortcuts.ts` (Liste aller Tasten für den Reiter Shortcuts der Einstellungen), `code.ts` (Code-Spalte mit Editor: CodeMirror 6, Speichern auf Wunsch, Abgleich mit Änderungen des Agenten, Konflikte, Umschalter für Markdown), `dxfview.ts` (DXF-Ansicht im Code-Panel: Pfade auf einer Canvas, Zoom, Layer, Mark up view, E80), `drawings.ts` (Dokument „Drawings“, E97: alle Blätter aus `.soma/drawings/index.json` als ein PDF in der Code-Spalte, Kopf je Blatt, Treffer auf Ansichten und Maße über die Blatt-mm des Index, Karte zur Auswahl), `drawlink.ts` (Zeichnung und 3D: Kamera in Blickrichtung, Schnittebene ins Schnittwerkzeug, Maß als Punkte, Strecke und Maßzahl), `markdown.ts` (Markdown als Dokument: Tokens von `marked` direkt als DOM, ohne `innerHTML`), `filetree.ts` (Dateibaum in der Seitenleiste, offene Datei hervorgehoben), `versions.ts` (Verlaufsleiste), `terminals.ts` (xterm.js, Tabs, Einklappen, Einfügen), `ui.ts` (Menüs, Meldungen, Helfer), `icons.ts` (Symbole), `style.css` (Farben mit fester Bedeutung, siehe Kopf der Datei) |
+| `src/renderer/` | Oberfläche: `main.ts` (Verdrahtung: Kopfzeile mit Spalten-Schaltern, Seitenleiste und Code-Spalte, Reiter Analysis und Animation mit Punkt für Neues, Werkzeuge neben dem Strukturbaum, Menüs, Auswahl, Export, Übergabe an den Agenten auch per Ziehen ins Terminal, Startseite), `viewer.ts` (three.js, Klick auf Code, Ansichten, Drehpunkt, Mausbelegungen und orthografische Kamera (E81), Schnittebene mit gefüllter Schnittfläche und Kontur, verschobene Bauteile der Explosion mit Wegen, Strahltest der Demontage-Analyse mit BVH aus `three-mesh-bvh`, Vorschaubild, Bild für die Markierung), `viewcube.ts` (Ansichtswürfel in 3D), `sectiontool.ts` (Schnitt: Karte, Ebene, Text für den Agenten), `explodetool.ts` (Explosion: Demontage-Analyse mit Baugruppen und schrägen Richtungen, Elternteile, Lage, Abspielen Schritt für Schritt, Karte, Texte für den Agenten), `busy.ts` (Ladeanzeige über dem Viewer mit Fortschritt und Abbrechen, für die Analyse der Explosion), `skills.ts` (Skills in der Seitenleiste: Zeilen mit Stufen-Schalter, Karte daneben mit Einstellungen), `help.ts` (Hilfe über der App: Abschnitte der Anleitung, E83), `tutorial.ts` (geführte Tour, E94: Karte mit Schritt, Titel und Text, oranger Rahmen um das Element, Abdunklung aus vier Flächen, Klicks gehen durch, ohne Element Karte in der Mitte; die zehn Schritte am Modell „Tutorial“), `settings.ts` (Einstellungen über der App mit Reitern, Reiter „Skills“ mit Liste, Markdown-Editor, Vorschau und Prüfung beim Tippen, E78), `settingspages.ts` (Reiter Viewer, Shortcuts, Storage und About, E81), `params.ts` (Parameter in der Seitenleiste: Felder nach Art, Gruppen, Zurücksetzen auf den Wert aus dem Code, E74), `markup.ts` (Zeichenfläche der Markierung, Formen als bearbeitbare Objekte), `measuretool.ts` (Messen: Ablauf, Karte, Text für den Agenten), `tree.ts` (Strukturbaum oben links im Viewer, E82: ohne Hintergrund, Baumstriche, Gruppen, Auge und Transparenz vor dem Namen, Referenzen als Gruppe am Ende, Suche, F3, Mehrfachauswahl, Ziehen über die Augen), `shortcuts.ts` (Liste aller Tasten für den Reiter Shortcuts der Einstellungen), `code.ts` (Code-Spalte mit Editor: CodeMirror 6, Speichern auf Wunsch, Abgleich mit Änderungen des Agenten, Konflikte, Umschalter für Markdown), `dxfview.ts` (DXF-Ansicht im Code-Panel: Pfade auf einer Canvas, Zoom, Layer, Mark up view, E80), `drawings.ts` (Dokument „Drawings“, E97: alle Blätter aus `.soma/drawings/index.json` als ein PDF in der Code-Spalte, Kopf je Blatt, Treffer auf Ansichten und Maße über die Blatt-mm des Index, Karte zur Auswahl), `drawlink.ts` (Zeichnung und 3D: Kamera in Blickrichtung, Schnittebene ins Schnittwerkzeug, Maß als Punkte, Strecke und Maßzahl), `markdown.ts` (Markdown als Dokument: Tokens von `marked` direkt als DOM, ohne `innerHTML`), `filetree.ts` (Dateibaum in der Seitenleiste, offene Datei hervorgehoben), `versions.ts` (Verlaufsleiste), `fileview.ts` (STEP-Datei aus dem Projekt im Viewer: Banner, Neuladen bei Änderung, schließt sich mit der Versionsvorschau aus), `terminals.ts` (xterm.js, Tabs, Einklappen, Einfügen), `ui.ts` (Menüs, Meldungen, Helfer), `icons.ts` (Symbole), `style.css` (Farben mit fester Bedeutung, siehe Kopf der Datei) |
| `src/renderer/` (E58) | `animdata.ts` (Animation aus der glTF-Datei auswerten), `animtool.ts` (Abspielleiste unten im Bild), `animpanel.ts` (Reiter Animation: Liste mit Videos, Schritte, E82), `overlay.ts` (Untertitel, Beschriftungen, Legende auf einer 2D-Fläche, im Viewer wie im Video), `resultview.ts` und `resulttool.ts` (Ergebnisse farbig, Legende, Leiste und Beschriftungen im Bild), `analysispanel.ts` (Reiter Analysis: Liste und Bericht, E82), `videoview.ts` (Video-Player mit Standbild markieren), `render.html` und `render.ts` (unsichtbares Render-Fenster: Bild, Übersicht, MP4 mit WebCodecs und mediabunny) |
| `src/shared/` | `help.ts` Anleitung in Abschnitte zerlegen (E83), `types.ts` Typen des IPC-Vertrags, `editable.ts` welche Dateien der Editor nur zeigt (gilt in Renderer und Hauptprozess), `skillname.ts` Kennung eines eigenen Skills aus seinem Namen |
| `resources/template/` | Vorlage für neue Projekte: `model.py`, `AGENTS.md`, `CLAUDE.md`, `NOTES.md`, `.gitignore` |
| `resources/skills/` | Mitgelieferte Skills (E17), je eine Markdown-Datei: Kopf mit `title`, `summary`, `topics`, `category` (Überschrift im Panel), `name` und `when` (englisch, für `AGENTS.md`: Name und Anlass), `order`, `default:` (Stufe bei neuen Modellen: `always`, `on-demand` oder `off`) und optional Einstellungen als `var name: Standard \| Einheit \| Bezeichnung \| 10..85` oder `\| a, b=Anzeige`, darunter die Regeln für den Agenten auf Englisch mit Platzhaltern `{{name}}` |
| `resources/help/` | Bilder der Anleitung (E83) mit nummerierten Markierungen, erzeugt mit `npm run help:shots` (`test/helpshots.mjs`, Ausschnitte und Nummern in `test/helpshots-spec.mjs`). Der Text ist der Skill `resources/skills/soma-app.md`, die Liste unter jedem Bild nennt dieselben Bezeichnungen wie die Markierungen (`npm run test:unit` prüft das) |
| `resources/icon.*` | App-Icon (E44) für Fenster und Taskleiste: `icon.svg` als Vorlage, `icon.ico` (16 bis 256 px) und `icon.png`. Neu erzeugen mit `python scripts/make-icon.py` (braucht Edge und Pillow, kleine Größen bekommen einen dickeren Strich) |
-| `../python/soma/` | Hilfsbibliothek und Kommandozeile (`soma build`, `soma export`, `soma glb` für Vorschauen, `soma serve` Messdienst, `soma warm` vorgewärmter Prozess der App, `soma env` und `env.py` Projektumgebung und `requirements.txt` (E67), `measure.py` exakte Werte mit OCC, `fasteners.py` Normteile mit Tabellen aus bd_warehouse in `data/fasteners/`, `anim.py` und `animrun.py` Animationen mit `soma anim`, `analysis.py` Auswertungen mit `soma analyze`, `fem.py` Festigkeit mit `soma analyze fem` (gmsh, Kontakt, Schrauben mit Vorspannung, eigener Solver mit pyamg als Rückfall), `ccx.py` CalculiX als Rechenwerk (E84), `render.py` Auftrag an die App für `soma render`, `drawing.py` und `drawrun.py` technische Zeichnungen mit `soma drawing` (E76: HLR aus OCP, DXF mit ezdxf, PDF und PNG über matplotlib, Prüfung), `dxfview.py` DXF für die Ansicht der App mit `soma dxfview` (E80, Zeichenmodul von ezdxf), `gltf.py` GLB-Schreiber, `progress.py` Fortschritt langer Befehle) |
-| `test/` | `smoke.mjs`, `versions.mjs`, `editor.mjs`, `measure.mjs`, `groups.mjs`, `section.mjs`, `explode.mjs`, `skills.mjs`, `params.mjs`, `tutorial.mjs`, `updates.mjs`, `fasteners.mjs`, `drawing.mjs`, `drawview.mjs`, `dxf.mjs`, `animation.mjs` (Ende-zu-Ende), `unit.mjs` (ohne Electron), `buildlock.mjs` (Sperre von `soma build`, nur Python), `harness.mjs` (App starten und steuern), `cdp.mjs` (kleiner DevTools-Client, puppeteer scheitert an Electron 44) |
+| `../python/soma/` | Hilfsbibliothek und Kommandozeile (`soma build`, `soma export`, `soma glb` für Vorschauen, `soma serve` Messdienst, `soma warm` vorgewärmter Prozess der App, `soma env` und `env.py` Projektumgebung und `requirements.txt` (E67), `measure.py` exakte Werte mit OCC, `fasteners.py` Normteile mit Tabellen aus bd_warehouse in `data/fasteners/`, `cqcompat.py` Kompatibilitätsmodus für CadQuery-Skripte ohne `add_part` (E100), `cqexport.py` mit `soma cadquery export|import` und `cqruntime.py` als Block exportierter Skripte (Apache 2.0, E101), `anim.py` und `animrun.py` Animationen mit `soma anim`, `analysis.py` Auswertungen mit `soma analyze`, `fem.py` Festigkeit mit `soma analyze fem` (gmsh, Kontakt, Schrauben mit Vorspannung, eigener Solver mit pyamg als Rückfall), `ccx.py` CalculiX als Rechenwerk (E84), `render.py` Auftrag an die App für `soma render`, `drawing.py` und `drawrun.py` technische Zeichnungen mit `soma drawing` (E76: HLR aus OCP, DXF mit ezdxf, PDF und PNG über matplotlib, Prüfung), `dxfview.py` DXF für die Ansicht der App mit `soma dxfview` (E80, Zeichenmodul von ezdxf), `gltf.py` GLB-Schreiber, `progress.py` Fortschritt langer Befehle) |
+| `test/` | `smoke.mjs`, `versions.mjs`, `editor.mjs`, `measure.mjs`, `stepview.mjs`, `cadquery.mjs`, `groups.mjs`, `section.mjs`, `explode.mjs`, `skills.mjs`, `params.mjs`, `tutorial.mjs`, `updates.mjs`, `fasteners.mjs`, `drawing.mjs`, `drawview.mjs`, `dxf.mjs`, `animation.mjs` (Ende-zu-Ende), `unit.mjs` (ohne Electron), `buildlock.mjs` (Sperre von `soma build`, nur Python), `harness.mjs` (App starten und steuern), `cdp.mjs` (kleiner DevTools-Client, puppeteer scheitert an Electron 44) |
## Noch nicht enthalten
diff --git a/app/package.json b/app/package.json
index 9411973..dfa1a43 100644
--- a/app/package.json
+++ b/app/package.json
@@ -15,6 +15,8 @@
"test:versions": "npm run build && node test/versions.mjs",
"test:editor": "npm run build && node test/editor.mjs",
"test:measure": "npm run build && node test/measure.mjs",
+ "test:stepview": "npm run build && node test/stepview.mjs",
+ "test:cadquery": "npm run build && node test/cadquery.mjs",
"test:groups": "npm run build && node test/groups.mjs",
"test:section": "npm run build && node test/section.mjs",
"test:explode": "npm run build && node test/explode.mjs",
diff --git a/app/resources/help/code.png b/app/resources/help/code.png
index a248efc..82be102 100644
Binary files a/app/resources/help/code.png and b/app/resources/help/code.png differ
diff --git a/app/resources/help/export.png b/app/resources/help/export.png
index 78494bf..58d58ff 100644
Binary files a/app/resources/help/export.png and b/app/resources/help/export.png differ
diff --git a/app/resources/help/history.png b/app/resources/help/history.png
index a482f1b..a3a8569 100644
Binary files a/app/resources/help/history.png and b/app/resources/help/history.png differ
diff --git a/app/resources/help/markup.png b/app/resources/help/markup.png
index 309552f..0289491 100644
Binary files a/app/resources/help/markup.png and b/app/resources/help/markup.png differ
diff --git a/app/resources/help/settings.png b/app/resources/help/settings.png
index bb136ff..6158475 100644
Binary files a/app/resources/help/settings.png and b/app/resources/help/settings.png differ
diff --git a/app/resources/help/start.png b/app/resources/help/start.png
index 2fd7927..4f73607 100644
Binary files a/app/resources/help/start.png and b/app/resources/help/start.png differ
diff --git a/app/resources/help/window.png b/app/resources/help/window.png
index 52b1def..f9c5391 100644
Binary files a/app/resources/help/window.png and b/app/resources/help/window.png differ
diff --git a/app/resources/skills/cadquery-scripts.md b/app/resources/skills/cadquery-scripts.md
new file mode 100644
index 0000000..90d3649
--- /dev/null
+++ b/app/resources/skills/cadquery-scripts.md
@@ -0,0 +1,51 @@
+---
+title: CadQuery scripts
+name: CadQuery scripts
+summary: Plain CadQuery scripts in SOMA: compatibility mode (show_object, ocp_vscode, result), converting them to add_part() and param(), and the block that "Export as CadQuery" writes.
+order: 7
+category: Way of working
+default: on-demand
+when: `soma build` reports "Compatibility mode", the model came from an existing CadQuery script, the code calls show_object() or ocp_vscode, or a file contains a "soma-compat" block
+topics: Compatibility mode; Converting to add_part and param; Checking the conversion; Exported scripts
+---
+# Skill: CadQuery scripts
+
+## Compatibility mode
+
+SOMA also builds plain CadQuery scripts that do not call `add_part()`. `soma build` then takes the parts from:
+
+1. `show_object(obj, name=..., options={"color": ..., "alpha": ...})` as in CQ-editor and cq-cli,
+2. `show(...)`, `show_object(...)` and `show_all()` of ocp_vscode (SOMA puts a stand-in in place of the package, it opens no viewer),
+3. otherwise the variable `result`.
+
+The build reports this as a warning starting with "Compatibility mode". The model works in the app (viewer, measuring, section, click to code on the `show_object()` line). What it lacks: groups, roles (reference, purchased part), parameters in the Parameters panel, and clear part names when `show_object()` has no `name`. `debug()` objects are left out.
+
+As soon as the script calls `add_part()` once, only the `add_part()` parts count and `show_object()` has no effect.
+
+## Converting to add_part and param
+
+Convert only when the user asks for it. The original script is kept in `inputs/` (the import copies it there), do not delete it.
+
+- `show_object(box, name="Box", options={"color": (255, 0, 0)})` becomes `add_part("Box", box, color=(1.0, 0.0, 0.0))`. Colors in SOMA are 0..1, CQ-editor also takes 0..255 and color names. A part with `alpha` below 1 that is only there for orientation is usually a `role="reference"`.
+- `show(a, b, names=["A", "B"])` of ocp_vscode becomes one `add_part()` per object. Remove `from ocp_vscode import ...` and calls like `set_port()` or `set_defaults()`.
+- `result = ...` alone becomes `add_part("<a good name>", result)`.
+- Every part needs a unique, meaningful name. Ask the user if the script does not say what a part is.
+- Groups: `group="Housing"` for parts that belong together.
+- Constants the user will want to change (length, wall, hole diameter) become `param(...)` with label, range and unit (skill "Parametric models"). Leave internal helper values as constants.
+- Do not change the geometry while converting. Improvements come afterwards, as a step of their own.
+- Imports: `from soma import add_part, param` at the top, `import cadquery as cq` stays.
+
+## Checking the conversion
+
+Build before and after (`soma build`) and compare `.soma/model.map.json`: the same number of parts, and for each part the same `bbox` and `volume` (rounded to 0.001). Tell the user if anything differs, and why.
+
+## Exported scripts
+
+"Export as CadQuery" in the app (Export menu, "As CadQuery script") writes the model as plain CadQuery that runs in CQ-editor, VS Code with ocp_vscode, cq-cli and plain Python, without soma:
+
+- Each `from soma import ...` line stays as a comment `# soma-import: ...`. The first one is followed by a block between `# >>> soma-compat` and `# <<< soma-compat` that provides `add_part()`, `param()`, `import_step()`, `import_assembly()` and, if used, the standard parts (Apache License 2.0). A footer at the end shows the parts and sets `result` to the assembly.
+- The values from the Parameters panel are in `_SOMA_VALUES` in the block. Only that line may change.
+- A model with modules in `parts/` becomes a folder with `soma_compat.py` instead of the block.
+- Animations, drawings and analyses stay in SOMA.
+
+"New from CadQuery script" in the app brings such a script back: the markers turn into the original imports again and the values go to `parameters.json`. Never edit the block by hand, otherwise SOMA keeps it as it is (it still builds, then in compatibility mode). If you find a block in `model.py`, tell the user that importing the script through "New from CadQuery script" removes it cleanly.
diff --git a/app/resources/skills/soma-app.md b/app/resources/skills/soma-app.md
index 9153d10..cbf16f2 100644
--- a/app/resources/skills/soma-app.md
+++ b/app/resources/skills/soma-app.md
@@ -26,7 +26,7 @@ things, and ask for changes.
![The main window](../help/window.png)
-1. **Model menu**: new model, open, recent models, save as. Next to it: whether the model is saved.
+1. **Model menu**: new model, new from CadQuery script, open, recent models, save as. Next to it: whether the model is saved.
2. **Build status**: "Built" when the model is up to date, "Build failed" if the code has an error. Click for details. With "Auto on" the model is rebuilt whenever the code changes.
3. **Columns**: show or hide the sidebar, the code and the agent (Ctrl 1, Ctrl 2, Ctrl 3).
4. **Import**: add files such as STEP models, images or sketches to `inputs/`, where the agent can use them. Dragging files or folders into the window does the same.
@@ -46,7 +46,7 @@ The logo at the top left opens the start page.
![The start page](../help/start.png)
1. **Tutorial**: a short guided tour of the app with an example model. No agent needed. "Got it" hides the card.
-2. **New model**: starts from a small example (a box with a lid) and opens a terminal in the model folder (Ctrl N).
+2. **New model**: starts from a small example (a box with a lid) and opens a terminal in the model folder (Ctrl N). Below it, **New from CadQuery script** starts from an existing CadQuery script instead (see "CadQuery scripts").
3. **Open**: opens a .soma or ZIP file (Ctrl O).
4. **Recent**: models you worked on. The bin on a card removes the model from this computer, a saved .soma file stays.
5. **Agents on this computer**: the agents SOMA found. You install them yourself, SOMA does not bring one.
@@ -155,6 +155,11 @@ Ask the agent for a technical drawing ("Make a drawing of the bracket with all d
Markdown files (such as `NOTES.md`) open as a document, PDF and DXF files open as a drawing.
+Click a STEP file (`.step`, `.stp`) to look at it in the viewer. A banner names the file. Measure, Section, Explode and the
+structure tree work as usual, but the parts have no link to code, and Animation and Analysis stay off. Builds of your model
+wait until you click **Back to model**. When the file changes on disk, the viewer loads it again. Large files can take a
+while the first time, after that they open from the preview cache.
+
## Saving and history
![Looking at an earlier version](../help/history.png)
@@ -173,9 +178,27 @@ after that Ctrl S saves to the same file. Copy or send the file like any other d
1. **Scope**: all parts, or only the selected one.
2. **Formats**: for 3D printing (STL, 3MF), CAD (STEP, IGES), graphics and 2D (DXF, SVG). All parts become one file per part in a folder you choose.
3. **Everything as ZIP**: the whole model with code, results and history, for someone without SOMA.
+4. **As CadQuery script**: the model as plain CadQuery for CQ-editor, VS Code with ocp_vscode and other tools, without SOMA.
Reference parts (for example an imported circuit board) are not included in "All parts".
+## CadQuery scripts
+
+SOMA works with plain CadQuery scripts in both directions.
+
+- **In:** **New from CadQuery script** in the model menu makes a new model from a `.py` file. The script stays as it is, the
+ original is kept in `inputs/`. Scripts for CQ-editor (`show_object`), for VS Code (`ocp_vscode`) or with a variable
+ `result` build in compatibility mode: the build shows a warning, the parts take their names and colors from there. Ask
+ the agent to convert the script to `add_part()` and `param()`, then you get groups and the Parameters panel.
+- **Out:** **As CadQuery script** in the Export menu writes one `.py` file. Your code stays the same, only the `from soma
+ import` lines are replaced by a marked block that provides `add_part()`, `param()` and the standard parts. The values
+ from the Parameters panel are in it. A model with modules in `parts/` becomes a folder with `soma_compat.py`. Animations,
+ drawings and analyses stay in SOMA.
+- **Back again:** import an exported script with **New from CadQuery script**. The block is removed, your original imports
+ and the values of the Parameters panel come back. Leave the block unchanged, otherwise SOMA keeps it as it is.
+
+The block and the standard parts are under the Apache License 2.0, so the exported script is yours like any model.
+
## Settings
![Settings](../help/settings.png)
diff --git a/app/src/main/dialogs.ts b/app/src/main/dialogs.ts
index 213d13c..725661e 100644
--- a/app/src/main/dialogs.ts
+++ b/app/src/main/dialogs.ts
@@ -52,6 +52,14 @@ export async function chooseExportTarget(win: BrowserWindow | null, o: { kind: '
export const documentsDir = () => app.getPath('documents');
+/** CadQuery-Skript für ein neues Modell (E100). null: abgebrochen. */
+export async function chooseCadQueryScript(win: BrowserWindow | null): Promise<string | null> {
+ if (testMode()) return nextAnswer<string | null>('New model from CadQuery script');
+ const opts = { title: 'New model from CadQuery script', defaultPath: documentsDir(), filters: [{ name: 'CadQuery script', extensions: ['py'] }], properties: ['openFile' as const] };
+ const r = win ? await dialog.showOpenDialog(win, opts) : await dialog.showOpenDialog(opts);
+ return r.canceled || !r.filePaths[0] ? null : r.filePaths[0];
+}
+
/** Markdown-Dateien, die als eigene Skills übernommen werden (E78). Leere Liste: abgebrochen. */
export async function chooseSkillFiles(win: BrowserWindow | null): Promise<string[]> {
if (testMode()) return nextAnswer<string[] | null>('Import skills') ?? [];
diff --git a/app/src/main/main.ts b/app/src/main/main.ts
index 41f4fd8..910b9c8 100644
--- a/app/src/main/main.ts
+++ b/app/src/main/main.ts
@@ -54,6 +54,8 @@ function registerIpc(ctl: ProjectController): void {
ipcMain.handle('project:save', (_e, saveAs?: boolean) => ctl.save(!!saveAs));
ipcMain.handle('project:openZip', () => ctl.openZip());
ipcMain.handle('project:exportZip', () => ctl.exportZip());
+ ipcMain.handle('project:createFromCadQuery', () => ctl.createFromCadQuery());
+ ipcMain.handle('project:exportCadQuery', () => ctl.exportCadQuery());
ipcMain.handle('project:reveal', () => ctl.reveal());
ipcMain.handle('project:setThumb', (_e, dataUrl: string) => {
const m = /^data:image\/jpeg;base64,([A-Za-z0-9+/=]+)$/.exec(String(dataUrl));
@@ -62,6 +64,7 @@ function registerIpc(ctl: ProjectController): void {
fs.writeFileSync(path.join(thumbnailsDir(), `${ctl.session.id}.jpg`), Buffer.from(m[1], 'base64'));
});
ipcMain.handle('project:remove', (_e, id: string) => ctl.remove(String(id)));
+ ipcMain.handle('project:viewFile', (_e, rel: unknown) => ctl.viewFile(rel));
ipcMain.handle('project:thumb', (_e, id: string) => {
if (!isProjectId(String(id))) return null;
try { return `data:image/jpeg;base64,${fs.readFileSync(path.join(thumbnailsDir(), `${id}.jpg`)).toString('base64')}`; } catch { return null; }
diff --git a/app/src/main/previews.ts b/app/src/main/previews.ts
index 2238a50..efce681 100644
--- a/app/src/main/previews.ts
+++ b/app/src/main/previews.ts
@@ -1,8 +1,8 @@
-import { randomUUID } from 'node:crypto';
+import { createHash, randomUUID } from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import type { ModelMap } from '../shared/types';
-import { readLastBuild, type LastBuild } from './build';
+import { readLastBuild, runSoma, type LastBuild } from './build';
/** Eine GLB-Datei ist vollständig, wenn ihr Kopf passt und die angegebene Gesamtlänge der Dateigröße entspricht. */
function completeGlb(file: string): boolean {
@@ -52,3 +52,103 @@ export async function storeBuildAsPreview(dir: string, target: string, last: Las
return false;
}
}
+
+// ---- STEP-Dateien aus dem Projekt im Viewer ------------------------------------------------------------------------
+
+/** Große Baugruppen einzulesen und zu vernetzen dauert Minuten, aber nicht ewig: danach gilt die Datei als zu groß. */
+export const STEP_VIEW_TIMEOUT_MS = 10 * 60 * 1000;
+/** Übrig gebliebene Arbeitsordner (App abgestürzt) älter als das werden beim nächsten Umwandeln entfernt. */
+const STALE_TMP_MS = 24 * 60 * 60 * 1000;
+
+/** Vorschau-Ordner vollständig: Zuordnung lesbar, GLB ganz und die Geometrie zum Messen da. */
+export function previewComplete(dir: string): boolean {
+ try {
+ const map = JSON.parse(fs.readFileSync(path.join(dir, 'model.map.json'), 'utf8')) as ModelMap;
+ return typeof map.build === 'string' && /^[0-9a-f]{32}$/.test(map.build) && Array.isArray(map.parts)
+ && completeGlb(path.join(dir, 'model.glb')) && fs.statSync(path.join(dir, 'geometry', `${map.build}.brep`)).isFile();
+ } catch { return false; }
+}
+
+function sha1File(file: string): Promise<string> {
+ return new Promise((resolve, reject) => {
+ const h = createHash('sha1');
+ fs.createReadStream(file).on('error', reject).on('data', (d) => h.update(d)).on('end', () => resolve(h.digest('hex')));
+ });
+}
+
+/** Größe und Zeitstempel einer Datei, deren Inhalt schon gehasht wurde: Unverändert muss sie nicht neu gelesen werden. */
+export interface StepStamp { size: number; mtimeMs: number; key: string }
+
+/**
+ * Wandelt eine STEP-Datei aus dem Projekt (`abs`, schon über resolveInside geprüft) mit `soma glb` für den Viewer um. Der
+ * Cache liegt unter `root/<SHA-1 des Inhalts>`, in derselben Form wie die Vorschau alter Stände (model.glb, model.map.json,
+ * geometry/), damit Messen, Schnitt und Explosion genauso gehen. Eine unveränderte Datei wird nicht neu umgewandelt.
+ *
+ * Umgewandelt wird eine Kopie: Schreibt der Agent die Datei währenddessen neu, passte das Ergebnis sonst nicht zum Hash.
+ * Alles entsteht in einem Arbeitsordner und wird erst fertig umbenannt, ein halber Cache-Ordner bleibt nie stehen.
+ * `cwd`: Projektordner für den Python-Prozess. Kein Wurf, Fehler stehen verständlich in `error`.
+ */
+export async function stepPreview(abs: string, root: string, cwd: string, memo: Map<string, StepStamp>): Promise<{ key: string; dir: string } | { error: string }> {
+ let st: fs.Stats;
+ try { st = await fs.promises.stat(abs); } catch { return { error: 'The file no longer exists.' }; }
+ if (!st.isFile()) return { error: 'This is not a file.' };
+ if (st.size === 0) return { error: 'The file is empty.' };
+ const known = memo.get(abs);
+ if (known && known.size === st.size && known.mtimeMs === st.mtimeMs && previewComplete(path.join(root, known.key))) return { key: known.key, dir: path.join(root, known.key) };
+
+ await fs.promises.mkdir(root, { recursive: true });
+ void removeStaleTmp(root);
+ const tmp = path.join(root, `.tmp-${randomUUID()}`);
+ const drop = () => fs.promises.rm(tmp, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 }).catch(() => {});
+ try {
+ await fs.promises.mkdir(tmp);
+ const copy = path.join(tmp, `source${path.extname(abs).toLowerCase()}`);
+ try { await fs.promises.copyFile(abs, copy); } catch (e) { await drop(); return { error: `The file could not be read: ${e instanceof Error ? e.message : String(e)}` }; }
+ const key = await sha1File(copy);
+ // Nur merken, wenn die Datei beim Kopieren stillstand: Sonst gehört der Hash zu einem anderen Zeitstempel
+ const after = await fs.promises.stat(abs).catch(() => null);
+ if (after && after.size === st.size && after.mtimeMs === st.mtimeMs) memo.set(abs, { size: st.size, mtimeMs: st.mtimeMs, key });
+ const target = path.join(root, key);
+ if (previewComplete(target)) { await drop(); return { key, dir: target }; }
+
+ const t0 = Date.now();
+ const r = await runSoma(['glb', copy, '--out', tmp], cwd, STEP_VIEW_TIMEOUT_MS);
+ if (!r.ok) {
+ await drop();
+ if (Date.now() - t0 >= STEP_VIEW_TIMEOUT_MS - 1000) return { error: `Reading the file took longer than ${STEP_VIEW_TIMEOUT_MS / 60000} minutes and was stopped. The file may be too large for the viewer.` };
+ // Die Meldung nennt sonst den Pfad der Arbeitskopie, mit dem der Nutzer nichts anfangen kann
+ const last = ((r.err || r.out).trim().split(/\r?\n/).pop() ?? '').replace(/^Conversion failed:\s*/, '').replace(/^\w+(Error|Exception):\s*/, '')
+ .split(copy).join(path.basename(abs));
+ if (/Error reading STEP file|could not be loaded/i.test(last)) return { error: 'The file is not a valid STEP file or it is damaged.' };
+ return { error: `The STEP file could not be read${last ? `: ${last}` : '.'}` };
+ }
+ await fs.promises.rm(copy, { force: true });
+ if (!previewComplete(tmp)) { await drop(); return { error: 'The conversion did not produce a complete result.' }; }
+ // Inzwischen gleichzeitig fertig geworden (zweiter Aufruf für dieselbe Datei): dessen Ergebnis nehmen
+ if (previewComplete(target)) { await drop(); return { key, dir: target }; }
+ try {
+ // Steht ein unvollständiger Rest unter dem Namen (etwa von einer älteren Fassung), weicht er erst
+ if (fs.existsSync(target)) await fs.promises.rm(target, { recursive: true, force: true });
+ await fs.promises.rename(tmp, target);
+ } catch {
+ // Gleichzeitig dieselbe Datei umgewandelt: Dann gilt die, die zuerst fertig war
+ await drop();
+ if (!previewComplete(target)) return { error: 'The result could not be stored in the preview cache.' };
+ }
+ return { key, dir: target };
+ } catch (e) {
+ await drop();
+ return { error: `The file could not be shown: ${e instanceof Error ? e.message : String(e)}` };
+ }
+}
+
+async function removeStaleTmp(root: string): Promise<void> {
+ try {
+ for (const n of await fs.promises.readdir(root)) {
+ if (!n.startsWith('.tmp-')) continue;
+ const p = path.join(root, n);
+ const st = await fs.promises.stat(p).catch(() => null);
+ if (st && Date.now() - st.mtimeMs > STALE_TMP_MS) await fs.promises.rm(p, { recursive: true, force: true }).catch(() => {});
+ }
+ } catch { /* Aufräumen ist verzichtbar */ }
+}
diff --git a/app/src/main/projects.ts b/app/src/main/projects.ts
index 6f3f0be..b09db37 100644
--- a/app/src/main/projects.ts
+++ b/app/src/main/projects.ts
@@ -3,7 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import type {
- AnimBuildResult, AnimList, DrawingBuildResult, DrawingList, ExportResult, GitLog, MeasureEntity, MeasurePrepared, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult,
+ AnimBuildResult, AnimList, CadQueryImportResult, DrawingBuildResult, DrawingList, ExportResult, FileViewResult, GitLog, MeasureEntity, MeasurePrepared, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult,
ParamResult, ParamState, ParamValue, ProjectInfo, RemoveResult, RenderResult, RestoreResult, ResultEntry, SaveResult, SaveState, SkillInfo, SkillResult,
} from '../shared/types';
import { affectsAnimation } from '../shared/editable';
@@ -12,15 +12,15 @@ import { DrawingBuilder, isDrawingFile, readDrawingList } from './drawings';
import { resolveInside } from './files';
import { BuildManager, buildIsStale, currentBuild, newestSourceMtime, runSoma } from './build';
import { checkRequest, RenderService, type RenderRequest } from './render';
-import { choose, chooseExportTarget, choosePath, documentsDir, trashItem } from './dialogs';
+import { choose, chooseCadQueryScript, chooseExportTarget, choosePath, documentsDir, trashItem } from './dialogs';
import { GitRepo, type GitStatus } from './git';
import { MeasureService } from './measure';
import { ensureEnv, envIsCurrent, installMissing, missingPackages } from './packages';
import { checkParamValue, isParamValue, readUserParams, writeUserParams } from './params';
-import { helpDir, previewsDir, skillBackupsDir, skillDirs } from './paths';
+import { backupsDir, helpDir, previewsDir, skillBackupsDir, skillDirs } from './paths';
import { syncHelpImages } from './help';
import { HELP_SKILL } from '../shared/help';
-import { storeBuildAsPreview } from './previews';
+import { stepPreview, storeBuildAsPreview, type StepStamp } from './previews';
import {
agentsEntries, checkValue, cleanValues, copySkill, isSkillId, isSkillMode, librarySkill, listSkills, modeOf, removeSkill, withMode, writeAgentsList, type SkillValues,
} from './skills';
@@ -52,9 +52,22 @@ interface Session {
caching?: boolean;
/** Projektumgebung bereit (E67): Fehlertext oder null. */
env: Promise<string | null>;
+ /** STEP-Dateien im Viewer: schon gehashte Dateien und laufende Umwandlungen (ein Doppelklick wandelt nicht zweimal um). */
+ stepStamps: Map<string, StepStamp>;
+ stepJobs: Map<string, Promise<FileViewResult>>;
}
+/** Nur diese Dateien zeigt der Viewer aus dem Projekt. */
+const STEP_FILE = /\.(step|stp)$/i;
+
const POLL_MS = 2000;
+/** Letzte JSON-Zeile einer Ausgabe von `soma … --json` (davor können Meldungen von Bibliotheken stehen). */
+function lastJson<T>(out: string): T | null {
+ for (const line of out.trim().split(/\r?\n/).reverse()) {
+ try { const v = JSON.parse(line) as unknown; if (v && typeof v === 'object') return v as T; } catch { /* keine JSON-Zeile */ }
+ }
+ return null;
+}
const safeFileName = (n: string) => n.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').trim() || 'Model';
/** Modelle werden als .soma gespeichert (E79), innen eine ZIP. Geöffnet wird auch eine .zip. */
const MODEL_EXT = '.soma';
@@ -132,7 +145,7 @@ export class ProjectController {
// Projektumgebung (E67): Meist steht sie schon, sonst legt `soma env` sie in rund 0,5 s an. Die Terminals kennen ihre
// Pfade vorab, gewartet wird nur vor dem Installieren von Paketen
const env = envIsCurrent(dir) ? Promise.resolve(null) : ensureEnv(dir);
- const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), anims, drawings, stopWatch, signature: '', env, poll: setInterval(() => void this.pollGit(), POLL_MS) };
+ const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), anims, drawings, stopWatch, signature: '', env, stepStamps: new Map(), stepJobs: new Map(), poll: setInterval(() => void this.pollGit(), POLL_MS) };
this.session = session;
void env.then((err) => { if (err) { console.error('[soma]', err); builds.reportPackageError(err); } });
builds.on('status', (st) => {
@@ -157,6 +170,33 @@ export class ProjectController {
return this.open(id);
}
+ /**
+ * Neues Modell aus einem CadQuery-Skript (E100). `soma cadquery import` läuft vor dem ersten Build und dem Startcommit:
+ * Ein Export aus SOMA wird zurückgedreht, ein fremdes Skript baut im Kompatibilitätsmodus. Das Original liegt danach in
+ * inputs/, die ersetzte Vorlage in workspace-backups/. Scheitert der Import, entsteht kein Modell.
+ */
+ async createFromCadQuery(): Promise<CadQueryImportResult> {
+ const file = await chooseCadQueryScript(this.getWin());
+ if (!file) return { cancelled: true, warnings: [] };
+ // Import, erster Build und Startcommit dauern einige Sekunden: Das Fenster zeigt die Schritte in einer Ladeanzeige
+ const step = (s: string) => this.send('cadquery:step', { step: s, file: path.basename(file) });
+ step('Reading the script');
+ let warnings: string[] = [];
+ try {
+ const { id } = await createProject(path.parse(file).name.trim() || undefined, async (dir, pid) => {
+ const r = await runSoma(['cadquery', 'import', file, '--project', dir, '--backup', path.join(backupsDir(), `${pid}-import`), '--json'], dir);
+ const res = lastJson<{ status?: string; error?: string; warnings?: string[] }>(r.out);
+ if (!r.ok || res?.status !== 'ok') throw new Error(res?.error || (r.err || r.out).trim().split(/\r?\n/).pop() || 'unknown error');
+ warnings = Array.isArray(res.warnings) ? res.warnings.map(String) : [];
+ step('Building the model for the first time');
+ });
+ step('Opening the model');
+ return { info: await this.open(id), warnings };
+ } catch (e) {
+ return { warnings: [], error: `The script could not be imported: ${e instanceof Error ? e.message : String(e)}` };
+ }
+ }
+
/**
* Fehlen Pakete aus requirements.txt in der Projektumgebung, werden sie installiert (E67), und Builds warten so lange.
* `build`: danach bauen. Gibt zurück, ob installiert wird.
@@ -286,6 +326,59 @@ export class ProjectController {
}
}
+ /**
+ * Das Modell als reines CadQuery-Skript (E100). soma schreibt erst in einen leeren Ordner unter Temp, danach weiß die App,
+ * ob es eine Datei wird oder (mit parts/) ein Ordner, und fragt nach dem Ziel. Vorhandenes ersetzt sie nur nach Rückfrage.
+ */
+ async exportCadQuery(): Promise<ExportResult> {
+ const s = this.need();
+ const name = safeFileName(readProjectJson(s.id)?.name ?? 'Model');
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'soma-cq-'));
+ try {
+ const r = await runSoma(['cadquery', 'export', '--project', s.dir, '--out', path.join(tmp, `${name}.py`), '--json'], s.dir);
+ const res = lastJson<{ status?: string; mode?: string; error?: string; warnings?: string[] }>(r.out);
+ if (!r.ok || res?.status !== 'ok') return { ok: false, files: [], error: res?.error || (r.err || r.out).trim().split(/\r?\n/).slice(-3).join('\n') || 'Export failed' };
+ const folder = res.mode === 'folder';
+ const last = getAppState(s.id).exportDir;
+ const startDir = last && fs.existsSync(last) ? last : documentsDir();
+ const target = await chooseExportTarget(this.getWin(), folder
+ ? { kind: 'dir', title: `Choose a folder for the CadQuery model (a folder “${name}” is created in it)`, defaultPath: startDir }
+ : { kind: 'file', title: 'Export as CadQuery script', defaultPath: path.join(startDir, `${name}.py`), ext: 'py', label: 'CadQuery script' });
+ if (!target) return { ok: false, files: [], cancelled: true };
+ const walk = (d: string): string[] => fs.readdirSync(d, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? walk(path.join(d, e.name)) : [path.join(d, e.name)]);
+ const plan: [string, string][] = [];
+ let dest: string;
+ if (folder) {
+ dest = path.join(target, name);
+ for (const f of walk(path.join(tmp, name))) plan.push([f, path.join(dest, path.relative(path.join(tmp, name), f))]);
+ } else {
+ dest = /\.py$/i.test(target) ? target : `${target}.py`;
+ plan.push([path.join(tmp, `${name}.py`), dest]);
+ // Mitgebrachte Dateien (inputs/), die das Skript lädt, kommen daneben
+ if (fs.existsSync(path.join(tmp, 'inputs'))) for (const f of walk(path.join(tmp, 'inputs'))) plan.push([f, path.join(path.dirname(dest), path.relative(tmp, f))]);
+ }
+ // Für die Hauptdatei hat der Speichern-Dialog schon gefragt, alles andere fragt die App
+ const exists = plan.filter(([, d], i) => !(!folder && i === 0) && fs.existsSync(d)).map(([, d]) => path.relative(path.dirname(dest), d));
+ if (exists.length) {
+ const c = await choose(this.getWin(), {
+ title: 'Export as CadQuery', message: exists.length === 1 ? 'This file already exists:' : `These ${exists.length} files already exist:`,
+ detail: `${exists.slice(0, 10).join('\n')}${exists.length > 10 ? `\n… and ${exists.length - 10} more` : ''}`, buttons: ['Replace', 'Cancel'],
+ });
+ if (c !== 0) return { ok: false, files: [], cancelled: true };
+ }
+ for (const [src, d] of plan) {
+ fs.mkdirSync(path.dirname(d), { recursive: true });
+ fs.copyFileSync(src, d);
+ }
+ patchAppState(s.id, { exportDir: folder ? target : path.dirname(dest) });
+ return { ok: true, files: plan.map(([, d]) => d), target: dest, warnings: Array.isArray(res.warnings) ? res.warnings.map(String) : [] };
+ } catch (e) {
+ return { ok: false, files: [], error: `Export failed: ${e instanceof Error ? e.message : String(e)}` };
+ } finally {
+ fs.rmSync(tmp, { recursive: true, force: true });
+ }
+ }
+
/**
* Das ganze Modell als ZIP exportieren (E79), etwa für jemanden ohne SOMA: derselbe Inhalt wie die .soma-Datei (Code,
* Ergebnisse, Verlauf). Anders als Speichern ohne Snapshot und ohne die Modelldatei zu ändern, der Speicherstand bleibt.
@@ -519,12 +612,46 @@ export class ProjectController {
/** Ordner des gemessenen Stands, den bestimmt der Hauptprozess. Unbekannte Quelle: null. */
private measureFolder(s: Session, source: unknown): string | null {
- const hash = (source as { preview?: unknown } | null)?.preview;
+ const src = source as { preview?: unknown; file?: unknown; key?: unknown } | null;
if (source === 'live') return path.join(s.dir, '.soma');
- if (typeof hash === 'string' && /^[0-9a-f]{7,40}$/.test(hash)) return path.join(previewsDir(), s.id, hash);
+ if (typeof src?.preview === 'string' && /^[0-9a-f]{7,40}$/.test(src.preview)) return path.join(previewsDir(), s.id, src.preview);
+ // STEP-Datei aus dem Projekt: nur innerhalb, und nur ein Stand, der schon im Cache liegt (der Renderer nennt ihn mit key)
+ if (typeof src?.file === 'string' && STEP_FILE.test(src.file) && typeof src.key === 'string' && /^[0-9a-f]{40}$/.test(src.key)) {
+ try { resolveInside(s.dir, src.file); } catch { return null; }
+ const dir = path.join(this.stepCache(s), src.key);
+ return fs.existsSync(dir) ? dir : null;
+ }
return null;
}
+ private stepCache(s: Session): string { return path.join(previewsDir(), s.id, 'files'); }
+
+ /**
+ * STEP-Datei aus dem Projekt für den Viewer (Klick im Dateibaum). Umgewandelt wird im Basismodus wie bei der Vorschau alter
+ * Stände, über den vorgewärmten Python-Prozess (runSoma). Gleichzeitige Aufrufe für dieselbe Datei teilen sich die Arbeit.
+ */
+ viewFile(rel: unknown): Promise<FileViewResult> {
+ const s = this.need();
+ const fail = (error: string): FileViewResult => ({ rel: typeof rel === 'string' ? rel : '', key: '', glb: new ArrayBuffer(0), map: { version: 0, parts: [] }, error });
+ if (typeof rel !== 'string' || !rel || rel.length > 1000) return Promise.resolve(fail('Invalid file.'));
+ if (!STEP_FILE.test(rel)) return Promise.resolve(fail('Only STEP files (.step, .stp) can be shown in the viewer.'));
+ let abs: string;
+ try { abs = resolveInside(s.dir, rel); } catch { return Promise.resolve(fail('The file is outside the project.')); }
+ const running = s.stepJobs.get(abs);
+ if (running) return running;
+ const job = (async (): Promise<FileViewResult> => {
+ const r = await stepPreview(abs, this.stepCache(s), s.dir, s.stepStamps);
+ if ('error' in r) return fail(r.error);
+ try {
+ const glb = await fs.promises.readFile(path.join(r.dir, 'model.glb'));
+ const map = JSON.parse(await fs.promises.readFile(path.join(r.dir, 'model.map.json'), 'utf8')) as ModelMap;
+ return { rel, key: r.key, glb: glb.buffer.slice(glb.byteOffset, glb.byteOffset + glb.byteLength) as ArrayBuffer, map };
+ } catch (e) { return fail(`The file could not be shown: ${e instanceof Error ? e.message : String(e)}`); }
+ })().finally(() => s.stepJobs.delete(abs));
+ s.stepJobs.set(abs, job);
+ return job;
+ }
+
/** Messdienst vorab starten, sobald der Nutzer den Messmodus einschaltet. */
async measureStart(): Promise<MeasurePrepared> {
return this.need().measure.warm();
diff --git a/app/src/main/workspace.ts b/app/src/main/workspace.ts
index 100b411..9bab866 100644
--- a/app/src/main/workspace.ts
+++ b/app/src/main/workspace.ts
@@ -53,11 +53,22 @@ const stateFile = (id: string) => path.join(projectStateDir(), `${id}.json`);
export const readProjectJson = (id: string) => readJson<ProjectJson>(path.join(projectDir(id), '.soma', 'project.json'));
/** Neues Projekt: UUID-Ordner in den App-Daten (E21), Vorlage kopieren, Zustand doppelt ablegen (E27), Git-Verlauf anlegen (E7). */
-export async function createProject(name = 'New model'): Promise<{ id: string; dir: string }> {
+/**
+ * Legt ein neues Modell aus der Vorlage an. `prepare` läuft vor dem ersten Build und dem Startcommit (etwa der Import eines
+ * CadQuery-Skripts, E100), so beginnt schon der erste Stand mit dem fremden Skript. Wirft `prepare`, wird der halb
+ * angelegte Ordner wieder entfernt und der Fehler weitergereicht.
+ */
+export async function createProject(name = 'New model', prepare?: (dir: string, id: string) => Promise<void>): Promise<{ id: string; dir: string }> {
const id = randomUUID();
const dir = projectDir(id);
fs.mkdirSync(dir, { recursive: true });
fs.cpSync(templateDir(), dir, { recursive: true });
+ if (prepare) {
+ try { await prepare(dir, id); } catch (e) {
+ fs.rmSync(dir, { recursive: true, force: true });
+ throw e;
+ }
+ }
// Skills für neue Modelle (E46) vor dem ersten Build und dem Startcommit: Der erste Stand enthält sie schon
const skills = applyDefaultSkills(dir, skillDirs(), skillBackupsDir(id), getSkillDefaults());
const pj: ProjectJson = { id, name, api_version: API_VERSION, app_version: SOMA_VERSION, entry: 'model.py', main_output: 'output/model.step', created: new Date().toISOString(),
diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.ts
index 9dd3a90..8248174 100644
--- a/app/src/preload/preload.ts
+++ b/app/src/preload/preload.ts
@@ -15,11 +15,15 @@ const api: SomaApi = {
save: (saveAs) => ipcRenderer.invoke('project:save', saveAs),
openZip: () => ipcRenderer.invoke('project:openZip'),
exportZip: () => ipcRenderer.invoke('project:exportZip'),
+ createFromCadQuery: () => ipcRenderer.invoke('project:createFromCadQuery'),
+ onCadQueryStep: (cb) => { ipcRenderer.on('cadquery:step', (_e, s) => cb(s)); },
+ exportCadQuery: () => ipcRenderer.invoke('project:exportCadQuery'),
onSaveState: (cb) => { ipcRenderer.on('save:state', (_e, st) => cb(st)); },
reveal: () => ipcRenderer.invoke('project:reveal'),
setThumb: (dataUrl) => ipcRenderer.invoke('project:setThumb', dataUrl),
thumb: (id) => ipcRenderer.invoke('project:thumb', id),
remove: (id) => ipcRenderer.invoke('project:remove', id),
+ viewFile: (rel) => ipcRenderer.invoke('project:viewFile', rel),
},
versions: {
log: () => ipcRenderer.invoke('versions:log'),
diff --git a/app/src/renderer/fileview.ts b/app/src/renderer/fileview.ts
new file mode 100644
index 0000000..3a41e6c
--- /dev/null
+++ b/app/src/renderer/fileview.ts
@@ -0,0 +1,115 @@
+import type { FileViewResult } from '../shared/types';
+import type { BusyHandle } from './busy';
+
+interface Ui {
+ banner: HTMLElement;
+ title: HTMLElement;
+ sub: HTMLElement;
+ back: HTMLButtonElement;
+ /** Bekommt die Klasse `fileview` (violetter Rahmen wie bei der Vorschau), solange eine Datei zu sehen ist. */
+ viewer: HTMLElement;
+}
+
+interface Hooks {
+ /** `res`: die Datei zeigen. `null`: zurück zum Modell. */
+ show(res: FileViewResult | null): Promise<void>;
+ /** Vor dem Zeigen einer Datei: eine laufende Versionsvorschau beenden, ohne das Modell neu zu laden. */
+ beforeShow(): void;
+ busy(title: string, cancel: () => void): BusyHandle;
+ toast(text: string, kind: 'ok' | 'info' | 'error'): void;
+}
+
+const base = (rel: string) => rel.split('/').pop() ?? rel;
+
+/**
+ * Eine STEP-Datei aus dem Projekt im Viewer (Klick im Dateibaum), schreibgeschützt wie die Vorschau eines alten Stands:
+ * Messen, Schnitt, Explosion und Baum gehen, Klick zum Code, Animation und Analyse nicht. Solange sie offen ist, ersetzt
+ * ein Build des Modells sie nicht. Ändert sich die Datei auf der Platte, wird sie neu geladen (der Hauptprozess wandelt
+ * nur um, wenn sich der Inhalt geändert hat).
+ */
+export class FileView {
+ private cur: { rel: string; key: string; parts: number } | null = null;
+ private seq = 0;
+ private loading = false;
+ /** Während des Ladens kam eine Änderung im Projekt: danach noch einmal nachsehen. */
+ private recheck = false;
+ /** Letzter Fehler beim Neuladen, damit dieselbe Meldung nicht bei jeder Änderung im Projekt wiederkommt. */
+ private reloadError = '';
+
+ constructor(private ui: Ui, private hooks: Hooks) {
+ ui.back.addEventListener('click', () => void this.close());
+ }
+
+ get active(): boolean { return this.cur !== null; }
+ /** Pfad der gezeigten Datei, relativ zum Projekt. */
+ get rel(): string | null { return this.cur?.rel ?? null; }
+ /** Quelle für das Messen. */
+ get source(): { file: string; key: string } | null { return this.cur ? { file: this.cur.rel, key: this.cur.key } : null; }
+ get title(): string | null { return this.cur ? base(this.cur.rel) : null; }
+
+ /** Datei zeigen. `reload`: Die angezeigte Datei hat sich vielleicht geändert, nur bei neuem Inhalt neu laden. */
+ async open(rel: string, reload = false): Promise<void> {
+ const seq = ++this.seq;
+ this.loading = true;
+ // Abbrechen lässt die Umwandlung im Hauptprozess zu Ende laufen (ihr Ergebnis landet im Cache), es wird nur nicht gezeigt
+ const busy = this.hooks.busy(`Loading ${base(rel)}`, () => { if (seq === this.seq) { this.seq++; this.loading = false; } });
+ busy.detail('Reading the STEP file. Large assemblies can take a while.');
+ let res: FileViewResult;
+ try { res = await window.soma.project.viewFile(rel); }
+ catch (e) { res = { rel, key: '', glb: new ArrayBuffer(0), map: { version: 0, parts: [] }, error: e instanceof Error ? e.message : String(e) }; }
+ busy.close();
+ if (seq !== this.seq) return;
+ this.loading = false;
+ if (res.error) {
+ if (!reload) this.hooks.toast(`${base(rel)} cannot be shown: ${res.error}`, 'error');
+ else if (res.error !== this.reloadError) this.hooks.toast(`${base(rel)} changed on disk but cannot be loaded again: ${res.error} The viewer still shows the last loaded state.`, 'error');
+ if (reload) this.reloadError = res.error;
+ } else if (!(this.cur?.rel === rel && this.cur.key === res.key)) { // derselbe Inhalt wird schon gezeigt: nichts zu tun
+ this.reloadError = '';
+ this.hooks.beforeShow();
+ this.cur = { rel, key: res.key, parts: res.map.parts.length };
+ this.render();
+ await this.hooks.show(res);
+ if (reload) this.hooks.toast(`${base(rel)} changed on disk and was loaded again.`, 'info');
+ }
+ if (this.recheck && this.cur) { this.recheck = false; void this.filesChanged(); }
+ }
+
+ /** Dateien im Projekt haben sich geändert: Gilt das auch für die gezeigte, neu laden. */
+ async filesChanged(): Promise<void> {
+ if (!this.cur) return;
+ if (this.loading) { this.recheck = true; return; }
+ await this.open(this.cur.rel, true);
+ }
+
+ /** Zurück zum Modell. */
+ async close(): Promise<void> {
+ if (!this.cur && !this.loading) return;
+ const was = this.cur;
+ this.drop();
+ if (was) await this.hooks.show(null);
+ }
+
+ /** Ohne Neuladen beenden: Projektwechsel oder eine Versionsvorschau übernimmt den Viewer. */
+ drop(): void {
+ this.seq++;
+ this.loading = false;
+ this.recheck = false;
+ this.reloadError = '';
+ this.cur = null;
+ this.render();
+ }
+
+ private render(): void {
+ const c = this.cur;
+ this.ui.banner.hidden = !c;
+ this.ui.viewer.classList.toggle('fileview', !!c);
+ if (!c) return;
+ this.ui.title.textContent = `Viewing ${c.rel}`;
+ this.ui.title.title = c.rel;
+ this.ui.sub.textContent = `STEP file · ${c.parts} part${c.parts === 1 ? '' : 's'} · shown in basic mode, without links to code`;
+ }
+
+ /** Prüfhilfe (nur Tests). */
+ state() { return { rel: this.cur?.rel ?? null, key: this.cur?.key ?? null, parts: this.cur?.parts ?? 0, loading: this.loading }; }
+}
diff --git a/app/src/renderer/index.html b/app/src/renderer/index.html
index 929633f..00a9478 100644
--- a/app/src/renderer/index.html
+++ b/app/src/renderer/index.html
@@ -318,6 +318,18 @@
<button id="btn-restore" class="btn vio" title="Restore this version as a new version">Restore</button>
</div>
+ <!-- STEP-Datei aus dem Projekt im Viewer (fileview.ts), schreibgeschützt wie die Vorschau -->
+ <div id="file-banner" class="float banner" hidden>
+ <span class="bn-ico"><i data-icon="file" data-size="18"></i></span>
+ <div class="bn-text">
+ <div class="bn-line"><b id="fb-title"></b><span class="tag">view only</span></div>
+ <span id="fb-sub" class="c2"></span>
+ <span class="c3">Measure, section and explode work as usual. Builds of your model wait until you go back.</span>
+ </div>
+ <span class="grow"></span>
+ <button id="btn-file-back" class="btn">Back to model</button>
+ </div>
+
<!-- Video (E58, videoview.ts): MP4 aus dem Projekt abspielen, Standbild markieren -->
<div id="videoview" class="videoview" hidden>
<video id="video-el" preload="auto" playsinline></video>
@@ -386,9 +398,21 @@
</aside>
</div>
+ <!-- Ladeanzeige über dem ganzen Fenster, solange ein CadQuery-Skript als neues Modell hereinkommt (E100) -->
+ <div id="app-busy" class="vbusy appbusy" hidden>
+ <div class="float vb-card" role="status" aria-live="polite">
+ <div class="vb-hd"><span class="spin"><i data-icon="spin" data-size="16" data-stroke="2.4"></i></span><b>Loading CadQuery script</b><span class="grow"></span><span id="app-busy-time" class="c3 small"></span></div>
+ <div id="app-busy-step" class="vb-sub"></div>
+ <div id="app-busy-file" class="vb-sub c3"></div>
+ <div class="vb-bar indet"><div></div></div>
+ <div class="vb-sub c3 small appbusy-note">The first build runs the script once. Large models can take a while.</div>
+ </div>
+ </div>
+
<!-- Menüs: fest im Dokument, damit Kurzbefehle und Tests die Einträge auch geschlossen finden -->
<div id="menu-doc" class="menu" role="menu" hidden>
<button id="btn-new" class="mi" role="menuitem"><i data-icon="plus" data-size="15"></i><span>New model</span><span class="k">Ctrl N</span></button>
+ <button id="btn-new-cq" class="mi" role="menuitem" title="A model from an existing CadQuery script (.py). The script stays as it is, the original is kept in inputs/."><i data-icon="f-py" data-size="15"></i><span>New from CadQuery script …</span></button>
<button id="btn-open" class="mi" role="menuitem"><i data-icon="folder" data-size="15"></i><span>Open …</span><span class="k">Ctrl O</span></button>
<div id="recent-wrap"><div class="msep"></div><div class="mh">RECENT</div><div id="recent-list"></div></div>
<div class="msep"></div>
@@ -439,6 +463,7 @@
<div class="msep"></div>
<div class="mh">WHOLE MODEL</div>
<button id="exp-zip" class="mi two" role="menuitem"><i data-icon="f-zip" data-size="15"></i><span class="t"><span>Everything as ZIP …</span><span class="sub">Code, results and history in one ZIP file, for example for someone without SOMA. The .soma file stays as it is.</span></span></button>
+ <button id="exp-cq" class="mi two" role="menuitem"><i data-icon="f-py" data-size="15"></i><span class="t"><span>As CadQuery script …</span><span class="sub">Plain CadQuery for CQ-editor, VS Code and others, with parameters and standard parts. “New from CadQuery script” brings it back.</span></span></button>
</div>
<div id="menu-agents" class="menu" role="menu" hidden>
@@ -513,6 +538,7 @@
<button id="start-new" class="bigcard"><span class="ico acc"><i data-icon="plus" data-size="22" data-stroke="2.2"></i></span><b>New model</b><span class="c2">Template with an example part, plus a terminal in the model folder</span><span class="c3 small">Ctrl N</span></button>
<button id="start-open" class="bigcard"><span class="ico"><i data-icon="folder" data-size="22"></i></span><b>Open …</b><span class="c2">.soma or ZIP file from this or another computer</span><span class="c3 small">Ctrl O</span></button>
</div>
+ <div class="start-alt"><button id="start-new-cq" class="btn sm ghost" title="A model from an existing CadQuery script (.py). The script stays as it is, the original is kept in inputs/."><i data-icon="f-py" data-size="14"></i>New from CadQuery script …</button></div>
<div class="cap">RECENT</div>
<div id="start-recent" class="recent-grid"></div>
</div>
diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.ts
index 8923483..199b780 100644
--- a/app/src/renderer/main.ts
+++ b/app/src/renderer/main.ts
@@ -1,6 +1,6 @@
import { affectsBuild } from '../shared/editable';
import { DEFAULT_SETTINGS, type SettingsPatch, type SettingsResult, type SettingsState } from '../shared/settings';
-import type { AgentInfo, AnimEntry, BuildStatus, DrawingEntry, DrawingList, ExportResult, FileNode, ImportResult, ModelMap, PartMap, PreviewResult, ProjectInfo, ProjectListEntry, ResultEntry, SaveState, UpdateInfo } from '../shared/types';
+import type { AgentInfo, AnimEntry, BuildStatus, CadQueryImportResult, DrawingEntry, DrawingList, ExportResult, FileNode, ImportResult, ModelMap, PartMap, PreviewResult, ProjectInfo, ProjectListEntry, ResultEntry, SaveState, UpdateInfo } from '../shared/types';
import { AnalysisPanel } from './analysispanel';
import { AnimPanel, animKey, videoKey } from './animpanel';
import { SOMA_VERSION } from '../shared/version';
@@ -10,6 +10,7 @@ import { DrawingLink } from './drawlink';
import { AnimTool } from './animtool';
import { Busy } from './busy';
import { DRAG_FILE, FileTree, IMAGE_EXT, TEXT_EXT, VIDEO_EXT } from './filetree';
+import { FileView } from './fileview';
import { hydrateIcons, icon } from './icons';
import { Markup } from './markup';
import { MAX_QUOTE } from './pdfview';
@@ -303,7 +304,8 @@ const files = new FileTree($('tab-files'), $('menu-ctx'), {
// Bilder (etwa Markierungen und Skizzen) öffnen auf der Zeichenfläche (E52), das Bildprogramm gibt es per Rechtsklick
else if (IMAGE_EXT.test(n.name)) void markImage(n.path);
else if (VIDEO_EXT.test(n.name)) void videoView.open(n.path);
- else if (/\.(step|stp)$/i.test(n.name)) toast('Viewing other STEP files in the viewer is coming in a later version. The agent can already use them in the script.', 'info');
+ // STEP-Dateien des Projekts im Viewer, schreibgeschützt wie die Vorschau eines alten Stands
+ else if (/\.(step|stp)$/i.test(n.name)) void fileView.open(n.path);
else toast('The app has no view for this file type. Right-click: “Open with default app”.', 'info');
},
create: async (parent, name, dir) => {
@@ -452,6 +454,13 @@ function fitDock(): void {
dock.classList.toggle('compact', dock.scrollWidth > room);
}
new ResizeObserver(() => fitDock()).observe($('viewer'));
+// Höhe des sichtbaren Banners (Vorschau, Dateiansicht): Die Karten unten links rücken darüber, sonst verdeckt es sie
+const bannerObserver = new ResizeObserver(() => {
+ const h = Math.max($('preview-banner').offsetHeight, $('file-banner').offsetHeight);
+ if (h) $('viewer').style.setProperty('--bn-h', `${h}px`);
+});
+bannerObserver.observe($('preview-banner'));
+bannerObserver.observe($('file-banner'));
const partEntry = (id: string): PartMap | undefined => map?.parts.find((x) => x.id === id);
const partInfo = (id: string) => viewer.partList().find((x) => x.id === id);
const lineRange = (e: PartMap) => ({ from: e.line!, to: e.end_line && e.end_line >= e.line! ? e.end_line : e.line! });
@@ -537,13 +546,15 @@ async function renderSelection(): Promise<void> {
/** Text für die Eingabe des Agenten. Zahlen mit Punkt, damit sie eindeutig bleiben. */
function selectionText(): string | null {
if (!selection) return null;
+ // In der Dateiansicht gehören die Teile zur STEP-Datei, nicht zum Modell: Das muss der Agent wissen
+ const inFile = fileView.rel ? ` in the STEP file ${fileView.rel}` : '';
if (picked.length > 1) {
const names = picked.map((id) => `"${partName(id)}"`);
- return `[Selection: ${picked.length} parts: ${names.slice(0, 40).join(', ')}${names.length > 40 ? ` and ${names.length - 40} more` : ''}] `;
+ return `[Selection: ${picked.length} parts${inFile}: ${names.slice(0, 40).join(', ')}${names.length > 40 ? ` and ${names.length - 40} more` : ''}] `;
}
const e = partEntry(selection.partId);
const group = partInfo(selection.partId)?.group;
- const bits = [`part "${e?.name ?? partInfo(selection.partId)?.name ?? selection.partId}"${group ? ` in group "${group}"` : ''}`];
+ const bits = [`part "${e?.name ?? partInfo(selection.partId)?.name ?? selection.partId}"${group ? ` in group "${group}"` : ''}${inFile}`];
if (e?.file && e.line) { const { from, to } = lineRange(e); bits.push(`${e.file} ${to !== from ? 'lines' : 'line'} ${from}${to !== from ? '-' + to : ''}`); }
const pk = selection.pick;
if (pk?.faceId != null) {
@@ -577,9 +588,9 @@ const measureTool = new MeasureTool({
again: $<HTMLButtonElement>('btn-measure-again'), agent: $<HTMLButtonElement>('btn-measure-agent'), viewerEl: $('viewer'),
}, {
viewer,
- source: () => (versions.previewed ? { preview: versions.previewed.hash } : 'live'),
+ source: () => fileView.source ?? (versions.previewed ? { preview: versions.previewed.hash } : 'live'),
build: () => map?.build ?? null,
- reload: () => void loadModel(),
+ reload: () => void (fileView.active ? fileView.filesChanged() : loadModel()),
part: (id) => partEntry(id),
insert: (t) => insertToAgent(t),
});
@@ -746,7 +757,7 @@ async function sendMarkup(): Promise<void> {
const r = await api.fs.saveFeedback(await markup.image());
// Ging das Speichern schief, bleibt die Zeichnung offen: Nichts geht verloren, der Nutzer kann es noch einmal versuchen
if (!r.ok || !r.path) { toast(`The markup could not be saved: ${r.error ?? 'unknown error'}`, 'error'); return; }
- const old = versions.previewed, source = markup.source;
+ const old = versions.previewed, source = markup.source, shownFile = fileView.rel;
markup.close();
void refreshFiles(); // die neue Markierung steht gleich im Dateibaum
// Zeigt das Bild einen alten Stand, einen Schnitt oder eine Explosion, soll der Agent das wissen (sonst vergleicht er es mit dem
@@ -754,7 +765,8 @@ async function sendMarkup(): Promise<void> {
// Auf einem Bild aus dem Projekt gezeichnet: Der Agent soll das Original kennen, Stand und Schnitt spielen dann keine Rolle
const cut = [sectionTool.agentText(), explodeTool.agentText(), animTool.agentText(), resultTool.agentText()].filter(Boolean).join(', ');
const note = source ? `, drawn on ${source}`
- : (old ? `, shows the older version ${old.short} "${old.subject.slice(0, 80)}"` : '') + (cut ? `, ${cut}` : '');
+ : (old ? `, shows the older version ${old.short} "${old.subject.slice(0, 80)}"` : '')
+ + (shownFile ? `, shows the STEP file ${shownFile}, not the model` : '') + (cut ? `, ${cut}` : '');
insertToAgent(`[Markup: ${r.path}${note}] `, `Markup saved: ${r.path}`);
} catch (e) {
toast(`The markup could not be saved: ${e instanceof Error ? e.message : String(e)}`, 'error');
@@ -990,7 +1002,7 @@ function renderBuild(s: BuildStatus): void {
async function renderErrorCard(): Promise<void> {
const s = buildStatus;
- const e = s.state === 'error' && !versions.previewing ? s.result?.error : undefined;
+ const e = s.state === 'error' && !showsOther() ? s.result?.error : undefined;
const hasModel = viewer.partList().length > 0;
$('viewer').classList.toggle('dim', !!e && hasModel);
$('lastgood').hidden = !(e && hasModel && lastOkAt);
@@ -1015,8 +1027,11 @@ async function renderErrorCard(): Promise<void> {
}
}
+/** Der Viewer zeigt gerade nicht das Modell, sondern einen alten Stand oder eine STEP-Datei: Builds warten. */
+const showsOther = () => versions.previewing || fileView.active;
+
async function loadModel(): Promise<void> {
- if (versions.previewing) return; // während einer Vorschau bleibt der alte Stand stehen
+ if (showsOther()) return; // während einer Vorschau oder Dateiansicht bleibt deren Bild stehen
const seq = ++loadSeq;
const msg = $('viewer-msg');
try {
@@ -1049,7 +1064,7 @@ let thumbTimer: ReturnType<typeof setTimeout> | undefined;
function scheduleThumb(): void {
clearTimeout(thumbTimer);
thumbTimer = setTimeout(() => {
- if (versions.previewing) return;
+ if (showsOther()) return;
const url = viewer.thumbnail();
if (url) void api.project.setThumb(url).catch(() => { /* Vorschaubild ist verzichtbar */ });
}, 1500);
@@ -1065,25 +1080,49 @@ const versions = new VersionsBar({
// der Stand erst Pakete (E67), kommt der Build nach der Installation.
if (!res && restored && (buildStatus.state === 'building' || buildStatus.installing)) return;
if (!res) { await loadModel(); return; }
- animTool.setActive(false);
- resultTool.setActive(false);
- try {
- map = res.map;
- textCache.clear();
- await viewer.load(res.glb);
- measureTool.reset();
- explodeTool.refresh();
- sectionTool.refresh();
- refreshTree();
- selectPart(null, null);
- void renderErrorCard();
- } catch (e) { toast(`The preview cannot be shown: ${e instanceof Error ? e.message : String(e)}`, 'error'); }
- renderResults();
+ // Eine offene STEP-Datei macht der Vorschau Platz, ohne dazwischen das Modell zu laden
+ if (fileView.active) { fileView.drop(); tree.setTitle(project?.name ?? ''); }
+ await showForeign(res.glb, res.map, 'The preview');
},
toast,
beforeRestore: () => leaveEditor('Restore version'), // Wiederherstellen ersetzt Dateien
});
+/**
+ * Zeigt einen fremden Stand (Vorschau eines alten Stands oder STEP-Datei) im Viewer. Animation und Analyse gehören zum
+ * Modell und gehen aus, Messen, Explosion und Schnitt fangen auf dem neuen Bild von vorn an.
+ */
+async function showForeign(glb: ArrayBuffer, m: ModelMap, what: string): Promise<void> {
+ loadSeq++; // ein noch laufendes Laden des Modells soll das Bild nicht überschreiben
+ animTool.setActive(false);
+ resultTool.setActive(false);
+ try {
+ map = m;
+ textCache.clear();
+ await viewer.load(glb);
+ measureTool.reset();
+ explodeTool.refresh();
+ sectionTool.refresh();
+ refreshTree();
+ selectPart(null, null);
+ void renderErrorCard();
+ } catch (e) { toast(`${what} cannot be shown: ${e instanceof Error ? e.message : String(e)}`, 'error'); }
+ renderResults();
+}
+
+const fileView = new FileView({
+ banner: $('file-banner'), title: $('fb-title'), sub: $('fb-sub'), back: $<HTMLButtonElement>('btn-file-back'), viewer: $('viewer'),
+}, {
+ async show(res) {
+ if (!res) { tree.setTitle(project?.name ?? ''); await loadModel(); return; }
+ tree.setTitle(fileView.title ?? '');
+ await showForeign(res.glb, res.map, 'The file');
+ },
+ beforeShow: () => versions.endPreview(),
+ busy: (title, cancel) => busy.show(title, cancel),
+ toast,
+});
+
// ---- Projekt ----------------------------------------------------------------------------------------------------
async function onProject(p: ProjectInfo): Promise<void> {
@@ -1103,6 +1142,7 @@ async function onProject(p: ProjectInfo): Promise<void> {
videoView.close();
viewer.clear();
versions.reset();
+ fileView.drop();
tree.setTitle(p.name);
terminals.closeAll();
code.reset();
@@ -1219,7 +1259,7 @@ async function doSave(saveAs = false): Promise<void> {
toast(lines.join('\n'), r.warnings?.length ? 'error' : 'ok');
project = await api.project.current(); // der Modellname folgt dem Dateinamen
$('doc-name').textContent = project.name;
- tree.setTitle(project.name);
+ tree.setTitle(fileView.title ?? project.name);
void refreshSaveState();
} finally {
saving = false;
@@ -1237,6 +1277,36 @@ async function doOpen(): Promise<boolean> {
}
const doNew = async () => { if (await leaveEditor('New model')) await api.project.create(); };
+// Ladeanzeige für den Import: erscheint mit dem ersten Schritt nach dem Dateidialog, zählt die Sekunden mit
+let cqBusyTick: ReturnType<typeof setInterval> | undefined;
+api.project.onCadQueryStep(({ step, file }) => {
+ const root = $('app-busy');
+ if (root.hidden) {
+ const t0 = performance.now();
+ $('app-busy-time').textContent = '';
+ clearInterval(cqBusyTick);
+ cqBusyTick = setInterval(() => { $('app-busy-time').textContent = `${Math.round((performance.now() - t0) / 1000)} s`; }, 1000);
+ root.hidden = false;
+ }
+ $('app-busy-step').textContent = `${step} …`;
+ $('app-busy-file').textContent = file;
+});
+function closeCadQueryBusy(): void {
+ clearInterval(cqBusyTick);
+ $('app-busy').hidden = true;
+}
+
+/** Neues Modell aus einem CadQuery-Skript (E100). Die Hinweise des Imports (Kompatibilitätsmodus, Werte) zeigt ein Toast. */
+async function doNewFromCadQuery(): Promise<CadQueryImportResult | null> {
+ if (!(await leaveEditor('New model'))) return null;
+ let r: CadQueryImportResult;
+ try { r = await api.project.createFromCadQuery(); } finally { closeCadQueryBusy(); }
+ if (r.cancelled) return r;
+ if (r.error) { toast(r.error, 'error'); return r; }
+ showStart(false);
+ toast(['Model created from the CadQuery script. The original is kept in inputs/.', ...r.warnings].join('\n'), 'info');
+ return r;
+}
/** „Jetzt bauen“: baut immer. Vorher werden die Eingaben im Editor gespeichert, sonst sähe der Build sie nicht. */
async function doBuild(): Promise<void> {
const r = await code.saveAll();
@@ -1283,6 +1353,7 @@ async function renderRecent(): Promise<void> {
$('btn-doc').addEventListener('click', () => { void renderRecent().then(() => menus.toggle($('menu-doc'), $('btn-doc'))); });
$('btn-new').addEventListener('click', () => void doNew());
+$('btn-new-cq').addEventListener('click', () => { menus.close(); void doNewFromCadQuery(); });
$('btn-open').addEventListener('click', () => void doOpen());
$('btn-save').addEventListener('click', () => void doSave(false));
$('btn-save-menu').addEventListener('click', () => void doSave(false));
@@ -1362,6 +1433,19 @@ $('exp-all').addEventListener('click', () => { exportScope = 'all'; renderExport
$('exp-sel').addEventListener('click', () => { exportScope = 'sel'; renderExportScope(); });
document.querySelectorAll<HTMLButtonElement>('#menu-export [data-fmt]').forEach((b) => b.addEventListener('click', () => void doExport(b.dataset.fmt!, b.textContent!)));
$('exp-zip').addEventListener('click', () => { menus.close(); void doExportZip(); });
+$('exp-cq').addEventListener('click', () => { menus.close(); void doExportCadQuery(); });
+
+/** Das Modell als reines CadQuery (E100). Wie beim ZIP fehlen Eingaben, die im Editor noch nicht gespeichert sind. */
+async function doExportCadQuery(): Promise<ExportResult> {
+ const r = await api.project.exportCadQuery();
+ if (r.cancelled) return r;
+ const open = code.unsaved();
+ if (r.ok) {
+ const notes = [...(r.warnings ?? []), ...(open.length ? [`Not included (not saved in the editor): ${open.join(', ')}`] : [])];
+ toast([`Model exported as CadQuery:\n${r.target ?? ''}`, ...notes].join('\n'), open.length ? 'error' : 'ok');
+ } else toast(r.error ?? 'Export failed', 'error');
+ return r;
+}
/**
* Das ganze Modell als ZIP (E79). Eingaben im Editor, die noch nicht gespeichert sind, fehlen darin wie in jedem Export:
@@ -1602,6 +1686,7 @@ async function showStart(on: boolean): Promise<void> {
$('btn-start-close').addEventListener('click', () => showStart(false));
$('start-new').addEventListener('click', () => { void doNew(); showStart(false); });
$('start-open').addEventListener('click', () => { void doOpen().then((ok) => { if (ok) showStart(false); }); });
+$('start-new-cq').addEventListener('click', () => void doNewFromCadQuery());
/**
* Karte „Updates“: neueste Version unter GitHub Releases (updates.ts, einmal je Sitzung). Der Knopf öffnet die Seite im
* Browser, laden und installieren tut der Nutzer selbst. Ausgeschaltet (Settings › About) oder im Test ohne Adresse: keine Karte.
@@ -1650,7 +1735,7 @@ api.build.onStatus((s) => {
if (panel === 'params' && s.state !== 'building') void paramsPanel.refresh();
});
// Auch bei geschlossenem Code abgleichen: Offene Dateien können ungesicherte Eingaben enthalten
-api.fs.onChanged(() => { textCache.clear(); void refreshFiles(); void code.refresh(); scheduleViewLists(); if (panel === 'params') void paramsPanel.refresh(); });
+api.fs.onChanged(() => { textCache.clear(); void fileView.filesChanged(); void refreshFiles(); void code.refresh(); scheduleViewLists(); if (panel === 'params') void paramsPanel.refresh(); });
// Beim Beenden fragt der Hauptprozess, was im Editor ungespeichert ist, und lässt speichern oder verwerfen
api.fs.onEditorRequest(async (action) => {
if (action === 'status') return { dirty: code.unsaved() };
@@ -1783,6 +1868,8 @@ if (api.testMode) {
saveState: () => saveState,
toast: () => ({ text: $('toast').textContent, hidden: $('toast').hidden, error: $('toast').classList.contains('error') }),
banner: () => ({ hidden: $('preview-banner').hidden, text: $('preview-banner').textContent }),
+ fileView: () => ({ ...fileView.state(), banner: $('file-banner').hidden ? null : $('file-banner').textContent, frame: $('viewer').classList.contains('fileview') }),
+ openFile: (rel: string) => fileView.open(rel),
partSize: (name: string) => { const p = viewer.partList().find((x) => x.name === name); return p ? viewer.partSize(p.id) : null; },
versionsUi: () => ({ restoreHidden: $('btn-restore').hidden, problem: $('vproblem').hidden ? '' : $('vproblem').textContent }),
selectionText, errorText,
@@ -1847,6 +1934,10 @@ if (api.testMode) {
exportAs: (fmt: string, scope: 'all' | 'sel') => { exportScope = scope; return doExport(fmt, fmt.toUpperCase()); },
/** „Everything as ZIP“ im Export-Menü (E79). */
exportZip: () => doExportZip(),
+ /** „As CadQuery script“ im Export-Menü und „New from CadQuery script“ (E100). */
+ exportCadQuery: () => doExportCadQuery(),
+ newFromCadQuery: () => doNewFromCadQuery(),
+ cqBusy: () => ({ hidden: $('app-busy').hidden, text: $('app-busy').textContent }),
showStart: (on: boolean) => showStart(on),
tour: () => tour.state(),
tourGo: (n: number) => tour.goTo(n),
diff --git a/app/src/renderer/style.css b/app/src/renderer/style.css
index b4b0d68..fd71ef8 100644
--- a/app/src/renderer/style.css
+++ b/app/src/renderer/style.css
@@ -440,7 +440,7 @@ code { font-family:var(--mono); font-size:.95em; }
background:radial-gradient(ellipse at 52% 44%, #272c34 0%, #1b1e23 60%, #16181c 100%); }
#viewer > canvas { position:absolute; inset:0; width:100%; height:100%; display:block; transition:opacity .2s; }
#viewer.dim > canvas { opacity:.35; filter:grayscale(.5); }
-#viewer.preview::after { content:''; position:absolute; inset:0; border:2px solid var(--vio); pointer-events:none; z-index:6; }
+#viewer.preview::after, #viewer.fileview::after { content:''; position:absolute; inset:0; border:2px solid var(--vio); pointer-events:none; z-index:6; }
#viewer-msg { position:absolute; left:50%; top:50%; transform:translate(-50%,-50%); color:var(--tx2); pointer-events:none; white-space:pre-wrap; text-align:center; z-index:1; max-width:70%; }
#viewer-msg.error { color:var(--err); }
/* Ladeanzeige (busy.ts): deckt den Viewer ab, bis die Explosion bereit ist. Unter Banner und Markierung */
@@ -451,6 +451,9 @@ code { font-family:var(--mono); font-size:.95em; }
.vb-sub { padding:0 14px; min-height:18px; font-size:12px; color:var(--tx2); overflow-wrap:anywhere; }
.vb-bar { position:relative; height:4px; margin:10px 14px 0; border-radius:2px; background:var(--s3); overflow:hidden; }
.vb-bar > div { height:100%; width:0; background:var(--acc); transition:width .15s; }
+/* Über Startseite und Menüs (40), unter den Meldungen (60): ein CadQuery-Skript kommt herein */
+.appbusy { position:fixed; z-index:50; background:rgba(8,9,11,.6); }
+.appbusy .appbusy-note { padding-top:10px; padding-bottom:12px; }
.vb-bar.indet > div { width:35%; position:absolute; animation:vb-run 1.2s ease-in-out infinite; transition:none; }
@keyframes vb-run { from { left:-35%; } to { left:100%; } }
.float { position:absolute; z-index:2; background:rgba(24,27,31,.95); border:1px solid var(--line2); border-radius:10px; box-shadow:var(--shadow); }
@@ -639,7 +642,8 @@ code { font-family:var(--mono); font-size:.95em; }
.bn-text b { font-size:14px; }
.bn-line { display:flex; align-items:center; gap:8px; }
.bn-text .tag { font-size:11px; padding:1px 7px; border-radius:9px; background:var(--vio-tint); color:#cdd2ff; }
-#bn-sub { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
+#bn-sub, #fb-sub, #fb-title { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
+.bn-line { min-width:0; }
/* ---- Animation, Analyse und Video (E58) ----------------------------------------------------------------------- */
.v-paint { pointer-events:none; }
@@ -707,6 +711,8 @@ code { font-family:var(--mono); font-size:.95em; }
@container viewer (max-width: 760px) { .tbar .tgl { padding:0 8px; font-size:0; gap:0; } .tbar .tgl svg.ic { margin:0; } }
/* Unten liegen die Leisten der Analyse und Animation: Karten (Messen, Schnitt, Auswahl) rücken darüber */
#viewer.analyzing .cards, #viewer.animating .cards { bottom:66px; }
+/* Vorschau und Dateiansicht: Die Karten (Messen, Schnitt, Explosion) stehen über dem Banner, --bn-h setzt main.ts */
+#viewer.preview .cards, #viewer.fileview .cards { bottom:calc(var(--bn-h, 108px) + 24px); }
/* ---- Reiter Analysis und Animation (E82): Liste und ruhiger Bericht ------------------------------------------ */
.cx { font-variant-numeric:tabular-nums; }
@@ -961,6 +967,10 @@ code { font-family:var(--mono); font-size:.95em; }
.bigcard b { font-size:16px; }
.bigcard .ico { width:40px; height:40px; border-radius:10px; display:flex; align-items:center; justify-content:center; margin-bottom:8px; background:var(--s3); }
.bigcard .ico.acc { background:var(--acc); color:#1b1206; }
+/* Weitere Wege zu einem neuen Modell, klein unter den Karten (E100) */
+.start-alt { display:flex; gap:6px; margin-top:8px; }
+.start-alt .btn { color:var(--tx3); padding:0 6px; }
+.start-alt .btn:hover { color:var(--tx); }
.cap { font-size:11px; letter-spacing:.06em; color:var(--tx3); margin:34px 0 12px; }
.recent-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(170px, 1fr)); gap:14px; }
.recent-item { position:relative; display:flex; min-width:0; }
diff --git a/app/src/renderer/versions.ts b/app/src/renderer/versions.ts
index f534d3f..37a8d0e 100644
--- a/app/src/renderer/versions.ts
+++ b/app/src/renderer/versions.ts
@@ -78,6 +78,14 @@ export class VersionsBar {
else this.render();
}
+ /** Vorschau beenden, ohne den Arbeitsstand zu laden: Etwas anderes (eine STEP-Datei) übernimmt den Viewer. */
+ endPreview(): void {
+ this.seq++;
+ if (!this.previewHash) return;
+ this.previewHash = null;
+ this.render();
+ }
+
/** Zurück zum Arbeitsstand, falls gerade eine Vorschau läuft. */
async leavePreview(): Promise<void> { if (this.previewHash) await this.select(this.log.commits.length); }
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index ddcb2cd..d604df6 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -69,6 +69,8 @@ export interface BuildStatus {
* Ordner. `cancelled`: Dialog oder Rückfrage abgebrochen, nichts geschrieben.
*/
export interface ExportResult { ok: boolean; files: string[]; target?: string; cancelled?: boolean; error?: string; warnings?: string[] }
+/** Neues Modell aus einem CadQuery-Skript (E100). `info`: das geöffnete Modell, `warnings`: Hinweise des Imports. */
+export interface CadQueryImportResult { info?: ProjectInfo; warnings: string[]; cancelled?: boolean; error?: string }
/** Dateien, die per Ziehen nach inputs/ kopiert wurden (E33). */
export interface ImportResult { files: string[]; errors: string[] }
/**
@@ -267,8 +269,11 @@ export interface AboutInfo {
components: ComponentInfo[];
}
-/** Was vermessen wird: der aktuelle Stand oder die Vorschau eines alten Stands. */
-export type MeasureSource = 'live' | { preview: string };
+/**
+ * Was vermessen wird: der aktuelle Stand, die Vorschau eines alten Stands oder eine STEP-Datei aus dem Projekt (`key`: die
+ * Kennung ihres Inhalts aus `project.viewFile`, damit eine inzwischen geänderte Datei nicht still anders vermessen wird).
+ */
+export type MeasureSource = 'live' | { preview: string } | { file: string; key: string };
/** Stand der Speicherung: was ist gesichert, was nicht (E21). */
export interface SaveState {
@@ -290,6 +295,8 @@ export interface OpenResult { cancelled: boolean; opened?: boolean; error?: stri
export interface CommitInfo { hash: string; short: string; author: string; date: string; subject: string; byApp: boolean }
export interface GitLog { commits: CommitInfo[]; problems: string[]; head: string | null; dirtyFiles: number }
export interface PreviewResult { commit: CommitInfo | null; glb: ArrayBuffer; map: ModelMap; error?: string }
+/** STEP-Datei aus dem Projekt im Viewer (`project.viewFile`). `key`: SHA-1 des Inhalts, unter dem die Umwandlung im Cache liegt. */
+export interface FileViewResult { rel: string; key: string; glb: ArrayBuffer; map: ModelMap; error?: string }
export interface RestoreResult { cancelled: boolean; commit?: string | null; safety?: string | null; error?: string }
/** Animation aus animations/*.py (E58), gebaut nach `glb`. `stale`: Code oder Animationsdatei sind neuer. */
@@ -428,6 +435,12 @@ export interface SomaApi {
openZip(): Promise<OpenResult>;
/** Das ganze Modell als ZIP exportieren (E79), ohne Snapshot. Die Modelldatei bleibt, wie sie ist. */
exportZip(): Promise<ExportResult>;
+ /** Neues Modell aus einem CadQuery-Skript (E100): Dateidialog, Import, erster Build. */
+ createFromCadQuery(): Promise<CadQueryImportResult>;
+ /** Schritte von createFromCadQuery nach dem Dateidialog, für die Ladeanzeige: `step` ist der laufende Schritt. */
+ onCadQueryStep(cb: (s: { step: string; file: string }) => void): void;
+ /** Das Modell als reines CadQuery-Skript (E100): eine .py, mit parts/ ein Ordner. */
+ exportCadQuery(): Promise<ExportResult>;
onSaveState(cb: (s: SaveState) => void): void;
/** Zeigt die Modelldatei im Dateimanager (noch nicht gespeichert: den Arbeitsordner). */
reveal(): Promise<void>;
@@ -436,6 +449,11 @@ export interface SomaApi {
thumb(id: string): Promise<string | null>;
/** Arbeitsordner eines Modells in den Papierkorb, nach Rückfrage. Nicht das gerade geöffnete. */
remove(id: string): Promise<RemoveResult>;
+ /**
+ * Eine STEP-Datei des Projekts (.step, .stp) für den Viewer umwandeln, im Basismodus wie die Vorschau alter Stände.
+ * Unveränderte Dateien kommen aus dem Cache. Fehler stehen in `error`.
+ */
+ viewFile(rel: string): Promise<FileViewResult>;
};
versions: {
log(): Promise<GitLog>;
diff --git a/app/test/cadquery.mjs b/app/test/cadquery.mjs
new file mode 100644
index 0000000..09f7503
--- /dev/null
+++ b/app/test/cadquery.mjs
@@ -0,0 +1,248 @@
+// Test für CadQuery rein und raus (E100). Ohne App: Kompatibilitätsmodus von `soma build` (show_object aus CQ-editor,
+// ocp_vscode, result), „Export as CadQuery“ als eine Datei und als Ordner, das exportierte Skript läuft ohne soma (mit
+// show_object wie in CQ-editor), der Import dreht den Export Zeichen für Zeichen zurück, ein veränderter Block bleibt
+// stehen, nicht exportierbare Imports werden mit Zeile gemeldet. Dann in der echten App: „New from CadQuery script“ und
+// „As CadQuery script“ im Export-Menü. Aufruf: npm run test:cadquery (baut vorher). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1
+// legt ein Bild der Ladeanzeige in test/shots/ ab.
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';
+
+const t = checker();
+const { check } = t;
+let app;
+
+const PY = process.env.SOMA_PYTHON || path.join(process.env.LOCALAPPDATA ?? '', 'soma-dev', 'venv', 'Scripts', 'python.exe');
+const ENV = { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' };
+const soma = (args, cwd) => spawnSync(PY, ['-m', 'soma', ...args], { cwd, encoding: 'utf8', env: ENV, windowsHide: true });
+const work = fs.mkdtempSync(path.join(os.tmpdir(), 'soma-cq-'));
+const write = (rel, text) => { fs.mkdirSync(path.dirname(path.join(work, rel)), { recursive: true }); fs.writeFileSync(path.join(work, rel), text); };
+const read = (rel) => fs.readFileSync(path.join(work, rel), 'utf8');
+const mapOf = (dir) => JSON.parse(fs.readFileSync(path.join(dir, '.soma', 'model.map.json'), 'utf8'));
+const buildOf = (dir) => JSON.parse(fs.readFileSync(path.join(dir, '.soma', 'build.json'), 'utf8'));
+
+// Läuft ein exportiertes Skript wie CQ-editor: show_object vorgegeben, soma gesperrt. Gibt die gezeigten Teile als JSON aus
+const RUNNER = String.raw`
+import json, runpy, sys
+sys.modules["soma"] = None
+shown = []
+def show_object(o, name=None, options=None):
+ bb = o.BoundingBox()
+ shown.append(dict(name=name, x=round(bb.xlen, 3), color=[round(c, 3) for c in options["color"]], alpha=options["alpha"]))
+ns = runpy.run_path(sys.argv[1], init_globals={"show_object": show_object})
+print(json.dumps(dict(shown=shown, result=type(ns.get("result")).__name__)))
+`;
+const runExported = (file) => {
+ const r = spawnSync(PY, ['-c', RUNNER, file], { cwd: path.dirname(file), encoding: 'utf8', env: ENV, windowsHide: true });
+ try { return JSON.parse(r.stdout.trim().split('\n').pop()); } catch { return { error: (r.stderr || r.stdout).slice(-400) }; }
+};
+
+const SOMA_MODEL = `"""Platte mit Schraube."""
+import cadquery as cq
+from soma import add_part, param # API
+from soma.fasteners import (
+ Screw,
+ Nut as N,
+)
+
+L = param(60.0, "Length", min=30, max=200, unit="mm")
+plate = cq.Workplane().box(L, 20, 4)
+s = Screw("ISO 4762", "M3x10", at=(0, 0, 2))
+add_part("Plate", plate.cut(s.clearance_hole()), color=(0.2, 0.4, 0.8), group="Base")
+add_part("Screw", s, group="Base/Hardware")
+add_part("Nut", N("ISO 4032", "M3", at=(10, 0, -2)))
+`;
+
+try {
+ // 1) Kompatibilitätsmodus: drei Arten fremder Skripte
+ write('cqe/model.py', `import cadquery as cq
+box = cq.Workplane().box(10, 10, 10)
+cyl = cq.Workplane().cylinder(20, 3)
+show_object(box, name="Box", options={"color": (255, 0, 0), "alpha": 0.5})
+show_object(cyl, options={"color": "steelblue"})
+debug(cyl)
+`);
+ write('ocp/model.py', `import cadquery as cq
+from ocp_vscode import show, set_port, Camera
+set_port(3939)
+plate = cq.Workplane().box(30, 20, 2)
+show(plate, cq.Workplane().sphere(4), names=["Plate"], colors=["#00ff00"], reset_camera=Camera.RESET)
+`);
+ write('res/model.py', 'import cadquery as cq\nresult = cq.Workplane().box(5, 5, 5)\n');
+ write('none/model.py', 'import cadquery as cq\nx = 1\n');
+ write('mixed/model.py', 'import cadquery as cq\nfrom soma import add_part\nadd_part("A", cq.Workplane().box(1, 1, 1))\nshow_object(cq.Workplane().box(2, 2, 2), name="B")\n');
+ // Wie viele Skripte für CQ-editor: fragen globals() ab und exportieren sonst selbst, die Teile stecken in einer Baugruppe
+ write('glob/model.py', `from pathlib import Path
+import cadquery as cq
+blade = cq.Workplane().box(50, 10, 1)
+handle = cq.Workplane().box(10, 10, 20).translate((-30, 0, 0))
+saw = (cq.Assembly(name="saw").add(blade, name="blade", color=cq.Color(0.75, 0.77, 0.80))
+ .add(handle, name="handle", color=cq.Color(0.55, 0.33, 0.15)))
+result = blade.union(handle)
+if "show_object" in globals():
+ show_object(saw, name="saw")
+elif __name__ == "__main__":
+ saw.export(str(Path(__file__).with_name("saw.step")))
+`);
+ for (const d of ['cqe', 'ocp', 'res', 'none', 'mixed', 'glob']) soma(['build', '--project', path.join(work, d)], path.join(work, d));
+ const m1 = mapOf(path.join(work, 'cqe')), b1 = buildOf(path.join(work, 'cqe'));
+ check('CQ-editor: show_object mit Name, sonst Variablenname, Zeile des Aufrufs, debug() fällt weg',
+ b1.status === 'ok' && JSON.stringify(m1.parts.map((p) => [p.name, p.line])) === '[["Box",4],["cyl",5]]', JSON.stringify(m1.parts.map((p) => [p.name, p.line])));
+ check('Warnung „Compatibility mode“ mit Verweis auf den Skill', b1.warnings.some((w) => w.startsWith('Compatibility mode') && w.includes('cadquery-scripts.md')), b1.warnings.join(' | '));
+ const m2 = mapOf(path.join(work, 'ocp'));
+ check('ocp_vscode: show() mit names, ohne Namen „Part 2“, set_port und Camera ohne Wirkung',
+ buildOf(path.join(work, 'ocp')).status === 'ok' && JSON.stringify(m2.parts.map((p) => p.name)) === '["Plate","Part 2"]', JSON.stringify(m2.parts.map((p) => p.name)));
+ check('Nur result: ein Teil „result“', buildOf(path.join(work, 'res')).status === 'ok' && mapOf(path.join(work, 'res')).parts.map((p) => p.name).join() === 'result');
+ const m6 = mapOf(path.join(work, 'glob'));
+ check('`if "show_object" in globals()`: Baugruppe als Teile mit Gruppe, kein eigener Export des Skripts, nicht result',
+ JSON.stringify(m6.parts.map((p) => [p.name, p.group])) === '[["blade","saw"],["handle","saw"]]' && !fs.existsSync(path.join(work, 'glob', 'saw.step')),
+ JSON.stringify(m6.parts.map((p) => [p.name, p.group])));
+ const b4 = buildOf(path.join(work, 'none'));
+ check('Ohne alles: Fehler NoParts mit Hinweis auf show_object und result', b4.status === 'error' && b4.error.kind === 'NoParts' && b4.error.message.includes('show_object'), b4.error?.message);
+ const b5 = buildOf(path.join(work, 'mixed'));
+ check('add_part und show_object gemischt: nur add_part zählt, keine Warnung', b5.status === 'ok' && mapOf(path.join(work, 'mixed')).parts.map((p) => p.name).join() === 'A'
+ && !b5.warnings.some((w) => w.startsWith('Compatibility')), JSON.stringify(b5.warnings));
+
+ // 2) Export als eine Datei, Lauf ohne soma, Rückweg
+ write('src/model.py', SOMA_MODEL);
+ write('src/parameters.json', JSON.stringify({ note: 'x', values: { L: 80 } }, null, 2));
+ write('src/inputs/board.step', 'ISO-10303-21;\n');
+ const ex = soma(['cadquery', 'export', '--out', path.join(work, 'out', 'plate.py'), '--project', path.join(work, 'src'), '--json'], work);
+ const exr = JSON.parse(ex.stdout.trim().split('\n').pop() || '{}');
+ const txt = fs.existsSync(path.join(work, 'out', 'plate.py')) ? read('out/plate.py') : '';
+ check('Export: eine Datei, Originalimporte als # soma-import, Block mit Prüfsumme, Fußblock, Werte des Panels',
+ exr.status === 'ok' && exr.mode === 'single' && txt.includes('# soma-import: from soma import add_part, param # API') && txt.includes('# soma-import: Nut as N,')
+ && /# soma-checksum: [0-9a-f]{16}/.test(txt) && txt.includes("_SOMA_VALUES = {'L': 80}") && txt.includes('# >>> soma-compat footer') && txt.includes('SPDX-License-Identifier: Apache-2.0'),
+ ex.stderr.slice(-300));
+ check('Der Modellcode dazwischen bleibt Zeichen für Zeichen gleich', txt.includes(SOMA_MODEL.split('\n').slice(8).join('\n').trimEnd()));
+ check('inputs/ wird nur kopiert, wenn das Skript es nutzt (hier nicht)', !fs.existsSync(path.join(work, 'out', 'inputs')));
+ const run = runExported(path.join(work, 'out', 'plate.py'));
+ check('Exportiertes Skript läuft ohne soma: show_object je Teil mit Farbe, param() liefert den Wert aus dem Panel (80)',
+ run.shown?.length === 3 && run.shown[0].name === 'Plate' && run.shown[0].x === 80 && JSON.stringify(run.shown[0].color) === '[0.2,0.4,0.8]'
+ && run.shown[1].name === 'Screw' && run.shown[2].name === 'Nut' && run.result === 'Assembly', JSON.stringify(run).slice(0, 300));
+ write('asis/model.py', txt);
+ const b6 = soma(['build', '--project', path.join(work, 'asis')], path.join(work, 'asis'));
+ check('Unverändert in SOMA gebaut: Kompatibilitätsmodus über den Fußblock, drei Teile', b6.status === 0 && b6.stdout.includes('3 part(s)'), (b6.stdout + b6.stderr).slice(-300));
+
+ fs.mkdirSync(path.join(work, 'back'));
+ const im = soma(['cadquery', 'import', path.join(work, 'out', 'plate.py'), '--project', path.join(work, 'back'), '--json'], work);
+ const imr = JSON.parse(im.stdout.trim().split('\n').pop() || '{}');
+ check('Import dreht den Export zurück: model.py gleich dem Original, Werte in parameters.json, Original in inputs/',
+ imr.mode === 'soma' && read('back/model.py') === SOMA_MODEL && JSON.parse(read('back/parameters.json')).values.L === 80 && fs.existsSync(path.join(work, 'back', 'inputs', 'plate.py')),
+ JSON.stringify(imr));
+ write('back/model.py', SOMA_MODEL + '# geaendert\n');
+ const im2 = soma(['cadquery', 'import', path.join(work, 'out', 'plate.py'), '--project', path.join(work, 'back')], work);
+ check('Ein zweiter Import ersetzt nichts ohne --backup', im2.status === 1 && im2.stderr.includes('already exists'), im2.stderr);
+
+ // 3) Veränderter Block bleibt stehen, nur _SOMA_VALUES darf sich ändern
+ write('tamper/a.py', txt.replace("_SOMA_VALUES = {'L': 80}", "_SOMA_VALUES = {'L': 90}"));
+ write('tamper/b.py', txt.replace('def _soma_path(path):', 'def _soma_path(path): # geaendert'));
+ fs.mkdirSync(path.join(work, 'ta')); fs.mkdirSync(path.join(work, 'tb'));
+ const ta = JSON.parse(soma(['cadquery', 'import', path.join(work, 'tamper', 'a.py'), '--project', path.join(work, 'ta'), '--json'], work).stdout.trim().split('\n').pop());
+ const tb = JSON.parse(soma(['cadquery', 'import', path.join(work, 'tamper', 'b.py'), '--project', path.join(work, 'tb'), '--json'], work).stdout.trim().split('\n').pop());
+ check('Geänderter Wert in _SOMA_VALUES: Import gelingt, neuer Wert in parameters.json', ta.mode === 'soma' && JSON.parse(read('ta/parameters.json')).values.L === 90);
+ check('Geänderter Block: Skript bleibt, wie es ist, mit Hinweis', tb.mode === 'cadquery' && read('tb/model.py') === read('tamper/b.py')
+ && tb.warnings.some((w) => w.includes('was changed')), JSON.stringify(tb.warnings));
+
+ // 4) Modell mit parts/: Ordner mit soma_compat.py, Rückweg
+ write('multi/model.py', 'import cadquery as cq\nfrom soma import add_part\nfrom parts.lid import make_lid\nadd_part("Lid", make_lid())\nadd_part("Box", cq.Workplane().box(10, 10, 10))\n');
+ write('multi/parts/lid.py', 'import cadquery as cq\nfrom soma import param\nW = param(12.0, "Width")\n\n\ndef make_lid():\n return cq.Workplane().box(W, W, 1).translate((0, 0, 6))\n');
+ write('multi/parameters.json', JSON.stringify({ values: { W: 14 } }));
+ const fx = JSON.parse(soma(['cadquery', 'export', '--out', path.join(work, 'mout', 'multi.py'), '--project', path.join(work, 'multi'), '--json'], work).stdout.trim().split('\n').pop());
+ const mdir = path.join(work, 'mout', 'multi');
+ check('Mit parts/: Ordner mit model.py, parts/lid.py und soma_compat.py', fx.mode === 'folder' && ['model.py', 'parts/lid.py', 'soma_compat.py'].every((f) => fs.existsSync(path.join(mdir, f)))
+ && fs.readFileSync(path.join(mdir, 'parts', 'lid.py'), 'utf8').includes('from soma_compat import param # soma-compat'), JSON.stringify(fx));
+ const mrun = runExported(path.join(mdir, 'model.py'));
+ check('Ordner läuft ohne soma, Wert W = 14 aus dem Panel', mrun.shown?.length === 2 && mrun.shown[0].name === 'Lid' && mrun.shown[0].x === 14, JSON.stringify(mrun).slice(0, 300));
+ fs.mkdirSync(path.join(work, 'mback'));
+ const mi = JSON.parse(soma(['cadquery', 'import', path.join(mdir, 'model.py'), '--project', path.join(work, 'mback'), '--json'], work).stdout.trim().split('\n').pop());
+ check('Ordner zurück: model.py und parts/lid.py wie im Original, kein soma_compat.py, W in parameters.json',
+ mi.mode === 'soma' && read('mback/model.py') === read('multi/model.py') && read('mback/parts/lid.py') === read('multi/parts/lid.py')
+ && !fs.existsSync(path.join(work, 'mback', 'soma_compat.py')) && JSON.parse(read('mback/parameters.json')).values.W === 14, JSON.stringify(mi));
+
+ // 4b) Namen, die cq.Assembly ablehnt: Teil wie seine Gruppe, Teil wie eine Gruppe daneben, Teil wie die Wurzel
+ write('names/model.py', `import cadquery as cq
+from soma import add_part
+add_part("X beam", cq.Workplane().box(100, 10, 10), group="X beam")
+add_part("Y beam", cq.Workplane().box(10, 100, 10), group="Frame")
+add_part("Frame", cq.Workplane().box(5, 5, 5))
+add_part("Model", cq.Workplane().box(3, 3, 3))
+`);
+ soma(['cadquery', 'export', '--out', path.join(work, 'names-out', 'names.py'), '--project', path.join(work, 'names')], work);
+ const nrun = runExported(path.join(work, 'names-out', 'names.py'));
+ check('Gleiche Namen von Teil und Gruppe: Export läuft, show_object behält die Namen aus add_part',
+ JSON.stringify(nrun.shown?.map((x) => x.name)) === '["X beam","Y beam","Frame","Model"]' && nrun.result === 'Assembly', JSON.stringify(nrun).slice(0, 300));
+
+ // 5) Was sich nicht exportieren lässt, wird mit Zeile gemeldet
+ write('bad1/model.py', 'import cadquery as cq\nimport soma\nsoma.add_part("A", cq.Workplane().box(1, 1, 1))\n');
+ write('bad2/model.py', 'import cadquery as cq\nfrom soma import add_part\nfrom soma.anim import Animation\n');
+ const e1 = soma(['cadquery', 'export', '--out', path.join(work, 'x1.py'), '--project', path.join(work, 'bad1')], work);
+ const e2 = soma(['cadquery', 'export', '--out', path.join(work, 'x2.py'), '--project', path.join(work, 'bad2')], work);
+ check('`import soma` und soma.anim: Fehler mit Zeile, keine Datei', e1.status === 1 && e1.stderr.includes('line 2') && e2.status === 1 && e2.stderr.includes('soma.anim')
+ && !fs.existsSync(path.join(work, 'x1.py')) && !fs.existsSync(path.join(work, 'x2.py')), e1.stderr + e2.stderr);
+
+ // 6) In der App: neues Modell aus einem CadQuery-Skript, Export über das Menü
+ app = await startApp({ name: 'cadquery' });
+ const { ev, waitFor, ud } = app;
+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok');
+ const first = await ev(() => window.__t.project());
+ await app.answers([path.join(work, 'cqe', 'model.py')]);
+ const nr = await ev(() => window.__t.newFromCadQuery());
+ await waitFor('neues Modell gebaut', (old) => window.__t.project().id !== old && window.__t.status().state === 'ok', 120000, first.id).catch(() => {});
+ const p2 = await ev(() => window.__t.project());
+ const w2 = buildOf(p2.dir).warnings ?? [];
+ check('New from CadQuery script: neues Modell mit dem Namen der Datei, Teile aus show_object, Warnung im Build',
+ !nr?.error && p2.id !== first.id && p2.name === 'model' && JSON.stringify(await ev(() => window.__t.treeNames())) === '["Box","cyl"]'
+ && w2.some((w) => w.startsWith('Compatibility mode')), `${p2.name} ${JSON.stringify(w2)}`);
+ check('Skript unverändert als model.py, Original in inputs/, Vorlage in workspace-backups/, Skill im Modell',
+ fs.readFileSync(path.join(p2.dir, 'model.py'), 'utf8') === read('cqe/model.py') && fs.existsSync(path.join(p2.dir, 'inputs', 'model.py'))
+ && fs.existsSync(path.join(ud, 'workspace-backups', `${p2.id}-import`, 'model.py')) && fs.existsSync(path.join(p2.dir, '.soma', 'skills', 'cadquery-scripts.md')));
+ check('Erster Stand im Verlauf enthält das Skript', (await ev(() => window.soma.versions.log())).commits?.length >= 1);
+
+ await app.answers([path.join(work, 'appout.py')]);
+ const er = await ev(() => window.__t.exportCadQuery());
+ check('As CadQuery script: Datei am gewählten Ort, ohne soma-Imports unverändert (fremdes Skript)', er.ok && fs.existsSync(path.join(work, 'appout.py'))
+ && read('appout.py') === read('cqe/model.py'), JSON.stringify(er));
+ await app.answers([null]);
+ check('Abbrechen im Dateidialog: nichts passiert', (await ev(() => window.__t.newFromCadQuery()))?.cancelled === true && (await ev(() => window.__t.project())).id === p2.id);
+ const count = (await ev(() => window.soma.project.list())).length;
+ await app.answers([path.join(work, 'missing.py')]);
+ const br = await ev(() => window.__t.newFromCadQuery());
+ check('Datei fehlt: Meldung, kein neues Modell, kein halber Ordner', !!br?.error && br.error.includes('not a Python file') && (await ev(() => window.__t.project())).id === p2.id
+ && (await ev(() => window.soma.project.list())).length === count, JSON.stringify(br));
+ // Ein Skript mit Syntaxfehler kommt trotzdem herein: Der Build meldet den Fehler mit Zeile, der Agent kann ihn beheben
+ write('broken/broken.py', 'import cadquery as cq\ndef (:\n');
+ await app.answers([path.join(work, 'broken', 'broken.py')]);
+ const bk = await ev(() => window.__t.newFromCadQuery());
+ await waitFor('Build mit Fehler', (old) => window.__t.project().id !== old && window.__t.status().state === 'error', 120000, p2.id).catch(() => {});
+ const p3 = await ev(() => window.__t.project());
+ const e3 = p3.id !== p2.id ? buildOf(p3.dir).error : null;
+ check('Syntaxfehler: Modell entsteht, der Build meldet Datei und Zeile', !bk?.error && e3?.file === 'model.py' && e3?.line === 2, JSON.stringify(e3 ?? bk));
+
+ // Kleiner Knopf auf der Startseite unter „New model“
+ await ev(() => window.__t.showStart(true));
+ await app.answers([path.join(work, 'res', 'model.py')]);
+ await app.domClick('start-new-cq');
+ await waitFor('Ladeanzeige', () => !window.__t.cqBusy().hidden, 30000).catch(() => {});
+ const busy = await ev(() => window.__t.cqBusy());
+ if (process.env.SMOKE_SHOTS && !busy.hidden) {
+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });
+ await sleep(300);
+ await app.screenshot(path.join(APP, 'test', 'shots', 'cadquery-busy.png')).catch((e) => console.log('Screenshot:', e.message));
+ }
+ check('Ladeanzeige über der Startseite: Titel, Schritt und Dateiname', !busy.hidden && busy.text.includes('Loading CadQuery script')
+ && busy.text.includes('model.py') && /Reading the script|Building the model|Opening the model/.test(busy.text), JSON.stringify(busy));
+ await waitFor('Modell von der Startseite', (old) => window.__t.project().id !== old && window.__t.status().state === 'ok'
+ && document.getElementById('start').hidden, 120000, p3.id).catch(() => {});
+ check('Startseite: „New from CadQuery script“ legt das Modell an und schließt die Startseite',
+ (await ev(() => window.__t.project())).id !== p3.id && JSON.stringify(await ev(() => window.__t.treeNames())) === '["result"]'
+ && await ev(() => document.getElementById('start').hidden) && (await ev(() => window.__t.cqBusy())).hidden, JSON.stringify(await ev(() => window.__t.treeNames())));
+} catch (e) {
+ check('Unerwarteter Fehler', false, e instanceof Error ? e.stack : String(e));
+} finally {
+ if (app) { await app.stop(); cleanup(app.ud); }
+ cleanup(work);
+}
+process.exit(t.fails ? 1 : 0);
diff --git a/app/test/helpshots-spec.mjs b/app/test/helpshots-spec.mjs
index 8e2754a..71c34cb 100644
--- a/app/test/helpshots-spec.mjs
+++ b/app/test/helpshots-spec.mjs
@@ -128,6 +128,7 @@ export const SHOTS = [
{ label: 'Scope', sel: '#menu-export .seg', at: 'l' },
{ label: 'Formats', sel: '#menu-export .chips', at: 'l', box: true },
{ label: 'Everything as ZIP', sel: '#exp-zip', at: 'l' },
+ { label: 'As CadQuery script', sel: '#exp-cq', at: 'l' },
],
},
{
diff --git a/app/test/run-all.mjs b/app/test/run-all.mjs
index 3239725..99494b9 100644
--- a/app/test/run-all.mjs
+++ b/app/test/run-all.mjs
@@ -11,7 +11,7 @@ import path from 'node:path';
const DIR = import.meta.dirname;
// Längste zuerst, damit sie nicht am Ende allein laufen
-const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'params', 'explode', 'fasteners', 'drawing', 'drawview', 'section', 'measure', 'groups', 'dxf', 'packages', 'settings', 'tutorial', 'updates', 'buildlock', 'unit'];
+const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'params', 'explode', 'fasteners', 'drawing', 'drawview', 'section', 'measure', 'stepview', 'cadquery', 'groups', 'dxf', 'packages', 'settings', 'tutorial', 'updates', 'buildlock', 'unit'];
const SLOW = ['animation', 'fem'];
const args = process.argv.slice(2);
const all = args.includes('--all');
diff --git a/app/test/skills.mjs b/app/test/skills.mjs
index e24c306..a72e364 100644
--- a/app/test/skills.mjs
+++ b/app/test/skills.mjs
@@ -60,13 +60,13 @@ try {
/** Die beiden Listen des Abschnitts: Immer vor „Read when relevant“, Bei Bedarf danach. */
const always = () => (block() ?? '').split('### Read when relevant')[0];
const demand = () => (block() ?? '').split('### Read when relevant')[1] ?? '';
- const DEMAND_NEW = 'shell-environment,soma-app,3d-printing,resin-powder,cnc,laser,sheet-metal,tolerances,joints,strength,assemblies,analysis,animation,fem,drawings';
+ const DEMAND_NEW = 'cadquery-scripts,shell-environment,soma-app,3d-printing,resin-powder,cnc,laser,sheet-metal,tolerances,joints,strength,assemblies,analysis,animation,fem,drawings';
// 1) Panel: die mitgelieferten Skills nach Kategorien und `order`
await ev(() => document.querySelector('#rail [data-panel="skills"]').click());
await waitFor('Skills geladen', () => window.__t.skills().skills.length >= 3, 10000);
let s = await st();
- const ORDER = 'design-workflow,cadquery,parametric,shell-environment,soma-app,3d-printing,resin-powder,cnc,laser,sheet-metal,tolerances,joints,standard-parts,strength,assemblies,analysis,animation,fem,drawings';
+ const ORDER = 'design-workflow,cadquery,parametric,cadquery-scripts,shell-environment,soma-app,3d-printing,resin-powder,cnc,laser,sheet-metal,tolerances,joints,standard-parts,strength,assemblies,analysis,animation,fem,drawings';
const heads = await ev(() => [...document.querySelectorAll('#skills-list .sk-cat')].map((h) => h.textContent).join(','));
check('Panel „Skills": Überschriften Way of working, Manufacturing, Design knowledge, Check and present, darunter die Skills nach `order`',
s.skills.map((x) => x.id).join(',') === ORDER && heads === 'Way of working,Manufacturing,Design knowledge,Check and present'
@@ -92,7 +92,7 @@ try {
&& always().includes('- `.soma/skills/parametric.md`: Parametric models') && !always().includes('3d-printing')
&& demand().includes('- `.soma/skills/3d-printing.md`: 3D printing (FDM). Read when the parts will be 3D printed on a filament printer (FDM).')
&& DEMAND_NEW.split(',').every((id) => demand().includes(`.soma/skills/${id}.md`))
- && (await g('ls-files', '.soma/skills')).split('\n').length === 19
+ && (await g('ls-files', '.soma/skills')).split('\n').length === 20
&& (await ev(() => window.__t.saveState())).dirtyFiles === 0, `${String((await ev(() => window.__t.saveState())).dirtyFiles)} | ${String(block()).slice(0, 200)}`);
// Anleitung (E83): Skill „Using the app“ bei Bedarf, Bilder in .soma/help/ (nicht im Verlauf), Hilfe-Fenster aus derselben Quelle
const helpPngs = fs.readdirSync(path.join(APP, 'resources', 'help')).filter((n) => n.endsWith('.png'));
@@ -375,12 +375,12 @@ try {
const fdm2 = fs.readFileSync(path.join(p2.dir, '.soma', 'skills', '3d-printing.md'), 'utf8');
const ka2 = fs.readFileSync(path.join(p2.dir, '.soma', 'skills', 'design-workflow.md'), 'utf8');
check('Neues Modell nach der Vorgabe: immer Sauber modellieren, Parametrik, 3D-Druck, Normteile, Laser aus, Konstruktionsablauf bei Bedarf, Standardwerte statt 55° und PETG',
- JSON.stringify(pj2.skills) === '["cadquery","parametric","3d-printing","standard-parts"]' && pj2.skills_on_demand.join(',') === 'design-workflow,shell-environment,soma-app,resin-powder,cnc,sheet-metal,tolerances,joints,strength,assemblies,analysis,animation,fem,drawings'
+ JSON.stringify(pj2.skills) === '["cadquery","parametric","3d-printing","standard-parts"]' && pj2.skills_on_demand.join(',') === 'design-workflow,cadquery-scripts,shell-environment,soma-app,resin-powder,cnc,sheet-metal,tolerances,joints,strength,assemblies,analysis,animation,fem,drawings'
&& !pj2.skill_settings && fdm2.includes('Overhangs up to 45°') && fdm2.includes('| Material | PLA |') && !fdm2.includes('On demand') && ka2.includes('> **On demand:**')
&& !fs.existsSync(path.join(p2.dir, '.soma', 'skills', 'laser.md'))
&& norm(fs.readFileSync(path.join(p2.dir, 'AGENTS.md'), 'utf8')).includes('- `.soma/skills/3d-printing.md`: 3D printing (FDM)\n'), JSON.stringify(pj2));
await waitFor('Speicherstand neu', () => window.__t.saveState() && !window.__t.saveState().unsaved, 10000).catch(() => {});
- check('Neues Modell: Skills im Startcommit, nichts ungespeichert', (await exec(['ls-files', '.soma/skills'], p2.dir)).stdout.trim().split('\n').length === 18
+ check('Neues Modell: Skills im Startcommit, nichts ungespeichert', (await exec(['ls-files', '.soma/skills'], p2.dir)).stdout.trim().split('\n').length === 19
&& (await ev(() => window.__t.saveState())).dirtyFiles === 0, String((await ev(() => window.__t.saveState())).dirtyFiles));
// 11) Einstellungen (E78): eigene Skills anlegen, mitgelieferte bearbeiten und zurücksetzen, löschen, importieren
@@ -399,9 +399,9 @@ try {
// Beim ersten Öffnen steht das Fenster im Reiter Viewer (E81), die Skills sind ein Reiter daneben
await waitFor('Einstellungen offen', () => window.__t.settings().open && window.__t.settings().section === 'viewer', 10000);
await ev(() => document.querySelector('#st-nav [data-sec="skills"]').click());
- await waitFor('Reiter Skills', () => window.__t.settings().section === 'skills' && window.__t.settings().skills.length >= 18, 10000);
+ await waitFor('Reiter Skills', () => window.__t.settings().section === 'skills' && window.__t.settings().skills.length >= 19, 10000);
let us = await ust();
- check('Einstellungen: alle mitgelieferten Skills nach Kategorien, keiner gewählt, Hintergrund gesperrt', us.skills.length === 19 && us.skills.every((s) => s.source === 'builtin') && us.selected === null
+ check('Einstellungen: alle mitgelieferten Skills nach Kategorien, keiner gewählt, Hintergrund gesperrt', us.skills.length === 20 && us.skills.every((s) => s.source === 'builtin') && us.selected === null
&& us.list.includes('3D printing (FDM)') && /way of working/i.test(us.list) && await ev(() => {
// Echte Klicks: Das Fenster selbst darf nicht gesperrt sein, der Knopf liegt oben (Treffertest)
const b = document.getElementById('btn-st-new').getBoundingClientRect();
diff --git a/app/test/stepview.mjs b/app/test/stepview.mjs
new file mode 100644
index 0000000..eac6007
--- /dev/null
+++ b/app/test/stepview.mjs
@@ -0,0 +1,181 @@
+// Test der Dateiansicht: Ein Klick auf eine STEP-Datei im Dateibaum zeigt sie im Viewer (Basismodus, Cache nach Inhalt),
+// mit Banner, Messen, Schnitt und Explosion. Ein Build des Modells ersetzt sie nicht, eine Änderung der Datei lädt neu,
+// „Back to model“ kehrt zurück. Dazu Zusammenspiel mit der Versionsvorschau und Störfälle (kaputte, leere Datei, außerhalb).
+// Aufruf: npm run test:stepview (baut vorher). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder in test/shots/ ab.
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';
+
+const t = checker();
+const { check } = t;
+let app;
+const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'soma-sv-'));
+
+// Platte und Block wie im Messtest, dazu später ein Stift: So unterscheidet sich das Modell von den STEP-Dateien
+const MODEL = (pin) => `import cadquery as cq
+from soma import add_part
+
+plate = (cq.Workplane("XY").box(40, 30, 5, centered=(True, True, False))
+ .faces(">Z").workplane().pushPoints([(-10, 0), (10, 0)]).hole(6))
+block = cq.Workplane("XY").box(20, 20, 5, centered=(True, True, False)).translate((45, 0, 15))
+
+add_part("Platte", plate)
+add_part("Block", block, color=(0.85, 0.55, 0.25))
+${pin ? 'add_part("Stift", cq.Workplane("XY").circle(2).extrude(30).translate((-45, 0, 0)))' : ''}
+`;
+
+try {
+ app = await startApp({ name: 'stepview' });
+ const { ev, waitFor, domClick, page, ud } = app;
+ const shot = async (name) => {
+ if (!process.env.SMOKE_SHOTS) return;
+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });
+ await sleep(900);
+ await app.screenshot(path.join(APP, 'test', 'shots', `${name}.png`)).catch((e) => console.log('Screenshot:', e.message));
+ };
+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok' && window.__t.partCount() === 2);
+ const proj = await ev(() => window.__t.project());
+ const dir = proj.dir;
+ const inputs = path.join(dir, 'inputs');
+ fs.mkdirSync(inputs, { recursive: true });
+ // Die STEP-Datei des Vorlagenmodells (Body, Lid) wird zur fremden Datei im Projekt
+ fs.copyFileSync(path.join(dir, 'output', 'model.step'), path.join(inputs, 'box.step'));
+ fs.writeFileSync(path.join(inputs, 'broken.step'), 'ISO-10303-21;\nHEADER;\nthis is not a STEP file\n');
+ fs.writeFileSync(path.join(inputs, 'empty.stp'), '');
+ fs.writeFileSync(path.join(dir, 'model.py'), MODEL(false));
+ await waitFor('Testmodell gebaut', () => window.__t.status().state === 'ok' && JSON.stringify(window.__t.treeNames()) === '["Platte","Block"]', 60000);
+ const plateStep = path.join(workDir, 'platte.step');
+ fs.copyFileSync(path.join(dir, 'output', 'model.step'), plateStep);
+
+ const fv = () => ev(() => window.__t.fileView());
+ const names = () => ev(() => JSON.stringify(window.__t.treeNames()));
+ const clickRow = (rel) => ev((r) => { const row = document.querySelector(`#tab-files .frow[data-path="${CSS.escape(r)}"]`); row?.click(); return !!row; }, rel);
+ const cacheRoot = path.join(ud, 'previews', proj.id, 'files');
+
+ // 1) Klick im Dateibaum öffnet die Datei im Viewer
+ await ev(() => window.__t.showPanel('files'));
+ await waitFor('Datei im Dateibaum', () => window.__t.fileRows().includes('box.step'), 20000).catch(() => {});
+ check('STEP-Datei steht im Dateibaum', await clickRow('inputs/box.step'));
+ await waitFor('Datei im Viewer', () => window.__t.fileView().rel === 'inputs/box.step' && JSON.stringify(window.__t.treeNames()) === '["Body","Lid"]', 90000).catch(() => {});
+ let f = await fv();
+ check('Klick auf box.step: Viewer zeigt die Teile der Datei (Body, Lid)', f.rel === 'inputs/box.step' && await names() === '["Body","Lid"]', `${JSON.stringify(f)} ${await names()}`);
+ check('Banner „Viewing inputs/box.step“ mit Teilezahl und „Back to model“, violetter Rahmen', !!f.banner && f.banner.includes('Viewing inputs/box.step')
+ && f.banner.includes('2 parts') && f.banner.includes('Back to model') && f.frame, f.banner ?? '');
+ check('Kein Banner der Versionsvorschau', (await ev(() => window.__t.banner())).hidden && !(await ev(() => window.__t.versions())).previewing);
+ check('Ladeanzeige ist wieder weg', await ev(() => document.getElementById('viewer-busy').hidden));
+ check('Baum trägt den Dateinamen als Titel', await ev(() => document.getElementById('tree').textContent.includes('box.step')));
+ const key1 = f.key;
+ check('Cache nach Inhalt: previews/<Projekt>/files/<SHA-1> mit GLB, Zuordnung und Geometrie, kein Arbeitsordner übrig',
+ /^[0-9a-f]{40}$/.test(key1 ?? '') && fs.existsSync(path.join(cacheRoot, key1, 'model.glb')) && fs.existsSync(path.join(cacheRoot, key1, 'geometry'))
+ && !fs.readdirSync(cacheRoot).some((n) => n.startsWith('.tmp-')), fs.existsSync(cacheRoot) ? fs.readdirSync(cacheRoot).join(',') : 'kein Cache');
+ const parts = await ev(() => window.__t.parts());
+ check('Teile im Basismodus (Rolle „basic“), ohne Code zum Bauteil', parts.length === 2 && parts.every((p) => p.role === 'basic'), JSON.stringify(parts).slice(0, 160));
+ await ev(() => window.__t.viewer.setView('iso'));
+ await shot('stepview-1');
+
+ // 2) Ein Build des Modells ersetzt die Ansicht nicht
+ const mapFile = path.join(dir, '.soma', 'model.map.json');
+ const buildId = () => { try { return JSON.parse(fs.readFileSync(mapFile, 'utf8')).build; } catch { return null; } };
+ const before = buildId();
+ fs.writeFileSync(path.join(dir, 'model.py'), MODEL(true));
+ const t0 = Date.now();
+ while (buildId() === before && Date.now() - t0 < 60000) await sleep(300);
+ await waitFor('Build fertig', () => window.__t.status().state === 'ok', 60000).catch(() => {});
+ await sleep(800);
+ check('Neuer Build des Modells (mit Stift) während der Ansicht: Viewer bleibt bei der Datei', buildId() !== before && await names() === '["Body","Lid"]'
+ && (await fv()).rel === 'inputs/box.step', await names());
+
+ // 3) Messen in der Datei: Oberseite des Deckels (60 × 40, Radius 4 in den Ecken)
+ await ev(() => window.__t.viewer.setView('iso'));
+ await sleep(300);
+ await domClick('btn-measure');
+ const lidTop = await ev((pid) => {
+ const fc = window.__t.viewer.facesOf(pid).filter((x) => x.surface === 'PLANE').sort((a, b) => b.center[2] - a.center[2])[0];
+ return { id: fc.id, screen: window.__t.viewer.screenOf(pid, fc.id) };
+ }, await ev(() => window.__t.parts().find((p) => p.name === 'Lid').id));
+ await page.click(lidTop.screen.x, lidTop.screen.y);
+ await waitFor('Messergebnis', () => !!window.__t.measure().result || !!window.__t.measure().error, 90000).catch(() => {});
+ let m = await ev(() => window.__t.measure());
+ check('Messen in der Datei: Oberseite des Deckels, exakte Fläche', m.result?.a.type === 'PLANE' && Math.abs(m.result.a.area - (60 * 40 - (4 - Math.PI) * 16)) < 1e-6,
+ m.error || `${m.result?.a.area}`);
+ await shot('stepview-2-messen');
+ await domClick('btn-measure');
+
+ // 4) Schnitt und Explosion
+ await domClick('btn-section');
+ await sleep(300);
+ const sec = await ev(() => ({ s: window.__t.section(), v: window.__t.viewer.sectionState() }));
+ check('Schnitt in der Datei: beide Teile geschnitten und gedeckelt', sec.s.active && sec.v.clipped && sec.v.capped.length === 2, JSON.stringify(sec.v).slice(0, 160));
+ await shot('stepview-3-schnitt');
+ await domClick('btn-section');
+ await domClick('btn-explode');
+ await waitFor('Explosion steht', () => window.__t.explode().active && !window.__t.explode().animating, 30000).catch(() => {});
+ const ex = await ev(() => window.__t.explode());
+ check('Explosion in der Datei: aktiv, Teile auseinander', ex.active && Object.keys(ex.spreads).length > 0, JSON.stringify(ex.spreads).slice(0, 120));
+ await domClick('btn-explode');
+
+ // 5) Auswahl für den Agenten nennt die Datei
+ const lidId = await ev(() => window.__t.parts().find((p) => p.name === 'Lid').id);
+ await page.click(lidTop.screen.x, lidTop.screen.y);
+ await waitFor('Auswahl', () => window.__t.info().startsWith('Lid'), 5000).catch(() => {});
+ const selText = await ev(() => window.__t.selectionText());
+ check('Text für den Agenten nennt die STEP-Datei', (selText ?? '').includes('in the STEP file inputs/box.step'), `${selText} (${lidId})`);
+
+ // 6) Datei ändert sich auf der Platte: neu laden, Ansicht bleibt offen
+ fs.copyFileSync(plateStep, path.join(inputs, 'box.step'));
+ await waitFor('Datei neu geladen', () => JSON.stringify(window.__t.treeNames()) === '["Platte","Block"]' && window.__t.fileView().rel === 'inputs/box.step', 90000).catch(() => {});
+ f = await fv();
+ check('Geänderte Datei wird neu geladen (jetzt Platte und Block), neuer Schlüssel, Hinweis', f.key !== key1 && await names() === '["Platte","Block"]'
+ && (await ev(() => window.__t.toast().text)).includes('changed on disk'), `${await names()} ${(await ev(() => window.__t.toast().text))}`);
+
+ // 7) Zurück zum Modell: jetzt mit dem Stift aus dem Build während der Ansicht
+ await domClick('btn-file-back');
+ await waitFor('Modell wieder da', () => JSON.stringify(window.__t.treeNames()) === '["Platte","Block","Stift"]', 30000).catch(() => {});
+ f = await fv();
+ check('„Back to model“: Banner und Rahmen weg, Viewer zeigt das aktuelle Modell (mit Stift)', !f.rel && !f.banner && !f.frame && await names() === '["Platte","Block","Stift"]', await names());
+ check('Baum trägt wieder den Modellnamen', await ev(() => !document.getElementById('tree').textContent.includes('box.step')));
+
+ // 8) Zusammenspiel mit der Versionsvorschau: eins schließt das andere
+ await clickRow('inputs/box.step');
+ await waitFor('Datei im Viewer', () => window.__t.fileView().rel === 'inputs/box.step' && !window.__t.fileView().loading, 60000).catch(() => {});
+ await ev(() => document.querySelectorAll('#vdots .vdot')[0].click());
+ await waitFor('Vorschau', () => !!window.__t.versions().previewing, 60000).catch(() => {});
+ f = await fv();
+ check('Version gewählt während der Dateiansicht: Vorschau läuft, Dateiansicht beendet', !!(await ev(() => window.__t.versions())).previewing && !f.rel && !f.banner
+ && !(await ev(() => window.__t.banner())).hidden, JSON.stringify(f));
+ await clickRow('inputs/box.step');
+ await waitFor('Datei im Viewer', () => window.__t.fileView().rel === 'inputs/box.step' && !window.__t.fileView().loading, 60000).catch(() => {});
+ check('Datei geöffnet während der Vorschau: Vorschau beendet, nur noch das Banner der Datei', !(await ev(() => window.__t.versions())).previewing
+ && (await ev(() => window.__t.banner())).hidden && !!(await fv()).banner && await ev(() => !document.getElementById('viewer').classList.contains('preview')));
+ await domClick('btn-file-back');
+ await waitFor('Modell wieder da', () => JSON.stringify(window.__t.treeNames()) === '["Platte","Block","Stift"]', 30000).catch(() => {});
+
+ // 9) Störfälle: kaputte und leere Datei, Pfade außerhalb, andere Dateitypen
+ await clickRow('inputs/broken.step');
+ await waitFor('Fehlermeldung', () => /broken\.step cannot be shown/.test(window.__t.toast().text) && !window.__t.fileView().loading, 60000).catch(() => {});
+ let toastText = await ev(() => window.__t.toast());
+ check('Kaputte STEP-Datei: verständliche Meldung, Viewer bleibt beim Modell', toastText.error && toastText.text.includes('not a valid STEP file') && !(await fv()).rel
+ && await names() === '["Platte","Block","Stift"]', toastText.text);
+ await clickRow('inputs/empty.stp');
+ await waitFor('Fehlermeldung', () => /empty\.stp cannot be shown/.test(window.__t.toast().text), 20000).catch(() => {});
+ toastText = await ev(() => window.__t.toast());
+ check('Leere Datei: „The file is empty.“', toastText.text.includes('The file is empty.'), toastText.text);
+ check('Kein halber Cache-Ordner nach den Fehlern', !fs.readdirSync(cacheRoot).some((n) => n.startsWith('.tmp-')), fs.readdirSync(cacheRoot).join(','));
+ const outside = await ev(() => window.soma.project.viewFile('../outside.step'));
+ check('Pfad außerhalb des Projekts wird abgelehnt', /outside the project/.test(outside.error ?? ''), outside.error);
+ const notStep = await ev(() => window.soma.project.viewFile('model.py'));
+ check('Andere Dateitypen werden abgelehnt', /Only STEP files/.test(notStep.error ?? ''), notStep.error);
+ const badMeasure = await ev(() => window.soma.measure.prepare({ file: '../x.step', key: '0'.repeat(40) }, '0'.repeat(32)));
+ check('Messquelle außerhalb oder unbekannt wird abgelehnt', !badMeasure.ok, badMeasure.error);
+
+ const relevant = page.errors.filter((e) => !/favicon/i.test(e));
+ check('Keine Konsolenfehler im Renderer', relevant.length === 0, relevant.slice(0, 2).join(' | ').slice(0, 100));
+} catch (e) {
+ console.log('ABBRUCH:', e.message);
+ t.fail();
+}
+if (app) { await app.stop(); cleanup(app.ud); }
+fs.rmSync(workDir, { recursive: true, force: true });
+console.log(t.fails ? `\n${t.fails} Prüfung(en) fehlgeschlagen` : '\nALLE PRÜFUNGEN BESTANDEN');
+process.exit(t.fails ? 1 : 0);
diff --git a/app/test/unit.mjs b/app/test/unit.mjs
index 2673498..df7072e 100644
--- a/app/test/unit.mjs
+++ b/app/test/unit.mjs
@@ -200,10 +200,10 @@ try {
const SKD = { bundled: path.join(APP, 'resources', 'skills'), user: path.join(tmp, 'keine-eigenen-skills') };
const dm = defaultModes(SKD, {});
check('Neue Modelle: ohne Vorgabe des Nutzers Arbeitsweise (mit Parametrik) und Normteile immer, alle übrigen bei Bedarf', dm.always.join(',') === 'design-workflow,cadquery,parametric,standard-parts'
- && dm.demand.join(',') === 'shell-environment,soma-app,3d-printing,resin-powder,cnc,laser,sheet-metal,tolerances,joints,strength,assemblies,analysis,animation,fem,drawings', JSON.stringify(dm));
+ && dm.demand.join(',') === 'cadquery-scripts,shell-environment,soma-app,3d-printing,resin-powder,cnc,laser,sheet-metal,tolerances,joints,strength,assemblies,analysis,animation,fem,drawings', JSON.stringify(dm));
const dm2 = defaultModes(SKD, { 'design-workflow': 'demand', tolerances: 'always', '3d-printing': 'always', laser: 'off' });
check('Neue Modelle: Vorgabe des Nutzers geht vor, in der Reihenfolge des Panels, „Aus“ fehlt ganz', dm2.always.join(',') === 'cadquery,parametric,3d-printing,tolerances,standard-parts'
- && dm2.demand.join(',') === 'design-workflow,shell-environment,soma-app,resin-powder,cnc,sheet-metal,joints,strength,assemblies,analysis,animation,fem,drawings', JSON.stringify(dm2));
+ && dm2.demand.join(',') === 'design-workflow,cadquery-scripts,shell-environment,soma-app,resin-powder,cnc,sheet-metal,joints,strength,assemblies,analysis,animation,fem,drawings', JSON.stringify(dm2));
// Bei Bedarf (E55): Hinweis unter der ersten Überschrift, Werte als Standard der App, vom Nutzer gesetzte mit Namen
const rd = renderSkill(SRC, {}, 'demand');
check('Bei Bedarf: Hinweis direkt unter der Überschrift, mit Leerzeilen, Werte als Standard der App, NOTES.md', rd.includes('# Skill\n\n> **On demand:**')