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: pip im Terminal installiert in die Projektumgebung, fehlende Pakete werden nachinstalliert (E67)
Kai-Jungsthoefelc7eca808173c
diff --git a/app/package.json b/app/package.jsonindex 26e4b8e..ec47a81 100644--- a/app/package.json+++ b/app/package.json@@ -18,6 +18,7 @@"test:skills": "npm run build && node test/skills.mjs","test:fasteners": "npm run build && node test/fasteners.mjs","test:animation": "npm run build && node test/animation.mjs",+ "test:packages": "npm run build && node test/packages.mjs","test:unit": "node test/unit.mjs","test": "npm run build && node test/run-all.mjs"},diff --git a/app/resources/template/.gitignore b/app/resources/template/.gitignoreindex ecda416..52f0c4a 100644--- a/app/resources/template/.gitignore+++ b/app/resources/template/.gitignore@@ -17,3 +17,6 @@ __pycache__/renders/.soma/anim/.soma/results/++# Environment with the model's extra packages (only requirements.txt is versioned)+.soma/env/diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.mdindex 4ab3552..8c8da2e 100644--- a/app/resources/template/AGENTS.md+++ b/app/resources/template/AGENTS.md@@ -55,8 +55,10 @@ This folder is a git repository, and the `git` on your PATH is the one the app u## 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.-- Install only what the model really needs. The app records the packages of the project.+- Use the `python` and `pip` on your PATH. They belong to this app and already have CadQuery, numpy, scipy and more.+- If the model needs another package, run `pip install <package>`. It goes into this model's own environment, and `soma build` records it in `requirements.txt` (do not edit that file). Install only what the model really needs.+- **Do not create virtual environments** (`.venv`, `venv`), and do not use `--user`, `uv` or another Python to install packages.+- If pip refuses a package because it needs other versions of the app's libraries, pick another version or another package. The app's libraries stay as they are.- Do not move or rename `model.py`, and do not create your own STEP writer: the app relies on `soma build`.## Feedback from the userdiff --git a/app/src/main/build.ts b/app/src/main/build.tsindex 2aa26ed..9dd0c9e 100644--- a/app/src/main/build.ts+++ b/app/src/main/build.ts@@ -34,6 +34,10 @@ export class BuildManager extends EventEmitter {private timer: NodeJS.Timeout | null = null;private rerun = false;private disposed = false;+ /** Pakete in Arbeit (E67) und ob danach gebaut wird. */+ private installing: string[] | null = null;+ private afterInstall = false;+ private packageError: string | null = null;constructor(private readonly dir: string) { super(); }@@ -65,6 +69,11 @@ export class BuildManager extends EventEmitter {start(reason = 'manuell'): void {if (this.disposed) return;if (this.timer) { clearTimeout(this.timer); this.timer = null; }+ if (this.installing) { // ohne die Pakete scheiterte der Build nur am Import+ this.afterInstall = true;+ this.setStatus({ ...this.status, queued: true });+ return;+ }if (this.proc) {this.rerun = true;this.setStatus({ ...this.status, queued: true });@@ -114,6 +123,33 @@ export class BuildManager extends EventEmitter {this.setStatus({ state: 'ok', result, reason: 'letzter Build', seconds, builtAt });}+ /**+ * Pakete aus requirements.txt installieren (E67), bevor gebaut wird. Wer in der Zwischenzeit bauen will, wartet, danach+ * läuft genau ein Build. `build`: danach auf jeden Fall bauen (es gibt keinen gültigen Build). `install` gibt einen+ * Fehlertext zurück oder null.+ */+ async installFirst(names: string[], install: () => Promise<string | null>, build: boolean): Promise<void> {+ if (this.installing || this.disposed) return;+ this.installing = names;+ this.afterInstall = build;+ this.setStatus(this.status);+ let error: string | null;+ try { error = await install(); } catch (e) { error = e instanceof Error ? e.message : String(e); }+ this.installing = null;+ if (this.disposed) return;+ this.packageError = error;+ const { queued: _q, ...rest } = this.status;+ this.setStatus(rest);+ if (this.afterInstall) { this.afterInstall = false; this.start('Pakete installiert'); }+ }++ /** Die Projektumgebung ließ sich nicht einrichten (E67): Die Oberfläche zeigt es als Hinweis. */+ reportPackageError(error: string): void {+ if (this.disposed) return;+ this.packageError = error;+ this.setStatus(this.status);+ }+/** Läuft gerade ein Build oder steht einer an? */get busy(): boolean { return this.proc !== null || this.timer !== null; }@@ -141,8 +177,10 @@ export class BuildManager extends EventEmitter {}private setStatus(s: BuildStatus): void {- this.status = s;- this.emit('status', s);+ // Installation und Paketfehler gehören zum Manager, nicht zum einzelnen Build: bei jedem Stand mitgeben+ const { installing: _i, packageError: _p, ...rest } = s;+ this.status = { ...rest, ...(this.installing ? { installing: this.installing } : {}), ...(this.packageError ? { packageError: this.packageError } : {}) };+ this.emit('status', this.status);}}diff --git a/app/src/main/git.ts b/app/src/main/git.tsindex eabbece..c8fe13d 100644--- a/app/src/main/git.ts+++ b/app/src/main/git.ts@@ -18,11 +18,12 @@ const APP_SUBJECT = /^(Neues Modell angelegt|Automatischer Snapshot beim Speicheconst COMMON = ['-c', 'core.quotepath=false', '-c', 'core.autocrlf=false'];/*** Zwischenergebnisse der App, die nie in den Verlauf gehören: Geometrie für das Messen, gebaute Animationen, Ergebnisse- * von soma analyze (bis zu 70 MB je Auswertung) und Bilder und Videos von soma render. Ältere Projekte haben sie noch+ * von soma analyze (bis zu 70 MB je Auswertung), Bilder und Videos von soma render und die Projektumgebung mit den+ * Zusatzpaketen (E67, im Verlauf steht nur requirements.txt). Ältere Projekte haben sie noch* nicht in der .gitignore, deshalb klammert die App sie selbst aus, beim Status und beim Hinzufügen (siehe addAll), und* trägt sie beim Öffnen in .git/info/exclude ein, damit auch die Commits des Agenten sie nicht aufnehmen (ensureIgnored).*/-const APP_CACHES = ['.soma/geometry', '.soma/anim', '.soma/results', 'renders'];+const APP_CACHES = ['.soma/geometry', '.soma/anim', '.soma/results', '.soma/env', 'renders'];/** `output/` zählt nicht als Änderung: STEP-Dateien sind nicht byte-stabil (Zeitstempel, teils Reihenfolge). */const NOT_OUTPUT = ['--', '.', ':(exclude)output', ...APP_CACHES.map((p) => `:(exclude)${p}`)];/** Was die Vorlage in der .gitignore hat (resources/template/.gitignore), für ältere Projekte in .git/info/exclude. */diff --git a/app/src/main/packages.ts b/app/src/main/packages.tsnew file mode 100644index 0000000..c6d0c77--- /dev/null+++ b/app/src/main/packages.ts@@ -0,0 +1,162 @@+import { spawn, type ChildProcess } from 'node:child_process';+import fs from 'node:fs';+import path from 'node:path';+import { samePath } from './animations';+import { pythonExe, warmDir } from './paths';++/**+ * Projektumgebung (E25, E67): eine kleine venv je Modell unter .soma/env, angelegt von `soma env` (python/soma/env.py).+ * Sie sieht die Basisumgebung, kostet daher nur rund 0,6 MB, und der Agent installiert Zusatzpakete einfach mit pip (die+ * Terminals leiten pip per PIP_PYTHON hierher, terminals.ts). Die Umgebung kommt weder in die ZIP noch in Git. Was das+ * Modell davon importiert, hält `soma build` in requirements.txt fest. Fehlt davon etwas (anderer Rechner, alter Stand+ * wiederhergestellt), installiert die App es vor dem nächsten Build.+ */+const ENV_FORMAT = 1; // gleich FORMAT in python/soma/env.py+const WIN = process.platform === 'win32';+const INSTALL_TIMEOUT_MS = 10 * 60 * 1000;++export interface EnvPaths { env: string; scripts: string; python: string }++/** Pfade der Projektumgebung. Stehen fest, bevor es sie gibt: Terminals bekommen sie gleich beim Öffnen. */+export function envPaths(dir: string): EnvPaths {+ const env = path.join(dir, '.soma', 'env');+ const scripts = path.join(env, WIN ? 'Scripts' : 'bin');+ return { env, scripts, python: path.join(scripts, WIN ? 'python.exe' : 'python') };+}++/** soma-env.json, von `soma env` geschrieben. */+interface EnvInfo { format?: number; base_python?: string; base_sites?: string[]; base_mtimes?: (number | null)[]; site?: string }++function readInfo(env: string): EnvInfo | null {+ try { return JSON.parse(fs.readFileSync(path.join(env, 'soma-env.json'), 'utf8')) as EnvInfo; } catch { return null; }+}++/**+ * Passt die Umgebung zur Basis (dasselbe Python, Basispakete seither unverändert)? Dann muss beim Öffnen kein Python+ * starten. Ändert sich die Basis (neue App, Paket in der Basis nachinstalliert), bringt `soma env` sie auf den Stand.+ */+export function envIsCurrent(dir: string): boolean {+ const { env, python } = envPaths(dir);+ const info = readInfo(env);+ if (!info || info.format !== ENV_FORMAT || !fs.existsSync(python) || !fs.existsSync(path.join(env, 'pyvenv.cfg'))) return false;+ if (!info.base_python || !samePath(info.base_python, pythonExe())) return false;+ const sites = info.base_sites ?? [];+ return sites.length > 0 && sites.every((s, i) => {+ try { return Math.floor(fs.statSync(s).mtimeMs) === info.base_mtimes?.[i]; } catch { return false; }+ });+}++interface RunResult { code: number | null; out: string; err: string }++function run(exe: string, args: string[], cwd: string, timeoutMs: number): Promise<RunResult> {+ return new Promise((resolve) => {+ let out = '', err = '';+ let child: ChildProcess;+ try {+ child = spawn(exe, args, { cwd, windowsHide: true, env: { ...process.env, PIP_PYTHON: undefined, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8' } });+ } catch (e) { resolve({ code: null, out, err: e instanceof Error ? e.message : String(e) }); return; }+ const timer = setTimeout(() => { err += '\nZeitlimit überschritten.'; child.kill(); }, timeoutMs);+ child.stdout?.on('data', (d: Buffer) => { out += d.toString('utf8'); });+ child.stderr?.on('data', (d: Buffer) => { err += d.toString('utf8'); });+ child.on('error', (e) => { clearTimeout(timer); resolve({ code: null, out, err: err + e.message }); });+ child.on('close', (code) => { clearTimeout(timer); resolve({ code, out, err }); });+ });+}++/**+ * `soma env` mit dem Python der Basis: Projektumgebung anlegen oder auf den Stand bringen (rund 0,5 s). Gibt einen+ * Fehlertext zurück oder null. Gestartet wird in einem leeren Ordner, damit keine Datei des Projekts Module überdeckt.+ */+export async function ensureEnv(dir: string): Promise<string | null> {+ const cwd = warmDir();+ try { fs.mkdirSync(cwd, { recursive: true }); } catch { /* dann scheitert der Start und meldet es */ }+ const r = await run(pythonExe(), ['-m', 'soma', 'env', '--project', dir, '--json'], cwd, 60000);+ const line = r.out.trim().split(/\r?\n/).pop() ?? '';+ try {+ const res = JSON.parse(line) as { ok?: boolean; error?: string; note?: string };+ if (res.note) console.log(`[soma] ${res.note}`);+ if (res.ok) return null;+ if (res.error) return res.error;+ } catch { /* kein Ergebnis: unten mit der Fehlerausgabe melden */ }+ return `Die Projektumgebung ließ sich nicht anlegen (${pythonExe()}): ${(r.err || r.out).trim().split('\n').slice(-3).join(' ')}`;+}++const norm = (name: string) => name.replace(/[-_.]+/g, '-').toLowerCase();++/** Eine Zeile aus requirements.txt: Paketname (normiert) und gepinnte Version, falls angegeben. Optionen (`-…`) ohne Namen. */+interface Requirement { name: string | null; version: string | null; line: string }++function parseRequirements(text: string): Requirement[] {+ const out: Requirement[] = [];+ for (const raw of text.split(/\r?\n/)) {+ const line = raw.split(' #')[0].trim();+ if (!line || line.startsWith('#')) continue;+ const m = /^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*(?:==\s*([^\s;,]+))?/.exec(line);+ out.push({ name: m && !line.startsWith('-') ? norm(m[1]) : null, version: m?.[2] ?? null, line });+ }+ return out;+}++/** Installierte Pakete der Projektumgebung (Name normiert, Version) laut METADATA in site-packages. */+function installedInEnv(env: string): Map<string, string> {+ const have = new Map<string, string>();+ const site = path.join(env, readInfo(env)?.site ?? (WIN ? path.join('Lib', 'site-packages') : ''));+ let entries: string[];+ try { entries = fs.readdirSync(site); } catch { return have; }+ for (const e of entries) {+ if (!e.endsWith('.dist-info')) continue;+ try {+ const head = fs.readFileSync(path.join(site, e, 'METADATA'), 'utf8').split(/\r?\n\r?\n/)[0];+ const name = /^Name:\s*(.+)$/m.exec(head)?.[1]?.trim();+ const version = /^Version:\s*(.+)$/m.exec(head)?.[1]?.trim();+ if (name && version) have.set(norm(name), version);+ } catch { /* unvollständig: gilt als nicht installiert */ }+ }+ return have;+}++/** Paketnamen der Basis (aus den Constraints, die `soma env` schreibt). Sie gelten immer als vorhanden: Die Basis gewinnt. */+function basePackages(env: string): Set<string> {+ try {+ return new Set(parseRequirements(fs.readFileSync(path.join(env, 'base-constraints.txt'), 'utf8')).flatMap((r) => (r.name ? [r.name] : [])));+ } catch { return new Set(); }+}++/** Zeilen aus requirements.txt, die in der Projektumgebung fehlen oder dort eine andere Version haben. */+function missingLines(dir: string): Requirement[] {+ let text: string;+ try { text = fs.readFileSync(path.join(dir, 'requirements.txt'), 'utf8'); } catch { return []; }+ const { env } = envPaths(dir);+ const have = installedInEnv(env);+ const base = basePackages(env);+ return parseRequirements(text).filter((r) => {+ if (!r.name || base.has(r.name)) return false;+ const v = have.get(r.name);+ return v === undefined || (r.version !== null && v !== r.version);+ });+}++/** Fehlende Pakete aus requirements.txt, für die Anzeige (z. B. „tabulate==0.10.0“). Leer: nichts zu tun. */+export function missingPackages(dir: string): string[] {+ return missingLines(dir).map((r) => r.line);+}++/**+ * Installiert, was laut requirements.txt fehlt, mit pip der Projektumgebung (die Constraints der Basis stehen in ihrer+ * pip.ini). Optionen aus der Datei (z. B. `--index-url`) gehen mit. Gibt einen Fehlertext zurück oder null.+ */+export async function installMissing(dir: string): Promise<string | null> {+ const missing = missingLines(dir);+ if (!missing.length) return null;+ const { env, python } = envPaths(dir);+ let options: string[] = [];+ try { options = parseRequirements(fs.readFileSync(path.join(dir, 'requirements.txt'), 'utf8')).filter((r) => !r.name).map((r) => r.line); } catch { /* nur die Pakete */ }+ const list = path.join(env, 'restore-requirements.txt');+ try { fs.writeFileSync(list, [...options, ...missing.map((r) => r.line)].join('\n') + '\n'); } catch (e) {+ return `Die Paketliste ließ sich nicht schreiben: ${e instanceof Error ? e.message : String(e)}`;+ }+ const r = await run(python, ['-m', 'pip', 'install', '-r', list], dir, INSTALL_TIMEOUT_MS);+ if (r.code === 0) return null;+ const tail = (r.err || r.out).trim().split(/\r?\n/).filter((l) => l.trim()).slice(-4).join('\n');+ return `Pakete aus requirements.txt ließen sich nicht installieren (${missing.map((m) => m.line).join(', ')}).\n${tail}`;+}diff --git a/app/src/main/projects.ts b/app/src/main/projects.tsindex 859d7da..421040d 100644--- a/app/src/main/projects.ts+++ b/app/src/main/projects.ts@@ -13,6 +13,7 @@ import { checkRequest, RenderService, type RenderRequest } from './render';import { choose, chooseExportTarget, choosePath, documentsDir } from './dialogs';import { GitRepo, type GitStatus } from './git';import { MeasureService } from './measure';+import { ensureEnv, envIsCurrent, installMissing, missingPackages } from './packages';import { previewsDir, skillBackupsDir, skillsDir } from './paths';import { storeBuildAsPreview } from './previews';import {@@ -42,6 +43,8 @@ interface Session {signature: string;/** Legt gerade den Build als Vorschau des letzten Commits ab (cachePreview). */caching?: boolean;+ /** Projektumgebung bereit (E67): Fehlertext oder null. */+ env: Promise<string | null>;}const POLL_MS = 2000;@@ -94,8 +97,12 @@ export class ProjectController {const anims = new AnimBuilder(dir, () => this.send('anim:changed'));const stopWatch = watchProject(dir, (rel) => builds.sourceChanged(rel ? path.join(dir, rel) : null), () => this.send('fs:changed'),(rel) => this.animFileChanged(rel));- const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), anims, stopWatch, signature: '', poll: setInterval(() => void this.pollGit(), POLL_MS) };+ // Projektumgebung (E67): Meist steht sie schon, sonst legt `soma env` sie in rund 0,5 s an. Die Terminals kennen ihre+ // Pfade vorab, gewartet wird nur vor dem Installieren von Paketen+ const env = envIsCurrent(dir) ? Promise.resolve(null) : ensureEnv(dir);+ const session: Session = { id, dir, builds, terminals, git, measure: new MeasureService(dir), anims, stopWatch, signature: '', env, poll: setInterval(() => void this.pollGit(), POLL_MS) };this.session = session;+ void env.then((err) => { if (err) { console.error('[soma]', err); builds.reportPackageError(err); } });builds.on('status', (st) => {this.send('build:status', st);if (st.state === 'ok' && !st.stale) void this.cachePreview(session);@@ -104,7 +111,8 @@ export class ProjectController {// Gilt der letzte Build noch (seit seinem Start nichts geändert), zeigt der Viewer ihn gleich, statt neu zu bauen. Sonst// erster Build direkt beim Öffnen, damit der Viewer nicht leer ist (der Nutzer kann Auto-Build danach abschalten).const last = currentBuild(dir);- if (!last) builds.start('Projekt geöffnet');+ // Fehlen Pakete aus requirements.txt (ZIP von einem anderen Rechner), erst installieren, dann bauen+ if (!this.installPackages(session, !last) && !last) builds.start('Projekt geöffnet');const info = this.info();this.send('project:changed', info);// Erst nach project:changed: Das Fenster räumt beim Projektwechsel den Viewer leer und lädt danach das Modell@@ -117,6 +125,17 @@ export class ProjectController {return this.open(id);}+ /**+ * Fehlen Pakete aus requirements.txt in der Projektumgebung, werden sie installiert (E67), und Builds warten so lange.+ * `build`: danach bauen. Gibt zurück, ob installiert wird.+ */+ private installPackages(s: Session, build: boolean): boolean {+ const missing = missingPackages(s.dir);+ if (!missing.length) return false;+ void s.builds.installFirst(missing, async () => (await s.env) ?? installMissing(s.dir), build);+ return true;+ }+/** 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;@@ -434,7 +453,8 @@ export class ProjectController {if (c !== 0) return { cancelled: true };try {const r = await s.git.restore(hash);- s.builds.start('Stand wiederhergestellt');+ // Ein alter Stand kann andere Zusatzpakete brauchen (E67)+ if (!this.installPackages(s, true)) s.builds.start('Stand wiederhergestellt');this.send('versions:changed');this.send('save:state', await this.saveState());return { cancelled: false, ...r };diff --git a/app/src/main/terminals.ts b/app/src/main/terminals.tsindex 4e34d2c..4d02d6f 100644--- a/app/src/main/terminals.ts+++ b/app/src/main/terminals.ts@@ -2,18 +2,23 @@ import path from 'node:path';import type { WebContents } from 'electron';import * as pty from 'node-pty';import { bridgeEnv } from './bridge';+import { envPaths } from './packages';import { gitCmdDir, pythonBinDir } from './paths';/**- * Umgebung fuer Terminals: Python-Basisumgebung vorn im PATH, damit `python`, `pip` und `soma` gefunden werden. Dazu Adresse- * und Schluessel der App fuer `soma render` (E58).+ * Umgebung fuer Terminals: vorn im PATH die Projektumgebung (E67, `python` sieht Basis und Zusatzpakete), dahinter die+ * Basisumgebung (`pip`, `soma`). PIP_PYTHON leitet jedes pip in die Projektumgebung, die Basis bleibt unverändert. Dazu+ * Adresse und Schluessel der App fuer `soma render` (E58).*/export function terminalEnv(projectDir: string): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = { ...process.env, PYTHONUTF8: '1', SOMA_PROJECT: projectDir, ...bridgeEnv() };const key = Object.keys(env).find((k) => k.toLowerCase() === 'path') ?? 'PATH';- const front: string[] = [];+ const pe = envPaths(projectDir);+ const front: string[] = [pe.scripts];+ env.VIRTUAL_ENV = pe.env;+ env.PIP_PYTHON = pe.python;const bin = pythonBinDir();- if (bin) { front.push(bin); env.VIRTUAL_ENV = path.dirname(bin); }+ if (bin) front.push(bin);const git = gitCmdDir(); // das mitgelieferte Git hat Vorrang vor einem Git des Systemsif (git) front.push(git);env[key] = [...front, env[key] ?? ''].join(path.delimiter);diff --git a/app/src/main/zip.ts b/app/src/main/zip.tsindex a3b4df9..ea8e88d 100644--- a/app/src/main/zip.ts+++ b/app/src/main/zip.ts@@ -14,8 +14,9 @@ const SKIP_FILES = new Set(['.soma/model.glb', '.soma/model.map.json', '.soma/bu/*** Ganze Ordner, die nie gepackt werden (Pfad relativ zum Projekt): die Geometrie für das Messen entsteht beim Bauen neu,* Animationen baut die App beim Öffnen neu, Ergebnisse von soma analyze (bis zu 70 MB je Auswertung) rechnet man neu.+ * Die Projektumgebung (E67) legt die App beim Öffnen an und installiert dabei requirements.txt.*/-const SKIP_PATHS = new Set(['.soma/geometry', '.soma/anim', '.soma/results']);+const SKIP_PATHS = new Set(['.soma/geometry', '.soma/anim', '.soma/results', '.soma/env']);/** Schon gepackt (Git-Objekte sind zlib, Bilder und Videos komprimiert): nur ablegen, nochmal Deflate kostet nur Zeit. */const STORED = /^\.git\/objects\/|\.(png|jpe?g|webp|mp4|webm|zip|gz|7z|pack)$/i;const MAX_UNPACKED = 2 * 1024 ** 3;diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex 5054d19..a43224a 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -586,20 +586,30 @@ function openGroupMenu(ids: string[], name: string, x: number, y: number): void// ---- Build und Modell -------------------------------------------------------------------------------------------+/** Zuletzt gezeigter Fehler der Projektumgebung (E67): als Hinweis nur einmal. */+let shownPackageError = '';+function renderBuild(s: BuildStatus): void {buildStatus = s;if (s.state === 'ok') lastOkAt = s.builtAt ?? Date.now();if (s.state === 'error') errorAt = Date.now();const dot = $('build-dot'), main = $('status'), detail = $('status-detail');$('build-pill').classList.toggle('err', s.state === 'error' && !s.stale);- $('btn-cancel').hidden = s.state !== 'building';+ $('btn-cancel').hidden = s.state !== 'building' || !!s.installing;$('btn-buildnow').hidden = !(s.stale && s.state !== 'building');const count = s.result?.parts?.length ?? 0;const secs = s.seconds ?? 0;dot.replaceChildren();dot.className = 'dot';dot.style.background = '';- if (s.state === 'building') {+ if (s.packageError && s.packageError !== shownPackageError) toast(s.packageError, 'error');+ shownPackageError = s.packageError ?? '';+ if (s.installing) {+ dot.className = 'spin';+ dot.append(icon('spin', 14, 2.4));+ main.textContent = 'Installiert Pakete …';+ detail.textContent = s.installing.join(', ');+ } else if (s.state === 'building') {dot.className = 'spin';dot.append(icon('spin', 14, 2.4));main.textContent = 'Baut …';@@ -694,8 +704,9 @@ const versions = new VersionsBar({}, {async show(res: PreviewResult | null, restored = false) {// Nach dem Wiederherstellen bleibt das Bild der Vorschau stehen, bis der Build danach fertig ist (er lädt dann wie jeder- // Build von selbst). Sonst wäre so lange wieder der vorherige Build zu sehen, bei großen Modellen viele Sekunden.- if (!res && restored && buildStatus.state === 'building') return;+ // Build von selbst). Sonst wäre so lange wieder der vorherige Build zu sehen, bei großen Modellen viele Sekunden. Braucht+ // der Stand erst Pakete (E67), kommt der Build nach der Installation.+ if (!res && restored && (buildStatus.state === 'building' || buildStatus.installing)) return;if (!res) { await loadModel(); return; }animTool.setActive(false);resultTool.setActive(false);diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex c70553a..4c8e2c0 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -30,6 +30,10 @@ export interface BuildStatus {builtAt?: number;/** Auto-Build ist aus und der Quelltext hat sich seit dem letzten Build geändert. */stale?: boolean;+ /** Pakete aus requirements.txt, die gerade installiert werden (E67). Builds warten so lange. */+ installing?: string[];+ /** Projektumgebung oder Pakete ließen sich nicht einrichten (E67). Bleibt, bis eine Installation gelingt. */+ packageError?: string;}/** Einzelexport über `soma export` (E34). `files` relativ zum Projekt. */diff --git a/app/test/packages.mjs b/app/test/packages.mjsnew file mode 100644index 0000000..a2e9c95--- /dev/null+++ b/app/test/packages.mjs@@ -0,0 +1,177 @@+// Test der Projektumgebung (E25, E67): kleine venv je Modell unter .soma/env, die die Basis mitbenutzt. `pip install` im+// Terminal landet dort, Basispakete gelten als vorhanden und behalten ihre Version, soma build schreibt die importierten+// Zusatzpakete in requirements.txt, Umgebung weder in ZIP noch in Git, auf einem „anderen Rechner“ (frische App-Daten)+// installiert die App die Liste vor dem Build, ein alter Stand bringt seine eigene Liste mit, ein Paket, das sich nicht+// installieren lässt, wird gemeldet und bleibt in der Liste. Ohne Netz: pip holt die Testpakete aus einem lokalen Ordner.+// Aufruf: node test/run-all.mjs packages (nach npm run build).+import { exec } from 'dugite';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import yauzl from 'yauzl';+import yazl from 'yazl';+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';++const t = checker();+const { check } = t;+let app;+const workDir = fs.mkdtempSync(path.join(os.tmpdir(), 'soma-packages-'));+const wheels = path.join(workDir, 'wheels');+const zipPath = path.join(workDir, 'Paketmodell.zip');++/** Ein Wheel ohne Build-Werkzeuge: Modul, METADATA, WHEEL und RECORD in einer ZIP. */+function makeWheel(name, version, code, requires = []) {+ const info = `${name}-${version}.dist-info`;+ const files = {+ [`${name}/__init__.py`]: code,+ [`${info}/METADATA`]: `Metadata-Version: 2.1\nName: ${name}\nVersion: ${version}\n${requires.map((r) => `Requires-Dist: ${r}\n`).join('')}`,+ [`${info}/WHEEL`]: 'Wheel-Version: 1.0\nGenerator: soma-test\nRoot-Is-Purelib: true\nTag: py3-none-any\n',+ };+ files[`${info}/RECORD`] = [...Object.keys(files), `${info}/RECORD`].map((f) => `${f},,`).join('\n') + '\n';+ const z = new yazl.ZipFile();+ for (const [f, text] of Object.entries(files)) z.addBuffer(Buffer.from(text), f);+ z.end();+ return new Promise((resolve) => z.outputStream.pipe(fs.createWriteStream(path.join(wheels, `${name}-${version}-py3-none-any.whl`))).on('close', resolve));+}++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 dirSize = (d) => {+ let n = 0;+ for (const e of fs.readdirSync(d, { withFileTypes: true })) n += e.isDirectory() ? dirSize(path.join(d, e.name)) : fs.statSync(path.join(d, e.name)).size;+ return n;+};++try {+ fs.mkdirSync(wheels);+ await makeWheel('somatestpkg', '1.0', 'SIZE = 12.5\n');+ await makeWheel('somabadpkg', '1.0', '', ['numpy<2']); // verträgt sich nicht mit dem numpy der Basis+ // Kein Netz im Test: pip sucht nur im Ordner mit den Wheels (gilt für Terminals und für die App)+ process.env.PIP_NO_INDEX = '1';+ process.env.PIP_FIND_LINKS = wheels;++ app = await startApp({ name: 'packages' });+ let { ev, waitFor, domClick } = app;+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok' && window.__t.partCount() === 2, 90000);+ const proj = await ev(() => window.__t.project());+ const dir = proj.dir;+ const envDir = path.join(dir, '.soma', 'env');+ const site = path.join(envDir, 'Lib', 'site-packages');+ const req = path.join(dir, 'requirements.txt');+ const g = async (...args) => (await exec(args, dir)).stdout.trim();+ const until = async (fn, ms = 20000) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(200)) if (fn()) return true; return fn(); };++ // ---- 1) Umgebung beim Öffnen ----+ check('Projektumgebung liegt unter .soma/env', await until(() => fs.existsSync(path.join(envDir, 'pyvenv.cfg')) && fs.existsSync(path.join(envDir, 'soma-env.json'))));+ check('Sie ist klein (Basis wird mitbenutzt, nicht kopiert)', dirSize(envDir) < 5 * 1024 ** 2, `${Math.round(dirSize(envDir) / 1024)} KB`);+ check('pip.ini legt die Basisversionen fest', fs.readFileSync(path.join(envDir, 'pip.ini'), 'utf8').includes('constraint = file:')+ && /^numpy==/m.test(fs.readFileSync(path.join(envDir, 'base-constraints.txt'), 'utf8')));+ check('.gitignore der Vorlage nennt .soma/env/', fs.readFileSync(path.join(dir, '.gitignore'), 'utf8').includes('.soma/env/'));+ check('Ohne Zusatzpakete entsteht keine requirements.txt', !fs.existsSync(req));++ // ---- 2) pip im Terminal ----+ const tid = await ev(() => window.__t.terminals.activeId);+ const termText = () => ev((id) => window.__t.termText(id), tid);+ const type = async (cmd, until, ms = 120000) => {+ await ev(([id, c]) => window.soma.term.write(id, c + '\r'), [tid, cmd]);+ return waitFor(cmd, ([id, re]) => new RegExp(re, 'm').test(window.__t.termText(id)), ms, [tid, until]).then(() => true, () => false);+ };+ const installed = await type('pip install somatestpkg', 'Successfully installed somatestpkg-1\\.0');+ check('`pip install` im Terminal installiert ein Zusatzpaket', installed, installed ? '' : (await termText()).trim().slice(-200));+ check('Es liegt in der Projektumgebung', fs.existsSync(path.join(site, 'somatestpkg', '__init__.py')));+ check('Basispakete gelten als vorhanden (numpy wird nicht noch einmal installiert)', await type('pip install numpy', 'Requirement already satisfied: numpy'));+ check('Eine andere numpy-Version lehnt pip ab (Basis bleibt, wie sie ist)', await type('pip install somabadpkg', 'constraint\\) numpy==|ResolutionImpossible')+ && !fs.existsSync(path.join(site, 'somabadpkg')));+ check('`python` im Terminal sieht Basis und Zusatzpaket', await type('python -c "import cadquery, somatestpkg; print(\'PKG\', somatestpkg.SIZE)"', '^PKG 12\\.5', 60000));++ // ---- 3) soma build hält das Paket fest ----+ const modelPy = path.join(dir, 'model.py');+ const original = fs.readFileSync(modelPy, 'utf8');+ fs.writeFileSync(modelPy, original.replace('import cadquery as cq\n', 'import cadquery as cq\nimport somatestpkg\n').replace('WALL = 2.0', 'WALL = somatestpkg.SIZE / 6.25'));+ check('Build mit dem Zusatzpaket (App-Build, vorgewärmter Prozess)', await until(() => fs.existsSync(req), 90000)+ && await waitFor('Build ok', () => window.__t.status().state === 'ok', 60000).then(() => true, () => false));+ const reqText = (file = req) => (fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '');+ check('requirements.txt nennt das Paket mit Version', /^somatestpkg==1\.0$/m.test(reqText()) && reqText().startsWith('# Extra Python packages'), reqText().split('\n').slice(2).join(' | '));+ check('… und nur Pakete, die das Modell importiert (keine Basispakete)', reqText().split('\n').filter((l) => l && !l.startsWith('#')).length === 1);+ const mtime = fs.statSync(req).mtimeMs;+ check('`soma build` im Terminal: Build ok, Datei unverändert', await type('soma build', 'Build ok', 90000) && fs.statSync(req).mtimeMs === mtime);+ const porcelain = await g('status', '--porcelain', '--untracked-files=all');+ check('Git sieht requirements.txt, aber nichts aus .soma/env', porcelain.includes('requirements.txt') && !porcelain.includes('.soma/env'), porcelain.replace(/\n/g, ' | '));+ await ev(([id, c]) => window.soma.term.write(id, c + '\r'), [tid, 'git add -A; git commit -q -m "Mit Zusatzpaket"']);+ for (const t0 = Date.now(); Date.now() - t0 < 20000 && (await g('log', '-1', '--format=%s')) !== 'Mit Zusatzpaket';) await sleep(300);+ check('Commit des Agenten enthält requirements.txt, aber keine Umgebung', (await g('show', '--stat', '--format=', 'HEAD')).includes('requirements.txt')+ && !(await g('ls-files')).includes('.soma/env'));++ // ---- 4) Speichern: requirements.txt in der ZIP, Umgebung nicht ----+ await app.answers([zipPath]);+ await domClick('btn-save');+ await waitFor('gespeichert', () => window.__t.saveState() && !window.__t.saveState().unsaved && window.__t.saveState().zipPath, 60000);+ const names = await listZip(zipPath);+ check('ZIP enthält requirements.txt, aber nichts aus .soma/env', names.includes('requirements.txt') && !names.some((n) => n.startsWith('.soma/env')), `${names.length} Einträge`);++ // ---- 5) Alter Stand: seine eigene Liste, kein Paket zu viel ----+ const first = await g('rev-list', '--max-parents=0', 'HEAD');+ await app.answers([0]);+ const restored = await ev((h) => window.soma.versions.restore(h), first);+ check('Startstand wiederhergestellt', !restored.error && !restored.cancelled, JSON.stringify(restored).slice(0, 120));+ await waitFor('Build nach Wiederherstellung', () => window.__t.status().state === 'ok' && !window.__t.status().text.includes('Installiert'), 90000).catch(() => {});+ await sleep(1500);+ check('Startstand hat keine requirements.txt, und der Build legt keine an (Paket nur noch installiert)', !fs.existsSync(req) && fs.existsSync(path.join(site, 'somatestpkg')));+ check('Nach dem Wiederherstellen keine ungespeicherte Änderung durch die Paketliste', !(await g('status', '--porcelain')).includes('requirements.txt'));+ await app.stop();+ cleanup(app.ud);+ app = null;++ // ---- 6) Anderer Rechner: frische App-Daten, ZIP öffnen ----+ app = await startApp({ name: 'packages2' });+ ({ ev, waitFor, domClick } = app);+ await waitFor('Startprojekt', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok', 90000);+ await app.answers([zipPath]);+ await domClick('btn-open');+ let sawInstalling = false;+ for (const t0 = Date.now(); Date.now() - t0 < 120000; await sleep(150)) {+ const st = await ev(() => ({ id: window.__t.project()?.id, ...window.__t.status(), parts: window.__t.partCount() }));+ if (st.id === proj.id && st.text.startsWith('Installiert Pakete')) sawInstalling = true;+ if (st.id === proj.id && st.state === 'ok' && st.parts === 2 && !st.text.startsWith('Installiert')) break;+ }+ check('Beim Öffnen zeigt die Statuszeile „Installiert Pakete …“', sawInstalling);+ const dir2 = (await ev(() => window.__t.project())).dir; // neue App-Daten, also ein anderer Arbeitsordner+ const site2 = path.join(dir2, '.soma', 'env', 'Lib', 'site-packages');+ const req2 = path.join(dir2, 'requirements.txt');+ check('Paket wurde aus requirements.txt installiert, der Build gelingt', fs.existsSync(path.join(site2, 'somatestpkg', '__init__.py'))+ && (await ev(() => window.__t.status().state)) === 'ok', (await ev(() => window.__t.status().viewerMsg)).slice(0, 120));+ check('Kein Hinweis auf einen Paketfehler', !(await ev(() => window.__t.toast())).error);++ // ---- 7) Paket lässt sich nicht installieren: melden, Liste behalten ----+ fs.appendFileSync(req2, 'somamissing==2.0\n');+ await exec(['-c', 'user.name=Agent', '-c', '[email protected]', 'commit', '-q', '-am', 'Paket ohne Quelle'], dir2);+ const head = (await exec(['rev-parse', 'HEAD'], dir2)).stdout.trim();+ await app.answers([0]);+ await ev((h) => window.soma.versions.restore(h), head);+ const toast = await waitFor('Hinweis', () => { const x = window.__t.toast(); return x.error && x.text.includes('somamissing') ? x : null; }, 120000).catch(() => null);+ check('Fehlendes Paket ohne Quelle: Hinweis nennt es', !!toast, toast?.text.slice(0, 120) ?? '');+ if (process.env.SMOKE_SHOTS) { // Hinweis ansehen: SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });+ await sleep(600);+ await app.screenshot(path.join(APP, 'test', 'shots', 'packages-fehler.png')).catch((e) => console.log('Screenshot:', e.message));+ }+ await waitFor('Build danach', () => window.__t.status().state === 'ok' && !window.__t.status().text.includes('Installiert'), 90000).catch(() => {});+ await sleep(1000);+ check('Build läuft trotzdem, die Liste behält das fehlende Paket', (await ev(() => window.__t.status().state)) === 'ok' && /^somamissing==2\.0$/m.test(reqText(req2)) && /^somatestpkg==1\.0$/m.test(reqText(req2)), reqText(req2).split('\n').slice(2).join(' | '));++ const relevant = app.page.errors.filter((e) => !/favicon/i.test(e));+ check('Keine Konsolenfehler im Renderer', relevant.length === 0, relevant.slice(0, 2).join(' | ').slice(0, 100));+} catch (e) {+ console.log('ABBRUCH:', e.message);+ t.fail();+}+if (app) { await app.stop(); cleanup(app.ud); }+cleanup(workDir);+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/run-all.mjs b/app/test/run-all.mjsindex f445323..b5d0a2f 100644--- a/app/test/run-all.mjs+++ b/app/test/run-all.mjs@@ -9,7 +9,7 @@ import path from 'node:path';const DIR = import.meta.dirname;// Längste zuerst, damit sie nicht am Ende allein laufen-const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'explode', 'fasteners', 'section', 'measure', 'groups', 'unit'];+const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'explode', 'fasteners', 'section', 'measure', 'groups', 'packages', 'unit'];const wanted = process.argv.slice(2);const unknown = wanted.filter((s) => !ALL.includes(s));if (unknown.length) { console.log(`Unbekannte Suite: ${unknown.join(', ')}. Vorhanden: ${ALL.join(', ')}`); process.exit(2); }