Desktop app for designing parametric 3D models in CadQuery together with the coding agent of your choice
TypeScript 3d-modeling3d-printing3d-printing-toolsagentagentic-aiai-cadcadcadqueryclaude-codecodexelectronfemllmmacdmakeropencodeparametric-designpythonsteptext-to-cad
App: Git-Verlauf, ZIP speichern und öffnen, Verlaufsleiste
Kai-Jungsthoefel026cb9bcfb04
diff --git a/.gitignore b/.gitignoreindex 656af86..401c7ce 100644--- a/.gitignore+++ b/.gitignore@@ -19,3 +19,6 @@ prototype/phase0/basic_example/# Betriebssystem und EditorenThumbs.db.DS_Store++# Testausgaben, die sich bei jedem Lauf ändern+app/test/versions.pngdiff --git a/app/README.md b/app/README.mdindex 99ccad2..9905e1f 100644--- a/app/README.md+++ b/app/README.md@@ -1,6 +1,6 @@# CAD-IDE: Desktop-App (Arbeitsname)-Electron-App (TypeScript) für 3D-Modelle mit einem Coding-Agenten im Terminal. Plan: [../PLAN.md](../PLAN.md). Dies ist der Stand von **Phase 1, Schritt 1** (lauffähiges Gerüst).+Electron-App (TypeScript) für 3D-Modelle mit einem Coding-Agenten im Terminal. Plan: [../PLAN.md](../PLAN.md). Stand: **Phase 1, Schritte 1 und 2** (Gerüst, Git und ZIP).## Voraussetzungen@@ -15,23 +15,27 @@ Electron-App (TypeScript) für 3D-Modelle mit einem Coding-Agenten im Terminal.npm installnpm start # baut und startetnpm run typecheck-npm run test:smoke # startet die echte App unsichtbar und prüft 21 Punkte (SMOKE_VISIBLE=1 zeigt das Fenster und macht einen Screenshot)+npm run test:smoke # echte App, unsichtbar: Projekt, Viewer, Terminal, Auto-Build, Fehlerfall (21 Prüfungen)+npm run test:versions # Git-Verlauf, Speichern, Öffnen, Vorschau, Wiederherstellen, Störfälle (46 Prüfungen)+npm test # beide```+`SMOKE_VISIBLE=1` zeigt das Fenster. `SMOKE_VISIBLE=offscreen` zeigt es weit außerhalb des Bildschirms ohne Fokus, dann sind Screenshots (`test/versions.png`) frisch. Ein unsichtbares Fenster zeichnet nicht neu, seine Screenshots sind veraltet, die DOM-Prüfungen sind davon nicht betroffen.+**Windows und Netzlaufwerk:** Liegt `node_modules` auf einem Netzlaufwerk, starten die sandboxed Prozesse von Electron nicht (`launch-failed`, Code 18, schwarzes Fenster). `npm start` und der Test nutzen deshalb automatisch eine lokale Kopie von Electron unter `%LOCALAPPDATA%\cadide-dev\` (`scripts/electron-local.mjs`, einmalig rund 370 MB). Die App selbst darf auf dem Netzlaufwerk liegen. Eine installierte App muss lokal liegen, sonst zeigt sie eine Fehlermeldung.## Aufbau| Pfad | Inhalt ||---|---|-| `src/main/` | Hauptprozess: `workspace.ts` (UUID-Arbeitsordner, Projektzustand doppelt, Projekt-Check nur melden), `build.ts` (Build als Einmal-Prozess mit Entprellung, Warteschlange, Zeitlimit), `watcher.ts`, `terminals.ts` (node-pty, `cadide` im PATH), `files.ts` (Pfadschutz), `agents.ts` |+| `src/main/` | Hauptprozess: `projects.ts` (offenes Projekt, Speichern, Öffnen, Verlauf, Wiederherstellen), `git.ts` (mitgeliefertes Git über dugite), `zip.ts` (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), `dialogs.ts` (native Dialoge, im Test beantwortbar), `watcher.ts`, `terminals.ts` (node-pty, `cadide` und `git` im PATH), `files.ts` (Pfadschutz), `agents.ts` || `src/preload/` | Schmale, feste Schnittstelle zum Renderer (kein Node-Zugriff dort) |-| `src/renderer/` | Oberfläche: `viewer.ts` (three.js, Klick auf Code, Ansichten), `terminals.ts` (xterm.js, Tabs), `main.ts` (Baum, Status, Dateien) |+| `src/renderer/` | Oberfläche: `viewer.ts` (three.js, Klick auf Code, Ansichten), `versions.ts` (Verlaufsleiste), `terminals.ts` (xterm.js, Tabs), `main.ts` (Baum, Status, Dateien, Speichern) || `src/shared/types.ts` | Typen des IPC-Vertrags || `resources/template/` | Vorlage für neue Projekte: `model.py`, `AGENTS.md`, `CLAUDE.md`, `NOTES.md`, `.gitignore` |-| `../python/cadide/` | Hilfsbibliothek und Kommandozeile (`cadide build`, `cadide export`) |-| `test/` | `smoke.mjs` (Ende-zu-Ende), `cdp.mjs` (kleiner DevTools-Client, puppeteer scheitert an Electron 44) |+| `../python/cadide/` | Hilfsbibliothek und Kommandozeile (`cadide build`, `cadide export`, `cadide glb` für Vorschauen) |+| `test/` | `smoke.mjs`, `versions.mjs` (Ende-zu-Ende), `harness.mjs` (App starten und steuern), `cdp.mjs` (kleiner DevTools-Client, puppeteer scheitert an Electron 44) |## Noch nicht enthalten (siehe PLAN.md, Abschnitt 10)-ZIP speichern und öffnen, Git, Projektumgebung mit `pip freeze`, Editor, Screenshot mit Markup, Auto-Start des Agenten, `cadide check`, Bündelung von Python und Installer, macOS und Linux (nur Windows getestet).+Projektumgebung mit `pip freeze`, Editor, Screenshot mit Markup, Auto-Start des Agenten, `cadide check`, Bündelung von Python und Installer, macOS und Linux (nur Windows getestet).diff --git a/app/esbuild.config.mjs b/app/esbuild.config.mjsindex 8596f6f..99c89d9 100644--- a/app/esbuild.config.mjs+++ b/app/esbuild.config.mjs@@ -6,7 +6,7 @@ import path from 'node:path';const common = { bundle: true, sourcemap: true, logLevel: 'info', target: 'es2022' };await Promise.all([build({ ...common, entryPoints: ['src/main/main.ts'], outfile: 'dist/main/main.js', platform: 'node', format: 'cjs',- external: ['electron', 'node-pty'] }),+ external: ['electron', 'node-pty', 'dugite'] }),build({ ...common, entryPoints: ['src/preload/preload.ts'], outfile: 'dist/preload/preload.js', platform: 'node', format: 'cjs',external: ['electron'] }),build({ ...common, entryPoints: ['src/renderer/main.ts'], outfile: 'dist/renderer/main.js', platform: 'browser', format: 'iife' }),diff --git a/app/package-lock.json b/app/package-lock.jsonindex 890392c..0e0ed7a 100644--- a/app/package-lock.json+++ b/app/package-lock.json@@ -10,12 +10,17 @@"dependencies": {"@xterm/addon-fit": "^0.11.0","@xterm/xterm": "^6.0.0",+ "dugite": "^3.2.3","node-pty": "^1.1.0",- "three": "^0.180.0"+ "three": "^0.180.0",+ "yauzl": "^3.4.0",+ "yazl": "^3.3.1"},"devDependencies": {"@types/node": "^22.0.0","@types/three": "^0.180.0",+ "@types/yauzl": "^3.4.0",+ "@types/yazl": "^3.3.1","electron": "^44.4.5","esbuild": "^0.28.2","typescript": "^5.9.0"@@ -548,6 +553,26 @@"dev": true,"license": "MIT"},+ "node_modules/@types/yauzl": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-3.4.0.tgz",+ "integrity": "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },+ "node_modules/@types/yazl": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/@types/yazl/-/yazl-3.3.1.tgz",+ "integrity": "sha512-DIWfCKpsTp6hE5BDBHV3+fIL/bLUF9Bv13iDrWnMlmhQpH67buNvI291ZauQ1xcccxK3FqQ9honnXpq4R8NMuQ==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*"+ }+ },"node_modules/@webgpu/types": {"version": "0.1.74","resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",@@ -570,6 +595,109 @@"addons/*"]},+ "node_modules/b4a": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",+ "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",+ "license": "Apache-2.0",+ "peerDependencies": {+ "react-native-b4a": "*"+ },+ "peerDependenciesMeta": {+ "react-native-b4a": {+ "optional": true+ }+ }+ },+ "node_modules/bare-events": {+ "version": "2.9.2",+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",+ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",+ "license": "Apache-2.0",+ "peerDependencies": {+ "bare-abort-controller": "*"+ },+ "peerDependenciesMeta": {+ "bare-abort-controller": {+ "optional": true+ }+ }+ },+ "node_modules/bare-fs": {+ "version": "4.8.2",+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.2.tgz",+ "integrity": "sha512-+ZI68KHMUvosXfKbg/UOHK0tbCdRnegbvPEdEcZ3Nd6TetieQsJPRXBRXPdLyy8+3VSEbPXtsumTpEtt78xv9w==",+ "license": "Apache-2.0",+ "dependencies": {+ "bare-events": "^2.5.4",+ "bare-path": "^3.0.0",+ "bare-stream": "^2.6.4",+ "bare-url": "^2.2.2",+ "fast-fifo": "^1.3.2"+ },+ "engines": {+ "bare": ">=1.28.0"+ },+ "peerDependencies": {+ "bare-buffer": "*"+ },+ "peerDependenciesMeta": {+ "bare-buffer": {+ "optional": true+ }+ }+ },+ "node_modules/bare-path": {+ "version": "3.1.2",+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.2.tgz",+ "integrity": "sha512-ZyKbsuuqK6Ag0K8pX6V5Txq6XeJRvY+wXucnFGRjiyVYP9YWDpIQugk/b+enRYrEYBJaqLzghRQpXPMR7341Nw==",+ "license": "Apache-2.0"+ },+ "node_modules/bare-stream": {+ "version": "2.13.4",+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",+ "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",+ "license": "Apache-2.0",+ "dependencies": {+ "b4a": "^1.8.1",+ "streamx": "^2.25.0",+ "teex": "^1.0.1"+ },+ "peerDependencies": {+ "bare-abort-controller": "*",+ "bare-buffer": "*",+ "bare-events": "*"+ },+ "peerDependenciesMeta": {+ "bare-abort-controller": {+ "optional": true+ },+ "bare-buffer": {+ "optional": true+ },+ "bare-events": {+ "optional": true+ }+ }+ },+ "node_modules/bare-url": {+ "version": "2.5.4",+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.4.tgz",+ "integrity": "sha512-Gxa7UVWBr0/edU1b+TJhn/AZvMQUj9OGspvYsaTYQrAbZA4BOTZGL3LiZxvD+CeMlDH4juwD84+eTAp/bLYW5g==",+ "license": "Apache-2.0",+ "dependencies": {+ "bare-path": "^3.0.0"+ }+ },+ "node_modules/buffer-crc32": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-1.0.0.tgz",+ "integrity": "sha512-Db1SbgBS/fg/392AblrMJk97KggmvYhr4pB5ZIMTWtaivCPMWLkmb7m21cJvpvgK+J3nsU2CmmixNBZx4vFj/w==",+ "license": "MIT",+ "engines": {+ "node": ">=8.0.0"+ }+ },"node_modules/debug": {"version": "4.4.3","resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",@@ -588,6 +716,20 @@}}},+ "node_modules/dugite": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/dugite/-/dugite-3.2.3.tgz",+ "integrity": "sha512-kPBJ0uevCPY4pcGl0R0+dgC/prPBvnHN9109ZUUWDttkWHz4HqFGwyFri9Btmd2YucAXIJTYMGECh/Q5VAfpfA==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "progress": "^2.0.3",+ "tar-stream": "^3.1.7"+ },+ "engines": {+ "node": ">= 20"+ }+ },"node_modules/electron": {"version": "44.4.5","resolved": "https://registry.npmjs.org/electron/-/electron-44.4.5.tgz",@@ -679,6 +821,21 @@"@esbuild/win32-x64": "0.28.2"}},+ "node_modules/events-universal": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",+ "license": "Apache-2.0",+ "dependencies": {+ "bare-events": "^2.7.0"+ }+ },+ "node_modules/fast-fifo": {+ "version": "1.3.2",+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",+ "license": "MIT"+ },"node_modules/fflate": {"version": "0.8.3","resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",@@ -723,11 +880,16 @@"node-addon-api": "^7.1.0"}},+ "node_modules/pend": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",+ "license": "MIT"+ },"node_modules/progress": {"version": "2.0.3","resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz","integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",- "dev": true,"license": "MIT","engines": {"node": ">=0.4.0"@@ -746,6 +908,17 @@"node": ">=10"}},+ "node_modules/streamx": {+ "version": "2.28.1",+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",+ "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==",+ "license": "MIT",+ "dependencies": {+ "events-universal": "^1.0.0",+ "fast-fifo": "^1.3.2",+ "text-decoder": "^1.1.0"+ }+ },"node_modules/sumchecker": {"version": "3.0.1","resolved": "https://registry.npmjs.org/sumchecker/-/sumchecker-3.0.1.tgz",@@ -759,6 +932,36 @@"node": ">= 8.0"}},+ "node_modules/tar-stream": {+ "version": "3.2.1",+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.1.tgz",+ "integrity": "sha512-nqsEO8zLZJvrOMdEwkA0QdCLFbetHMn95Zqu4fKwX+hkaTWJPZZOrxx/PwtxoK0MMGQmBQNRW3CPs8IFYQz4cQ==",+ "license": "MIT",+ "dependencies": {+ "b4a": "^1.6.4",+ "bare-fs": "^4.5.5",+ "fast-fifo": "^1.2.0",+ "streamx": "^2.15.0"+ }+ },+ "node_modules/teex": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",+ "license": "MIT",+ "dependencies": {+ "streamx": "^2.12.5"+ }+ },+ "node_modules/text-decoder": {+ "version": "1.2.7",+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",+ "license": "Apache-2.0",+ "dependencies": {+ "b4a": "^1.6.4"+ }+ },"node_modules/three": {"version": "0.180.0","resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",@@ -796,6 +999,27 @@"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==","dev": true,"license": "MIT"+ },+ "node_modules/yauzl": {+ "version": "3.4.0",+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.4.0.tgz",+ "integrity": "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw==",+ "license": "MIT",+ "dependencies": {+ "pend": "~1.2.0"+ },+ "engines": {+ "node": ">=12"+ }+ },+ "node_modules/yazl": {+ "version": "3.3.1",+ "resolved": "https://registry.npmjs.org/yazl/-/yazl-3.3.1.tgz",+ "integrity": "sha512-BbETDVWG+VcMUle37k5Fqp//7SDOK2/1+T7X8TD96M3D9G8jK5VLUdQVdVjGi8im7FGkazX7kk5hkU8X4L5Bng==",+ "license": "MIT",+ "dependencies": {+ "buffer-crc32": "^1.0.0"+ }}}}diff --git a/app/package.json b/app/package.jsonindex 28fe9b1..f42493c 100644--- a/app/package.json+++ b/app/package.json@@ -8,17 +8,24 @@"typecheck": "tsc --noEmit","build": "node esbuild.config.mjs","start": "npm run build && node scripts/start.mjs",- "test:smoke": "npm run build && node test/smoke.mjs"+ "test:smoke": "npm run build && node test/smoke.mjs",+ "test:versions": "npm run build && node test/versions.mjs",+ "test": "npm run build && node test/smoke.mjs && node test/versions.mjs"},"dependencies": {"@xterm/addon-fit": "^0.11.0","@xterm/xterm": "^6.0.0",+ "dugite": "^3.2.3","node-pty": "^1.1.0",- "three": "^0.180.0"+ "three": "^0.180.0",+ "yauzl": "^3.4.0",+ "yazl": "^3.3.1"},"devDependencies": {"@types/node": "^22.0.0","@types/three": "^0.180.0",+ "@types/yauzl": "^3.4.0",+ "@types/yazl": "^3.3.1","electron": "^44.4.5","esbuild": "^0.28.2","typescript": "^5.9.0"diff --git a/app/resources/template/.gitignore b/app/resources/template/.gitignoreindex 032f64b..c504aec 100644--- a/app/resources/template/.gitignore+++ b/app/resources/template/.gitignore@@ -9,4 +9,5 @@ __pycache__/.cadide/model.glb.cadide/model.map.json.cadide/build.json+.cadide/zip-info.json.cadide/feedback/diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.mdindex 5382e2d..6561753 100644--- a/app/resources/template/AGENTS.md+++ b/app/resources/template/AGENTS.md@@ -37,6 +37,14 @@ Run them in this terminal. They work without the app.If `cadide build` fails, fix the error before doing anything else. Keep the model buildable at all times.+## Version history (git)++This folder is a git repository, and the `git` on your PATH is the one the app uses. The app shows the commits as a timeline under the 3D view, so the user can look at earlier versions and restore them.++- After every meaningful iteration that **builds successfully** (`cadide build` says "Build ok"), commit it: `git add -A`, then `git commit -m "<short description>"`. Write the message in the language the user speaks. Build first, so `output/model.step` in the commit matches the code.+- Do not rewrite history: no `git reset`, `rebase`, `commit --amend` or `push --force`, no new branches, no `checkout` or `switch` to old commits. To go back to an earlier version, tell the user to use "Restore version" in the app.+- Do not delete or re-create `.git` and do not remove `.gitignore`.+## Environment- Use the `python` and `pip` on your PATH. They belong to this app. **Do not create virtual environments** (`.venv`, `venv`) and do not install packages globally.diff --git a/app/src/main/build.ts b/app/src/main/build.tsindex e8b29bd..d2d5c16 100644--- a/app/src/main/build.ts+++ b/app/src/main/build.ts@@ -1,4 +1,6 @@import { spawn, type ChildProcess } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';import { EventEmitter } from 'node:events';import type { BuildResult, BuildStatus } from '../shared/types';import { pythonExe } from './paths';@@ -76,6 +78,20 @@ export class BuildManager extends EventEmitter {});}+ /** Läuft gerade ein Build oder steht einer an? */+ get busy(): boolean { return this.proc !== null || this.timer !== null; }++ /** Wartet, bis kein Build mehr läuft oder ansteht (mit Zeitlimit, damit Speichern nie ewig hängt). */+ whenIdle(timeoutMs = 120000): Promise<void> {+ if (!this.busy) return Promise.resolve();+ return new Promise((resolve) => {+ const done = () => { clearTimeout(t); this.off('status', onStatus); resolve(); };+ const onStatus = () => { if (!this.busy) done(); };+ const t = setTimeout(done, timeoutMs);+ this.on('status', onStatus);+ });+ }+cancel(): void {this.rerun = false;if (this.timer) { clearTimeout(this.timer); this.timer = null; }@@ -97,3 +113,42 @@ export class BuildManager extends EventEmitter {function errorResult(kind: string, message: string): BuildResult {return { status: 'error', error: { kind, message, file: null, line: null, traceback: '' } };}++/** Neuester Änderungszeitpunkt von Einstiegspunkt, parts/ und inputs/ (Quelltext des Modells). */+export function newestSourceMtime(dir: string): number {+ let newest = 0;+ const walk = (d: string, depth: number) => {+ if (depth > 4) return;+ let entries: fs.Dirent[];+ try { entries = fs.readdirSync(d, { withFileTypes: true }); } catch { return; }+ for (const e of entries) {+ if (e.isSymbolicLink()) continue;+ const p = path.join(d, e.name);+ if (e.isDirectory()) walk(p, depth + 1);+ else try { newest = Math.max(newest, fs.statSync(p).mtimeMs); } catch { /* verschwunden */ }+ }+ };+ for (const top of ['parts', 'inputs']) walk(path.join(dir, top), 0);+ for (const f of fs.readdirSync(dir)) if (f.endsWith('.py')) try { newest = Math.max(newest, fs.statSync(path.join(dir, f)).mtimeMs); } catch { /* weg */ }+ return newest;+}++/** Ist der Quelltext neuer als das letzte Build-Ergebnis (oder gibt es noch keines)? */+export function buildIsStale(dir: string): boolean {+ try { return newestSourceMtime(dir) > fs.statSync(path.join(dir, '.cadide', 'build.json')).mtimeMs; } catch { return true; }+}++/** Führt `python -m cadide <args>` aus (z. B. glb für Vorschauen). Kein Wurf: das Ergebnis trägt den Fehler. */+export function runCadide(args: string[], cwd: string, timeoutMs = 120000): Promise<{ ok: boolean; out: string; err: string }> {+ return new Promise((resolve) => {+ const child = spawn(pythonExe(), ['-m', 'cadide', ...args], {+ cwd, windowsHide: true, env: { ...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' },+ });+ let out = '', err = '';+ child.stdout.on('data', (d: Buffer) => { out += d.toString('utf8'); });+ child.stderr.on('data', (d: Buffer) => { err += d.toString('utf8'); });+ const timer = setTimeout(() => child.kill(), timeoutMs);+ child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, out, err: e.message }); });+ child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, out, err }); });+ });+}diff --git a/app/src/main/dialogs.ts b/app/src/main/dialogs.tsnew file mode 100644index 0000000..f04b569--- /dev/null+++ b/app/src/main/dialogs.ts@@ -0,0 +1,43 @@+import { app, dialog, type BrowserWindow } from 'electron';+import path from 'node:path';++/**+ * Alle Dialoge laufen hier durch. Im Testmodus (CADIDE_TEST=1) beantwortet eine vorbereitete Warteschlange sie,+ * damit Tests nicht an nativen Fenstern hängen. Ist die Schlange leer, schlägt der Aufruf laut fehl.+ */+const testMode = () => process.env.CADIDE_TEST === '1';+const answers: unknown[] = [];+export const setTestAnswers = (a: unknown[]) => { answers.length = 0; answers.push(...a); };+export const pendingTestAnswers = () => answers.length;++function nextAnswer<T>(what: string): T {+ if (!answers.length) throw new Error(`Testmodus: Für den Dialog „${what}“ ist keine Antwort vorbereitet.`);+ return answers.shift() as T;+}++export async function choosePath(win: BrowserWindow | null, kind: 'save' | 'open', defaultName: string): Promise<string | null> {+ if (testMode()) return nextAnswer<string | null>(`${kind}-Pfad`);+ const filters = [{ name: 'CAD-IDE-Modell (ZIP)', extensions: ['zip'] }];+ const defaultPath = path.join(app.getPath('documents'), defaultName);+ if (kind === 'save') {+ const r = win ? await dialog.showSaveDialog(win, { title: 'Modell speichern', defaultPath, filters }) : await dialog.showSaveDialog({ title: 'Modell speichern', defaultPath, filters });+ return r.canceled || !r.filePath ? null : r.filePath;+ }+ const opts = { title: 'Modell öffnen', filters, 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];+}++/** Liefert den Index des gewählten Knopfs. Der letzte Knopf gilt als Abbrechen (Esc, Fenster schließen). */+export async function choose(win: BrowserWindow | null, o: { title: string; message: string; detail?: string; buttons: string[] }): Promise<number> {+ if (testMode()) return nextAnswer<number>(o.title);+ const opts = { type: 'question' as const, title: o.title, message: o.message, detail: o.detail, buttons: o.buttons, defaultId: 0, cancelId: o.buttons.length - 1, noLink: true };+ const r = win ? await dialog.showMessageBox(win, opts) : await dialog.showMessageBox(opts);+ return r.response;+}++export function notify(win: BrowserWindow | null, title: string, message: string): void {+ if (testMode()) return;+ if (win) void dialog.showMessageBox(win, { type: 'info', title, message });+ else void dialog.showMessageBox({ type: 'info', title, message });+}diff --git a/app/src/main/git.ts b/app/src/main/git.tsnew file mode 100644index 0000000..fa5f49c--- /dev/null+++ b/app/src/main/git.ts@@ -0,0 +1,172 @@+import { exec, spawn } from 'dugite';+import fs from 'node:fs';+import path from 'node:path';+import { resolveInside } from './files';++export interface Commit { hash: string; short: string; author: string; date: string; subject: string }+export interface RunResult { ok: boolean; code: number; out: string; err: string }+export interface GitStatus { dirty: boolean; changed: number; head: string | null }++/** Gilt für jeden Aufruf: UTF-8-Pfade lesbar, keine Zeilenenden-Umwandlung (ZIPs wandern zwischen Systemen). */+const COMMON = ['-c', 'core.quotepath=false', '-c', 'core.autocrlf=false'];+/** `output/` zählt nicht als Änderung: STEP-Dateien sind nicht byte-stabil (Zeitstempel, teils Reihenfolge). */+const NOT_OUTPUT = ['--', '.', ':(exclude)output'];+const HASH = /^[0-9a-f]{7,40}$/;+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++/**+ * Das Git-Repository eines Projekts (mitgeliefertes Git, E31). Der Agent committet unabhängig von der App (E7),+ * deshalb: App-eigene Schreibvorgänge laufen nacheinander und wiederholen sich bei gesperrtem Index,+ * lesende Aufrufe nehmen keine Sperren. Nichts hier baut den Verlauf um (kein Reset, kein Checkout, keine Branches, E35).+ */+export class GitRepo {+ private chain: Promise<unknown> = Promise.resolve();+ constructor(readonly dir: string) {}++ private serial<T>(fn: () => Promise<T>): Promise<T> {+ const r = this.chain.then(fn, fn);+ this.chain = r.catch(() => undefined);+ return r;+ }++ /** Ein Git-Aufruf. `write` = ändert das Repository (mit Wiederholung bei index.lock). */+ async run(args: string[], write = false): Promise<RunResult> {+ for (let attempt = 0; ; attempt++) {+ const r = await exec([...COMMON, ...args], this.dir, { env: write ? {} : { GIT_OPTIONAL_LOCKS: '0' } });+ const res: RunResult = { ok: r.exitCode === 0, code: r.exitCode, out: String(r.stdout), err: String(r.stderr) };+ const locked = !res.ok && /index\.lock|Unable to create .*\.lock|another git process/i.test(res.err);+ if (!locked || attempt >= 8) return res;+ await sleep(250);+ }+ }++ private async mustRun(args: string[], write = false): Promise<string> {+ const r = await this.run(args, write);+ if (!r.ok) throw new Error(`git ${args[0]} fehlgeschlagen: ${(r.err || r.out).trim().slice(0, 400)}`);+ return r.out;+ }++ /**+ * Ist `dir` selbst ein Repository (und nicht nur Teil eines übergeordneten)? Liegt das Repository direkt hier, meldet+ * `rev-parse --git-dir` schlicht ".git". Ein Pfadvergleich wäre fragil (Windows-Kurznamen wie NAME~1, Groß-/Kleinschreibung).+ */+ async isRepo(): Promise<boolean> {+ if (!fs.existsSync(path.join(this.dir, '.git'))) return false;+ const r = await this.run(['rev-parse', '--git-dir']);+ return r.ok && r.out.trim() === '.git';+ }++ /** Neues Repository mit erstem Commit. Nur für neue Projekte, nie als stille Reparatur. */+ async init(message: string): Promise<string> {+ return this.serial(async () => {+ await this.mustRun(['init', '-b', 'main'], true);+ await this.mustRun(['config', '--local', 'core.autocrlf', 'false'], true);+ await this.mustRun(['config', '--local', 'core.longpaths', 'true'], true);+ // Ohne eingerichtete Identität würden auch die Commits des Agenten scheitern.+ const name = await this.run(['config', 'user.name']);+ const email = await this.run(['config', 'user.email']);+ if (!name.out.trim()) await this.mustRun(['config', '--local', 'user.name', 'CAD-IDE'], true);+ if (!email.out.trim()) await this.mustRun(['config', '--local', 'user.email', 'cadide@localhost'], true);+ await this.mustRun(['add', '-A'], true);+ await this.mustRun(['commit', '--allow-empty', '--no-verify', '-m', message], true);+ return (await this.mustRun(['rev-parse', 'HEAD'])).trim();+ });+ }++ async head(): Promise<string | null> {+ const r = await this.run(['rev-parse', '--verify', '-q', 'HEAD']);+ return r.ok ? r.out.trim() : null;+ }++ async status(): Promise<GitStatus> {+ const r = await this.run(['status', '--porcelain=v1', '-z', '--untracked-files=all', ...NOT_OUTPUT]);+ const changed = r.ok ? r.out.split('\0').filter(Boolean).length : 0;+ return { dirty: changed > 0, changed, head: await this.head() };+ }++ /** Auto-Snapshot (E8): committet nur, wenn Quelltext, Eingaben oder Einstellungen geändert sind. Liefert den neuen Hash. */+ async snapshot(message: string): Promise<string | null> {+ return this.serial(async () => {+ if (!(await this.status()).dirty) return null;+ await this.mustRun(['add', '-A'], true);+ await this.mustRun(['commit', '--no-verify', '-m', message], true);+ return (await this.mustRun(['rev-parse', 'HEAD'])).trim();+ });+ }++ /** Verlauf, älteste zuerst. Ein kaputtes oder leeres Repository liefert eine leere Liste. */+ async log(limit = 500): Promise<Commit[]> {+ const r = await this.run(['log', `-n${limit}`, '--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s%x1e', 'HEAD']);+ if (!r.ok) return [];+ return r.out.split('\x1e').map((e) => e.trim()).filter(Boolean).map((e) => {+ const [hash, short, author, date, subject] = e.split('\x1f');+ return { hash, short, author, date, subject };+ }).reverse();+ }++ /** Schreibt eine Datei eines Standes in `outFile` (binärsicher, Arbeitsordner bleibt unberührt). */+ exportFile(hash: string, rel: string, outFile: string): Promise<void> {+ if (!HASH.test(hash)) return Promise.reject(new Error('Ungültiger Commit'));+ return new Promise((resolve, reject) => {+ fs.mkdirSync(path.dirname(outFile), { recursive: true });+ const child = spawn([...COMMON, 'show', `${hash}:${rel}`], this.dir, { env: { GIT_OPTIONAL_LOCKS: '0' } });+ const out = fs.createWriteStream(outFile);+ let err = '';+ child.stderr?.on('data', (d: Buffer) => { err += d.toString(); });+ child.stdout?.pipe(out);+ child.on('error', reject);+ child.on('close', (code) => {+ out.end();+ if (code === 0) resolve(); else { fs.rmSync(outFile, { force: true }); reject(new Error(err.trim() || `git show endete mit Code ${code}`)); }+ });+ });+ }++ /**+ * Stand wiederherstellen (E35): Dateien des gewählten Stands in den Arbeitsordner kopieren und als NEUEN Commit ablegen.+ * Vorher wird ein ungesicherter Arbeitsstand als eigener Commit gesichert, damit nichts verloren geht.+ */+ async restore(hash: string): Promise<{ commit: string | null; safety: string | null }> {+ if (!HASH.test(hash)) throw new Error('Ungültiger Commit');+ return this.serial(async () => {+ const type = await this.run(['cat-file', '-t', hash]);+ if (!type.ok || type.out.trim() !== 'commit') throw new Error('Dieser Stand existiert im Verlauf nicht mehr.');+ const subject = (await this.mustRun(['log', '-1', '--format=%s', hash])).trim();+ const short = (await this.mustRun(['rev-parse', '--short', hash])).trim();++ let safety: string | null = null;+ if ((await this.status()).dirty) {+ await this.mustRun(['add', '-A'], true);+ await this.mustRun(['commit', '--no-verify', '-m', 'Sicherung vor Wiederherstellung'], true);+ safety = (await this.mustRun(['rev-parse', 'HEAD'])).trim();+ }+ const target = new Set((await this.mustRun(['ls-tree', '-r', '-z', '--name-only', hash])).split('\0').filter(Boolean));+ const current = (await this.mustRun(['ls-files', '-z'])).split('\0').filter(Boolean);+ for (const f of current) {+ if (!target.has(f)) fs.rmSync(resolveInside(this.dir, f), { force: true });+ }+ await this.mustRun(['restore', `--source=${hash}`, '--staged', '--worktree', '--', '.'], true);+ await this.mustRun(['add', '-A'], true);+ const diff = await this.run(['diff', '--cached', '--quiet']);+ if (diff.ok) return { commit: null, safety }; // Stand war schon identisch+ await this.mustRun(['commit', '--no-verify', '-m', `Stand wiederhergestellt: ${subject} (${short})`], true);+ return { commit: (await this.mustRun(['rev-parse', 'HEAD'])).trim(), safety };+ });+ }++ /** Auffälligkeiten im Verlauf. Nur melden, nichts reparieren (E28). */+ async problems(): Promise<string[]> {+ if (!(await this.isRepo())) return ['Kein Git-Verlauf gefunden (.git fehlt oder ist unlesbar). Der Verlauf ist nicht verfügbar, Speichern als ZIP geht weiter.'];+ const out: string[] = [];+ if (!(await this.head())) out.push('Der Git-Verlauf hat noch keinen Commit.');+ const branch = await this.run(['symbolic-ref', '-q', '--short', 'HEAD']);+ if (!branch.ok) out.push('Git steht auf einem losen Stand (detached HEAD). Neue Commits gehören auf den Branch main.');+ else if (branch.out.trim() !== 'main') out.push(`Git steht auf dem Branch „${branch.out.trim()}“ statt main.`);+ return out;+ }++ async isAncestor(ancestor: string, of: string): Promise<boolean> {+ if (!HASH.test(ancestor) || !HASH.test(of)) return false;+ return (await this.run(['merge-base', '--is-ancestor', ancestor, of])).ok;+ }+}diff --git a/app/src/main/main.ts b/app/src/main/main.tsindex b4f2d25..007b0f0 100644--- a/app/src/main/main.ts+++ b/app/src/main/main.ts@@ -1,125 +1,118 @@import { app, BrowserWindow, dialog, ipcMain, type WebContents } from 'electron';import fs from 'node:fs';import path from 'node:path';-import type { ProjectInfo } from '../shared/types';import { detectAgents } from './agents';-import { BuildManager } from './build';+import { setTestAnswers } from './dialogs';import { listFiles, resolveInside } from './files';-import { TerminalManager, terminalEnv } from './terminals';-import { watchProject } from './watcher';-import { createProject, getLastProject, inspectProject, listProjects, projectDir, setLastProject } from './workspace';+import { ProjectController } from './projects';+import { terminalEnv } from './terminals';+import { createProject, getLastProject } from './workspace';// App-Daten (Arbeitsordner, Caches) gehören auf die lokale Platte. Das Roaming-Profil (%APPDATA%) kann in Firmennetzen// umgeleitet oder synchronisiert sein, das ist für Arbeitsordner und GPU-Cache ungeeignet. Tests leiten alles um.if (process.env.CADIDE_USER_DATA) app.setPath('userData', process.env.CADIDE_USER_DATA);else if (process.platform === 'win32' && process.env.LOCALAPPDATA) app.setPath('userData', path.join(process.env.LOCALAPPDATA, 'cadide'));-/** Alles, was zu einem geoeffneten Projekt gehoert. Beim Wechsel wird es vollstaendig abgebaut. */-interface Session {- id: string;- dir: string;- builds: BuildManager;- terminals: TerminalManager;- stopWatch: () => void;-}-let win: BrowserWindow | null = null;-let session: Session | null = null;--function info(): ProjectInfo {- if (!session) throw new Error('Kein Projekt geöffnet');- const { name, problems } = inspectProject(session.id);- return { id: session.id, name, dir: session.dir, problems, autoBuild: session.builds.autoBuild };-}-function closeSession(): void {- if (!session) return;- session.stopWatch();- session.builds.dispose();- session.terminals.killAll();- session = null;-}--function openSession(id: string, wc: WebContents): ProjectInfo {- closeSession();- const dir = projectDir(id);- const builds = new BuildManager(dir);- const terminals = new TerminalManager(wc, dir);- builds.on('status', (s) => { if (!wc.isDestroyed()) wc.send('build:status', s); });- const stopWatch = watchProject(dir, () => builds.sourceChanged(), () => { if (!wc.isDestroyed()) wc.send('fs:changed'); });- session = { id, dir, builds, terminals, stopWatch };- setLastProject(id);- // Erster Build direkt beim Öffnen, damit der Viewer nicht leer ist (der Nutzer kann Auto-Build danach abschalten).- builds.start('Projekt geöffnet');- return info();-}+function registerIpc(ctl: ProjectController): void {+ const dir = () => ctl.need().dir;-function registerIpc(wc: WebContents): void {- const need = (): Session => { if (!session) throw new Error('Kein Projekt geöffnet'); return session; };+ ipcMain.handle('project:current', () => ctl.info());+ ipcMain.handle('project:create', () => ctl.create());+ ipcMain.handle('project:list', async () => (await import('./workspace')).listProjects());+ ipcMain.handle('project:open', (_e, id: string) => ctl.open(id));+ ipcMain.handle('project:saveState', () => ctl.saveState());+ ipcMain.handle('project:save', (_e, saveAs?: boolean) => ctl.save(!!saveAs));+ ipcMain.handle('project:openZip', () => ctl.openZip());- ipcMain.handle('project:current', () => info());- ipcMain.handle('project:create', () => { const { id } = createProject(); const p = openSession(id, wc); wc.send('project:changed', p); return p; });- ipcMain.handle('project:list', () => listProjects());- ipcMain.handle('project:open', (_e, id: string) => { const p = openSession(id, wc); wc.send('project:changed', p); return p; });+ ipcMain.handle('versions:log', () => ctl.gitLog());+ ipcMain.handle('versions:preview', (_e, hash: string) => ctl.preview(hash));+ ipcMain.handle('versions:restore', (_e, hash: string) => ctl.restore(hash));- ipcMain.handle('build:run', () => need().builds.start('manuell'));- ipcMain.handle('build:cancel', () => need().builds.cancel());- ipcMain.handle('build:setAuto', (_e, on: boolean) => { need().builds.autoBuild = !!on; });- ipcMain.handle('build:status', () => need().builds.status);+ ipcMain.handle('build:run', () => ctl.need().builds.start('manuell'));+ ipcMain.handle('build:cancel', () => ctl.need().builds.cancel());+ ipcMain.handle('build:setAuto', (_e, on: boolean) => { ctl.need().builds.autoBuild = !!on; });+ ipcMain.handle('build:status', () => ctl.need().builds.status);- ipcMain.handle('fs:list', () => listFiles(need().dir));- ipcMain.handle('fs:readText', (_e, rel: string) => fs.readFileSync(resolveInside(need().dir, rel), 'utf8'));+ ipcMain.handle('fs:list', () => listFiles(dir()));+ ipcMain.handle('fs:readText', (_e, rel: string) => fs.readFileSync(resolveInside(dir(), rel), 'utf8'));ipcMain.handle('fs:readBinary', (_e, rel: string) => {- const b = fs.readFileSync(resolveInside(need().dir, rel));+ const b = fs.readFileSync(resolveInside(dir(), rel));return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength);});- ipcMain.handle('term:create', (_e, opts?: { command?: string }) => need().terminals.create(opts));- ipcMain.on('term:write', (_e, id: number, data: string) => session?.terminals.write(id, data));- ipcMain.on('term:resize', (_e, id: number, cols: number, rows: number) => session?.terminals.resize(id, cols, rows));- ipcMain.on('term:kill', (_e, id: number) => session?.terminals.kill(id));+ ipcMain.handle('term:create', (_e, opts?: { command?: string }) => ctl.need().terminals.create(opts));+ ipcMain.on('term:write', (_e, id: number, data: string) => ctl.session?.terminals.write(id, data));+ ipcMain.on('term:resize', (_e, id: number, cols: number, rows: number) => ctl.session?.terminals.resize(id, cols, rows));+ ipcMain.on('term:kill', (_e, id: number) => ctl.session?.terminals.kill(id));++ ipcMain.handle('agents:detect', () => detectAgents(terminalEnv(dir())));- ipcMain.handle('agents:detect', () => detectAgents(terminalEnv(need().dir)));+ // Nur im Testmodus: vorbereitete Antworten für Dialoge (siehe dialogs.ts)+ if (process.env.CADIDE_TEST === '1') {+ ipcMain.handle('test:answers', (_e, a: unknown[]) => setTestAnswers(a));+ // Screenshot auch aus unsichtbaren Fenstern (CDP liefert dort kein Bild)+ ipcMain.handle('test:screenshot', async (e, file: string) => {+ const img = await e.sender.capturePage();+ fs.writeFileSync(file, img.toPNG());+ return img.getSize();+ });+ }}+function onRendererGone(wc: WebContents, reason: string, exitCode: number): void {+ console.error(`[cadide] Renderer-Prozess beendet: Grund=${reason} Code=${exitCode}`);+ if (reason === 'launch-failed' && process.env.CADIDE_HIDDEN !== '1') {+ // Häufigste Ursache unter Windows: das Programm liegt auf einem Netzlaufwerk. Die sandboxed Prozesse laufen mit+ // eingeschränktem Token, verlieren dort den Zugriff und starten nicht. Ohne Meldung bliebe nur ein schwarzes Fenster.+ dialog.showErrorBox('CAD-IDE kann die Oberfläche nicht starten',+ `Der Anzeigeprozess ließ sich nicht starten (Code ${exitCode}).\n\nHäufige Ursache: Das Programm liegt auf einem Netzlaufwerk. ` ++ 'Installiere oder starte es von einer lokalen Platte (z. B. C:).');+ app.quit();+ }+ void wc;+}++/** Tests: CADIDE_HIDDEN=1 unsichtbar (zeichnet nicht neu), =offscreen angezeigt, aber weit außerhalb des Bildschirms und ohne Fokus. */+const testWindowMode = process.env.CADIDE_HIDDEN;+function createWindow(): void {win = new BrowserWindow({- width: 1600, height: 950, title: 'CAD-IDE', backgroundColor: '#1e2227', show: process.env.CADIDE_HIDDEN !== '1',+ width: 1600, height: 950, title: 'CAD-IDE', backgroundColor: '#1e2227', show: testWindowMode !== '1' && testWindowMode !== 'offscreen',webPreferences: {preload: path.join(__dirname, '..', 'preload', 'preload.js'),contextIsolation: true, nodeIntegration: false, sandbox: true,- backgroundThrottling: process.env.CADIDE_HIDDEN !== '1', // unsichtbare Testfenster sollen trotzdem zeichnen+ backgroundThrottling: !testWindowMode || testWindowMode === '0', // Testfenster sollen trotzdem zeichnen},});win.setMenuBarVisibility(false);+ if (testWindowMode === 'offscreen') { win.setBounds({ x: -20000, y: -20000, width: 1600, height: 950 }); win.showInactive(); }const wc = win.webContents;- registerIpc(wc);+ const ctl = new ProjectController(() => win, wc);+ registerIpc(ctl);// Stürzt der Anzeigeprozess ab, steht der Grund im Protokoll (sonst bliebe nur ein schwarzes Fenster).- wc.on('render-process-gone', (_e, d) => {- console.error(`[cadide] Renderer-Prozess beendet: Grund=${d.reason} Code=${d.exitCode}`);- if (d.reason === 'launch-failed' && process.env.CADIDE_HIDDEN !== '1') {- // Häufigste Ursache unter Windows: das Programm liegt auf einem Netzlaufwerk. Die sandboxed Prozesse laufen mit- // eingeschränktem Token, verlieren dort den Zugriff und starten nicht. Ohne Meldung bliebe nur ein schwarzes Fenster.- dialog.showErrorBox('CAD-IDE kann die Oberfläche nicht starten',- `Der Anzeigeprozess ließ sich nicht starten (Code ${d.exitCode}).--Häufige Ursache: Das Programm liegt auf einem Netzlaufwerk. ` +- 'Installiere oder starte es von einer lokalen Platte (z. B. C:).');- app.quit();- }- });+ wc.on('render-process-gone', (_e, d) => onRendererGone(wc, d.reason, d.exitCode));wc.on('unresponsive', () => console.error('[cadide] Renderer reagiert nicht'));wc.on('console-message', (_e, level, message, line, source) => { if (level >= 2) console.error(`[renderer] ${message} (${source}:${line})`); });wc.once('did-finish-load', () => {- // Zuletzt geöffnetes Projekt, sonst ein neues. Vor dem Öffnen kann der Renderer schon fragen, daher hier zuerst.- const last = getLastProject();- const id = last ?? createProject().id;- const p = openSession(id, wc);- wc.send('project:changed', p);+ // Zuletzt geöffnetes Projekt (ungespeicherter Arbeitsstand bleibt so nach einem Absturz erhalten), sonst ein neues.+ void (async () => {+ try { await ctl.open(getLastProject() ?? (await createProject()).id); }+ catch (e) { console.error('[cadide] Projekt konnte nicht geöffnet werden:', e); }+ })();});win.loadFile(path.join(__dirname, '..', 'renderer', 'index.html'));- win.on('closed', () => { closeSession(); win = null; });++ // Schließen: bei ungespeicherten Änderungen nachfragen (der Arbeitsstand bleibt in jedem Fall erhalten)+ let allowClose = false;+ win.on('close', (e) => {+ if (allowClose) return;+ e.preventDefault();+ void ctl.confirmClose().then((ok) => { if (ok) { allowClose = true; win?.close(); } });+ });+ win.on('closed', () => { ctl.close(); win = null; });}app.whenReady().then(createWindow);-app.on('window-all-closed', () => { closeSession(); app.quit(); });+app.on('window-all-closed', () => app.quit());diff --git a/app/src/main/paths.ts b/app/src/main/paths.tsindex 01c29c0..41209ed 100644--- a/app/src/main/paths.ts+++ b/app/src/main/paths.ts@@ -11,6 +11,10 @@ export const workspacesDir = () => path.join(userDataDir(), 'workspaces');/** Zweite Kopie des Projektzustands ausserhalb des Arbeitsordners (E27). */export const projectStateDir = () => path.join(userDataDir(), 'projects');export const appStateFile = () => path.join(userDataDir(), 'state.json');+/** Gesicherte Arbeitsordner (wenn eine ZIP den Arbeitsstand ersetzt). */+export const backupsDir = () => path.join(userDataDir(), 'workspace-backups');+/** Vorschauen alter Stände (aus dem Verlauf erzeugt, jederzeit neu erzeugbar). */+export const previewsDir = () => path.join(userDataDir(), 'previews');/** Vorlage fuer neue Projekte (liegt neben dem Programm, spaeter im Installationspaket). */export const templateDir = () => path.join(app.getAppPath(), 'resources', 'template');@@ -28,6 +32,14 @@ export function pythonExe(): string {return process.platform === 'win32' ? 'python.exe' : 'python3';}+/** Ordner des mitgelieferten Git (dugite). Kommt in die Terminals, damit Agent und App dasselbe Git benutzen (E31). */+export function gitCmdDir(): string | null {+ try {+ // eslint-disable-next-line @typescript-eslint/no-require-imports+ return path.dirname((require('dugite') as typeof import('dugite')).resolveGitBinary());+ } catch { return null; }+}+/** Ordner mit python und cadide-Startprogramm, kommt bei Terminals an den Anfang von PATH. */export function pythonBinDir(): string | null {const exe = pythonExe();diff --git a/app/src/main/projects.ts b/app/src/main/projects.tsnew file mode 100644index 0000000..af0ee2a--- /dev/null+++ b/app/src/main/projects.ts@@ -0,0 +1,298 @@+import type { BrowserWindow, WebContents } from 'electron';+import fs from 'node:fs';+import path from 'node:path';+import type { GitLog, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState } from '../shared/types';+import { BuildManager, buildIsStale, newestSourceMtime, runCadide } from './build';+import { choose, choosePath } from './dialogs';+import { GitRepo } from './git';+import { previewsDir } from './paths';+import { TerminalManager } from './terminals';+import { watchProject } from './watcher';+import {+ backupWorkspace, createProject, extractProject, getAppState, inspectProject, isProjectId, patchAppState, projectDir,+ readProjectJson, renameProject, setLastProject,+} from './workspace';+import { readZipTexts, saveProjectZip, ZIP_INFO_PATH, type ZipInfo } from './zip';++/** Alles, was zu einem geöffneten Projekt gehört. Beim Wechsel wird es vollständig abgebaut. */+interface Session {+ id: string;+ dir: string;+ builds: BuildManager;+ terminals: TerminalManager;+ git: GitRepo;+ stopWatch: () => void;+ poll: NodeJS.Timeout;+ signature: string;+}++const POLL_MS = 2000;+const safeFileName = (n: string) => n.replace(/[<>:"/\\|?*\x00-\x1f]/g, '_').trim() || 'Modell';++/**+ * Das offene Projekt und alles, was mit Speichern, Öffnen und Verlauf zu tun hat.+ *+ * Grundsätze: Speichern nur ausdrücklich (E21). Nichts wird still überschrieben oder gelöscht: ein Arbeitsordner, den eine+ * ZIP ersetzt, wandert in die Sicherungen. Der Agent committet selbst, die App legt nur beim Speichern einen Snapshot an (E8).+ */+export class ProjectController {+ session: Session | null = null;++ constructor(private readonly getWin: () => BrowserWindow | null, private readonly wc: WebContents) {}++ private send(channel: string, ...args: unknown[]) { if (!this.wc.isDestroyed()) this.wc.send(channel, ...args); }+ need(): Session { if (!this.session) throw new Error('Kein Projekt geöffnet'); return this.session; }++ // ---- Sitzung ----------------------------------------------------------------------------------------------------++ info(): ProjectInfo {+ const s = this.need();+ const { name, problems } = inspectProject(s.id);+ return { id: s.id, name, dir: s.dir, problems, autoBuild: s.builds.autoBuild };+ }++ close(): void {+ const s = this.session;+ if (!s) return;+ clearInterval(s.poll);+ s.stopWatch();+ s.builds.dispose();+ s.terminals.killAll();+ this.session = null;+ }++ async open(id: string): Promise<ProjectInfo> {+ this.close();+ const dir = projectDir(id);+ const builds = new BuildManager(dir);+ const terminals = new TerminalManager(this.wc, dir);+ const git = new GitRepo(dir);+ builds.on('status', (st) => this.send('build:status', st));+ const stopWatch = watchProject(dir, () => builds.sourceChanged(), () => this.send('fs:changed'));+ const session: Session = { id, dir, builds, terminals, git, stopWatch, signature: '', poll: setInterval(() => void this.pollGit(), POLL_MS) };+ this.session = session;+ setLastProject(id);+ // Erster Build direkt beim Öffnen, damit der Viewer nicht leer ist (der Nutzer kann Auto-Build danach abschalten).+ builds.start('Projekt geöffnet');+ const info = this.info();+ this.send('project:changed', info);+ return info;+ }++ async create(): Promise<ProjectInfo> {+ const { id } = await createProject();+ return this.open(id);+ }++ /** Meldet dem Fenster, wenn sich Verlauf oder Änderungsstand geändert haben (auch durch Commits des Agenten). */+ private async pollGit(): Promise<void> {+ const s = this.session;+ if (!s) return;+ try {+ const hasRepo = fs.existsSync(path.join(s.dir, '.git'));+ const st = hasRepo ? await s.git.status() : { head: null, changed: 0 };+ const sig = `${hasRepo ? 1 : 0}|${st.head}|${st.changed}`;+ if (this.session !== s || sig === s.signature) return;+ s.signature = sig;+ this.send('versions:changed');+ this.send('save:state', await this.saveState());+ } catch { /* nächster Durchlauf */ }+ }++ // ---- Speicherstand ----------------------------------------------------------------------------------------------++ async saveState(): Promise<SaveState> {+ const s = this.need();+ const app = getAppState(s.id);+ const hasRepo = await s.git.isRepo();+ const st = hasRepo ? await s.git.status() : { dirty: false, changed: 0, head: null };+ let unsaved: boolean;+ if (!app.zipPath) unsaved = true;+ else if (hasRepo) unsaved = st.dirty || st.head !== (app.savedHead ?? null);+ else unsaved = newestSourceMtime(s.dir) > (app.savedAt ?? 0); // ohne Git bleibt nur der Zeitvergleich+ return { zipPath: app.zipPath ?? null, savedHead: app.savedHead ?? null, head: st.head, dirtyFiles: st.changed, unsaved, hasRepo };+ }++ /** Speichern: Snapshot im Verlauf, dann ZIP. Fragt beim ersten Mal nach dem Ort. */+ async save(saveAs = false): Promise<SaveResult> {+ const s = this.need();+ const app = getAppState(s.id);+ let zipPath = saveAs ? undefined : app.zipPath;+ if (zipPath && !fs.existsSync(path.dirname(zipPath))) zipPath = undefined; // Zielordner weg (z. B. USB-Stick ab): neu fragen+ if (!zipPath) {+ const pj = readProjectJson(s.id);+ const chosen = await choosePath(this.getWin(), 'save', `${safeFileName(pj?.name ?? 'Modell')}.zip`);+ if (!chosen) return { cancelled: true };+ zipPath = /\.zip$/i.test(chosen) ? chosen : `${chosen}.zip`;+ renameProject(s.id, path.basename(zipPath).replace(/\.zip$/i, '')); // der Modellname folgt dem Dateinamen+ }+ const warnings: string[] = [];+ try {+ // Die ZIP soll das aktuelle Ergebnis enthalten: laufenden Build abwarten, veralteten vorher nachholen.+ if (!s.builds.busy && buildIsStale(s.dir)) s.builds.start('vor dem Speichern');+ await s.builds.whenIdle();+ if (s.builds.status.state === 'error') warnings.push('Der letzte Build ist fehlgeschlagen. Die ZIP enthält den letzten erfolgreichen Stand von output/model.step.');++ let snapshot: string | null = null;+ if (await s.git.isRepo()) {+ try { snapshot = await s.git.snapshot('Automatischer Snapshot beim Speichern'); }+ catch (e) { warnings.push(`Snapshot im Verlauf nicht möglich: ${e instanceof Error ? e.message : String(e)}`); }+ } else warnings.push('Kein Git-Verlauf vorhanden: Es wurde kein Snapshot angelegt.');++ const head = await s.git.head();+ const pj = readProjectJson(s.id);+ const info: ZipInfo = { savedAt: new Date().toISOString(), head, id: s.id, name: pj?.name ?? s.id };+ const r = await saveProjectZip(s.dir, zipPath, info);+ patchAppState(s.id, { zipPath, savedHead: head, savedAt: Date.now() });+ this.send('save:state', await this.saveState());+ this.send('versions:changed');+ return { cancelled: false, zipPath, snapshot, files: r.files, bytes: r.bytes, warnings };+ } catch (e) {+ return { cancelled: false, error: `Speichern fehlgeschlagen: ${e instanceof Error ? e.message : String(e)}` };+ }+ }++ // ---- Öffnen -----------------------------------------------------------------------------------------------------++ async openZip(): Promise<OpenResult> {+ const picked = await choosePath(this.getWin(), 'open', '');+ if (!picked) return { cancelled: true };+ return this.openZipFile(picked);+ }++ /**+ * Öffnet eine ZIP als Projekt (E21). Existiert der Arbeitsordner schon, entscheidet der Nutzer bei Abweichungen:+ * Arbeitsstand behalten oder ZIP laden. Beim Laden wandert der Arbeitsordner in die Sicherungen, nichts wird gelöscht.+ */+ async openZipFile(zipPath: string): Promise<OpenResult> {+ let texts: Record<string, string | null>;+ try { texts = await readZipTexts(zipPath, ['.cadide/project.json', ZIP_INFO_PATH]); }+ catch (e) { return { cancelled: false, error: `Die ZIP lässt sich nicht lesen: ${e instanceof Error ? e.message : String(e)}` }; }+ let id: string;+ let info: ZipInfo | null = null;+ try {+ id = (JSON.parse(texts['.cadide/project.json'] ?? '') as { id?: string }).id ?? '';+ if (texts[ZIP_INFO_PATH]) info = JSON.parse(texts[ZIP_INFO_PATH]!) as ZipInfo;+ } catch { id = ''; }+ if (!isProjectId(id)) return { cancelled: false, error: 'Das ist keine CAD-IDE-Datei (.cadide/project.json fehlt oder ist ungültig).' };++ const dir = projectDir(id);+ const remember = () => patchAppState(id, { zipPath, savedHead: info?.head ?? null, savedAt: Date.now() });++ if (!fs.existsSync(dir)) {+ try { await extractProject(zipPath, id); } catch (e) { return { cancelled: false, error: `Entpacken fehlgeschlagen: ${e instanceof Error ? e.message : String(e)}` }; }+ remember();+ await this.open(id);+ return { cancelled: false, opened: true };+ }++ // Arbeitsordner existiert: vergleichen+ const git = new GitRepo(dir);+ const wsHead = (await git.isRepo()) ? await git.head() : null;+ const st = wsHead ? await git.status() : { dirty: false };+ if (info?.head && info.head === wsHead && !st.dirty) { // identisch: nichts zu entscheiden, Chats und Arbeitsordner bleiben+ remember();+ await this.open(id);+ return { cancelled: false, opened: true };+ }+ let why: string;+ if (st.dirty) why = 'Der Arbeitsordner enthält ungespeicherte Änderungen.';+ else if (info?.head && wsHead && (await git.isAncestor(info.head, wsHead))) why = 'Der Arbeitsordner ist neuer als die ZIP.';+ else if (info?.head && wsHead && (await git.isAncestor(wsHead, info.head))) why = 'Die ZIP ist neuer als der Arbeitsordner.';+ else why = 'Arbeitsordner und ZIP haben verschiedene Stände.';+ const choice = await choose(this.getWin(), {+ title: 'Arbeitsordner und ZIP weichen ab',+ message: `${why} Was soll geöffnet werden?`,+ detail: 'Arbeitsstand behalten: Das Modell wird so geöffnet, wie es auf diesem Rechner liegt.\n' ++ 'ZIP laden: Der Stand aus der ZIP wird geöffnet. Der bisherige Arbeitsordner wird gesichert, nichts wird gelöscht.',+ buttons: ['Arbeitsstand behalten', 'ZIP laden', 'Abbrechen'],+ });+ if (choice === 0) { patchAppState(id, { zipPath }); await this.open(id); return { cancelled: false, opened: true }; }+ if (choice !== 1) return { cancelled: true };+ try {+ if (this.session?.id === id) this.close(); // offene Handles würden das Umbenennen blockieren+ await backupWorkspace(id);+ await extractProject(zipPath, id);+ } catch (e) { return { cancelled: false, error: `ZIP laden fehlgeschlagen: ${e instanceof Error ? e.message : String(e)}` }; }+ remember();+ await this.open(id);+ return { cancelled: false, opened: true };+ }++ // ---- Verlauf ----------------------------------------------------------------------------------------------------++ async gitLog(): Promise<GitLog> {+ const s = this.need();+ const problems = await s.git.problems();+ const hasRepo = await s.git.isRepo();+ const commits = hasRepo ? await s.git.log() : [];+ const st = hasRepo ? await s.git.status() : { changed: 0, head: null };+ return { commits, problems, head: st.head, dirtyFiles: st.changed };+ }++ /** Vorschau eines alten Standes: STEP per `git show` holen und im Basismodus umwandeln. Der Arbeitsordner bleibt unberührt. */+ async preview(hash: string): Promise<PreviewResult> {+ const s = this.need();+ const empty = { commit: null, glb: new ArrayBuffer(0), map: { version: 0, parts: [] } as ModelMap };+ if (!/^[0-9a-f]{7,40}$/.test(hash)) return { ...empty, error: 'Ungültiger Stand' };+ const commit = (await s.git.log()).find((c) => c.hash === hash) ?? null;+ const dir = path.join(previewsDir(), s.id, hash);+ try {+ if (!fs.existsSync(path.join(dir, 'model.glb'))) {+ const step = path.join(dir, 'model.step');+ await s.git.exportFile(hash, 'output/model.step', step);+ const r = await runCadide(['glb', step, '--out', dir], s.dir);+ if (!r.ok) throw new Error((r.err || r.out).trim().split('\n').pop() || 'Umwandlung fehlgeschlagen');+ }+ const glb = fs.readFileSync(path.join(dir, 'model.glb'));+ const map = JSON.parse(fs.readFileSync(path.join(dir, 'model.map.json'), 'utf8')) as ModelMap;+ return { commit, glb: glb.buffer.slice(glb.byteOffset, glb.byteOffset + glb.byteLength) as ArrayBuffer, map };+ } catch (e) {+ fs.rmSync(dir, { recursive: true, force: true });+ const msg = e instanceof Error ? e.message : String(e);+ return { ...empty, commit, error: /exists on disk, but not in|does not exist|Path .* does not exist|invalid object/i.test(msg)+ ? 'Dieser Stand enthält kein output/model.step (noch nicht gebaut).' : `Vorschau nicht möglich: ${msg}` };+ }+ }++ async restore(hash: string): Promise<RestoreResult> {+ const s = this.need();+ const commit = (await s.git.log()).find((c) => c.hash === hash);+ if (!commit) return { cancelled: false, error: 'Dieser Stand existiert im Verlauf nicht mehr.' };+ const c = await choose(this.getWin(), {+ title: 'Stand wiederherstellen',+ message: `„${commit.subject}“ (${commit.short}) wiederherstellen?`,+ detail: 'Die Dateien dieses Standes werden in den Arbeitsordner kopiert und als neuer Stand im Verlauf abgelegt. ' ++ 'Ungesicherte Änderungen werden vorher als eigener Stand gesichert. Der Verlauf bleibt vollständig.',+ buttons: ['Wiederherstellen', 'Abbrechen'],+ });+ if (c !== 0) return { cancelled: true };+ try {+ const r = await s.git.restore(hash);+ s.builds.start('Stand wiederhergestellt');+ this.send('versions:changed');+ this.send('save:state', await this.saveState());+ return { cancelled: false, ...r };+ } catch (e) {+ return { cancelled: false, error: `Wiederherstellen fehlgeschlagen: ${e instanceof Error ? e.message : String(e)}` };+ }+ }++ // ---- Beenden ----------------------------------------------------------------------------------------------------++ /** Darf das Fenster schließen? Bei ungespeicherten Änderungen fragt die App. Der Arbeitsstand bleibt in jedem Fall erhalten. */+ async confirmClose(): Promise<boolean> {+ if (!this.session || process.env.CADIDE_TEST === '1') return true;+ const st = await this.saveState();+ if (!st.unsaved) return true;+ const c = await choose(this.getWin(), {+ title: 'CAD-IDE beenden',+ message: 'Das Modell hat ungespeicherte Änderungen.',+ detail: 'Der Arbeitsstand bleibt auf diesem Rechner erhalten und wird beim nächsten Start wieder geöffnet. Die ZIP-Datei wird nur beim Speichern aktualisiert.',+ buttons: ['Speichern', 'Nicht speichern', 'Abbrechen'],+ });+ if (c === 2) return false;+ if (c === 0) { const r = await this.save(false); if (r.cancelled || r.error) return false; }+ return true;+ }+}diff --git a/app/src/main/terminals.ts b/app/src/main/terminals.tsindex 641db84..0305b8f 100644--- a/app/src/main/terminals.ts+++ b/app/src/main/terminals.ts@@ -1,17 +1,18 @@import path from 'node:path';import type { WebContents } from 'electron';import * as pty from 'node-pty';-import { pythonBinDir } from './paths';+import { gitCmdDir, pythonBinDir } from './paths';/** Umgebung fuer Terminals: Python-Basisumgebung vorn im PATH, damit `python`, `pip` und `cadide` gefunden werden. */export function terminalEnv(projectDir: string): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = { ...process.env, PYTHONUTF8: '1', CADIDE_PROJECT: projectDir };+ const key = Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';+ const front: string[] = [];const bin = pythonBinDir();- if (bin) {- const key = Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';- env[key] = bin + path.delimiter + (env[key] ?? '');- env.VIRTUAL_ENV = path.dirname(bin);- }+ if (bin) { front.push(bin); env.VIRTUAL_ENV = path.dirname(bin); }+ const git = gitCmdDir(); // das mitgelieferte Git hat Vorrang vor einem Git des Systems+ if (git) front.push(git);+ env[key] = [...front, env[key] ?? ''].join(path.delimiter);return env;}diff --git a/app/src/main/workspace.ts b/app/src/main/workspace.tsindex 6a7c652..3e689eb 100644--- a/app/src/main/workspace.ts+++ b/app/src/main/workspace.ts@@ -2,9 +2,13 @@ import { randomUUID } from 'node:crypto';import fs from 'node:fs';import path from 'node:path';import type { ProjectListEntry } from '../shared/types';-import { appStateFile, projectStateDir, templateDir, workspacesDir } from './paths';+import { runCadide } from './build';+import { GitRepo } from './git';+import { appStateFile, backupsDir, projectStateDir, templateDir, workspacesDir } from './paths';+import { extractZip } from './zip';export const API_VERSION = 1;+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;export interface ProjectJson {id: string;@@ -15,37 +19,78 @@ export interface ProjectJson {created: string;}+/** Zweite Kopie des Projektzustands in den App-Daten (E27) plus Angaben, die nur die App braucht. */+export interface AppState { zipPath?: string; savedHead?: string | null; savedAt?: number }+interface ProjectState extends ProjectJson { app?: AppState }+const readJson = <T>(file: string): T | null => {try { return JSON.parse(fs.readFileSync(file, 'utf8')) as T; } catch { return null; }};+const writeJson = (file: string, value: unknown) => {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, JSON.stringify(value, null, 2));+};++export const isProjectId = (id: string) => UUID.test(id);export function projectDir(id: string): string {- if (!/^[0-9a-f-]{36}$/.test(id)) throw new Error(`Ungueltige Projekt-ID: ${id}`);+ if (!isProjectId(id)) throw new Error(`Ungültige Projekt-ID: ${id}`);return path.join(workspacesDir(), id);}-/** Neues Projekt: UUID-Ordner in den App-Daten (E21), Vorlage kopieren, Zustand doppelt ablegen (E27). */-export function createProject(name = 'Neues Modell'): { id: string; dir: string } {+const stateFile = (id: string) => path.join(projectStateDir(), `${id}.json`);+export const readProjectJson = (id: string) => readJson<ProjectJson>(path.join(projectDir(id), '.cadide', '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 = 'Neues Modell'): Promise<{ id: string; dir: string }> {const id = randomUUID();const dir = projectDir(id);fs.mkdirSync(dir, { recursive: true });fs.cpSync(templateDir(), dir, { recursive: true });const pj: ProjectJson = { id, name, api_version: API_VERSION, entry: 'model.py', main_output: 'output/model.step', created: new Date().toISOString() };- fs.mkdirSync(path.join(dir, '.cadide'), { recursive: true });- fs.writeFileSync(path.join(dir, '.cadide', 'project.json'), JSON.stringify(pj, null, 2));- fs.mkdirSync(projectStateDir(), { recursive: true });- fs.writeFileSync(path.join(projectStateDir(), `${id}.json`), JSON.stringify(pj, null, 2));+ writeJson(path.join(dir, '.cadide', 'project.json'), pj);+ writeJson(stateFile(id), { ...pj, app: {} } satisfies ProjectState);+ // Einmal bauen, bevor der Startcommit entsteht: So enthält auch der erste Stand eine output/model.step+ // und lässt sich im Verlauf als Vorschau öffnen. Scheitert der Build, geht das Anlegen trotzdem weiter.+ await runCadide(['build', '--project', dir], dir, 90000);+ try {+ await new GitRepo(dir).init('Neues Modell angelegt');+ } catch (e) {+ // Ohne Git bleibt das Projekt benutzbar. Der Verlauf meldet den Grund (Projekt-Check), statt das Anlegen scheitern zu lassen.+ console.error('[cadide] Git-Verlauf konnte nicht angelegt werden:', e);+ }setLastProject(id);return { id, dir };}-/** Prueft ein Projekt und MELDET Auffaelligkeiten. Repariert nichts (E28). */+/** Angaben, die nur die App braucht (Pfad der ZIP, zuletzt gespeicherter Stand). */+export function getAppState(id: string): AppState {+ return readJson<ProjectState>(stateFile(id))?.app ?? {};+}++export function patchAppState(id: string, patch: AppState): void {+ const cur = readJson<ProjectState>(stateFile(id)) ?? (readProjectJson(id) as ProjectJson | null);+ if (!cur) return;+ writeJson(stateFile(id), { ...cur, app: { ...(cur as ProjectState).app, ...patch } });+}++/** Benennt das Projekt um (project.json und App-Kopie). Die Änderung landet beim nächsten Snapshot im Verlauf. */+export function renameProject(id: string, name: string): void {+ const file = path.join(projectDir(id), '.cadide', 'project.json');+ const pj = readJson<ProjectJson>(file);+ if (!pj || pj.name === name) return;+ writeJson(file, { ...pj, name });+ const cur = readJson<ProjectState>(stateFile(id));+ if (cur) writeJson(stateFile(id), { ...cur, name });+}++/** Prüft ein Projekt und MELDET Auffälligkeiten. Repariert nichts (E28). */export function inspectProject(id: string): { name: string; problems: string[] } {const dir = projectDir(id);const problems: string[] = [];if (!fs.existsSync(dir)) return { name: id, problems: ['Der Arbeitsordner existiert nicht.'] };const pj = readJson<ProjectJson>(path.join(dir, '.cadide', 'project.json'));- const backup = readJson<ProjectJson>(path.join(projectStateDir(), `${id}.json`));+ const backup = readJson<ProjectState>(stateFile(id));if (!pj) {problems.push(backup? '.cadide/project.json fehlt oder ist unlesbar. Eine Kopie liegt in den App-Daten (nicht automatisch wiederhergestellt).'@@ -58,7 +103,7 @@ export function inspectProject(id: string): { name: string; problems: string[] }const entry = pj?.entry ?? 'model.py';if (!fs.existsSync(path.join(dir, entry))) problems.push(`Einstiegspunkt ${entry} fehlt.`);for (const bad of ['.venv', 'venv', 'env']) {- if (fs.existsSync(path.join(dir, bad, 'pyvenv.cfg'))) problems.push(`Im Projekt liegt eine eigene Python-Umgebung (${bad}/). Sie wird ignoriert.`);+ if (fs.existsSync(path.join(dir, bad, 'pyvenv.cfg'))) problems.push(`Im Projekt liegt eine eigene Python-Umgebung (${bad}/). Sie wird ignoriert und nicht in die ZIP gepackt.`);}return { name: pj?.name ?? backup?.name ?? id, problems };}@@ -68,7 +113,7 @@ export function listProjects(): ProjectListEntry[] {if (!fs.existsSync(root)) return [];const out: ProjectListEntry[] = [];for (const id of fs.readdirSync(root)) {- if (!/^[0-9a-f-]{36}$/.test(id)) continue;+ if (!isProjectId(id)) continue;const dir = path.join(root, id);const pj = readJson<ProjectJson>(path.join(dir, '.cadide', 'project.json'));out.push({ id, name: pj?.name ?? id.slice(0, 8), modified: fs.statSync(dir).mtimeMs });@@ -78,11 +123,47 @@ export function listProjects(): ProjectListEntry[] {export function getLastProject(): string | null {const s = readJson<{ lastProject?: string }>(appStateFile());- return s?.lastProject && fs.existsSync(projectDir(s.lastProject)) ? s.lastProject : null;+ return s?.lastProject && isProjectId(s.lastProject) && fs.existsSync(projectDir(s.lastProject)) ? s.lastProject : null;}export function setLastProject(id: string): void {- fs.mkdirSync(path.dirname(appStateFile()), { recursive: true });const s = readJson<Record<string, unknown>>(appStateFile()) ?? {};- fs.writeFileSync(appStateFile(), JSON.stringify({ ...s, lastProject: id }, null, 2));+ writeJson(appStateFile(), { ...s, lastProject: id });+}++/**+ * Verschiebt einen Arbeitsordner in die Sicherungen, statt ihn zu löschen (Regel 5: nichts geht still verloren).+ * Unter Windows hält ein eben beendetes Terminal den Ordner noch kurz als aktuelles Verzeichnis fest, daher mehrere Versuche.+ */+export async function backupWorkspace(id: string): Promise<string> {+ const src = projectDir(id);+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');+ const dst = path.join(backupsDir(), `${id}-${stamp}`);+ fs.mkdirSync(backupsDir(), { recursive: true });+ for (let attempt = 0; ; attempt++) {+ try { fs.renameSync(src, dst); return dst; } catch (e) {+ const code = (e as NodeJS.ErrnoException).code ?? '';+ if (!['EPERM', 'EBUSY', 'EACCES'].includes(code) || attempt >= 20) {+ throw new Error('Der Arbeitsordner ist noch in Benutzung (ein Terminal oder Programm liegt darin). Schließe es und versuche es erneut.');+ }+ await new Promise((r) => setTimeout(r, 300));+ }+ }+}++/** Entpackt eine ZIP als Arbeitsordner `id`. Erst in einen Temp-Ordner, dann umbenennen: nie ein halb entpacktes Projekt. */+export async function extractProject(zipPath: string, id: string): Promise<string> {+ const dst = projectDir(id);+ if (fs.existsSync(dst)) throw new Error('Der Arbeitsordner existiert schon (erst sichern).');+ const tmp = path.join(workspacesDir(), `.tmp-${randomUUID()}`);+ try {+ await extractZip(zipPath, tmp);+ // Der Marker ist nur fürs Öffnen da. Bliebe er liegen, wäre er für Git eine unversionierte Datei ("ungespeichert").+ fs.rmSync(path.join(tmp, '.cadide', 'zip-info.json'), { force: true });+ fs.renameSync(tmp, dst);+ } catch (e) {+ fs.rmSync(tmp, { recursive: true, force: true });+ throw e;+ }+ return dst;}diff --git a/app/src/main/zip.ts b/app/src/main/zip.tsnew file mode 100644index 0000000..6a763c3--- /dev/null+++ b/app/src/main/zip.ts@@ -0,0 +1,107 @@+import fs from 'node:fs';+import path from 'node:path';+import { pipeline } from 'node:stream/promises';+import yauzl from 'yauzl';+import yazl from 'yazl';++/** Marker, den die App beim Speichern in die ZIP legt. Damit erkennt sie beim Öffnen, ob der Arbeitsordner abweicht (E21). */+export interface ZipInfo { savedAt: string; head: string | null; id: string; name: string }+export const ZIP_INFO_PATH = '.cadide/zip-info.json';++/** Wird nie gepackt: Umgebungen und Caches (Umgebung wird aus requirements.txt neu gebaut, Cache neu erzeugt). */+const SKIP_DIRS = new Set(['.venv', 'venv', 'env', '__pycache__', 'node_modules']);+const SKIP_FILES = new Set(['.cadide/model.glb', '.cadide/model.map.json', '.cadide/build.json']);+const MAX_UNPACKED = 2 * 1024 ** 3;++function collect(root: string): string[] {+ const out: string[] = [];+ const walk = (dir: string, rel: string) => {+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {+ const r = rel ? `${rel}/${e.name}` : e.name;+ if (e.isSymbolicLink()) continue;+ if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) walk(path.join(dir, e.name), r); continue; }+ if (SKIP_FILES.has(r) || (r.startsWith('.git/') && r.endsWith('.lock'))) continue;+ out.push(r);+ }+ };+ walk(root, '');+ return out;+}++/** Packt den Projektordner (inklusive .git) atomar in `zipPath`: erst eine .part-Datei, dann umbenennen. */+export async function saveProjectZip(dir: string, zipPath: string, info: ZipInfo): Promise<{ files: number; bytes: number }> {+ const files = collect(dir);+ const zip = new yazl.ZipFile();+ for (const rel of files) if (rel !== ZIP_INFO_PATH) zip.addFile(path.join(dir, rel), rel);+ zip.addBuffer(Buffer.from(JSON.stringify(info, null, 2)), ZIP_INFO_PATH);+ zip.end();+ const tmp = zipPath + '.part';+ fs.mkdirSync(path.dirname(zipPath), { recursive: true });+ try {+ await pipeline(zip.outputStream, fs.createWriteStream(tmp));+ fs.renameSync(tmp, zipPath);+ } catch (e) {+ fs.rmSync(tmp, { force: true });+ throw e;+ }+ return { files: files.length + 1, bytes: fs.statSync(zipPath).size };+}++function openZip(zipPath: string): Promise<yauzl.ZipFile> {+ return new Promise((resolve, reject) => {+ yauzl.open(zipPath, { lazyEntries: true, autoClose: true }, (err, z) => (err || !z ? reject(err ?? new Error('ZIP nicht lesbar')) : resolve(z)));+ });+}++/** Ein Eintrag ist nur sicher, wenn er relativ ist und den Zielordner nicht verlässt (Zip-Slip). */+export function isSafeEntryName(name: string): boolean {+ if (!name || name.startsWith('/') || name.startsWith('\\') || /^[a-zA-Z]:/.test(name) || name.includes('\0')) return false;+ return !name.split(/[\\/]/).includes('..');+}++/** Liest einzelne Textdateien aus der ZIP, ohne sie zu entpacken. Fehlende Dateien liefern null. */+export async function readZipTexts(zipPath: string, names: string[]): Promise<Record<string, string | null>> {+ const zip = await openZip(zipPath);+ const found: Record<string, string | null> = Object.fromEntries(names.map((n) => [n, null]));+ return new Promise((resolve, reject) => {+ zip.on('error', reject);+ zip.on('end', () => resolve(found));+ zip.on('entry', (entry: yauzl.Entry) => {+ if (!names.includes(entry.fileName) || entry.uncompressedSize > 5 * 1024 * 1024) { zip.readEntry(); return; }+ zip.openReadStream(entry, (err, stream) => {+ if (err || !stream) { reject(err ?? new Error('Eintrag nicht lesbar')); return; }+ const chunks: Buffer[] = [];+ stream.on('data', (c: Buffer) => chunks.push(c));+ stream.on('end', () => { found[entry.fileName] = Buffer.concat(chunks).toString('utf8'); zip.readEntry(); });+ stream.on('error', reject);+ });+ });+ zip.readEntry();+ });+}++/** Entpackt nach `dest` (muss leer bzw. neu sein). Unsichere Pfade und zu große Archive werden abgelehnt. */+export async function extractZip(zipPath: string, dest: string): Promise<number> {+ const zip = await openZip(zipPath);+ const root = path.resolve(dest);+ fs.mkdirSync(root, { recursive: true });+ let count = 0, total = 0;+ return new Promise((resolve, reject) => {+ zip.on('error', reject);+ zip.on('end', () => resolve(count));+ zip.on('entry', (entry: yauzl.Entry) => {+ total += entry.uncompressedSize;+ if (total > MAX_UNPACKED) { reject(new Error('Die ZIP ist entpackt größer als 2 GB und wird nicht geöffnet.')); zip.close(); return; }+ if (!isSafeEntryName(entry.fileName)) { reject(new Error(`Unsicherer Pfad in der ZIP: ${entry.fileName}`)); zip.close(); return; }+ const target = path.resolve(root, entry.fileName);+ if (target !== root && !target.startsWith(root + path.sep)) { reject(new Error(`Unsicherer Pfad in der ZIP: ${entry.fileName}`)); zip.close(); return; }+ if (entry.fileName.endsWith('/')) { fs.mkdirSync(target, { recursive: true }); zip.readEntry(); return; }+ fs.mkdirSync(path.dirname(target), { recursive: true });+ zip.openReadStream(entry, (err, stream) => {+ if (err || !stream) { reject(err ?? new Error('Eintrag nicht lesbar')); return; }+ pipeline(stream, fs.createWriteStream(target)).then(() => { count++; zip.readEntry(); }, reject);+ });+ });+ zip.readEntry();+ });+}diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.tsindex e576b60..ca7f493 100644--- a/app/src/preload/preload.ts+++ b/app/src/preload/preload.ts@@ -10,6 +10,16 @@ const api: CadideApi = {list: () => ipcRenderer.invoke('project:list'),open: (id) => ipcRenderer.invoke('project:open', id),onChanged: (cb) => { ipcRenderer.on('project:changed', (_e, p) => cb(p)); },+ saveState: () => ipcRenderer.invoke('project:saveState'),+ save: (saveAs) => ipcRenderer.invoke('project:save', saveAs),+ openZip: () => ipcRenderer.invoke('project:openZip'),+ onSaveState: (cb) => { ipcRenderer.on('save:state', (_e, st) => cb(st)); },+ },+ versions: {+ log: () => ipcRenderer.invoke('versions:log'),+ preview: (hash) => ipcRenderer.invoke('versions:preview', hash),+ restore: (hash) => ipcRenderer.invoke('versions:restore', hash),+ onChanged: (cb) => { ipcRenderer.on('versions:changed', () => cb()); },},build: {run: () => ipcRenderer.invoke('build:run'),@@ -33,6 +43,10 @@ const api: CadideApi = {onExit: (cb) => { ipcRenderer.on('term:exit', (_e, id, code) => cb(id, code)); },},agents: { detect: () => ipcRenderer.invoke('agents:detect') },+ // Nur im Testmodus: vorbereitete Antworten für native Dialoge+ test: process.env.CADIDE_TEST === '1'+ ? { answers: (a) => ipcRenderer.invoke('test:answers', a), screenshot: (f) => ipcRenderer.invoke('test:screenshot', f) }+ : undefined,};contextBridge.exposeInMainWorld('cadide', api);diff --git a/app/src/renderer/index.html b/app/src/renderer/index.htmlindex 1806054..090792d 100644--- a/app/src/renderer/index.html+++ b/app/src/renderer/index.html@@ -12,7 +12,12 @@<header id="topbar"><span class="brand">CAD-IDE</span><button id="btn-new" title="Neues Modell anlegen">Neu</button>- <select id="sel-projects" title="Zuletzt geöffnete Modelle"></select>+ <button id="btn-open" title="Modell aus einer ZIP-Datei öffnen (Strg+O)">Öffnen …</button>+ <select id="sel-projects" title="Modelle auf diesem Rechner"></select>+ <span class="sep"></span>+ <button id="btn-save" title="Speichern: Snapshot im Verlauf und ZIP schreiben (Strg+S)">Speichern</button>+ <button id="btn-saveas" title="Als neue ZIP-Datei speichern">Speichern unter …</button>+ <span id="save-badge" class="badge">–</span><span class="sep"></span><button id="btn-build" title="Modell jetzt bauen">Bauen</button><button id="btn-cancel" title="Laufenden Build abbrechen" disabled>Abbrechen</button>@@ -41,7 +46,15 @@<label class="chk"><input type="checkbox" id="chk-wire"> Drahtgitter</label><label class="chk"><input type="checkbox" id="chk-ghost"> Transparent</label></div>- <div id="viewer"><div id="viewer-msg"></div></div>+ <div id="viewer"><div id="viewer-msg"></div><div id="preview-banner" hidden></div></div>+ <div id="versions">+ <span class="vlabel">Verlauf</span>+ <div id="vtrack"><input type="range" id="vslider" min="0" max="0" step="1" value="0" disabled><div id="vdots"></div></div>+ <span id="vinfo"></span>+ <button id="btn-restore" hidden title="Diesen Stand als neuen Stand übernehmen">Stand wiederherstellen</button>+ <button id="btn-live" hidden>Zurück zum Arbeitsstand</button>+ </div>+ <div id="vproblem" hidden></div><div id="info-panel"><div id="info">Klick auf ein Bauteil zeigt die zugehörige Codestelle.</div><pre id="code"></pre>@@ -53,6 +66,7 @@<div id="term-panes"></div></aside></main>+ <div id="toast" hidden></div><footer id="statusbar"><span id="status" data-state="idle">Bereit</span><span class="grow"></span><span id="status-detail"></span></footer></div><script src="main.js"></script>diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex f6bf7c7..4f8637a 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -1,5 +1,6 @@-import type { AgentInfo, BuildStatus, FileNode, ModelMap, ProjectInfo } from '../shared/types';+import type { AgentInfo, BuildStatus, FileNode, ModelMap, PreviewResult, ProjectInfo, SaveState } from '../shared/types';import { TerminalTabs } from './terminals';+import { VersionsBar } from './versions';import { PickResult, Viewer, ViewName } from './viewer';const $ = <T extends HTMLElement>(id: string) => document.getElementById(id) as T;@@ -9,6 +10,7 @@ const viewer = new Viewer($('viewer'));const terminals = new TerminalTabs($('term-tabs'), $('term-panes'), $('btn-term-add'));let project: ProjectInfo | null = null;+let saveState: SaveState | null = null;let map: ModelMap | null = null;let loadSeq = 0;const textCache = new Map<string, string>();@@ -20,6 +22,34 @@ function el<K extends keyof HTMLElementTagNameMap>(tag: K, props: Partial<HTMLElreturn e;}+let toastTimer: ReturnType<typeof setTimeout> | undefined;+function toast(text: string, kind: 'info' | 'error' = 'info'): void {+ const t = $('toast');+ t.textContent = text;+ t.className = kind === 'error' ? 'error' : '';+ t.hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => { t.hidden = true; }, kind === 'error' ? 12000 : 6000);+}++const versions = new VersionsBar({+ slider: $<HTMLInputElement>('vslider'), dots: $('vdots'), info: $('vinfo'), problem: $('vproblem'),+ restore: $<HTMLButtonElement>('btn-restore'), live: $<HTMLButtonElement>('btn-live'), banner: $('preview-banner'),+}, {+ async show(res: PreviewResult | null) {+ if (!res) { await loadModel(); return; }+ try {+ map = res.map;+ textCache.clear();+ await viewer.load(res.glb);+ buildModelTree();+ $('info').textContent = 'Vorschau eines alten Standes: Ein Klick zeigt Bauteil und Fläche, aber keinen Code.';+ $('code').replaceChildren();+ } catch (e) { toast(`Vorschau nicht darstellbar: ${e instanceof Error ? e.message : String(e)}`, 'error'); }+ },+ toast,+});+// ---- Projekt ----------------------------------------------------------------------------------------------------async function onProject(p: ProjectInfo): Promise<void> {@@ -28,6 +58,7 @@ async function onProject(p: ProjectInfo): Promise<void> {map = null;textCache.clear();viewer.clear();+ versions.reset();terminals.closeAll();$('tab-model').replaceChildren(el('div', { className: 'hint' }, 'Modell wird gebaut …'));$('info').textContent = 'Klick auf ein Bauteil zeigt die zugehörige Codestelle.';@@ -37,6 +68,8 @@ async function onProject(p: ProjectInfo): Promise<void> {showProblems(p.problems);await refreshProjects();void refreshFiles();+ void versions.refresh();+ void refreshSaveState();void terminals.add({ title: 'Terminal' });void refreshAgents();setStatusFromBuild(await api.build.status());@@ -87,6 +120,7 @@ function setStatusFromBuild(s: BuildStatus): void {}async function loadModel(): Promise<void> {+ if (versions.previewing) return; // während einer Vorschau bleibt der alte Stand stehenconst seq = ++loadSeq;try {const [mapText, glb] = await Promise.all([api.fs.readText('.cadide/model.map.json'), api.fs.readBinary('.cadide/model.glb')]);@@ -190,6 +224,47 @@ async function refreshAgents(): Promise<void> {}));}+// ---- Speichern und Öffnen ---------------------------------------------------------------------------------------++function renderSaveState(st: SaveState): void {+ saveState = st;+ const b = $('save-badge');+ b.textContent = st.unsaved ? '● ungespeichert' : '✓ gespeichert';+ b.className = 'badge' + (st.unsaved ? ' unsaved' : '');+ b.title = st.zipPath ? `ZIP: ${st.zipPath}` : 'Noch nicht als ZIP gespeichert';+ document.title = `CAD-IDE – ${project?.name ?? ''}${st.unsaved ? ' ●' : ''}`;+}++async function refreshSaveState(): Promise<void> {+ try { renderSaveState(await api.project.saveState()); } catch { /* Projekt wechselt gerade */ }+}++async function doSave(saveAs = false): Promise<void> {+ const r = await api.project.save(saveAs);+ if (r.cancelled) return;+ if (r.error) { toast(r.error, 'error'); return; }+ const kb = Math.round((r.bytes ?? 0) / 1024);+ const lines = [`Gespeichert: ${r.zipPath}`, `${r.files} Dateien, ${kb} KB${r.snapshot ? ' · Snapshot im Verlauf angelegt' : ''}`];+ if (r.warnings?.length) lines.push(`Hinweis: ${r.warnings.join(' ')}`);+ toast(lines.join('\n'), r.warnings?.length ? 'error' : 'info');+ project = await api.project.current(); // der Modellname folgt dem Dateinamen+ void refreshProjects();+ void refreshSaveState();+}++async function doOpen(): Promise<void> {+ const r = await api.project.openZip();+ if (r.error) toast(r.error, 'error');+}++// Kurzbefehle gelten nicht im Terminal: dort gehören Strg+S/Strg+O den Programmen (Claude Code nutzt Strg+O selbst)+window.addEventListener('keydown', (e) => {+ if ((e.target as HTMLElement | null)?.closest?.('#terminals') || !e.ctrlKey) return;+ const k = e.key.toLowerCase();+ if (k === 's') { e.preventDefault(); void doSave(e.shiftKey); }+ else if (k === 'o' && !e.shiftKey) { e.preventDefault(); void doOpen(); }+}, true);+// ---- Bedienelemente ---------------------------------------------------------------------------------------------document.querySelectorAll<HTMLButtonElement>('.tab[data-tab]').forEach((b) => b.addEventListener('click', () => {@@ -202,6 +277,9 @@ $<HTMLInputElement>('chk-edges').addEventListener('change', (e) => viewer.setEdg$<HTMLInputElement>('chk-wire').addEventListener('change', (e) => viewer.setWireframe((e.target as HTMLInputElement).checked));$<HTMLInputElement>('chk-ghost').addEventListener('change', (e) => viewer.setGhost((e.target as HTMLInputElement).checked));$('btn-new').addEventListener('click', () => void api.project.create());+$('btn-open').addEventListener('click', () => void doOpen());+$('btn-save').addEventListener('click', () => void doSave(false));+$('btn-saveas').addEventListener('click', () => void doSave(true));$('btn-build').addEventListener('click', () => void api.build.run());$('btn-cancel').addEventListener('click', () => void api.build.cancel());$<HTMLInputElement>('chk-auto').addEventListener('change', (e) => void api.build.setAuto((e.target as HTMLInputElement).checked));@@ -233,6 +311,8 @@ api.build.onStatus((s) => {if (s.state === 'ok') { void loadModel(); void refreshFiles(); }});api.fs.onChanged(() => void refreshFiles());+api.versions.onChanged(() => void versions.refresh());+api.project.onSaveState((st) => renderSaveState(st));// Das Projekt kommt ausschließlich über das Ereignis (der Hauptprozess öffnet es beim Start). Ein zweiter Weg würde alles doppelt aufbauen.// Prüfschnittstelle, nur im Testmodus@@ -247,5 +327,11 @@ if (api.testMode) {codeHighlight: () => [...document.querySelectorAll('#code .hl')].map((x) => x.textContent),treeNames: () => [...document.querySelectorAll('#tab-model .part .name')].map((x) => x.textContent),termText: (id: number) => terminals.text(id),+ versions: () => versions.state(),+ saveState: () => saveState,+ toast: () => ({ text: $('toast').textContent, hidden: $('toast').hidden, error: $('toast').className === 'error' }),+ banner: () => ({ hidden: $('preview-banner').hidden, text: $('preview-banner').textContent }),+ 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 }),};}diff --git a/app/src/renderer/style.css b/app/src/renderer/style.cssindex b43a1a7..212d28c 100644--- a/app/src/renderer/style.css+++ b/app/src/renderer/style.css@@ -31,7 +31,7 @@ aside, section { min-width:0; min-height:0; }.ftree li { padding:1px 0; white-space:nowrap; }.ftree .dir { color:var(--dim); }.hint { color:var(--dim); padding:4px 0; }-#center { display:grid; grid-template-rows:auto 1fr auto; background:var(--bg); }+#center { display:grid; grid-template-columns:minmax(0,1fr); grid-template-rows:auto 1fr auto auto auto; background:var(--bg); overflow:hidden; }#viewer-toolbar { display:flex; gap:6px; align-items:center; padding:4px 8px; background:var(--panel); border-bottom:1px solid var(--line); flex-wrap:wrap; }#viewer { position:relative; min-height:120px; }#viewer canvas { position:absolute; inset:0; width:100%; height:100%; display:block; }@@ -52,3 +52,21 @@ pre { margin:0; font:12px ui-monospace, Consolas, monospace; }#status[data-state=ok] { color:var(--ok); }#status[data-state=error] { color:var(--err); }#status[data-state=building] { color:var(--accent); }++.badge { color:var(--dim); font-size:12px; white-space:nowrap; }+.badge.unsaved { color:var(--warn); }+#versions { display:flex; flex-wrap:wrap; align-items:center; gap:6px 10px; padding:5px 10px; min-width:0; background:var(--panel); border-top:1px solid var(--line); }+.vlabel { color:var(--dim); font-size:12px; }+#vtrack { position:relative; flex:1 1 220px; height:26px; min-width:120px; }+#vslider { position:absolute; inset:0; width:100%; margin:0; background:transparent; }+#vdots { position:absolute; left:8px; right:8px; top:0; bottom:0; pointer-events:none; }+.vdot { position:absolute; top:3px; width:9px; height:9px; margin-left:-4.5px; padding:0; border-radius:50%; background:var(--accent); border:1px solid #0008; pointer-events:auto; cursor:pointer; }+.vdot.cur { outline:2px solid #fff8; }+.vdot.live { background:transparent; border:2px solid var(--ok); }+.vdot.live.dirty { border-color:var(--warn); }+#vinfo { color:var(--dim); font-size:12px; flex:0 1 auto; min-width:0; max-width:34%; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }+#versions button { white-space:nowrap; flex:0 0 auto; }+#vproblem { padding:3px 10px; background:#3a3020; color:var(--warn); font-size:12px; border-top:1px solid var(--line); }+#preview-banner { position:absolute; left:10px; right:10px; bottom:10px; max-width:calc(100% - 20px); overflow-wrap:anywhere; padding:6px 10px; background:#12324f; border:1px solid var(--accent); border-radius:4px; color:#cfe6ff; z-index:2; }+#toast { position:fixed; right:14px; bottom:34px; max-width:440px; padding:8px 12px; background:var(--panel2); border:1px solid var(--accent); border-radius:4px; z-index:10; white-space:pre-wrap; }+#toast.error { border-color:var(--err); color:#ffc9c9; }diff --git a/app/src/renderer/versions.ts b/app/src/renderer/versions.tsnew file mode 100644index 0000000..3c05ccb--- /dev/null+++ b/app/src/renderer/versions.ts@@ -0,0 +1,128 @@+import type { CommitInfo, GitLog, PreviewResult } from '../shared/types';++interface Ui {+ slider: HTMLInputElement;+ dots: HTMLElement;+ info: HTMLElement;+ problem: HTMLElement;+ restore: HTMLButtonElement;+ live: HTMLButtonElement;+ banner: HTMLElement;+}++interface Hooks {+ /** `res` = Vorschau eines alten Standes, `null` = zurück zum Arbeitsstand. */+ show(res: PreviewResult | null): Promise<void>;+ toast(text: string, kind: 'info' | 'error'): void;+}++const fmt = (iso: string) => new Date(iso).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' });++/**+ * Verlaufsleiste unter dem Viewer (E7, E35): jeder Commit ein Punkt, ganz rechts der Arbeitsstand.+ * Alte Stände sind eine schreibgeschützte Vorschau, der Arbeitsordner bleibt unberührt.+ * „Stand wiederherstellen" legt einen neuen Commit an, es gibt kein Zurückspulen.+ */+export class VersionsBar {+ private log: GitLog = { commits: [], problems: [], head: null, dirtyFiles: 0 };+ private previewHash: string | null = null;+ private seq = 0;++ constructor(private ui: Ui, private hooks: Hooks) {+ ui.slider.addEventListener('change', () => void this.select(Number(ui.slider.value)));+ ui.live.addEventListener('click', () => void this.select(this.log.commits.length));+ ui.restore.addEventListener('click', () => void this.restore());+ }++ get previewing(): boolean { return this.previewHash !== null; }++ /** Beim Projektwechsel: alles zurücksetzen. */+ reset(): void {+ this.seq++;+ this.previewHash = null;+ this.log = { commits: [], problems: [], head: null, dirtyFiles: 0 };+ this.ui.banner.hidden = true;+ this.render();+ }++ async refresh(): Promise<void> {+ try { this.log = await window.cadide.versions.log(); } catch { return; }+ // Existiert der angezeigte Stand nicht mehr (Verlauf umgebaut), zurück zum Arbeitsstand+ if (this.previewHash && !this.log.commits.some((c) => c.hash === this.previewHash)) await this.select(this.log.commits.length);+ else this.render();+ }++ private index(): number {+ if (!this.previewHash) return this.log.commits.length;+ return this.log.commits.findIndex((c) => c.hash === this.previewHash);+ }++ private async select(i: number): Promise<void> {+ const seq = ++this.seq;+ const n = this.log.commits.length;+ if (i >= n || i < 0) { // Arbeitsstand+ this.previewHash = null;+ this.ui.banner.hidden = true;+ this.render();+ await this.hooks.show(null);+ return;+ }+ const commit = this.log.commits[i];+ this.ui.info.textContent = 'Lade Vorschau …';+ const res = await window.cadide.versions.preview(commit.hash);+ if (seq !== this.seq) return; // inzwischen etwas anderes gewählt+ if (res.error) {+ this.hooks.toast(res.error, 'error');+ this.render();+ return;+ }+ this.previewHash = commit.hash;+ this.ui.banner.textContent = `Vorschau: ${commit.subject} · ${fmt(commit.date)} · ${commit.short} (schreibgeschützt, der Arbeitsordner bleibt unverändert)`;+ this.ui.banner.hidden = false;+ this.render();+ await this.hooks.show(res);+ }++ private async restore(): Promise<void> {+ if (!this.previewHash) return;+ const r = await window.cadide.versions.restore(this.previewHash);+ if (r.cancelled) return;+ if (r.error) { this.hooks.toast(r.error, 'error'); return; }+ this.hooks.toast(r.commit ? 'Stand wiederhergestellt und als neuer Stand im Verlauf abgelegt.' : 'Dieser Stand war schon der aktuelle.', 'info');+ this.previewHash = null;+ this.ui.banner.hidden = true;+ await this.refresh();+ await this.hooks.show(null);+ }++ private render(): void {+ const { commits, problems, dirtyFiles } = this.log;+ const n = commits.length;+ const idx = this.index();+ const ui = this.ui;+ ui.slider.max = String(n);+ ui.slider.value = String(Math.max(idx, 0));+ ui.slider.disabled = n === 0;+ ui.dots.replaceChildren(...[...commits, null].map((c: CommitInfo | null, i) => {+ const dot = document.createElement('button');+ dot.className = 'vdot' + (c ? '' : ' live') + (i === idx ? ' cur' : '') + (!c && dirtyFiles ? ' dirty' : '');+ dot.style.left = n === 0 ? '0%' : `${(i / n) * 100}%`;+ dot.title = c ? `${c.subject}\n${c.author} · ${fmt(c.date)}` : `Arbeitsstand${dirtyFiles ? ` (${dirtyFiles} ungesicherte Änderungen)` : ''}`;+ dot.addEventListener('click', () => void this.select(i));+ return dot;+ }));+ const previewCommit = this.previewHash ? commits.find((c) => c.hash === this.previewHash) : null;+ ui.info.textContent = previewCommit+ ? `${previewCommit.subject} · ${fmt(previewCommit.date)}`+ : n === 0 ? 'Kein Verlauf' : `${n} ${n === 1 ? 'Stand' : 'Stände'}${dirtyFiles ? ` · ${dirtyFiles} ungesicherte Änderung${dirtyFiles === 1 ? '' : 'en'}` : ''}`;+ ui.restore.hidden = !previewCommit;+ ui.live.hidden = !previewCommit;+ ui.problem.hidden = problems.length === 0;+ ui.problem.textContent = problems.join(' ');+ }++ /** Prüfhilfe (nur Tests). */+ state() {+ return { count: this.log.commits.length, index: this.index(), previewing: this.previewHash, subjects: this.log.commits.map((c) => c.subject), problems: this.log.problems, dirtyFiles: this.log.dirtyFiles };+ }+}diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.tsindex 8bfd852..50d99d0 100644--- a/app/src/renderer/viewer.ts+++ b/app/src/renderer/viewer.ts@@ -263,6 +263,14 @@ export class Viewer {facesOf(partId: string): FaceEntry[] { return this.parts.get(partId)?.meta.faces ?? []; }+ /** Ausdehnung (x, y, z in mm) eines Bauteils. */+ partSize(partId: string): number[] | null {+ const p = this.parts.get(partId);+ if (!p) return null;+ const s = new THREE.Box3().setFromObject(p.group).getSize(new THREE.Vector3());+ return [+s.x.toFixed(3), +s.y.toFixed(3), +s.z.toFixed(3)];+ }+/** Bildschirmposition (Pixel im Fenster) des Flächenmittelpunkts. */screenOf(partId: string, faceId: number): { x: number; y: number } {const f = this.facesOf(partId).find((x) => x.id === faceId)!;diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex d2742d2..723d729 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -34,6 +34,24 @@ export interface PartMap {}export interface ModelMap { version: number; parts: PartMap[] }+/** Stand der Speicherung: was ist gesichert, was nicht (E21). */+export interface SaveState {+ zipPath: string | null;+ savedHead: string | null;+ head: string | null;+ /** Geänderte Dateien seit dem letzten Commit (ohne output/). */+ dirtyFiles: number;+ unsaved: boolean;+ hasRepo: boolean;+}+export interface SaveResult { cancelled: boolean; zipPath?: string; snapshot?: string | null; files?: number; bytes?: number; warnings?: string[]; error?: string }+export interface OpenResult { cancelled: boolean; opened?: boolean; error?: string }++export interface CommitInfo { hash: string; short: string; author: string; date: string; subject: string }+export interface GitLog { commits: CommitInfo[]; problems: string[]; head: string | null; dirtyFiles: number }+export interface PreviewResult { commit: CommitInfo | null; glb: ArrayBuffer; map: ModelMap; error?: string }+export interface RestoreResult { cancelled: boolean; commit?: string | null; safety?: string | null; error?: string }+export interface CadideApi {testMode: boolean;project: {@@ -42,7 +60,19 @@ export interface CadideApi {list(): Promise<ProjectListEntry[]>;open(id: string): Promise<ProjectInfo>;onChanged(cb: (p: ProjectInfo) => void): void;+ saveState(): Promise<SaveState>;+ save(saveAs?: boolean): Promise<SaveResult>;+ openZip(): Promise<OpenResult>;+ onSaveState(cb: (s: SaveState) => void): void;+ };+ versions: {+ log(): Promise<GitLog>;+ preview(hash: string): Promise<PreviewResult>;+ restore(hash: string): Promise<RestoreResult>;+ onChanged(cb: () => void): void;};+ /** Nur im Testmodus (CADIDE_TEST=1) vorhanden. */+ test?: { answers(a: unknown[]): Promise<void>; screenshot(file: string): Promise<{ width: number; height: number }> };build: {run(): Promise<void>;cancel(): Promise<void>;diff --git a/app/test/harness.mjs b/app/test/harness.mjsnew file mode 100644index 0000000..7487744--- /dev/null+++ b/app/test/harness.mjs@@ -0,0 +1,68 @@+// Gemeinsame Testhilfe: startet die echte Electron-App mit isolierten App-Daten und steuert sie per CDP.+import { spawn, spawnSync } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { electronExe } from '../scripts/electron-local.mjs';+import { connectPage } from './cdp.mjs';++export const APP = path.resolve(import.meta.dirname, '..');+export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++/**+ * Startet die App. Standard: Fenster unsichtbar (SMOKE_VISIBLE=1 zeigt es), eigener App-Daten-Ordner,+ * Watchdog (hängt etwas, wird alles hart beendet). `userData` erlaubt einen Neustart mit denselben Daten.+ */+export async function startApp({ port = 9333, userData, watchdogMs = 6 * 60 * 1000, name = 'test' } = {}) {+ // SMOKE_VISIBLE=1 sichtbar, =offscreen angezeigt außerhalb des Bildschirms (frische Screenshots, kein Fokusklau), sonst unsichtbar+ const mode = process.env.SMOKE_VISIBLE;+ const visible = mode === '1';+ const ud = userData ?? fs.mkdtempSync(path.join(os.tmpdir(), `cadide-${name}-`));+ const child = spawn(electronExe(APP), ['.', `--remote-debugging-port=${port}`], {+ cwd: APP, env: { ...process.env, CADIDE_USER_DATA: ud, CADIDE_TEST: '1', CADIDE_HIDDEN: visible ? '0' : mode === 'offscreen' ? 'offscreen' : '1' }, stdio: ['ignore', 'pipe', 'pipe'],+ });+ let log = '';+ child.stdout.on('data', (d) => { log += d; });+ child.stderr.on('data', (d) => { log += d; });+ const kill = () => {+ if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });+ else child.kill('SIGKILL');+ };+ const dog = setTimeout(() => { console.log('ABBRUCH: Watchdog'); kill(); process.exit(1); }, watchdogMs);+ dog.unref();++ const page = await connectPage(port, 'index.html', 60000);+ if (!page) { kill(); throw new Error('Electron nicht erreichbar oder kein Fenster. ' + log.slice(-600)); }++ const ev = (fn, arg) => page.evaluate(fn, arg);+ const app = {+ ud, page, ev, visible, log: () => log,+ /** Wartet, bis fn im Fenster einen wahren Wert liefert. */+ async waitFor(desc, fn, timeout = 60000, arg) {+ const t0 = Date.now();+ for (;;) {+ try { const v = await ev(fn, arg); if (v) return v; } catch { /* Seite lädt noch */ }+ if (Date.now() - t0 > timeout) throw new Error(`Zeitüberschreitung: ${desc}`);+ await sleep(200);+ }+ },+ domClick: (id) => ev((i) => document.getElementById(i).click(), id),+ /** Antworten für die nächsten nativen Dialoge (Pfade, Knopf-Indizes). */+ answers: (list) => ev((a) => window.cadide.test.answers(a), list),+ /** Screenshot des Fensters (über Electron, funktioniert auch bei unsichtbarem Fenster). */+ screenshot: (file) => ev((f) => window.cadide.test.screenshot(f), file),+ /** Beendet die App hart (wie ein Absturz). */+ crash() { clearTimeout(dog); page.close(); kill(); },+ async stop() { clearTimeout(dog); page.close(); kill(); await sleep(600); },+ };+ return app;+}++/** Sammelt Prüfungen und gibt sie einheitlich aus. */+export function checker() {+ let fails = 0;+ const check = (label, ok, detail = '') => { console.log((ok ? 'OK ' : 'FEHLER ') + label.padEnd(68) + detail); if (!ok) fails++; };+ return { check, fail: () => { fails++; }, get fails() { return fails; } };+}++export function cleanup(dir) { try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* Dateien noch gesperrt */ } }diff --git a/app/test/smoke.mjs b/app/test/smoke.mjsindex 423666d..ea81251 100644--- a/app/test/smoke.mjs+++ b/app/test/smoke.mjs@@ -1,61 +1,26 @@-// Smoke-Test der echten Electron-App: startet sie mit isolierten App-Daten und steuert sie über den Debug-Port (CDP).-// Aufruf: npm run test:smoke (baut vorher). Beendet sich mit Exit-Code 1, wenn eine Prüfung scheitert.-import { spawn, spawnSync } from 'node:child_process';+// Smoke-Test der echten Electron-App: Projekt, Viewer, Terminal, Auto-Build, Fehlerfall, Projektwechsel.+// Aufruf: npm run test:smoke (baut vorher). SMOKE_VISIBLE=1 zeigt das Fenster und macht einen Screenshot.import fs from 'node:fs';-import os from 'node:os';import path from 'node:path';-import { electronExe } from '../scripts/electron-local.mjs';-import { connectPage } from './cdp.mjs';+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';-const APP = path.resolve(import.meta.dirname, '..');-const PORT = 9333;-const userData = fs.mkdtempSync(path.join(os.tmpdir(), 'cadide-smoke-'));-const electron = electronExe(APP);+const t = checker();+const { check } = t;+let app;-let fails = 0;-const check = (label, ok, detail = '') => { console.log((ok ? 'OK ' : 'FEHLER ') + label.padEnd(66) + detail); if (!ok) fails++; };-const sleep = (ms) => new Promise((r) => setTimeout(r, ms));--// Standard: Fenster unsichtbar (CADIDE_HIDDEN), zeichnet aber weiter. Mit SMOKE_VISIBLE=1 sichtbar, nur dann gibt es einen Screenshot.-const visible = process.env.SMOKE_VISIBLE === '1';-const child = spawn(electron, ['.', `--remote-debugging-port=${PORT}`], {- cwd: APP, env: { ...process.env, CADIDE_USER_DATA: userData, CADIDE_TEST: '1', CADIDE_HIDDEN: visible ? '0' : '1' }, stdio: ['ignore', 'pipe', 'pipe'],-});-let appLog = '';-child.stdout.on('data', (d) => { appLog += d; });-child.stderr.on('data', (d) => { appLog += d; });-const killApp = () => {- if (process.platform === 'win32') spawnSync('taskkill', ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true });- else child.kill('SIGKILL');-};--// Watchdog: hängt irgendetwas, wird der Test nach 4 Minuten hart beendet, statt ewig zu laufen-setTimeout(() => { console.log('ABBRUCH: Watchdog nach 4 Minuten'); killApp(); process.exit(1); }, 4 * 60 * 1000).unref();--async function main() {- const page = await connectPage(PORT, 'index.html', 60000);- if (!page) throw new Error('Electron nicht erreichbar oder kein Fenster. ' + appLog.slice(-600));- check('App gestartet, Fenster verbunden', true);-- const ev = (fn, arg) => page.evaluate(fn, arg);- const waitFor = async (desc, fn, timeout = 60000, arg) => {- const t0 = Date.now();- for (;;) {- try { const v = await ev(fn, arg); if (v) return v; } catch { /* Seite lädt noch */ }- if (Date.now() - t0 > timeout) throw new Error(`Zeitüberschreitung: ${desc}`);- await sleep(200);- }- };+try {+ app = await startApp({ name: 'smoke' });+ const { ev, waitFor, domClick, ud, page } = app;const status = () => ev(() => window.__t.status());- const domClick = (id) => ev((i) => document.getElementById(i).click(), id);+ check('App gestartet, Fenster verbunden', true);// 1) Start: Projekt angelegt, automatischer erster Build, Bauteile im Viewerawait waitFor('window.__t', () => !!window.__t && !!window.__t.project());await waitFor('Build ok', () => window.__t.status().state === 'ok' && window.__t.partCount() === 2);const proj = await ev(() => window.__t.project());- check('Projekt liegt unter <App-Daten>/workspaces/<uuid>', proj.dir.startsWith(path.join(userData, 'workspaces')) && /[0-9a-f-]{36}$/.test(proj.dir), proj.dir.slice(-45));+ check('Projekt liegt unter <App-Daten>/workspaces/<uuid>', proj.dir.startsWith(path.join(ud, 'workspaces')) && /[0-9a-f-]{36}$/.test(proj.dir), proj.dir.slice(-45));check('Vorlagen-Dateien vorhanden (AGENTS.md, CLAUDE.md, NOTES.md, model.py …)',- ['AGENTS.md', 'CLAUDE.md', 'NOTES.md', 'model.py', '.gitignore', '.cadide/project.json'].every((f) => fs.existsSync(path.join(proj.dir, f))));+ ['AGENTS.md', 'CLAUDE.md', 'NOTES.md', 'model.py', '.gitignore', '.cadide/project.json', '.git/HEAD'].every((f) => fs.existsSync(path.join(proj.dir, f))));check('Erster Build automatisch, 2 Bauteile im Baum', JSON.stringify(await ev(() => window.__t.treeNames())) === '["Body","Lid"]');check('Nach dem Build kein Fehlerhinweis', (await status()).viewerMsg === '', (await status()).text);@@ -124,15 +89,13 @@ async function main() {check('Projektwechsel: genau ein frisches Terminal', await ev(() => window.__t.terminals.count) === 1);check('Beide Arbeitsordner existieren getrennt', fs.existsSync(proj.dir) && fs.existsSync(p2.dir) && proj.dir !== p2.dir);- if (visible) { await sleep(500); await page.screenshot(path.join(APP, 'test', 'smoke.png')); }+ if (app.visible) { await sleep(500); await page.screenshot(path.join(APP, 'test', 'smoke.png')); }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));- page.close();+} catch (e) {+ console.log('ABBRUCH:', e.message);+ t.fail();}--try { await main(); } catch (e) { console.log('ABBRUCH:', e.message); fails++; }-killApp();-await sleep(600);-try { fs.rmSync(userData, { recursive: true, force: true }); } catch { /* Dateien noch gesperrt */ }-console.log(fails ? `\n${fails} Prüfung(en) fehlgeschlagen` : '\nALLE PRÜFUNGEN BESTANDEN');-process.exit(fails ? 1 : 0);+if (app) { await app.stop(); cleanup(app.ud); }+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/versions.mjs b/app/test/versions.mjsnew file mode 100644index 0000000..177325a--- /dev/null+++ b/app/test/versions.mjs@@ -0,0 +1,200 @@+// Test für Git-Verlauf, ZIP speichern/öffnen, Vorschau und Wiederherstellen, dazu die Störfälle aus PLAN.md Abschnitt 9.+// Aufruf: npm run test:versions (baut vorher).+import { exec } from 'dugite';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { randomUUID } from 'node:crypto';+import yauzl from 'yauzl';+import yazl from 'yazl';+import { checker, cleanup, sleep, startApp } from './harness.mjs';++const t = checker();+const { check } = t;+const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cadide-vt-'));+let app;++const listZip = (p) => new Promise((resolve, reject) => yauzl.open(p, { lazyEntries: true }, (e, z) => {+ if (e) return reject(e);+ const names = [];+ z.on('entry', (en) => { names.push(en.fileName); z.readEntry(); });+ z.on('end', () => resolve(names));+ z.readEntry();+}));+const rmRetry = async (p) => { for (let i = 0; i < 10; i++) { try { fs.rmSync(p, { recursive: true, force: true }); return; } catch { await sleep(300); } } };++try {+ app = await startApp({ name: 'versions' });+ const { ev, waitFor, domClick, ud, page } = app;+ 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 g = async (...args) => (await exec(args, dir)).stdout.trim();+ const modelPy = path.join(dir, 'model.py');+ const term = () => ev(() => window.__t.terminals.activeId);+ const type = async (cmd) => { const id = await term(); await ev(([i, c]) => window.cadide.term.write(i, c + '\r'), [id, cmd]); };+ const termText = async () => ev((i) => window.__t.termText(i), await term());+ const zipPath = path.join(workDir, 'Testmodell.zip');+ const versions = () => ev(() => window.__t.versions());+ const saveState = () => ev(() => window.__t.saveState());++ // ---- 1) Neues Projekt hat einen Git-Verlauf, mitgeliefertes Git im Terminal ----+ await waitFor('Verlauf geladen', () => window.__t.versions().count === 1);+ check('Neues Projekt: Git-Repository mit Startcommit', (await g('log', '--format=%s')) === 'Neues Modell angelegt');+ check('Startcommit enthält output/model.step (Vorschau des ersten Standes möglich)', (await g('ls-files', 'output/model.step')) === 'output/model.step');+ check('Nach dem ersten Build gilt der Stand als sauber (output/ zählt nicht)', (await versions()).dirtyFiles === 0);+ check('Git-Identität ist gesetzt (Agent kann committen)', (await g('config', 'user.name')).length > 0 && (await g('config', 'user.email')).length > 0);+ check('Zeilenenden werden nicht umgewandelt (autocrlf aus)', (await g('config', 'core.autocrlf')) === 'false');+ await type('git --version');+ await waitFor('git im Terminal', (i) => /git version 2\.\d+/.test(window.__t.termText(i)), 20000, await term());+ check('Im Terminal läuft das mitgelieferte Git (2.53)', /git version 2\.53/.test(await termText()), (await termText()).match(/git version [\d.]+\S*/)?.[0] ?? '');++ // ---- 2) Agent committet selbst ----+ const src = fs.readFileSync(modelPy, 'utf8');+ fs.writeFileSync(modelPy, src.replace('LENGTH = 60.0', 'LENGTH = 80.0'));+ await waitFor('Build mit Länge 80', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] > 79);+ check('Änderung am Modell erscheint im Viewer (Body 80 mm lang)', (await ev(() => window.__t.partSize('Body')))[0] === 80);+ await waitFor('ungesicherte Änderung', () => window.__t.versions().dirtyFiles === 1);+ check('Ungesicherte Änderung wird angezeigt (1 Datei)', true);+ await type('git add -A; git commit -q -m "Laenge auf 80"');+ await waitFor('zweiter Stand im Verlauf', () => window.__t.versions().count === 2, 20000);+ check('Commit des Agenten erscheint in der Verlaufsleiste', (await versions()).subjects.includes('Laenge auf 80'));+ check('Commit enthält die STEP-Datei des gebauten Standes', (await g('show', '--stat', '--format=', 'HEAD')).includes('output/model.step'));++ // ---- 3) Speichern: Snapshot + ZIP ----+ fs.appendFileSync(path.join(dir, 'NOTES.md'), '\nWunsch: Deckel mit Lippe\n');+ await waitFor('Notizänderung', () => window.__t.saveState() && window.__t.saveState().dirtyFiles === 1);+ check('Vor dem Speichern: Badge „ungespeichert"', (await saveState()).unsaved === true);+ await app.answers([zipPath]);+ await domClick('btn-save');+ await waitFor('gespeichert', () => window.__t.saveState() && !window.__t.saveState().unsaved && window.__t.saveState().zipPath, 60000);+ check('ZIP wurde geschrieben', fs.existsSync(zipPath), `${Math.round(fs.statSync(zipPath).size / 1024)} KB`);+ const names = await listZip(zipPath);+ check('ZIP enthält Modell, .git, Projektdaten und Marker', ['model.py', '.git/HEAD', '.cadide/project.json', '.cadide/zip-info.json', 'AGENTS.md'].every((n) => names.includes(n)));+ check('ZIP enthält keine Caches (GLB, Mapping, build.json, __pycache__)', !names.some((n) => /model\.glb|model\.map\.json|build\.json|__pycache__/.test(n)));+ await waitFor('Meldung und Name', () => window.__t.toast().text.startsWith('Gespeichert') && window.__t.project().name === 'Testmodell', 20000);+ check('Auto-Snapshot beim Speichern hat die Notiz gesichert', (await g('log', '-1', '--format=%s')) === 'Automatischer Snapshot beim Speichern');+ check('Modellname folgt dem Dateinamen der ZIP', (await ev(() => window.__t.project())).name === 'Testmodell');+ check('Nach dem Speichern: sauber, gespeichert-Anzeige', (await saveState()).dirtyFiles === 0 && (await ev(() => document.getElementById('save-badge').textContent)).includes('gespeichert'));+ check('Meldung „Gespeichert" erscheint', (await ev(() => window.__t.toast())).text.startsWith('Gespeichert'));+ const commitsBefore = (await g('rev-list', '--count', 'HEAD'));+ await app.domClick('btn-save');+ await sleep(2500);+ check('Zweites Speichern ohne Änderung legt keinen leeren Snapshot an', (await g('rev-list', '--count', 'HEAD')) === commitsBefore);++ // ---- 4) Vorschau alter Stände ----+ const first = await g('rev-parse', 'HEAD~2');+ await ev(() => document.querySelectorAll('#vdots .vdot')[0].click());+ await waitFor('Vorschau aktiv', () => !!window.__t.versions().previewing, 60000);+ await waitFor('Vorschau geladen', () => window.__t.partCount() === 2 && !window.__t.banner().hidden);+ check('Vorschau des ersten Standes: Body ist 60 mm lang (Arbeitsstand: 80)', (await ev(() => window.__t.partSize('Body')))[0] === 60);+ check('Banner zeigt „Vorschau … schreibgeschützt"', (await ev(() => window.__t.banner())).text.includes('schreibgeschützt'));+ await sleep(800); // capturePage liefert bei unsichtbaren Fenstern sonst ein etwas älteres Bild+ const shot = await app.screenshot(path.join(import.meta.dirname, 'versions.png')).catch((e) => ({ error: String(e) }));+ check('Screenshot der Vorschau (Verlaufsleiste sichtbar)', !!shot.width, shot.width ? `${shot.width}x${shot.height}` : shot.error);+ check('Arbeitsordner blieb unberührt (model.py hat weiter 80)', fs.readFileSync(modelPy, 'utf8').includes('LENGTH = 80.0'));+ check('Kein neuer Commit durch die Vorschau', (await g('rev-list', '--count', 'HEAD')) === commitsBefore);+ fs.appendFileSync(modelPy, '\n# Kommentar während der Vorschau\n');+ await sleep(4000);+ check('Ein Build während der Vorschau ändert die Anzeige nicht', (await ev(() => window.__t.partSize('Body')))[0] === 60);+ fs.writeFileSync(modelPy, fs.readFileSync(modelPy, 'utf8').replace('\n# Kommentar während der Vorschau\n', ''));++ // ---- 5) Wiederherstellen als neuer Commit ----+ await app.answers([0]);+ await domClick('btn-restore');+ await waitFor('wiederhergestellt', () => !window.__t.versions().previewing && window.__t.versions().subjects.some((s) => s.startsWith('Stand wiederhergestellt')), 60000);+ check('Wiederherstellen legt einen NEUEN Commit an', (await g('log', '-1', '--format=%s')).startsWith('Stand wiederhergestellt: Neues Modell angelegt'));+ check('Verlauf blieb vollständig (alter Startcommit unverändert vorhanden)', (await g('cat-file', '-t', first)) === 'commit' && (await g('rev-list', '--count', 'HEAD')) > commitsBefore);+ check('Dateien sind zurück: model.py mit 60, Notiz-Wunsch entfernt', fs.readFileSync(modelPy, 'utf8').includes('LENGTH = 60.0') && !fs.readFileSync(path.join(dir, 'NOTES.md'), 'utf8').includes('Wunsch'));+ await waitFor('Build nach Wiederherstellung', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] === 60);+ check('Live-Ansicht zeigt wieder den (wiederhergestellten) Stand, Body 60 mm', true);+ check('Kein HEAD-Umbau: Branch ist weiter main, nicht detached', (await g('symbolic-ref', '--short', 'HEAD')) === 'main');++ // ---- 6) Störfall: .git verschwindet (Agent hat es gelöscht/verschoben) ----+ await app.domClick('btn-save');+ await waitFor('gespeichert nach Restore', () => !window.__t.saveState().unsaved, 60000);+ fs.renameSync(path.join(dir, '.git'), path.join(dir, '.git_weg'));+ await waitFor('Problem gemeldet', () => window.__t.versions().problems.some((p) => p.includes('Kein Git-Verlauf')), 20000);+ check('Ohne .git: Verlauf meldet das Problem verständlich', (await versions()).problems[0].includes('Kein Git-Verlauf'), (await versions()).problems[0].slice(0, 50));+ check('Ohne .git: App und Terminal laufen weiter', await ev(() => window.__t.terminals.count) === 1);+ fs.appendFileSync(path.join(dir, 'NOTES.md'), '\nohne git geändert\n');+ await sleep(300);+ await app.domClick('btn-save');+ await waitFor('Speichern ohne Git', () => window.__t.toast().text.includes('Kein Git-Verlauf'), 60000);+ check('Ohne .git: Speichern klappt trotzdem, mit Warnung', !(await ev(() => window.__t.toast())).hidden);+ fs.renameSync(path.join(dir, '.git_weg'), path.join(dir, '.git'));+ await waitFor('Problem weg', () => window.__t.versions().problems.length === 0, 20000);+ check('.git zurück: Meldung verschwindet', true);+ // Aufräumen: die Notiz-Änderung wieder in den Verlauf und die ZIP+ await app.domClick('btn-save');+ await waitFor('gespeichert', () => !window.__t.saveState().unsaved, 60000);++ // ---- 7) ZIP öffnen ----+ // A) identisch: kein Dialog, Arbeitsordner bleibt+ await app.answers([zipPath]);+ await domClick('btn-open');+ await sleep(2500);+ check('Öffnen der identischen ZIP: gleicher Arbeitsordner, keine Rückfrage', (await ev(() => window.__t.project())).id === proj.id && !(await ev(() => window.__t.toast())).error);+ // B) Arbeitsordner weicht ab -> „ZIP laden" sichert den Arbeitsstand+ fs.appendFileSync(path.join(dir, 'NOTES.md'), '\nLOKALE ÄNDERUNG\n');+ await waitFor('dirty', () => window.__t.saveState().dirtyFiles >= 1, 20000);+ await app.answers([zipPath, 1]);+ await domClick('btn-open');+ await waitFor('neu geöffnet', () => window.__t.status().state === 'ok' && !window.__t.saveState().unsaved && window.__t.saveState().dirtyFiles === 0, 60000);+ check('ZIP laden: Stand aus der ZIP ist da (lokale Änderung weg)', !fs.readFileSync(path.join(dir, 'NOTES.md'), 'utf8').includes('LOKALE ÄNDERUNG'));+ const backups = fs.existsSync(path.join(ud, 'workspace-backups')) ? fs.readdirSync(path.join(ud, 'workspace-backups')).filter((n) => n.startsWith(proj.id)) : [];+ check('Bisheriger Arbeitsordner liegt gesichert in workspace-backups/', backups.length === 1 && fs.readFileSync(path.join(ud, 'workspace-backups', backups[0], 'NOTES.md'), 'utf8').includes('LOKALE ÄNDERUNG'));+ const logBefore = await g('log', '--format=%s');+ // C) anderer Rechner: Arbeitsordner existiert nicht -> entpacken+ await domClick('btn-new');+ await waitFor('zweites Projekt', (id) => window.__t.project().id !== id && window.__t.status().state === 'ok', 90000, proj.id);+ await rmRetry(dir);+ fs.rmSync(path.join(ud, 'projects', `${proj.id}.json`), { force: true });+ await app.answers([zipPath]);+ await domClick('btn-open');+ await waitFor('entpackt und geöffnet', (id) => window.__t.project().id === id && window.__t.status().state === 'ok' && window.__t.versions().count > 1, 90000, proj.id);+ check('Arbeitsordner fehlt (anderer Rechner): ZIP wird entpackt und geöffnet', fs.existsSync(modelPy) && fs.readFileSync(modelPy, 'utf8').includes('LENGTH = 60.0'));+ check('Der Verlauf ist mitgekommen (gleiche Commits wie vorher)', (await g('log', '--format=%s')) === logBefore);+ check('Entpacktes Projekt gilt als gespeichert', (await saveState()).unsaved === false);+ // D) böse ZIP (Zip-Slip)+ const evil = path.join(workDir, 'boese.zip');+ const z = new yazl.ZipFile();+ z.addBuffer(Buffer.from(JSON.stringify({ id: randomUUID() })), '.cadide/project.json');+ z.addBuffer(Buffer.from('böse'), 'xx/evil.txt');+ z.end();+ const chunks = [];+ await new Promise((res) => { z.outputStream.on('data', (c) => chunks.push(c)); z.outputStream.on('end', res); });+ const raw = Buffer.concat(chunks);+ let at = 0, replaced = 0;+ while ((at = raw.indexOf('xx/evil.txt', at)) >= 0) { raw.write('../evil.txt', at); at += 11; replaced++; }+ fs.writeFileSync(evil, raw);+ await app.answers([evil]);+ await domClick('btn-open');+ await waitFor('Fehlermeldung', () => window.__t.toast().error, 20000);+ const evilToast = (await ev(() => window.__t.toast())).text;+ // Zwei Schichten: yauzl lehnt ungültige Pfade schon beim Lesen ab, unsere Prüfung beim Entpacken ist die zweite+ check(`Böse ZIP („../evil.txt", ${replaced} Einträge im Archiv) wird abgelehnt`, /Unsicher|invalid relative path/.test(evilToast), evilToast.slice(0, 70));+ check('Nichts außerhalb des Zielordners geschrieben, keine Reste', !fs.existsSync(path.join(ud, 'evil.txt')) && !fs.existsSync(path.join(ud, 'workspaces', 'evil.txt')) && !fs.readdirSync(path.join(ud, 'workspaces')).some((n) => n.startsWith('.tmp-')));+ check('Keine ZIP-Datei im Weg: Projekt bleibt offen und nutzbar', (await ev(() => window.__t.project().id)) === proj.id);++ // ---- 8) Absturz-Wiederherstellung: ungespeicherte Änderung überlebt ----+ fs.appendFileSync(path.join(dir, 'NOTES.md'), '\nungespeichert vor dem Absturz\n');+ await waitFor('ungespeichert', () => window.__t.saveState().unsaved, 20000);+ const ud2 = app.ud;+ app.crash();+ await sleep(1500);+ app = await startApp({ name: 'versions', userData: ud2 });+ await app.waitFor('Projekt wieder da', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok');+ check('Nach hartem Beenden öffnet die App dasselbe Projekt wieder', (await app.ev(() => window.__t.project().id)) === proj.id);+ check('Die ungespeicherte Änderung ist noch da und als ungespeichert markiert', fs.readFileSync(path.join(dir, 'NOTES.md'), 'utf8').includes('vor dem Absturz') && (await app.ev(() => window.__t.saveState().unsaved)));++ const relevant = page.errors.filter((e) => !/favicon/i.test(e));+ check('Keine Konsolenfehler im Renderer (vor dem Neustart)', relevant.length === 0, relevant.slice(0, 2).join(' | ').slice(0, 120));+} catch (e) {+ console.log('ABBRUCH:', e.message);+ t.fail();+}+if (app) { await app.stop(); cleanup(app.ud); }+cleanup(workDir);+console.log(t.fails ? `\n${t.fails} Prüfung(en) fehlgeschlagen` : '\nALLE PRÜFUNGEN BESTANDEN');+process.exit(t.fails ? 1 : 0);