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: Schnittansicht und Skills (E17)
Kai-Jungsthoefel6e3f408d3c05
diff --git a/app/package.json b/app/package.jsonindex ad080f8..23c555a 100644--- a/app/package.json+++ b/app/package.json@@ -13,8 +13,10 @@"test:editor": "npm run build && node test/editor.mjs","test:measure": "npm run build && node test/measure.mjs","test:groups": "npm run build && node test/groups.mjs",+ "test:section": "npm run build && node test/section.mjs",+ "test:skills": "npm run build && node test/skills.mjs","test:unit": "node test/unit.mjs",- "test": "npm run build && node test/unit.mjs && node test/smoke.mjs && node test/versions.mjs && node test/editor.mjs && node test/measure.mjs && node test/groups.mjs"+ "test": "npm run build && node test/unit.mjs && node test/smoke.mjs && node test/versions.mjs && node test/editor.mjs && node test/measure.mjs && node test/groups.mjs && node test/section.mjs && node test/skills.mjs"},"dependencies": {"@codemirror/autocomplete": "^6.20.3",diff --git a/app/resources/skills/3d-druck.md b/app/resources/skills/3d-druck.mdnew file mode 100644index 0000000..b162f0b--- /dev/null+++ b/app/resources/skills/3d-druck.md@@ -0,0 +1,55 @@+---+title: 3D-Druck (FDM)+name: 3D printing (FDM)+summary: Druckbare Wandstärken, Überhänge bis 45°, Spiel für Passungen, Ausrichtung auf dem Druckbett, Gewinde über Einschmelzmuttern.+order: 10+topics: Wände und kleine Details; Überhänge und Brücken; Ausrichtung und Bauraum; Spiel und Passungen; Schrauben und Gewinde; Export als STL oder 3MF+---+# Skill: 3D printing (FDM)++The parts will be printed on a filament printer (FDM). Unless `NOTES.md` or the user says otherwise, assume a 0.4 mm+nozzle, 0.2 mm layers, PLA or PETG and a build volume of 220 × 220 × 250 mm. Put these assumptions into named constants+at the top of `model.py` (`NOZZLE = 0.4`, `CLEARANCE = 0.3`, `BED = (220, 220, 250)`) so the user can change them.++## Walls and small features++- Walls at least 1.2 mm (three lines of 0.4 mm), 2 mm or more where the part carries load or holds screws. Prefer+ multiples of the line width (0.8, 1.2, 1.6, 2.0 mm).+- No feature thinner than 0.8 mm, no gap narrower than 0.5 mm, no pin thinner than 2 mm.+- Embossed or engraved text: at least 0.6 mm high or deep, letters at least 5 mm tall.++## Overhangs and bridges++- Overhangs up to 45° from vertical print without support. Avoid shapes that need support, or say clearly where they do.+- Bridges (flat ceilings between two walls) up to about 10 mm are fine.+- Horizontal holes larger than about 8 mm: give them a pointed (teardrop) or flat top instead of a round one.+- Edges on the print bed: chamfer them (0.5 to 1 mm) instead of filleting. A fillet there becomes an overhang.++## Orientation and size++- Design each part with its largest flat face on the bed and say which orientation you assume.+- Layers are the weak direction. Loads should run along the layers, not pull them apart. Snap hooks and clips lie flat.+- If a part does not fit the build volume, split it into pieces that do (with alignment pins or a lap joint) and register+ every piece with `add_part`.+- One `add_part` per printed body. Do not merge parts that are printed separately.++## Fits and clearances++- Parts that slide or turn in each other: 0.3 mm clearance per side. Loose fit 0.4 mm. Press fit 0.1 mm or less,+ suggest a small test print first.+- Lids, drawers and sliding parts: 0.3 to 0.5 mm gap on every side.+- Printed holes come out about 0.1 to 0.2 mm smaller than modeled. Model screw holes 0.2 mm larger than the nominal+ clearance hole.+- Every clearance is a named constant. Mating faces never touch with zero gap.++## Screws and threads++- Do not print metric threads below M6. Use heat-set inserts or self-tapping screws instead.+- Heat-set inserts, typical hole sizes for short inserts: M2 Ø 3.2, M2.5 Ø 3.6, M3 Ø 4.0, M4 Ø 5.6, M5 Ø 6.4 mm, depth+ insert length + 1 mm. Sizes differ between makers: note your assumption in `NOTES.md` or ask the user.+- Self-tapping screws for plastic (about 3 mm): hole Ø 2.5 mm.+- Screw bosses: outer diameter at least 2.5 × the hole, joined to the wall or with ribs, never free-standing and thin.++## Export++- Printable parts go out as STL or 3MF, one file per part: `soma export "Lid" --format 3mf`. References are not printed.diff --git a/app/resources/skills/gehaeuse.md b/app/resources/skills/gehaeuse.mdnew file mode 100644index 0000000..cc03752--- /dev/null+++ b/app/resources/skills/gehaeuse.md@@ -0,0 +1,48 @@+---+title: Gehäusebau+name: Enclosure design+summary: Gehäuse um eine Platine oder ein Gerät: Wand und Deckel mit Falz, Abstand zur Referenz, Dome für Schrauben, Ausschnitte, Belüftung.+order: 30+topics: Aufbau aus Unterteil, Deckel und Referenz; Startwerte für Wand, Boden und Abstand; Dome für die Platine; Ausschnitte, Belüftung, Kabel; Prüfungen vor dem Abschluss+---+# Skill: Enclosure design++Build enclosures around a circuit board or another part the user brought.++## Structure++- Separate parts for base and lid (more if needed), in one group: `add_part("Base", base, group="Enclosure")`,+ `add_part("Lid", lid, group="Enclosure")`.+- The board or device stays a reference (`role="reference"`, usually loaded with `import_assembly`). Never change or+ export it.+- Derive positions from the reference instead of typing numbers: `asm.toCompound().BoundingBox()` for an assembly,+ `shape.val().BoundingBox()` for a single shape. Write the key dimensions of the reference into `NOTES.md`.+- Constants at the top: `WALL`, `FLOOR`, `LID`, `GAP` (reference to wall), `CLEARANCE` (lid to base), the screw size.++## Starting values++Change them when the user or another active skill says otherwise.++- Wall 2 mm, floor and lid 2 mm. Inner corner radius at least the wall thickness, outer edges rounded 1 to 2 mm.+- At least 1 mm between the reference and every inner wall, 2 mm above the tallest component.+- Lid with a lip 1.5 to 2 mm high that reaches into the base, 0.2 to 0.3 mm clearance per side. Or a flat lid on screws.++## Mounting the board++- Standoffs under the mounting holes of the board: outer Ø about 2.2 × the screw size, hole for a heat-set insert or a+ tap drill, high enough that the lowest component on the underside clears the floor by 1 mm.+- The hole positions must match the reference exactly. Take them from the reference and check them with a measurement.++## Openings++- Cutouts for connectors, buttons, LEDs and displays come from the position of the part in the reference, plus 0.5 mm+ clearance per side (1 mm for plugs with molded housings).+- Ventilation: slots 1.5 to 2 mm wide with webs of at least 2 mm, not where liquid could drip in.+- Cable entry: a hole or slot with rounded edges, optionally with a strain relief.++## Checks before you finish++- No part may intersect the reference or another part: `base.intersect(board).val().Volume()` is 0 for every pair that+ matters (for an assembly use `board = asm.toCompound()`).+- The lid can be removed: no undercuts in the direction it comes off.+- Tell the user how the enclosure goes together: which screws, how many, what length.diff --git a/app/resources/skills/toleranzen.md b/app/resources/skills/toleranzen.mdnew file mode 100644index 0000000..657ce89--- /dev/null+++ b/app/resources/skills/toleranzen.md@@ -0,0 +1,70 @@+---+title: Toleranzen und Passungen+name: Tolerances and fits+summary: Spiel als benannte Konstanten, Kollisionsprüfung im Code, Durchgangs- und Kernlöcher, Senkungen für Zylinderschrauben, ISO-Passungen.+order: 20+topics: Spiel als benannte Konstanten; Kollisionen und Abstände im Code prüfen; Durchgangs- und Kernlöcher (ISO 273); Senkungen für Zylinderschrauben; ISO-Passungen für gefertigte Teile; Laser- und Blechteile+---+# Skill: Tolerances and fits++Every real part deviates from its nominal size. Design so that parts still fit when they do.++## General rules++- If `NOTES.md` does not say how the parts are made (3D printing, CNC milling, laser cutting, sheet metal), ask. The+ clearances depend on it.+- Put every clearance, fit and allowance into a named constant at the top of `model.py` (`SCREW_CLEARANCE`, `LID_GAP`).+ Never hide them in expressions.+- Mating faces never share the exact same coordinate: leave a defined gap, or a defined overlap for a press fit.+- Dimension from the functional faces: a hole follows the part it has to meet, not an arbitrary outer edge.+- After building, check the critical gaps (measure them or compute them, see below) and tell the user the values.++## Checking clearances in code++- Interference: `a.intersect(b).val().Volume()` must be (close to) 0 for parts that must not touch, and for a part and+ a reference (`role="reference"`).+- Smallest gap between two shapes in mm: `a.val().distance(b.val())`.+- Print such checks only while you work on them and remove the debug output afterwards.++## Holes for metric screws++Clearance holes after ISO 273 and tap drills (core holes) for coarse threads, in mm. Use "medium" unless the user wants+otherwise. For printed parts the 3D printing skill adds to these values.++| Thread | Close | Medium | Free | Tap drill |+|---|---|---|---|---|+| M2 | 2.2 | 2.4 | 2.6 | 1.6 |+| M2.5 | 2.7 | 2.9 | 3.1 | 2.05 |+| M3 | 3.2 | 3.4 | 3.6 | 2.5 |+| M4 | 4.3 | 4.5 | 4.8 | 3.3 |+| M5 | 5.3 | 5.5 | 5.8 | 4.2 |+| M6 | 6.4 | 6.6 | 7.0 | 5.0 |+| M8 | 8.4 | 9.0 | 10.0 | 6.8 |++## Counterbores for socket head screws++For ISO 4762 (DIN 912) screws, so that the head sits flush. Values in mm, with some room around the head. If the exact+standard matters, say which values you used.++| Thread | Head Ø | Counterbore Ø | Depth |+|---|---|---|---|+| M2 | 3.8 | 4.4 | 2.4 |+| M2.5 | 4.5 | 5.5 | 2.9 |+| M3 | 5.5 | 6.5 | 3.4 |+| M4 | 7.0 | 8.0 | 4.4 |+| M5 | 8.5 | 10.0 | 5.4 |+| M6 | 10.0 | 11.0 | 6.4 |+| M8 | 13.0 | 15.0 | 8.6 |++In CadQuery: `.cboreHole(diameter, cboreDiameter, cboreDepth)`. Countersunk screws (ISO 10642, 90°):+`.cskHole(diameter, cskDiameter, 90)`.++## Fits for machined parts (ISO 286)++- Shaft turning or sliding in a hole: H7/g6. Located, assembled by hand: H7/h6. Press fit: H7/p6.+- Model the nominal size. Write the fit as a comment next to the constant and in `NOTES.md` (`BORE = 8 # H7`). Do not+ build the tolerance band into the geometry.++## Laser-cut and sheet parts++- Slots and tabs: 0.1 to 0.2 mm clearance per side, depending on the kerf. Keep the material thickness as a constant.diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.mdindex 165c872..bf23e73 100644--- a/app/resources/template/AGENTS.md+++ b/app/resources/template/AGENTS.md@@ -13,7 +13,7 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes| `inputs/` | Files the user brought (STEP, images). Never modify them, load them from `model.py` || `output/model.step` | Main result with all parts, written by `soma build`. Never write it yourself || `exports/` | Single-part exports written by `soma export` |-| `.soma/` | App data (viewer cache, build status, feedback images). Do not edit, except reading files in `.soma/feedback/` when the user points you to them |+| `.soma/` | App data (viewer cache, build status, feedback images, skills). Do not edit. Read the skills in `.soma/skills/` listed at the end of this file, and files in `.soma/feedback/` when the user points you to them |## Rules for model.py@@ -59,5 +59,12 @@ The app pastes short notes into your input. The user adds their own words and se- `[Markierung: .soma/feedback/markierung-20260930-1405.png]`: a picture of the 3D view (or a blank sketch) with the user's drawings: arrows, circles, handwritten text, often with dimensions. **Open the image file and look at it**, compare it with the model, then change the code. If the note says `zeigt den älteren Stand <hash>`, the picture shows that older commit, not the current code (`git show <hash>:model.py`). Leave the images where they are.- `[Auswahl: Bauteil "…", model.py Zeile …]`: the part the user clicked, with the lines of its `add_part` call and the clicked face.- `[Build-Fehler: …]`: the message of the last failed build.+- `[Skill: .soma/skills/<name>.md]`: the user switched on this rule set. Read the file now and follow it from here on. When the user switches a skill off, it disappears from the list below: stop applying it.The user can also edit files directly in the app's editor. Read a file again right before you change it, do not rely on an older copy.++<!-- soma:skills -->+## Skills++No skills are active for this model. The user can switch on rule sets (for example 3D printing) in the app.+<!-- /soma:skills -->diff --git a/app/src/main/main.ts b/app/src/main/main.tsindex 602e7a9..85affcb 100644--- a/app/src/main/main.ts+++ b/app/src/main/main.ts@@ -77,6 +77,8 @@ function registerIpc(ctl: ProjectController): void {ipcMain.handle('agents:detect', () => detectAgents(terminalEnv(dir())));ipcMain.handle('measure:query', (_e, source: unknown, req: unknown) => ctl.measure(source, req));+ ipcMain.handle('skills:list', () => ctl.skills());+ ipcMain.handle('skills:set', (_e, id: unknown, on: unknown) => ctl.setSkill(id, !!on));// Rückfragen aus dem Renderer (etwa ungespeicherte Eingaben im Editor) laufen über dieselben Dialoge wie im HauptprozessipcMain.handle('dialog:choose', (_e, o: { title?: unknown; message?: unknown; detail?: unknown; buttons?: unknown }) => {const buttons = Array.isArray(o?.buttons) ? o.buttons.slice(0, 4).map(String) : [];diff --git a/app/src/main/paths.ts b/app/src/main/paths.tsindex 01f5c6c..34c490f 100644--- a/app/src/main/paths.ts+++ b/app/src/main/paths.ts@@ -15,6 +15,8 @@ export const appStateFile = () => path.join(userDataDir(), 'state.json');export const backupsDir = () => path.join(userDataDir(), 'workspace-backups');/** Sicherungen aus dem Editor (Fassungen, die bei einem Konflikt ersetzt wurden), je Projekt. */export const editBackupsDir = (id: string) => path.join(backupsDir(), `${id}-editor`);+/** Sicherungen von Skill-Kopien, die beim Ein- oder Ausschalten ersetzt oder entfernt wurden, je Projekt. */+export const skillBackupsDir = (id: string) => path.join(backupsDir(), `${id}-skills`);/** Vorschauen alter Stände (aus dem Verlauf erzeugt, jederzeit neu erzeugbar). */export const previewsDir = () => path.join(userDataDir(), 'previews');/** Vorschaubilder für die Startseite (vom Viewer nach dem Laden des Modells, jederzeit neu erzeugbar). */@@ -23,6 +25,9 @@ export const thumbnailsDir = () => path.join(userDataDir(), 'thumbnails');/** Vorlage fuer neue Projekte (liegt neben dem Programm, spaeter im Installationspaket). */export const templateDir = () => path.join(app.getAppPath(), 'resources', 'template');+/** Mitgelieferte Skills (E17), je einer als Markdown. */+export const skillsDir = () => path.join(app.getAppPath(), 'resources', 'skills');+/** App-Icon (E44) für Fenster und Taskleiste. Windows nimmt die ICO mit allen Größen, andere Systeme das PNG. */export const appIcon = () => path.join(app.getAppPath(), 'resources', process.platform === 'win32' ? 'icon.ico' : 'icon.png');diff --git a/app/src/main/projects.ts b/app/src/main/projects.tsindex 05f22f0..3cc3d9c 100644--- a/app/src/main/projects.ts+++ b/app/src/main/projects.ts@@ -1,17 +1,18 @@import { shell, type BrowserWindow, type WebContents } from 'electron';import fs from 'node:fs';import path from 'node:path';-import type { ExportResult, GitLog, MeasureEntity, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState } from '../shared/types';+import type { ExportResult, GitLog, MeasureEntity, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState, SkillInfo, SkillResult } from '../shared/types';import { BuildManager, buildIsStale, newestSourceMtime, runSoma } from './build';import { choose, choosePath } from './dialogs';import { GitRepo } from './git';import { MeasureService } from './measure';-import { previewsDir } from './paths';+import { previewsDir, skillBackupsDir, skillsDir } from './paths';+import { copySkill, isSkillId, listSkills, removeSkill, skillName, writeAgentsList } from './skills';import { TerminalManager } from './terminals';import { watchProject } from './watcher';import {backupWorkspace, createProject, extractProject, getAppState, inspectProject, isProjectId, patchAppState, projectDir,- readProjectJson, renameProject, setLastProject,+ readProjectJson, renameProject, setLastProject, setProjectSkills,} from './workspace';import { readZipTexts, saveProjectZip, ZIP_INFO_PATH, type ZipInfo } from './zip';@@ -335,6 +336,40 @@ export class ProjectController {* Darf das Fenster schließen? Bei ungespeicherten Änderungen fragt die App. Der Arbeitsstand bleibt in jedem Fall erhalten,* Eingaben im Editor (`editor.dirty`) aber nur, wenn sie gespeichert werden. „Nicht speichern“ legt sie als Sicherung ab.*/+ // ---- Skills (E17) -----------------------------------------------------------------------------------------------++ /** Aktive Skills laut project.json, null wenn sie unlesbar ist. */+ private activeSkills(id: string): string[] | null {+ const pj = readProjectJson(id);+ return pj ? (Array.isArray(pj.skills) ? pj.skills.filter(isSkillId) : []) : null;+ }++ skills(): SkillInfo[] {+ const s = this.need();+ return listSkills(s.dir, skillsDir(), this.activeSkills(s.id));+ }++ /**+ * Skill ein- oder ausschalten: Kopie in .soma/skills/ anlegen oder entfernen (Abweichendes vorher in die Sicherung),+ * project.json und den Abschnitt in AGENTS.md nachziehen. Erst die Prüfung, dann die Änderungen.+ */+ setSkill(skill: unknown, on: unknown): SkillResult {+ const s = this.need();+ const active = this.activeSkills(s.id);+ const list = () => this.skills();+ if (!isSkillId(skill)) return { ok: false, error: 'Unbekannter Skill.', skills: list() };+ if (!active) return { ok: false, error: '.soma/project.json fehlt oder ist unlesbar. Ohne sie lässt sich kein Skill ein- oder ausschalten.', skills: list() };+ try {+ const backup = on ? copySkill(s.dir, skillsDir(), skill, skillBackupsDir(s.id)) : removeSkill(s.dir, skillsDir(), skill, skillBackupsDir(s.id));+ const next = on ? [...new Set([...active, skill])] : active.filter((x) => x !== skill);+ setProjectSkills(s.id, next);+ const warning = writeAgentsList(s.dir, next.map((id) => ({ id, name: skillName(s.dir, skillsDir(), id) })));+ return { ok: true, backup, ...(warning ? { warning } : {}), skills: list() };+ } catch (e) {+ return { ok: false, error: e instanceof Error ? e.message : String(e), skills: list() };+ }+ }+async confirmClose(editor: { dirty: string[]; save(): Promise<boolean>; discard(): Promise<void> }): Promise<boolean> {if (!this.session || process.env.SOMA_TEST === '1') return true;const st = await this.saveState();diff --git a/app/src/main/skills.ts b/app/src/main/skills.tsnew file mode 100644index 0000000..c65c81f--- /dev/null+++ b/app/src/main/skills.ts@@ -0,0 +1,210 @@+import fs from 'node:fs';+import path from 'node:path';+import type { SkillInfo } from '../shared/types';+import { backupText, resolveInside } from './files';++/**+ * Skills (E17): Regelwerke als Markdown, die der Nutzer pro Modell zuschaltet. Die App liefert sie mit+ * (`resources/skills/`). Ein aktivierter Skill wird nach `.soma/skills/<id>.md` kopiert, steht in `project.json` und wird+ * in einem eigenen Abschnitt der `AGENTS.md` aufgeführt. So wandert er mit ZIP und Git und gilt für jeden Agenten.+ * Die Kopie im Projekt bleibt, wie sie ist, auch wenn eine neuere App eine neuere Fassung mitbringt.+ */++/** Kennung = Dateiname ohne .md. Nur Kleinbuchstaben, Ziffern und Bindestrich: Sie landet in Pfaden und in AGENTS.md. */+const ID = /^[a-z0-9][a-z0-9-]{0,40}$/;+export const isSkillId = (id: unknown): id is string => typeof id === 'string' && ID.test(id);+export const SKILLS_DIR = '.soma/skills';+const BEGIN = '<!-- soma:skills -->';+const END = '<!-- /soma:skills -->';+const MAX_BYTES = 256 * 1024;++interface Parsed { id: string; title: string; name: string; summary: string; order: number; topics: string[]; text: string }++/** Zeilenenden vereinheitlichen: Eine Kopie mit CRLF (etwa nach einem Git-Checkout) gilt nicht als geändert. */+const norm = (t: string) => t.replace(/\r\n?/g, '\n');++/**+ * Liest Kopf und Inhalt. Der Kopf steht zwischen zwei `---`-Zeilen als `schlüssel: wert` (title, summary und topics für+ * die Oberfläche auf Deutsch, name auf Englisch für AGENTS.md). Fehlt er, gilt die erste Überschrift als Titel.+ */+export function parseSkill(id: string, raw: string): Parsed {+ const text = norm(raw);+ const meta: Record<string, string> = {};+ let body = text;+ const m = /^---\n([\s\S]*?)\n---\n?/.exec(text);+ if (m) {+ for (const line of m[1].split('\n')) {+ const kv = /^([a-z_]+):\s*(.*)$/.exec(line.trim());+ if (kv) meta[kv[1]] = kv[2].trim();+ }+ body = text.slice(m[0].length);+ }+ const heading = /^#\s+(.+)$/m.exec(body)?.[1]?.trim();+ // Themen für die Übersicht: aus dem Kopf (deutsch, mit „;“ getrennt), sonst die Zwischenüberschriften+ const topics = (meta.topics ? meta.topics.split(';') : [...body.matchAll(/^##\s+(.+)$/gm)].map((x) => x[1]))+ .map((x) => x.trim()).filter(Boolean).slice(0, 12);+ return {+ id, text: raw,+ title: meta.title || heading || id,+ name: meta.name || heading || meta.title || id,+ summary: meta.summary ?? '',+ order: Number(meta.order) || 100,+ topics,+ };+}++function readSkillFile(file: string): string | null {+ try {+ if (fs.statSync(file).size > MAX_BYTES) return null;+ return fs.readFileSync(file, 'utf8');+ } catch { return null; }+}++/** Mitgelieferte Skills aus dem Ordner der App. Unlesbare oder falsch benannte Dateien fallen weg. */+export function bundledSkills(dir: string): Map<string, Parsed> {+ const out = new Map<string, Parsed>();+ let names: string[] = [];+ try { names = fs.readdirSync(dir); } catch { return out; }+ for (const n of names.sort()) {+ const id = n.replace(/\.md$/i, '');+ if (!/\.md$/i.test(n) || !isSkillId(id)) continue;+ const raw = readSkillFile(path.join(dir, n));+ if (raw != null) out.set(id, parseSkill(id, raw));+ }+ return out;+}++const relOf = (id: string) => `${SKILLS_DIR}/${id}.md`;++/** Kopie im Projekt, sofern lesbar. Der Pfad geht durch resolveInside: Ein Verweis nach außen wird nicht gelesen. */+function projectCopy(root: string, id: string): string | null {+ try { return readSkillFile(resolveInside(root, relOf(id))); } catch { return null; }+}++function agentsText(root: string): string | null {+ try { return fs.readFileSync(path.join(root, 'AGENTS.md'), 'utf8'); } catch { return null; }+}++/** Die Liste der Skills in AGENTS.md: der Abschnitt zwischen den Markierungen, ohne sie die ganze Datei. */+function agentsList(text: string): string {+ const a = text.indexOf(BEGIN), z = text.indexOf(END);+ return a >= 0 && z > a ? text.slice(a, z) : text;+}++/**+ * Alle Skills für die Oberfläche: die mitgelieferten und solche, die nur im Projekt liegen (etwa aus einer neueren App).+ * `active` stammt aus project.json (null: unlesbar). Auffälligkeiten werden gemeldet, nicht behoben (E28).+ */+export function listSkills(root: string, bundledDir: string, active: string[] | null): SkillInfo[] {+ const bundled = bundledSkills(bundledDir);+ const on = new Set((active ?? []).filter(isSkillId));+ let files: string[] = [];+ try { files = fs.readdirSync(path.join(root, SKILLS_DIR)).filter((n) => /\.md$/i.test(n)).map((n) => n.replace(/\.md$/i, '')).filter(isSkillId); } catch { /* noch keiner aktiv */ }+ const raw = agentsText(root);+ const agents = raw == null ? null : agentsList(raw);+ const ids = [...new Set([...bundled.keys(), ...on, ...files])];+ const out: SkillInfo[] = ids.map((id) => {+ const b = bundled.get(id);+ const copy = projectCopy(root, id);+ const meta = b ?? (copy != null ? parseSkill(id, copy) : null);+ const isOn = on.has(id);+ const info: SkillInfo = {+ id, title: meta?.title ?? id, summary: meta?.summary ?? '', topics: meta?.topics ?? [], order: meta?.order ?? 100,+ bundled: !!b, active: isOn, file: copy != null ? relOf(id) : null,+ changed: !!b && copy != null && norm(copy) !== norm(b.text),+ problems: [],+ };+ if (isOn && copy == null) info.problems.push(`Aktiv, aber ${relOf(id)} fehlt oder ist unlesbar. Der Agent findet die Regeln nicht.`);+ if (!isOn && copy != null) info.problems.push(`Nicht aktiv, aber ${relOf(id)} liegt noch im Projekt.`);+ if (isOn && agents != null && !agents.includes(relOf(id))) info.problems.push('AGENTS.md nennt diesen Skill nicht. Ein Agent erfährt nichts davon.');+ if (!b && isOn) info.problems.push('Diese App bringt den Skill nicht mit. Die Kopie im Projekt gilt weiter.');+ return info;+ });+ return out.sort((a, b) => a.order - b.order || a.title.localeCompare(b.title, 'de'));+}++/** Text atomar schreiben: erst eine Nebendatei, dann umbenennen. */+function writeAtomic(file: string, text: string): void {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.soma-tmp`;+ try {+ fs.writeFileSync(tmp, text, 'utf8');+ fs.renameSync(tmp, file);+ } catch (e) {+ try { fs.rmSync(tmp, { force: true }); } catch { /* bleibt liegen, stört nicht */ }+ throw e;+ }+}++/**+ * Skill ins Projekt kopieren. Liegt dort schon eine abweichende Fassung (vom Nutzer, vom Agenten oder aus einer älteren+ * App), wandert sie vorher in die Sicherung. Gibt den Pfad der Sicherung zurück, falls es eine gab.+ */+export function copySkill(root: string, bundledDir: string, id: string, backupDir: string): string | null {+ const b = bundledSkills(bundledDir).get(id);+ const abs = resolveInside(root, relOf(id));+ const old = projectCopy(root, id);+ if (!b) {+ // Nicht mitgeliefert: Nur einschalten, was schon im Projekt liegt+ if (old == null) throw new Error(`Den Skill „${id}“ gibt es in dieser App nicht.`);+ return null;+ }+ if (old != null && norm(old) === norm(b.text)) return null;+ const backup = old != null ? backupText(backupDir, relOf(id), old) : null;+ writeAtomic(abs, b.text);+ return backup;+}++/**+ * Kopie aus dem Projekt entfernen. Eine unveränderte Kopie eines mitgelieferten Skills lässt sich jederzeit neu anlegen und+ * wird einfach gelöscht, alles andere kommt vorher in die Sicherung.+ */+export function removeSkill(root: string, bundledDir: string, id: string, backupDir: string): string | null {+ const abs = resolveInside(root, relOf(id));+ const old = projectCopy(root, id);+ if (old == null) { fs.rmSync(abs, { force: true }); return null; }+ const b = bundledSkills(bundledDir).get(id);+ const backup = b && norm(old) === norm(b.text) ? null : backupText(backupDir, relOf(id), old);+ fs.rmSync(abs, { force: true });+ return backup;+}++/** Abschnitt der AGENTS.md mit den aktiven Skills (auf Englisch wie der Rest der Datei). */+export function skillsBlock(entries: { id: string; name: string }[]): string {+ const lines = [BEGIN, '## Skills', ''];+ if (!entries.length) {+ lines.push('No skills are active for this model. The user can switch on rule sets (for example 3D printing) in the app.');+ } else {+ lines.push('The user switched on these rule sets for this model. **Read each file before you change the model and follow it.**',+ 'They take precedence over your general habits, but not over explicit wishes of the user. If a rule cannot be met, say so.', '');+ for (const e of entries) lines.push(`- \`${relOf(e.id)}\`: ${e.name}`);+ }+ lines.push(END);+ return lines.join('\n');+}++/**+ * Trägt die aktiven Skills in AGENTS.md ein: zwischen den Markierungen, ohne Markierungen (ältere Projekte) am Ende.+ * Fehlt AGENTS.md, legt die App sie nicht neu an (E28), sondern meldet das. Rückgabe: Warnung oder null.+ */+export function writeAgentsList(root: string, entries: { id: string; name: string }[]): string | null {+ const file = path.join(root, 'AGENTS.md');+ const cur = agentsText(root);+ if (cur == null) return 'AGENTS.md fehlt. Der Skill liegt im Projekt, ein Agent erfährt aber nichts davon.';+ const eol = cur.includes('\r\n') ? '\r\n' : '\n';+ const block = skillsBlock(entries).replace(/\n/g, eol);+ const a = cur.indexOf(BEGIN), z = cur.indexOf(END);+ const next = a >= 0 && z > a+ ? cur.slice(0, a) + block + cur.slice(z + END.length)+ : cur.replace(/\s*$/, '') + eol + eol + block + eol;+ if (next !== cur) writeAtomic(file, next);+ return null;+}++/** Englischer Name eines Skills für AGENTS.md, aus der mitgelieferten Fassung oder der Kopie im Projekt. */+export function skillName(root: string, bundledDir: string, id: string): string {+ const b = bundledSkills(bundledDir).get(id);+ if (b) return b.name;+ const copy = projectCopy(root, id);+ return copy != null ? parseSkill(id, copy).name : id;+}diff --git a/app/src/main/workspace.ts b/app/src/main/workspace.tsindex b9415a4..6cca41c 100644--- a/app/src/main/workspace.ts+++ b/app/src/main/workspace.ts@@ -5,6 +5,7 @@ import type { ProjectListEntry } from '../shared/types';import { runSoma } from './build';import { GitRepo } from './git';import { appStateFile, backupsDir, projectStateDir, templateDir, workspacesDir } from './paths';+import { SKILLS_DIR, isSkillId } from './skills';import { extractZip } from './zip';export const API_VERSION = 1;@@ -17,6 +18,8 @@ export interface ProjectJson {entry: string;main_output: string;created: string;+ /** Aktive Skills (E17), ihre Kopien liegen in .soma/skills/. */+ skills?: string[];}/** Zweite Kopie des Projektzustands in den App-Daten (E27) plus Angaben, die nur die App braucht. */@@ -84,6 +87,16 @@ export function renameProject(id: string, name: string): void {if (cur) writeJson(stateFile(id), { ...cur, name });}+/** Aktive Skills ins Projekt schreiben, in project.json und die App-Kopie (E27). Wirft, wenn project.json unlesbar ist. */+export function setProjectSkills(id: string, skills: string[]): void {+ const file = path.join(projectDir(id), '.soma', 'project.json');+ const pj = readJson<ProjectJson>(file);+ if (!pj) throw new Error('.soma/project.json fehlt oder ist unlesbar. Ohne sie lässt sich kein Skill eintragen.');+ writeJson(file, { ...pj, skills });+ const cur = readJson<ProjectState>(stateFile(id));+ if (cur) writeJson(stateFile(id), { ...cur, skills });+}+/** Prüft ein Projekt und MELDET Auffälligkeiten. Repariert nichts (E28). */export function inspectProject(id: string): { name: string; problems: string[] } {const dir = projectDir(id);@@ -102,6 +115,9 @@ 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 s of (Array.isArray(pj?.skills) ? pj.skills : []).filter(isSkillId)) {+ if (!fs.existsSync(path.join(dir, SKILLS_DIR, `${s}.md`))) problems.push(`Der Skill „${s}“ ist eingeschaltet, aber ${SKILLS_DIR}/${s}.md 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 und nicht in die ZIP gepackt.`);}diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.tsindex fae29f4..a0c5f4f 100644--- a/app/src/preload/preload.ts+++ b/app/src/preload/preload.ts@@ -56,6 +56,7 @@ const api: SomaApi = {},agents: { detect: () => ipcRenderer.invoke('agents:detect') },measure: { query: (source, req) => ipcRenderer.invoke('measure:query', source, req) },+ skills: { list: () => ipcRenderer.invoke('skills:list'), set: (id, on) => ipcRenderer.invoke('skills:set', id, on) },dialog: { choose: (o) => ipcRenderer.invoke('dialog:choose', o) },// Nur im Testmodus: vorbereitete Antworten für native Dialogetest: process.env.SOMA_TEST === '1'diff --git a/app/src/renderer/code.ts b/app/src/renderer/code.tsindex 03905d5..004cdde 100644--- a/app/src/renderer/code.ts+++ b/app/src/renderer/code.ts@@ -187,7 +187,11 @@ export class CodePanel {if (d.writing) continue;let disk: string | null;try { disk = await this.deps.read(d.file); } catch { disk = null; }- if (this.docs.get(d.file) !== d || d.writing || disk === d.base) continue;+ if (this.docs.get(d.file) !== d || d.writing) continue;+ // Wieder so wie zuletzt gelesen (etwa gelöscht und neu angelegt): Der Konflikt hat sich erledigt+ if (disk === d.base) { d.conflict = null; continue; }+ // Nur lesbare Dateien haben nie Eingaben: Ist die Datei weg, geht der Reiter zu, sonst wird neu geladen+ if (d.locked) { if (disk === null) await this.close(d.file); else this.takeExternal(d, disk); continue; }// Hier liegt Ungespeichertes oder die Datei ist weg: nicht still ersetzen, sondern fragenif (d.dirty || disk === null) d.conflict = { disk };else this.takeExternal(d, disk);diff --git a/app/src/renderer/icons.ts b/app/src/renderer/icons.tsindex d049761..74af133 100644--- a/app/src/renderer/icons.ts+++ b/app/src/renderer/icons.ts@@ -19,6 +19,7 @@ const PATHS: Record<string, string> = {layers: '<path d="m12 3 9 5-9 5-9-5z"/><path d="m3 13 9 5 9-5"/>',ruler: '<path d="M3 17 17 3l4 4L7 21z"/><path d="m7 13 2 2M10 10l2 2M13 7l2 2"/>',section: '<path d="M5 9 12 5l7 4v8l-7 4-7-4z"/><path d="M2 13h20"/>',+ flip: '<path d="M7 4 3 8l4 4M3 8h14M17 12l4 4-4 4M21 16H7"/>',camera: '<path d="M4 8h3l2-3h6l2 3h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/><circle cx="12" cy="13" r="3.5"/>',fit: '<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>', home: '<path d="M3 11 12 4l9 7"/><path d="M5 10v10h14V10"/>',x: '<path d="M18 6 6 18M6 6l12 12"/>', plus: '<path d="M12 5v14M5 12h14"/>', send: '<path d="M5 12h14M13 6l6 6-6 6"/>',diff --git a/app/src/renderer/index.html b/app/src/renderer/index.htmlindex 30e6acf..c27beb8 100644--- a/app/src/renderer/index.html+++ b/app/src/renderer/index.html@@ -33,7 +33,7 @@<nav id="rail" aria-label="Seitenleisten"><button data-panel="files" aria-pressed="false" title="Dateien des Modells"><i data-icon="folder" data-size="20" data-stroke="1.7"></i><span>Dateien</span></button><button data-panel="code" aria-pressed="false" title="Code ansehen und bearbeiten"><i data-icon="code" data-size="20" data-stroke="1.7"></i><span>Code</span></button>- <button disabled title="Skills kommen in einem späteren Schritt"><i data-icon="book" data-size="20" data-stroke="1.7"></i><span>Skills</span></button>+ <button data-panel="skills" aria-pressed="false" title="Skills: Regeln für den Agenten, je Modell zuschaltbar (3D-Druck, Toleranzen …)"><i data-icon="book" data-size="20" data-stroke="1.7"></i><span>Skills</span></button><button disabled title="Die Paketliste kommt in einem späteren Schritt"><i data-icon="pkg" data-size="20" data-stroke="1.7"></i><span>Pakete</span></button><span class="grow"></span><button disabled title="Hilfe kommt in einem späteren Schritt"><i data-icon="help" data-size="20" data-stroke="1.7"></i><span>Hilfe</span></button>@@ -48,6 +48,12 @@<div id="tab-files" class="ftree"></div><div id="dropzone" class="dropzone"><i data-icon="upload" data-size="20"></i><b>Dateien hierher ziehen</b><span>STEP-Dateien, Bilder und Skizzen landen in <code>inputs/</code>. Vorhandenes wird nicht überschrieben.</span></div></section>+ <section id="panel-skills" class="panel" aria-label="Skills" hidden>+ <div class="side-hd"><b>Skills</b><span class="grow"></span>+ <button class="ibtn s side-close" aria-label="Skills schließen"><i data-icon="x" data-size="15" data-stroke="2"></i></button></div>+ <div class="sk-intro">Regeln für den Agenten, je Modell zuschaltbar. Aktive Skills liegen in <code>.soma/skills/</code>, stehen in <code>AGENTS.md</code> und wandern mit der ZIP.</div>+ <div id="skills-list" class="sk-list" role="list"></div>+ </section><section id="panel-code" class="panel" aria-label="Code" hidden><div class="side-hd code-hd"><div id="code-tabs" class="ctabs"></div><span class="grow"></span><button id="btn-codelink" class="btn sm ghost" aria-pressed="true" title="Klick auf ein Bauteil springt zur Codestelle"><i data-icon="link" data-size="14" data-stroke="1.9"></i>Mit Auswahl verknüpft</button>@@ -79,7 +85,7 @@<button id="btn-display" aria-haspopup="menu" aria-expanded="false" title="Darstellung"><i data-icon="layers"></i><span class="lbl">Darstellung</span><span class="c2"><i data-icon="down" data-size="13" data-stroke="2"></i></span></button><span class="vsep"></span><button id="btn-measure" aria-pressed="false" title="Messen: Fläche oder Kante anklicken, ein zweiter Klick misst Abstand und Winkel (exakte Werte)"><i data-icon="ruler"></i><span class="lbl">Messen</span></button>- <button disabled title="Die Schnittansicht kommt in einem späteren Schritt"><i data-icon="section"></i><span class="lbl">Schnitt</span></button>+ <button id="btn-section" aria-pressed="false" title="Schnitt: das Modell an einer Ebene aufschneiden (senkrecht zu X, Y, Z oder parallel zu einer Fläche)"><i data-icon="section"></i><span class="lbl">Schnitt</span></button><span class="vsep"></span><button id="btn-mark" class="hot" title="Viewer-Bild markieren und an den Agenten geben"><i data-icon="camera"></i><span class="lbl">Markieren</span></button></div>@@ -114,6 +120,28 @@</div></div>+ <!-- Schnittansicht (sectiontool.ts): Ebene, Lage, Seite. Ändert nichts am Modell. -->+ <div id="section-card" class="float sectcard" hidden>+ <div class="mc-hd"><span class="mc-ico"><i data-icon="section" data-size="16"></i></span><b>Schnitt</b><span class="grow"></span>+ <button id="btn-section-close" class="ibtn s" aria-label="Schnitt aufheben" title="Schnitt aufheben"><i data-icon="x" data-size="14" data-stroke="2"></i></button></div>+ <div id="section-axes" class="seg" role="radiogroup" aria-label="Schnittebene">+ <button data-axis="x" role="radio" aria-checked="true" title="Ebene senkrecht zur X-Achse">X</button>+ <button data-axis="y" role="radio" aria-checked="false" title="Ebene senkrecht zur Y-Achse">Y</button>+ <button data-axis="z" role="radio" aria-checked="false" title="Ebene senkrecht zur Z-Achse">Z</button>+ <button data-axis="face" role="radio" aria-checked="false" title="Parallel zu einer ebenen Fläche: danach die Fläche im Modell anklicken"><i data-icon="target" data-size="13" data-stroke="2"></i>Fläche</button>+ </div>+ <div class="sx-pos">+ <label id="section-label" for="section-value">X =</label>+ <input id="section-range" type="range" aria-label="Lage der Schnittebene">+ <span class="sx-val"><input id="section-value" type="text" inputmode="decimal" spellcheck="false" autocomplete="off" aria-label="Lage der Schnittebene in mm" title="Wert eingeben und Enter. Pfeiltasten: 1 mm, mit Umschalt 10 mm, mit Alt 0,1 mm"><span class="c3">mm</span></span>+ </div>+ <div id="section-hint" class="mc-hint"></div>+ <div class="sc-actions">+ <button id="btn-section-flip" class="btn sm" title="Die andere Seite wegschneiden"><i data-icon="flip" data-size="14" data-stroke="1.9"></i>Seite wechseln</button>+ <button id="btn-section-look" class="btn sm" title="Senkrecht auf die Schnittfläche blicken"><i data-icon="eye" data-size="14" data-stroke="1.9"></i>Blick auf den Schnitt</button>+ </div>+ </div>+<div id="errcard" class="float errcard" hidden><div class="ec-hd"><span class="err-ico"><i data-icon="alert" data-size="18"></i></span><div class="ec-title"><b>Build fehlgeschlagen</b><span id="err-where" class="c2"></span></div><span class="grow"></span>diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex b134220..3b5a1dd 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -5,6 +5,8 @@ import { FileTree, TEXT_EXT } from './filetree';import { hydrateIcons, icon } from './icons';import { Markup } from './markup';import { MeasureTool } from './measuretool';+import { SectionTool } from './sectiontool';+import { SkillsPanel } from './skills';import { PartsCard } from './parts';import { TerminalTabs } from './terminals';import { $, el, fmtWhen, menuItem, menus, toast } from './ui';@@ -48,9 +50,9 @@ const SURFACE: Record<string, string> = {const surfaceName = (s: string | null) => (s ? SURFACE[s] ?? s.toLowerCase() : 'Fläche');const ERROR_KIND: Record<string, string> = { Timeout: 'Zeitlimit überschritten', PythonStart: 'Python ließ sich nicht starten', NoResult: 'Build ohne Ergebnis' };-// ---- Seitenpanels: Dateien, Code --------------------------------------------------------------------------------+// ---- Seitenpanels: Dateien, Code, Skills -------------------------------------------------------------------------type PanelName = 'files' | 'code';+type PanelName = 'files' | 'code' | 'skills';let panel: PanelName | null = null;let filesDirty = true;@@ -61,8 +63,10 @@ function showPanel(p: PanelName | null): void {$('side').classList.toggle('code', p === 'code');$('panel-files').hidden = p !== 'files';$('panel-code').hidden = p !== 'code';+ $('panel-skills').hidden = p !== 'skills';document.querySelectorAll<HTMLButtonElement>('#rail [data-panel]').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.panel === p)));if (p === 'files' && filesDirty) void refreshFiles();+ if (p === 'skills') void skills.refresh();}const code = new CodePanel(@@ -80,6 +84,15 @@ async function openCode(file: string, mark?: Mark): Promise<void> {await code.open(file, mark);}+const skills = new SkillsPanel($('skills-list'), {+ list: () => api.skills.list(),+ set: (id, on) => api.skills.set(id, on),+ open: (file) => void openCode(file),+ insert: (text) => insertToAgent(text),+ toast,+ changed: () => { filesDirty = true; textCache.clear(); void refreshSaveState(); void code.refresh(); },+});+const files = new FileTree($('tab-files'), (n) => {if (TEXT_EXT.test(n.name)) void openCode(n.path);else if (/\.(step|stp)$/i.test(n.name)) toast('Fremde STEP-Dateien im Viewer ansehen kommt in einem späteren Schritt. Der Agent kann sie schon jetzt im Skript einbinden.', 'info');@@ -161,7 +174,7 @@ async function renderSelection(): Promise<void> {$('sel-swatch').style.background = p?.color ?? '';const bits = pick?.faceId != null? ['Fläche', surfaceName(pick.surface), ...(pick.area != null ? [`${num(pick.area)} mm²`] : [])]- : ['ganzes Bauteil'];+ : pick?.cut ? ['Schnittfläche', 'ganzes Bauteil'] : ['ganzes Bauteil'];$('info').textContent = bits.join(' · ');const peek = $('code');const hasCode = !!(e?.file && e.line);@@ -225,6 +238,14 @@ const measureTool = new MeasureTool({insert: (t) => insertToAgent(t),});+// ---- Schnitt ----------------------------------------------------------------------------------------------------++const sectionTool = new SectionTool({+ card: $('section-card'), button: $<HTMLButtonElement>('btn-section'), close: $<HTMLButtonElement>('btn-section-close'),+ axes: $('section-axes'), label: $('section-label'), range: $<HTMLInputElement>('section-range'), value: $<HTMLInputElement>('section-value'),+ hint: $('section-hint'), flip: $<HTMLButtonElement>('btn-section-flip'), look: $<HTMLButtonElement>('btn-section-look'),+}, { viewer });+// ---- Markierung (E16) -------------------------------------------------------------------------------------------const markup = new Markup({@@ -251,8 +272,10 @@ async function sendMarkup(): Promise<void> {if (!r.ok || !r.path) { toast(`Die Markierung ließ sich nicht speichern: ${r.error ?? 'unbekannter Fehler'}`, 'error'); return; }const old = versions.previewed;markup.close();- // Zeigt das Bild einen alten Stand, soll der Agent das wissen (sonst vergleicht er es mit dem aktuellen Code)- const note = old ? `, zeigt den älteren Stand ${old.short} "${old.subject.slice(0, 80)}"` : '';+ // Zeigt das Bild einen alten Stand oder einen Schnitt, soll der Agent das wissen (sonst vergleicht er es mit dem aktuellen Code+ // oder hält die Schnittfläche für eine echte Fläche)+ const cut = sectionTool.agentText();+ const note = (old ? `, zeigt den älteren Stand ${old.short} "${old.subject.slice(0, 80)}"` : '') + (cut ? `, ${cut}` : '');insertToAgent(`[Markierung: ${r.path}${note}] `, `Markierung gespeichert: ${r.path}`);} catch (e) {toast(`Die Markierung ließ sich nicht speichern: ${e instanceof Error ? e.message : String(e)}`, 'error');@@ -380,6 +403,7 @@ async function loadModel(): Promise<void> {textCache.clear();await viewer.load(glb);measureTool.reset(); // neuer Build: die Nummern der Flächen und Kanten gelten nicht mehr+ sectionTool.refresh();msg.className = ''; msg.textContent = '';refreshPartsCard();// Flächen-IDs gelten nur für einen Build: nach dem Neuladen bleibt das Bauteil gewählt, die Fläche nicht@@ -414,6 +438,7 @@ const versions = new VersionsBar({textCache.clear();await viewer.load(res.glb);measureTool.reset();+ sectionTool.refresh();refreshPartsCard();selectPart(null, null);void renderErrorCard();@@ -433,10 +458,13 @@ async function onProject(p: ProjectInfo): Promise<void> {textCache.clear();markup.close();if (measureTool.isActive) measureTool.setActive(false);+ sectionTool.setActive(false);viewer.clear();versions.reset();terminals.closeAll();code.reset();+ skills.reset();+ if (panel === 'skills') void skills.refresh();selection = null;void renderSelection();partsCard.message('Modell wird gebaut …');@@ -818,6 +846,9 @@ if (api.testMode) {selectionText, errorText,markup: () => markup.state(),measure: () => measureTool.state(),+ section: () => sectionTool.state(),+ skills: () => skills.state(),+ pick: () => selection?.pick ?? null,markPixel: (x: number, y: number) => markup.pixel(x, y),markHandles: () => markup.handles(),insert: (text: string) => insertToAgent(text),diff --git a/app/src/renderer/measuretool.ts b/app/src/renderer/measuretool.tsindex 7edf34c..ece5d6e 100644--- a/app/src/renderer/measuretool.ts+++ b/app/src/renderer/measuretool.ts@@ -61,6 +61,8 @@ export class MeasureTool {private busy = false;private seq = 0;private warm = false;+ /** Einmaliger Hinweis, etwa nach einem Klick auf die Schnittfläche. Verschwindet beim nächsten Klick. */+ private note = '';constructor(private ui: Ui, private deps: Deps) {ui.button.addEventListener('click', () => this.setActive(!this.active));@@ -68,8 +70,10 @@ export class MeasureTool {ui.again.addEventListener('click', () => this.reset());ui.agent.addEventListener('click', () => { const t = this.agentText(); if (t) deps.insert(t); });deps.viewer.onMeasurePick = (h) => void this.pick(h);+ // Die Schnittfläche hat keine exakte Geometrie. Der Klick verwirft nichts, ein Hinweis sagt, was geht.+ deps.viewer.onMeasureCut = () => { this.note = 'Die Schnittfläche selbst lässt sich nicht messen. Ein Klick nahe ihrem Rand wählt die geschnittene Fläche.'; this.render(); };window.addEventListener('keydown', (e) => {- if (!this.active || e.key !== 'Escape') return;+ if (!this.active || e.key !== 'Escape' || e.defaultPrevented) return;const t = e.target as HTMLElement | null;if (t?.closest?.('#terminals, #code-view, input, textarea, .menu')) return;e.preventDefault();@@ -103,7 +107,8 @@ export class MeasureTool {}private async pick(h: ProbeHit | null): Promise<void> {- if (!h) { if (this.a) this.reset(); return; } // daneben geklickt: von vorn+ this.note = '';+ if (!h) { if (this.a) this.reset(); else this.render(); return; } // daneben geklickt: von vornconst sameAsA = this.a && !this.b && this.a.partId === h.partId && this.a.kind === h.kind && this.a.id === h.id;if (!this.a || this.b || sameAsA) { this.a = h; this.b = null; } else this.b = h;this.result = null;@@ -211,6 +216,7 @@ export class MeasureTool {rows.push(el('div', { className: 'mc-sep' }));rows.push(this.entityLine('A', r.a), this.entityLine('B', r.b!));}+ if (this.note) rows.push(el('div', { className: 'mc-hint warn', textContent: this.note }));body.replaceChildren(...rows);again.disabled = !this.a;agent.disabled = !this.result;diff --git a/app/src/renderer/sectiontool.ts b/app/src/renderer/sectiontool.tsnew file mode 100644index 0000000..fa51d71--- /dev/null+++ b/app/src/renderer/sectiontool.ts@@ -0,0 +1,267 @@+import type { PlaneHit, Viewer } from './viewer';++type Axis = 'x' | 'y' | 'z' | 'face';++const AXES: Record<'x' | 'y' | 'z', number[]> = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] };+/**+ * Welche Seite zunächst wegfällt: die, von der die Standardansicht kommt (rechts, vorne, oben). So sieht man nach dem+ * Einschalten gleich in den Schnitt. „Seite wechseln“ dreht das um.+ */+const REMOVE: Record<'x' | 'y' | 'z', number> = { x: 1, y: -1, z: 1 };++interface Ui {+ card: HTMLElement;+ /** Knopf „Schnitt“ im Viewer, Schließen in der Karte. */+ button: HTMLButtonElement; close: HTMLButtonElement;+ /** Knöpfe mit `data-axis` (x, y, z, face). */+ axes: HTMLElement;+ label: HTMLElement; range: HTMLInputElement; value: HTMLInputElement; hint: HTMLElement;+ flip: HTMLButtonElement; look: HTMLButtonElement;+}+interface Deps { viewer: Viewer }++const num = (v: number, digits = 2) => (Math.abs(v) < 5e-4 ? 0 : v).toLocaleString('de-DE', { minimumFractionDigits: digits, maximumFractionDigits: 3 }).replace(/^-/, '−');+/** Für den Agenten: Punkt als Dezimalzeichen, drei Stellen, kein „-0“. */+const f3 = (v: number) => (Math.abs(v) < 5e-4 ? 0 : v).toFixed(3);+const vec = (d: number[]) => `(${d.map((x) => +(Math.abs(x) < 5e-7 ? 0 : x).toFixed(4)).join(', ')})`;+const dot = (a: number[], b: number[]) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];++/** Schrittweite für Schieber und Pfeiltasten: 1, 2 oder 5 mal einer Zehnerpotenz, etwa ein Fünfhundertstel des Bereichs. */+function niceStep(span: number): number {+ const raw = Math.max(span / 500, 1e-4);+ const p = 10 ** Math.floor(Math.log10(raw));+ return [1, 2, 5, 10].map((k) => k * p).find((s) => s >= raw) ?? p * 10;+}++/**+ * Schnittansicht: Eine Ebene senkrecht zu X, Y oder Z oder parallel zu einer angeklickten ebenen Fläche schneidet das Modell.+ * Der Viewer füllt die Schnittflächen und zieht die Kontur. Klicks und Messungen gehen nur an das, was stehen bleibt.+ * Der Schnitt ändert nichts am Modell und wird nicht gespeichert.+ */+export class SectionTool {+ private active = false;+ private axis: Axis = 'x';+ /** Lage der Ebene entlang der Richtung (`a·p = value`). */+ private value = 0;+ private flipped = false;+ /** Fläche, an der der Schnitt ausgerichtet ist. `normal` zeigt aus dem Material heraus, `base` ist ihre Lage entlang der Normalen. */+ private face: { normal: number[]; point: number[]; name: string; base: number } | null = null;+ private range: [number, number] = [0, 1];+ private picking = false;+ private note = '';++ constructor(private ui: Ui, private deps: Deps) {+ ui.button.addEventListener('click', () => this.setActive(!this.active));+ ui.close.addEventListener('click', () => this.setActive(false));+ ui.axes.querySelectorAll<HTMLButtonElement>('[data-axis]').forEach((b) => b.addEventListener('click', () => {+ const a = b.dataset.axis as Axis;+ if (a === 'face') this.startPick(); else this.setAxis(a);+ }));+ ui.range.addEventListener('input', () => this.setShown(Number(ui.range.value)));+ ui.value.addEventListener('change', () => this.takeInput());+ ui.value.addEventListener('blur', () => this.showValue());+ // Während getippt wird, bleibt der Text stehen (render lässt das fokussierte Feld in Ruhe). Enter, Escape und die Pfeiltasten+ // schreiben den übernommenen Wert danach ausdrücklich hinein.+ ui.value.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); this.takeInput(); this.showValue(); ui.value.select(); }+ else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); this.showValue(); ui.value.blur(); }+ else if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {+ // Pfeiltasten: 1 mm, mit Umschalt 10 mm, mit Alt 0,1 mm+ e.preventDefault();+ const step = (e.shiftKey ? 10 : e.altKey ? 0.1 : 1) * (e.key === 'ArrowUp' ? 1 : -1);+ this.setShown(this.shown() + step);+ this.showValue();+ ui.value.select();+ }+ });+ ui.flip.addEventListener('click', () => { this.flipped = !this.flipped; this.apply(); });+ ui.look.addEventListener('click', () => this.deps.viewer.lookFrom(this.removedDir()));+ // Escape bricht das Anklicken einer Fläche ab. Vor allen anderen (Messen verlässt sonst seinen Modus).+ window.addEventListener('keydown', (e) => {+ if (!this.picking || e.key !== 'Escape') return;+ const t = e.target as HTMLElement | null;+ if (t?.closest?.('#terminals, #code-view, .menu')) return;+ e.preventDefault();+ e.stopPropagation();+ this.cancelPick();+ }, true);+ this.render();+ }++ get isActive(): boolean { return this.active; }++ setActive(on: boolean): void {+ if (on === this.active) return;+ this.active = on;+ this.ui.button.setAttribute('aria-pressed', String(on));+ this.ui.card.hidden = !on;+ this.stopPick();+ this.note = '';+ if (on) { this.updateRange(); this.value = this.mid(); this.apply(); } else this.deps.viewer.setSection(null);+ this.render();+ }++ /** Neues Modell (Build oder anderer Stand): Bereich neu bestimmen, die Ebene bleibt, wo sie war. */+ refresh(): void {+ if (!this.active) return;+ this.updateRange();+ this.apply();+ }++ /** Beschreibung für den Agenten, etwa beim Markieren: welche Ebene, welche Seite fehlt. Ohne Schnitt null. */+ agentText(): string | null {+ if (!this.active) return null;+ if (this.axis !== 'face') {+ const name = this.axis.toUpperCase();+ const gone = this.removedSign() > 0 ? '>' : '<';+ return `Schnittansicht bei ${name} = ${f3(this.value)} mm, weggeschnitten ist ${name} ${gone} ${f3(this.value)}`;+ }+ const r = this.removedDir();+ const p = this.planePoint();+ return `Schnittansicht, Ebene durch (${p.map(f3).join(', ')}) mm parallel zu einer Fläche von "${this.face!.name}", `+ + `weggeschnitten ist die Seite in Richtung ${vec(r)}`;+ }++ // ---- Zustand ------------------------------------------------------------------------------------------------++ /** Richtung, entlang der `value` gemessen wird. */+ private dir(): number[] { return this.axis === 'face' ? this.face!.normal : AXES[this.axis]; }++ private removedSign(): number {+ const s = this.axis === 'face' ? 1 : REMOVE[this.axis];+ return this.flipped ? -s : s;+ }++ /** Richtung zur weggeschnittenen Seite. Von dort blickt man auf den Schnitt. */+ private removedDir(): number[] { return this.dir().map((x) => x * this.removedSign()); }++ private planePoint(): number[] {+ const a = this.dir();+ if (this.axis !== 'face') return a.map((x) => x * this.value);+ // Punkt der Fläche, entlang der Normalen in die Ebene geschoben+ const off = this.value - this.face!.base;+ return this.face!.point.map((x, i) => x + a[i] * off);+ }++ /** Was Schieber und Eingabe zeigen: die Koordinate, bei einer Fläche die Tiefe ab der Fläche (positiv ins Material). */+ private shown(): number { return this.axis === 'face' ? this.face!.base - this.value : this.value; }++ private setShown(u: number): void {+ if (!Number.isFinite(u)) return;+ this.value = this.axis === 'face' ? this.face!.base - u : u;+ this.apply();+ }++ private showValue(): void { if (this.active) this.ui.value.value = num(this.shown()); }++ private takeInput(): void {+ const t = this.ui.value.value.trim().replace(/\s/g, '').replace('−', '-').replace(',', '.');+ const u = Number(t);+ if (t === '' || !Number.isFinite(u)) { this.render(); return; }+ this.setShown(u);+ }++ private updateRange(): void {+ this.range = this.deps.viewer.extent(this.dir()) ?? [-1, 1];+ }++ private mid(): number { return (this.range[0] + this.range[1]) / 2; }++ private setAxis(a: 'x' | 'y' | 'z'): void {+ this.stopPick();+ this.note = '';+ if (this.axis === a) { this.render(); return; }+ this.axis = a;+ this.flipped = false;+ this.updateRange();+ this.value = this.mid();+ this.apply();+ }++ // ---- Fläche anklicken ---------------------------------------------------------------------------------------++ private startPick(): void {+ this.picking = true;+ this.note = '';+ this.deps.viewer.pickPlane((h) => this.picked(h));+ this.render();+ }++ private picked(h: PlaneHit | null): void {+ if (!this.picking) return;+ if (!h || h.surface !== 'PLANE') {+ // Weiter warten: Ein Fehlklick soll nicht gleich alles abbrechen+ this.note = h ? 'Das ist keine ebene Fläche. Bitte eine ebene Fläche anklicken.' : 'Dort ist keine Fläche. Bitte eine ebene Fläche anklicken.';+ this.deps.viewer.pickPlane((x) => this.picked(x));+ this.render();+ return;+ }+ this.picking = false;+ this.note = '';+ this.axis = 'face';+ this.flipped = false;+ this.face = { normal: h.normal, point: h.point, name: h.name, base: dot(h.normal, h.point) };+ this.updateRange();+ // Anfangs mitten durch das Bauteil der Fläche, nicht genau in die Fläche (dort fiele die Schnittfläche mit ihr zusammen)+ const own = this.deps.viewer.extent(h.normal, [h.partId]);+ this.value = own ? (own[0] + own[1]) / 2 : this.mid();+ this.apply();+ }++ private cancelPick(): void { this.stopPick(); this.note = ''; this.render(); }++ private stopPick(): void {+ if (!this.picking) return;+ this.picking = false;+ this.deps.viewer.pickPlane(null);+ }++ // ---- Anzeige ------------------------------------------------------------------------------------------------++ private apply(): void {+ if (!this.active) return;+ // Ebene: a·p = value. Behalten wird die Gegenseite der weggeschnittenen: n = −s·a, c = s·value+ const s = this.removedSign();+ const n = this.dir().map((x) => -s * x);+ this.deps.viewer.setSection({ normal: n, constant: s * this.value });+ this.render();+ }++ private render(): void {+ const { ui } = this;+ ui.axes.querySelectorAll<HTMLButtonElement>('[data-axis]').forEach((b) => {+ const a = b.dataset.axis as Axis;+ const on = this.picking ? a === 'face' : a === this.axis;+ b.setAttribute('aria-checked', String(on));+ b.classList.toggle('waiting', this.picking && a === 'face');+ });+ if (!this.active) return;+ const faceMode = this.axis === 'face' && !!this.face;+ // Schieber in der angezeigten Größe: bei einer Fläche die Tiefe, sonst die Koordinate+ const [lo, hi] = faceMode ? [this.face!.base - this.range[1], this.face!.base - this.range[0]] : this.range;+ const u = this.shown();+ const step = niceStep(hi - lo);+ ui.range.min = String(Math.min(lo, u));+ ui.range.max = String(Math.max(hi, u));+ ui.range.step = String(step);+ ui.range.value = String(u);+ if (document.activeElement !== ui.value) this.showValue();+ ui.label.textContent = faceMode ? 'Tiefe' : `${this.axis.toUpperCase()} =`;+ ui.flip.disabled = ui.look.disabled = this.picking;+ ui.range.disabled = ui.value.disabled = this.picking;+ let hint: string;+ if (this.picking) hint = this.note || 'Ebene Fläche im Modell anklicken. Escape bricht ab.';+ else if (faceMode) hint = `Parallel zu einer Fläche von „${this.face!.name}“, Tiefe ab der Fläche.`;+ else hint = `Weggeschnitten: ${this.axis.toUpperCase()} ${this.removedSign() > 0 ? '>' : '<'} ${num(this.value)} mm`;+ ui.hint.textContent = hint;+ ui.hint.classList.toggle('warn', !!this.note);+ }++ /** Für Tests. */+ state() {+ return {+ active: this.active, axis: this.axis, value: this.value, shown: this.active ? this.shown() : null, flipped: this.flipped, picking: this.picking,+ range: this.range, face: this.face, text: this.ui.card.innerText, agent: this.agentText(),+ };+ }+}diff --git a/app/src/renderer/skills.ts b/app/src/renderer/skills.tsnew file mode 100644index 0000000..9f8f387--- /dev/null+++ b/app/src/renderer/skills.ts@@ -0,0 +1,113 @@+import type { SkillInfo, SkillResult } from '../shared/types';+import { icon } from './icons';+import { el } from './ui';++interface Deps {+ list(): Promise<SkillInfo[]>;+ set(id: string, on: boolean): Promise<SkillResult>;+ /** Kopie im Projekt im Code-Panel zeigen (nur lesen). */+ open(file: string): void;+ /** Text in die Eingabe des Agenten einfügen (E11). */+ insert(text: string): void;+ toast(text: string, kind?: 'ok' | 'info' | 'error'): void;+ /** Dateien im Projekt haben sich geändert (Speicherstand, Dateibaum). */+ changed(): void;+}++/**+ * Seitenpanel „Skills“ (E17): mitgelieferte Regelwerke mit Schalter je Modell. Ein- und Ausschalten erledigt der+ * Hauptprozess (Kopie in .soma/skills/, project.json, AGENTS.md). Das Panel zeigt nur, was er meldet.+ */+export class SkillsPanel {+ private skills: SkillInfo[] = [];+ private error = '';+ private busy = new Set<string>();+ private expanded = new Set<string>();+ private loaded = false;++ constructor(private list: HTMLElement, private deps: Deps) {}++ async refresh(): Promise<void> {+ try { this.skills = await this.deps.list(); this.error = ''; } catch (e) { this.error = e instanceof Error ? e.message : String(e); }+ this.loaded = true;+ this.render();+ }++ /** Neues Modell: alte Liste weg, beim nächsten Öffnen neu laden. */+ reset(): void { this.skills = []; this.expanded.clear(); this.loaded = false; this.render(); }++ get isLoaded(): boolean { return this.loaded; }++ private async toggle(s: SkillInfo): Promise<void> {+ if (this.busy.has(s.id)) return;+ const on = !s.active;+ this.busy.add(s.id);+ this.render();+ let r: SkillResult;+ try { r = await this.deps.set(s.id, on); } catch (e) { r = { ok: false, error: e instanceof Error ? e.message : String(e), skills: this.skills }; }+ this.busy.delete(s.id);+ this.skills = r.skills;+ this.render();+ this.deps.changed();+ if (!r.ok) { this.deps.toast(`„${s.title}“ ließ sich nicht ${on ? 'einschalten' : 'ausschalten'}: ${r.error ?? 'unbekannter Fehler'}`, 'error'); return; }+ const kept = r.backup ? ' Die vorige Fassung im Projekt liegt in der Sicherung.' : '';+ if (r.warning) { this.deps.toast(`„${s.title}“ ist ${on ? 'an' : 'aus'}. ${r.warning}${kept}`, 'error'); return; }+ // Ein laufender Agent liest AGENTS.md nicht von selbst neu+ this.deps.toast(on+ ? `„${s.title}“ ist an und steht in AGENTS.md. Einem laufenden Agenten sagt „An Agent geben“ Bescheid.${kept}`+ : `„${s.title}“ ist aus. Ein laufender Agent kennt die Regeln noch: Sag ihm Bescheid oder starte ihn neu.${kept}`);+ }++ private render(): void {+ if (this.error) { this.list.replaceChildren(el('div', { className: 'hint', textContent: `Skills nicht lesbar: ${this.error}` })); return; }+ if (!this.skills.length) { this.list.replaceChildren(el('div', { className: 'hint', textContent: this.loaded ? 'Diese App bringt keine Skills mit.' : 'Lädt …' })); return; }+ this.list.replaceChildren(...this.skills.map((s) => this.row(s)));+ }++ private row(s: SkillInfo): HTMLElement {+ const open = this.expanded.has(s.id);+ const sw = el('button', { className: 'sk-switch', title: s.active ? 'Ausschalten' : 'Einschalten' });+ sw.setAttribute('role', 'switch');+ sw.setAttribute('aria-checked', String(s.active));+ sw.setAttribute('aria-label', `${s.title} ${s.active ? 'ausschalten' : 'einschalten'}`);+ sw.disabled = this.busy.has(s.id) || (!s.bundled && !s.file);+ sw.addEventListener('click', () => void this.toggle(s));+ const more = el('button', { className: 'sk-more' + (open ? ' open' : ''), title: open ? 'Weniger zeigen' : 'Inhalt und Aktionen' }, icon('down', 15, 2));+ more.setAttribute('aria-expanded', String(open));+ more.setAttribute('aria-label', `${s.title}: ${open ? 'weniger zeigen' : 'Inhalt zeigen'}`);+ more.addEventListener('click', () => { if (open) this.expanded.delete(s.id); else this.expanded.add(s.id); this.render(); });+ const text = el('div', { className: 'sk-text' }, el('b', { textContent: s.title }), el('span', { textContent: s.summary }));+ const row = el('div', { className: 'sk-row' + (s.active ? ' on' : '') }, el('div', { className: 'sk-head' }, sw, text, more));+ row.setAttribute('role', 'listitem');+ row.dataset.id = s.id;+ if (s.changed) row.append(el('div', { className: 'sk-note', textContent: 'Die Kopie im Projekt weicht von der Fassung dieser App ab. Aus- und wieder Einschalten übernimmt die Fassung der App, die bisherige kommt in die Sicherung.' }));+ for (const p of s.problems) row.append(el('div', { className: 'sk-warn', textContent: p }));+ if (open) {+ const body = el('div', { className: 'sk-body' });+ if (s.topics.length) body.append(el('div', { textContent: 'Darauf achtet der Agent:' }), el('ul', {}, ...s.topics.map((t) => el('li', { textContent: t }))));+ const actions = el('div', { className: 'sk-actions' });+ if (s.file) {+ const view = el('button', { className: 'btn sm', title: 'Die Kopie im Projekt im Code-Panel zeigen' }, icon('file', 14, 1.9), 'Ansehen');+ view.addEventListener('click', () => this.deps.open(s.file!));+ actions.append(view);+ }+ if (s.active && s.file) {+ const send = el('button', { className: 'btn sm acc', title: 'Den Pfad in die Eingabe des Agenten einfügen' }, icon('send', 14, 1.9), 'An Agent geben');+ send.addEventListener('click', () => this.deps.insert(`[Skill: ${s.file}] `));+ actions.append(send);+ }+ if (!s.file) body.append(el('div', { className: 'c3', textContent: 'Eingeschaltet liegt der Skill als Markdown im Projekt und lässt sich ansehen.' }));+ if (actions.childElementCount) body.append(actions);+ row.append(body);+ }+ return row;+ }++ /** Für Tests. */+ state() {+ return {+ skills: this.skills.map((s) => ({ id: s.id, title: s.title, active: s.active, file: s.file, changed: s.changed, problems: s.problems })),+ busy: [...this.busy], text: this.list.innerText,+ };+ }+}diff --git a/app/src/renderer/style.css b/app/src/renderer/style.cssindex c8d7e6a..30c0e3c 100644--- a/app/src/renderer/style.css+++ b/app/src/renderer/style.css@@ -108,6 +108,31 @@ code { font-family:var(--mono); font-size:.95em; }.frow.dim { color:var(--tx2); }.ftree .gap { height:8px; }.ftree .hint { color:var(--tx3); padding:6px 14px; }+/* Skills (E17): eine Karte je Skill mit Schalter. Eingeschaltet in Orange (Auswahl), Auffälligkeiten in Gelb. */+.sk-intro { padding:10px 14px 4px; font-size:12px; color:var(--tx2); }+.sk-intro code, .sk-row code { font:11.5px var(--mono); color:var(--tx); }+.sk-list { flex:1; overflow:auto; padding:6px 10px 12px; display:flex; flex-direction:column; gap:8px; }+.sk-list .hint { color:var(--tx3); padding:6px 4px; }+.sk-row { border:1px solid var(--line2); border-radius:9px; background:var(--s2); }+.sk-row.on { border-color:var(--acc-line); background:linear-gradient(var(--acc-tint), var(--acc-tint)), var(--s2); }+.sk-head { display:flex; align-items:flex-start; gap:10px; padding:10px 8px 8px 12px; }+.sk-text { flex:1; min-width:0; display:flex; flex-direction:column; gap:2px; }+.sk-text b { font-size:13px; font-weight:600; }+.sk-text span { font-size:12px; color:var(--tx2); }+.sk-switch { position:relative; width:34px; height:20px; flex-shrink:0; margin-top:1px; border-radius:10px; background:var(--s3); box-shadow:inset 0 0 0 1px var(--line2); transition:background .15s; }+.sk-switch::after { content:''; position:absolute; left:3px; top:3px; width:14px; height:14px; border-radius:50%; background:var(--tx2); transition:transform .15s, background .15s; }+.sk-switch[aria-checked=true] { background:var(--acc); box-shadow:none; }+.sk-switch[aria-checked=true]::after { transform:translateX(14px); background:#1b1206; }+.sk-switch:disabled { opacity:.5; }+.sk-more { color:var(--tx3); display:flex; width:24px; height:24px; align-items:center; justify-content:center; border-radius:5px; flex-shrink:0; }+.sk-more:hover { background:var(--s3); color:var(--tx); }+.sk-more.open { transform:rotate(180deg); }+.sk-body { padding:0 12px 10px; font-size:12px; color:var(--tx2); }+.sk-body ul { margin:2px 0 8px; padding-left:18px; }+.sk-body li { margin:1px 0; }+.sk-actions { display:flex; gap:6px; flex-wrap:wrap; }+.sk-note { padding:0 12px 8px 56px; font-size:12px; color:var(--tx3); }+.sk-warn { padding:0 12px 8px 56px; font-size:12px; color:var(--warn); }.dropzone { margin:12px; padding:16px 14px; border:1.5px dashed var(--line2); border-radius:10px; display:flex; flex-direction:column; align-items:center; gap:6px; text-align:center; color:var(--tx2); font-size:12px; flex-shrink:0; }.dropzone b { color:var(--tx); font-size:13px; font-weight:600; }.dropzone.over, body.dragging .dropzone { border-color:var(--acc); background:var(--acc-tint); }@@ -259,6 +284,23 @@ code { font-family:var(--mono); font-size:.95em; }.mc-ent b { color:var(--acc-tx); }.mc-ent span { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }.v-overlay { position:absolute; inset:0; pointer-events:none; z-index:1; overflow:hidden; }++/* Schnitt: Karte unten rechts, neben Auswahl- und Messkarte. Im schmalen Viewer rückt sie unter den Würfel. */+.sectcard { right:14px; bottom:12px; width:300px; overflow:hidden; }+@container viewer (max-width: 760px) { .sectcard { bottom:auto; top:212px; width:272px; } }+.seg { display:flex; gap:2px; margin:2px 12px 8px; padding:3px; border:1px solid var(--line2); border-radius:8px; background:var(--term); }+.seg button { flex:1; display:flex; align-items:center; justify-content:center; gap:5px; height:26px; border-radius:5px; color:var(--tx2); font-weight:500; }+.seg button:hover { background:var(--s3); color:var(--tx); }+.seg button[aria-checked=true] { background:var(--acc-tint); color:var(--acc-tx); box-shadow:inset 0 0 0 1px var(--acc-line); }+.seg button.waiting { animation:pulse 1.2s ease-in-out infinite; }+@keyframes pulse { 50% { background:transparent; } }+.sx-pos { display:flex; align-items:center; gap:8px; padding:0 12px 2px 14px; }+.sx-pos label { width:38px; flex-shrink:0; color:var(--tx2); font-size:12px; white-space:nowrap; }+.sx-pos input[type=range] { flex:1; min-width:0; accent-color:var(--acc); height:18px; }+.sx-val { display:flex; align-items:center; gap:4px; flex-shrink:0; }+.sx-val input { width:72px; height:26px; padding:0 6px; border-radius:5px; border:1px solid var(--line2); background:var(--term); color:var(--tx); font:12px var(--mono); text-align:right; }+.sx-val input:disabled, .sx-pos input[type=range]:disabled { opacity:.45; }+.mc-hint.warn { color:var(--warn); }.v-pt { position:absolute; left:-5px; top:-5px; width:10px; height:10px; border-radius:50%; background:var(--acc); box-shadow:0 0 0 2px var(--bg); }.v-label { position:absolute; left:0; top:0; margin:-32px 0 0 10px; padding:3px 8px; border-radius:6px; background:rgba(24,27,31,.95);border:1px solid var(--acc-line); color:var(--acc-tx); font:600 12.5px var(--mono); white-space:nowrap; }diff --git a/app/src/renderer/viewer.ts b/app/src/renderer/viewer.tsindex 323128e..89a9b0c 100644--- a/app/src/renderer/viewer.ts+++ b/app/src/renderer/viewer.ts@@ -12,15 +12,33 @@ THREE.Object3D.DEFAULT_UP.set(0, 0, 1);interface FaceEntry { id: number; surface: string; area?: number; center?: number[]; triStart: number; triCount: number }interface EdgeEntry { id: number; curve: string; length?: number; segStart: number; segCount: number }interface VertexEntry { id: number; p: number[] }-interface PartMeta { partId: string; name: string; role: string; group?: string | null; faces: FaceEntry[]; edges?: EdgeEntry[]; vertices?: VertexEntry[] }-interface PartEntry { group: THREE.Object3D; meta: PartMeta; meshes: THREE.Mesh[]; lines: THREE.LineSegments[] }+/** `solid`: geschlossener Körper (fehlt bei älteren Builds, gilt dann als geschlossen). Nur dann füllt der Schnitt die Schnittfläche. */+interface PartMeta { partId: string; name: string; role: string; group?: string | null; solid?: boolean; faces: FaceEntry[]; edges?: EdgeEntry[]; vertices?: VertexEntry[] }+interface PartEntry {+ group: THREE.Object3D; meta: PartMeta; meshes: THREE.Mesh[]; lines: THREE.LineSegments[];+ /** Deckel der Schnittfläche: Zählnetze für den Schablonenpuffer und die Platte in der Ebene (erst beim ersten Schnitt angelegt). */+ cap?: { stencils: THREE.Mesh[]; plate: THREE.Mesh };+ /** Dreiecke in Weltkoordinaten, für die Schnittkontur und den Bereich des Schiebers (erst bei Bedarf berechnet). */+ world?: { pos: Float32Array; idx: ArrayLike<number>; faces: boolean }[];+}++/** Treffer eines Strahls. `cut`: Er trifft die Schnittfläche (dort steckt er in der Schnittebene im Material). */+type Hit = THREE.Intersection & { cut?: boolean };export interface PickResult {partId: string; name: string; role: string;faceId: number | null; surface: string | null; area: number | null;point: number[];+ /** Angeklickt wurde die Schnittfläche, keine Fläche des Modells. */+ cut?: boolean;}+/** Schnittebene: sichtbar bleibt, was auf der Seite der Normalen liegt (n·p + c ≥ 0). */+export interface SectionPlane { normal: number[]; constant: number }++/** Angeklickte Fläche, an der sich der Schnitt ausrichten soll. `normal` zeigt aus dem Material heraus. */+export interface PlaneHit { partId: string; name: string; faceId: number; surface: string; normal: number[]; point: number[] }+export type ViewName = 'iso' | 'front' | 'back' | 'top' | 'bottom' | 'right' | 'left' | 'fit';/** Treffer beim Messen: Fläche, Kante oder Eckpunkt eines Bauteils, mit Punkt auf dem Netz (beim Eckpunkt seine Lage). */@@ -45,6 +63,10 @@ export interface MeasureMarks {const EDGE_PX = 7;const VERTEX_PX = 9;const ORANGE = 0xf29a38;+/** Zeichenreihenfolge der Deckel: nach allen deckenden Bauteilen (0, Referenzen 1), je Bauteil zwei Schritte. */+const CAP_ORDER = 100;+const CONTOUR_ORDER = 100000;+const CONTOUR_COLOR = 0x0d0f12;export class Viewer {private renderer: THREE.WebGLRenderer;@@ -81,13 +103,31 @@ export class Viewer {/** Punkt am Drehpunkt, sichtbar während der Bewegung und kurz nach dem Setzen. */private pivot: THREE.Points;private pivotTimer: ReturnType<typeof setTimeout> | undefined;+ /**+ * Schnittansicht: Diese eine Liste hängt an allen geschnittenen Materialien (Bauteile, Kanten, Hervorhebungen). Ohne Schnitt+ * ist sie leer, mit Schnitt enthält sie `plane`. three.js merkt die geänderte Anzahl und baut die Shader neu.+ */+ private clip: THREE.Plane[] = [];+ private plane = new THREE.Plane(new THREE.Vector3(1, 0, 0), 0);+ /** Platten der Schnittflächen, je Bauteil eine. */+ private caps = new THREE.Group();+ private contour: LineSegments2 | null = null;+ /** Zu jedem Segment der Schnittkontur Bauteil und Fläche: Beim Messen lässt sich so die Kontur anklicken. */+ private contourOf: { part: PartEntry; face: number }[] = [];+ private contourDirty = false;+ /** Wartet auf einen Klick auf eine Fläche (Schnitt an Fläche ausrichten). */+ private planePick: ((h: PlaneHit | null) => void) | null = null;onPick: (r: PickResult | null) => void = () => {};/** Klick im Messmodus. null: daneben geklickt. */onMeasurePick: (h: ProbeHit | null) => void = () => {};+ /** Klick im Messmodus auf die Schnittfläche selbst (die hat keine exakte Geometrie). */+ onMeasureCut: () => void = () => {};constructor(private container: HTMLElement) {// Durchsichtiger Hintergrund: den Verlauf dahinter zeichnet CSS, so passt er zur übrigen Oberfläche- this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true, alpha: true });+ // Schablonenpuffer (stencil) für die gefüllten Schnittflächen, seit three.js r163 nicht mehr von selbst da+ this.renderer = new THREE.WebGLRenderer({ antialias: true, preserveDrawingBuffer: true, alpha: true, stencil: true });+ this.renderer.localClippingEnabled = true;this.renderer.setPixelRatio(window.devicePixelRatio);this.renderer.setClearColor(0x000000, 0);container.appendChild(this.renderer.domElement);@@ -95,7 +135,7 @@ export class Viewer {this.scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.6));const sun = new THREE.DirectionalLight(0xffffff, 2.2);sun.position.set(80, -120, 200);- this.scene.add(sun, this.highlight, this.hover, this.marks);+ this.scene.add(sun, this.highlight, this.hover, this.marks, this.caps);this.overlay = document.createElement('div');this.overlay.className = 'v-overlay';container.appendChild(this.overlay);@@ -134,10 +174,14 @@ export class Viewer {if ((c as THREE.LineSegments).isLineSegments) lines.push(c as THREE.LineSegments);});// Auch die Kanten brauchen ihr eigenes Material, sonst würden sie mit einem transparenten Teil überall blass- for (const l of lines) l.material = (l.material as THREE.LineBasicMaterial).clone();+ for (const l of lines) {+ l.material = (l.material as THREE.LineBasicMaterial).clone();+ l.material.clippingPlanes = this.clip;+ }for (const m of meshes) {// Eigenes Material je Netz: die Auswahl färbt ein Bauteil ein, gleichfarbige Teile dürfen nicht mitleuchtenconst mat = (m.material as THREE.MeshStandardMaterial).clone();+ mat.clippingPlanes = this.clip;m.material = mat;// Flächen minimal nach hinten, damit Kantenlinien nicht mit ihnen um die Tiefe kämpfenmat.polygonOffset = true; mat.polygonOffsetFactor = 1; mat.polygonOffsetUnits = 1;@@ -147,6 +191,7 @@ export class Viewer {}fresh.set(meta.partId, { group: o, meta, meshes, lines });});+ this.clearCaps();this.disposeModel();this.model = gltf.scene;this.parts = fresh;@@ -164,10 +209,12 @@ export class Viewer {if (!box.isEmpty()) { box.getCenter(this.center); this.radius = Math.max(box.getSize(new THREE.Vector3()).length() / 2, 1); }if (!this.hasFitted && this.parts.size) { this.setView('iso'); this.hasFitted = true; }this.fitClip();+ this.syncSection();this.requestRender();}clear(): void {+ this.clearCaps();this.disposeModel();this.parts.clear();this.hidden.clear();@@ -176,6 +223,7 @@ export class Viewer {this.highlight.clear();this.clearGroup(this.hover);this.setMeasureMarks(null);+ this.syncSection();this.requestRender();}@@ -231,6 +279,7 @@ export class Viewer {private applyVisibility(): void {for (const [id, p] of this.parts) p.group.visible = !this.hidden.has(id);+ this.syncSection();}setEdges(on: boolean): void { this.edges = on; this.applyDisplay(); this.requestRender(); }@@ -258,6 +307,7 @@ export class Viewer {mat.needsUpdate = true;}}+ this.syncSection();}/** Sichtbare Bauteile, getrennt nach deckend und einzeln transparent. Treffer gehen zuerst an die deckenden. */@@ -267,10 +317,38 @@ export class Viewer {}/** Erste Fläche unter dem Strahl, transparente Teile nur, wenn dahinter nichts Deckendes liegt. */- private firstHit(): THREE.Intersection | undefined {+ private firstHit(): Hit | undefined {const [solid, ghost] = this.pickSets();- return this.raycaster.intersectObjects(solid.flatMap((p) => p.meshes), false)[0]- ?? this.raycaster.intersectObjects(ghost.flatMap((p) => p.meshes), false)[0];+ return this.visibleHit(solid.flatMap((p) => p.meshes)) ?? this.visibleHit(ghost.flatMap((p) => p.meshes));+ }++ private partOf(o: THREE.Object3D): PartEntry | undefined {+ return [...this.parts.values()].find((p) => p.meshes.includes(o as THREE.Mesh));+ }++ /**+ * Erster sichtbarer Treffer des Strahls: Was der Schnitt wegnimmt, zählt nicht. Ist der erste verbleibende Treffer die+ * Rückseite eines Bauteils mit Deckel, steckt der Strahl in der Schnittebene im Material. Er trifft dann die Schnittfläche.+ */+ private visibleHit(meshes: THREE.Mesh[]): Hit | undefined {+ const hits = this.raycaster.intersectObjects(meshes, false);+ if (!this.clip.length) return hits[0];+ const first = hits.find((h) => !this.clipped(h.point));+ if (!first?.face) return first;+ const ray = this.raycaster.ray;+ const at = ray.intersectPlane(this.plane, new THREE.Vector3());+ if (!at) return first;+ const d = at.distanceTo(ray.origin);+ const back = first.face.normal.clone().transformDirection(first.object.matrixWorld).dot(ray.direction) > 0;+ if (d < first.distance && back && this.partOf(first.object)?.cap?.plate.visible) {+ return { ...first, point: at, distance: d, face: null, faceIndex: undefined, cut: true };+ }+ return first;+ }++ /** Liegt der Punkt auf der weggeschnittenen Seite? Etwas Toleranz, sonst flackerten Punkte genau in der Ebene. */+ private clipped(p: THREE.Vector3): boolean {+ return this.clip.length > 0 && this.plane.distanceToPoint(p) < -Math.max(1e-6, this.radius * 1e-7);}// ---- Kamera ---------------------------------------------------------------------------------------------------@@ -333,6 +411,9 @@ export class Viewer {});}+ /** Wie orient, mit der Richtung als Zahlen (vom Drehpunkt zur Kamera). */+ lookFrom(dir: number[]): void { this.orient(new THREE.Vector3(dir[0], dir[1], dir[2])); }+/** Um den Drehpunkt drehen, wie OrbitControls es tut (Kugelkoordinaten zur Hochachse). */orbit(dTheta: number, dPhi: number): void {this.anim?.stop();@@ -423,7 +504,7 @@ export class Viewer {const hit = this.firstHit();this.highlight.clear();if (!hit) { this.selectedId = null; this.applySelection(); this.requestRender(); return null; }- const part = [...this.parts.values()].find((p) => p.meshes.includes(hit.object as THREE.Mesh))!;+ const part = this.partOf(hit.object)!;const face = hit.faceIndex != null ? Viewer.faceOfTriangle(part.meta.faces, hit.faceIndex) : null;this.selectedId = part.meta.partId;this.applySelection();@@ -433,6 +514,7 @@ export class Viewer {partId: part.meta.partId, name: part.meta.name, role: part.meta.role,faceId: face?.id ?? null, surface: face?.surface ?? null, area: face?.area ?? null,point: hit.point.toArray().map((v) => +v.toFixed(3)),+ ...(hit.cut ? { cut: true } : {}),};}@@ -443,7 +525,8 @@ export class Viewer {g.setAttribute('position', src.geometry.getAttribute('position'));g.setIndex(Array.from(src.geometry.index!.array.slice(face.triStart * 3, (face.triStart + face.triCount) * 3)));const o = new THREE.Mesh(g, new THREE.MeshBasicMaterial({- color: 0xf29a38, transparent: true, opacity: 0.85, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, side: THREE.DoubleSide }));+ color: 0xf29a38, transparent: true, opacity: 0.85, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, side: THREE.DoubleSide,+ clippingPlanes: this.clip }));o.renderOrder = 2;this.highlight.add(o);}@@ -454,15 +537,26 @@ export class Viewer {el.addEventListener('pointerdown', (e) => { down = [e.clientX, e.clientY]; });el.addEventListener('pointerup', (e) => {if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4) return; // Ziehen ist kein Klick- if (this.mode === 'measure') { this.onMeasurePick(this.probe(e.clientX, e.clientY)); return; }+ if (this.planePick) { const cb = this.planePick; this.pickPlane(null); cb(this.planeAt(e.clientX, e.clientY)); return; }+ if (this.mode === 'measure') {+ const h = this.probeAt(e.clientX, e.clientY);+ if (h === 'cut') this.onMeasureCut(); else this.onMeasurePick(h);+ return;+ }const r = el.getBoundingClientRect();this.onPick(this.pickAt(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1));});// Messen: Element unter dem Zeiger hervorheben (höchstens einmal pro Bild berechnet)let queued: [number, number] | null = null;el.addEventListener('pointermove', (e) => {- if (this.mode !== 'measure' || e.buttons) return;- if (!queued) requestAnimationFrame(() => { const q = queued; queued = null; if (q && this.mode === 'measure') this.showHover(this.probe(q[0], q[1])); });+ if ((this.mode !== 'measure' && !this.planePick) || e.buttons) return;+ if (!queued) requestAnimationFrame(() => {+ const q = queued;+ queued = null;+ if (!q) return;+ if (this.planePick) { const f = this.planeAt(q[0], q[1]); this.showHover(f ? { partId: f.partId, name: f.name, kind: 'face', id: f.faceId, type: f.surface, size: null, point: f.point } : null); }+ else if (this.mode === 'measure') this.showHover(this.probe(q[0], q[1]));+ });queued = [e.clientX, e.clientY];});el.addEventListener('pointerleave', () => this.showHover(null));@@ -480,16 +574,26 @@ export class Viewer {/** Umschalten zwischen Auswählen (Klick wählt ein Bauteil) und Messen (Klick wählt Fläche oder Kante). */setMode(m: 'select' | 'measure'): void {this.mode = m;- this.renderer.domElement.style.cursor = m === 'measure' ? 'crosshair' : '';+ this.updateCursor();if (m !== 'measure') this.showHover(null);}+ private updateCursor(): void {+ this.renderer.domElement.style.cursor = this.mode === 'measure' || this.planePick ? 'crosshair' : '';+ }+/*** Eckpunkt, Kante oder Fläche unter einem Bildschirmpunkt, in dieser Reihenfolge: Punkte gewinnen im Umkreis von VERTEX_PX,* Kanten im Umkreis von EDGE_PX, sonst gilt die Fläche (sonst ließen sich Punkte und Kanten kaum treffen). Verdeckte Punkte* und Kanten zählen nicht, ebenso wenig ausgeblendete Bauteile. Ohne sichtbare Kanten gibt es auch keine Punkte.*/probe(clientX: number, clientY: number): ProbeHit | null {+ const h = this.probeAt(clientX, clientY);+ return h === 'cut' ? null : h;+ }++ /** Wie probe, nur mit 'cut', wenn der Klick die Schnittfläche selbst trifft. */+ private probeAt(clientX: number, clientY: number): ProbeHit | 'cut' | null {const el = this.renderer.domElement;const r = el.getBoundingClientRect();if (!r.width || !r.height) return null;@@ -500,28 +604,32 @@ export class Viewer {return this.probeIn(px, py, r.width, r.height, solid) ?? this.probeIn(px, py, r.width, r.height, ghost);}- private probeIn(px: number, py: number, w: number, h: number, parts: PartEntry[]): ProbeHit | null {+ private probeIn(px: number, py: number, w: number, h: number, parts: PartEntry[]): ProbeHit | 'cut' | null {if (!parts.length) return null;const targets = parts.flatMap((p) => p.meshes);this.raycaster.setFromCamera(new THREE.Vector2((px / w) * 2 - 1, -(py / h) * 2 + 1), this.camera);- const hit = this.raycaster.intersectObjects(targets, false)[0];+ const hit = this.visibleHit(targets);const vertex = this.nearestVertex(px, py, w, h, parts, targets);if (vertex) return vertex;const edge = this.nearestEdge(px, py, w, h, parts, targets);if (edge) return edge;+ // Am Schnitt: Ein Klick nahe der Kontur wählt die Fläche, aus der sie stammt (so misst man Wandstärken im Schnitt)+ const rim = this.nearestContour(px, py, w, h, parts, targets);+ if (rim) return rim;if (!hit) return null;- const part = [...this.parts.values()].find((p) => p.meshes.includes(hit.object as THREE.Mesh))!;+ if (hit.cut) return 'cut';+ const part = this.partOf(hit.object)!;const face = hit.faceIndex != null ? Viewer.faceOfTriangle(part.meta.faces, hit.faceIndex) : null;if (!face) return null;return { partId: part.meta.partId, name: part.meta.name, kind: 'face', id: face.id, type: face.surface, size: face.area ?? null, point: hit.point.toArray() };}- /** Liegt der Weltpunkt hinter einer Fläche? Toleranz für die Vernetzung, sonst verdeckte die eigene Fläche ihre Kanten. */+ /** Liegt der Weltpunkt hinter einer Fläche oder einer Schnittfläche? Toleranz für die Vernetzung, sonst verdeckte die eigene Fläche ihre Kanten. */private occluded(p: THREE.Vector3, occluders: THREE.Mesh[]): boolean {const eye = this.camera.position;const dist = eye.distanceTo(p);this.raycaster.set(eye, p.clone().sub(eye).normalize());- const first = this.raycaster.intersectObjects(occluders, false)[0];+ const first = this.visibleHit(occluders);return !!first && first.distance < dist - Math.max(0.5, dist * 0.002);}@@ -533,6 +641,7 @@ export class Viewer {p.group.updateMatrixWorld();for (const vx of p.meta.vertices) {v.set(vx.p[0], vx.p[1], vx.p[2]).applyMatrix4(p.group.matrixWorld);+ if (this.clipped(v)) continue;s.copy(v).project(this.camera);if (s.z > 1) continue;const d = Math.hypot((s.x + 1) / 2 * w - px, (1 - s.y) / 2 * h - py);@@ -572,7 +681,7 @@ export class Viewer {}cands.sort((x, y) => x.d - y.d);for (const c of cands.slice(0, 8)) {- if (this.occluded(c.point, occluders)) continue;+ if (this.clipped(c.point) || this.occluded(c.point, occluders)) continue;const edge = Viewer.edgeOfSegment(c.part.meta.edges!, c.seg);if (!edge) continue;return { partId: c.part.meta.partId, name: c.part.meta.name, kind: 'edge', id: edge.id, type: edge.curve, size: edge.length ?? null, point: c.point.toArray() };@@ -580,6 +689,38 @@ export class Viewer {return null;}+ /** Nächstes Segment der Schnittkontur in der Nähe: liefert die Fläche, die dort geschnitten wird. */+ private nearestContour(px: number, py: number, w: number, h: number, parts: PartEntry[], occluders: THREE.Mesh[]): ProbeHit | null {+ if (!this.clip.length) return null;+ this.prepareSection();+ if (!this.contour) return null;+ const pos = (this.contour.geometry as LineSegmentsGeometry).getAttribute('instanceStart') as THREE.InterleavedBufferAttribute;+ const end = (this.contour.geometry as LineSegmentsGeometry).getAttribute('instanceEnd') as THREE.InterleavedBufferAttribute;+ const allowed = new Set(parts);+ const a = new THREE.Vector3(), b = new THREE.Vector3(), sa = new THREE.Vector3(), sb = new THREE.Vector3();+ const cands: { k: number; d: number; point: THREE.Vector3 }[] = [];+ for (let k = 0; k < this.contourOf.length; k++) {+ if (!allowed.has(this.contourOf[k].part)) continue;+ a.fromBufferAttribute(pos, k); b.fromBufferAttribute(end, k);+ sa.copy(a).project(this.camera); sb.copy(b).project(this.camera);+ if (sa.z > 1 || sb.z > 1) continue;+ const ax = (sa.x + 1) / 2 * w, ay = (1 - sa.y) / 2 * h, bx = (sb.x + 1) / 2 * w, by = (1 - sb.y) / 2 * h;+ const dx = bx - ax, dy = by - ay, len = dx * dx + dy * dy;+ const t = len ? Math.max(0, Math.min(1, ((px - ax) * dx + (py - ay) * dy) / len)) : 0;+ const d = Math.hypot(px - ax - t * dx, py - ay - t * dy);+ if (d <= EDGE_PX) cands.push({ k, d, point: a.clone().lerp(b, t) });+ }+ cands.sort((x, y) => x.d - y.d);+ for (const c of cands.slice(0, 8)) {+ if (this.occluded(c.point, occluders)) continue;+ const { part, face: fid } = this.contourOf[c.k];+ const face = part.meta.faces.find((f) => f.id === fid);+ if (!face) continue;+ return { partId: part.meta.partId, name: part.meta.name, kind: 'face', id: face.id, type: face.surface, size: face.area ?? null, point: c.point.toArray() };+ }+ return null;+ }+private static edgeOfSegment(edges: EdgeEntry[], seg: number): EdgeEntry | null {let lo = 0, hi = edges.length - 1, ans = -1;while (lo <= hi) {@@ -650,7 +791,8 @@ export class Viewer {}const g = new THREE.BufferGeometry();g.setAttribute('position', new THREE.BufferAttribute(tri, 3));- const o = new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, side: THREE.DoubleSide }));+ const o = new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color, transparent: true, opacity, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2, side: THREE.DoubleSide,+ clippingPlanes: this.clip }));o.renderOrder = 3;group.add(o);return;@@ -664,7 +806,7 @@ export class Viewer {for (let s = edge.segStart; s < edge.segStart + edge.segCount; s++) {for (const k of [s * 2, s * 2 + 1]) { v.fromBufferAttribute(pos, k).applyMatrix4(l.matrixWorld); flat.push(v.x, v.y, v.z); }}- group.add(this.fatLines(flat, color, width, false));+ group.add(this.fatLines(flat, color, width, false, true));}private static dotTexture: THREE.Texture | null = null;@@ -686,11 +828,15 @@ export class Viewer {return Viewer.dotTexture;}- /** Linien mit fester Breite in Pixeln (WebGL-Linien sind sonst immer 1 px). Immer sichtbar, auch hinter Flächen. */- private fatLines(flat: number[], color: number, width: number, dashed: boolean): LineSegments2 {+ /**+ * Linien mit fester Breite in Pixeln (WebGL-Linien sind sonst immer 1 px). Immer sichtbar, auch hinter Flächen.+ * `clipped`: Der Schnitt nimmt sie mit weg (Kanten des Modells, nicht aber Messstrecken).+ */+ private fatLines(flat: number[], color: number, width: number, dashed: boolean, clipped = false): LineSegments2 {const g = new LineSegmentsGeometry();g.setPositions(flat);const m = new LineMaterial({ color, linewidth: width, depthTest: false, transparent: true, dashed, dashSize: 1.2, gapSize: 0.9 });+ if (clipped) m.clippingPlanes = this.clip;m.resolution.set(this.container.clientWidth || 1, this.container.clientHeight || 1);this.lineMats.add(m);const l = new LineSegments2(g, m);@@ -749,6 +895,7 @@ export class Viewer {requestAnimationFrame(() => {this.renderQueued = false;this.pivot.position.copy(this.controls.target);+ this.prepareSection();this.renderer.render(this.scene, this.camera);this.placeOverlay();this.cube?.render();@@ -769,6 +916,7 @@ export class Viewer {this.marks.visible = false;const pivotShown = this.pivot.visible;this.pivot.visible = false;+ this.prepareSection();this.renderer.render(this.scene, this.camera);const c = document.createElement('canvas');try { this.paintSnapshot(c); } finally {@@ -810,7 +958,11 @@ export class Viewer {thumbnail(w = 360, h = 240): string | null {const src = this.renderer.domElement;if (!this.parts.size || !src.width || !src.height) return null;+ // Ohne Schnitt: Auf der Startseite soll das Modell ganz zu sehen sein+ const cut = this.clip.length > 0;+ if (cut) { this.clip.length = 0; this.caps.visible = false; if (this.contour) this.contour.visible = false; }this.renderer.render(this.scene, this.camera);+ if (cut) { this.clip.push(this.plane); this.caps.visible = true; if (this.contour) this.contour.visible = true; this.requestRender(); }const c = document.createElement('canvas');c.width = w; c.height = h;const g = c.getContext('2d');@@ -825,6 +977,235 @@ export class Viewer {return c.toDataURL('image/jpeg', 0.82);}+ // ---- Schnitt --------------------------------------------------------------------------------------------------++ /** Schnittebene setzen oder mit null aufheben. Sichtbar bleibt, was auf der Seite der Normalen liegt. */+ setSection(s: SectionPlane | null): void {+ if (s) {+ this.plane.normal.set(s.normal[0], s.normal[1], s.normal[2]).normalize();+ this.plane.constant = s.constant;+ if (!this.clip.length) this.clip.push(this.plane);+ } else this.clip.length = 0;+ this.syncSection();+ this.requestRender();+ }++ get section(): SectionPlane | null {+ return this.clip.length ? { normal: this.plane.normal.toArray(), constant: this.plane.constant } : null;+ }++ /** Von wo bis wo reichen die sichtbaren Bauteile entlang einer Richtung? Für den Bereich des Schiebers. */+ extent(dir: number[], ids?: string[]): [number, number] | null {+ const d = new THREE.Vector3(dir[0], dir[1], dir[2]).normalize();+ let lo = Infinity, hi = -Infinity;+ for (const [id, p] of this.parts) {+ if (ids ? !ids.includes(id) : !p.group.visible) continue;+ for (const w of this.worldOf(p)) {+ const pos = w.pos;+ for (let i = 0; i < pos.length; i += 3) {+ const v = d.x * pos[i] + d.y * pos[i + 1] + d.z * pos[i + 2];+ if (v < lo) lo = v;+ if (v > hi) hi = v;+ }+ }+ }+ return lo <= hi ? [lo, hi] : null;+ }++ /** Der nächste Klick ins Modell wählt eine Fläche (Rückruf mit null: daneben). pickPlane(null) bricht ab. */+ pickPlane(cb: ((h: PlaneHit | null) => void) | null): void {+ this.planePick = cb;+ this.updateCursor();+ if (!cb) this.showHover(null);+ }++ get pickingPlane(): boolean { return !!this.planePick; }++ /** Fläche unter dem Zeiger mit ihrer Normalen (nach außen) und einem Punkt darauf. */+ private planeAt(clientX: number, clientY: number): PlaneHit | null {+ const r = this.renderer.domElement.getBoundingClientRect();+ if (!r.width || !r.height) return null;+ this.camera.updateMatrixWorld();+ this.raycaster.setFromCamera(new THREE.Vector2(((clientX - r.left) / r.width) * 2 - 1, -((clientY - r.top) / r.height) * 2 + 1), this.camera);+ const hit = this.firstHit();+ if (!hit || hit.cut || !hit.face || hit.faceIndex == null) return null;+ const part = this.partOf(hit.object)!;+ const face = Viewer.faceOfTriangle(part.meta.faces, hit.faceIndex);+ if (!face) return null;+ const n = hit.face.normal.clone().transformDirection(hit.object.matrixWorld);+ // Achsparallel bleibt exakt achsparallel (die Normale des Dreiecks hat Rundungsfehler im Netz)+ const snapped = n.toArray().map((x) => (Math.abs(x) < 1e-6 ? 0 : Math.abs(Math.abs(x) - 1) < 1e-6 ? Math.sign(x) : x));+ n.fromArray(snapped).normalize();+ const point = face.center && face.surface === 'PLANE'+ ? new THREE.Vector3(...(face.center as [number, number, number])).applyMatrix4(part.group.matrixWorld) : hit.point;+ return { partId: part.meta.partId, name: part.meta.name, faceId: face.id, surface: face.surface, normal: n.toArray(), point: point.toArray() };+ }++ /** Dreiecke eines Bauteils in Weltkoordinaten (einmal berechnet, das Modell bewegt sich nicht). */+ private worldOf(p: PartEntry): NonNullable<PartEntry['world']> {+ if (p.world) return p.world;+ p.group.updateMatrixWorld(true);+ const v = new THREE.Vector3();+ const faceMesh = p.meshes.find((m) => m.geometry.index);+ p.world = p.meshes.map((m) => {+ const src = m.geometry.getAttribute('position');+ const pos = new Float32Array(src.count * 3);+ for (let i = 0; i < src.count; i++) { v.fromBufferAttribute(src, i).applyMatrix4(m.matrixWorld); pos[i * 3] = v.x; pos[i * 3 + 1] = v.y; pos[i * 3 + 2] = v.z; }+ const idx = m.geometry.index ? m.geometry.index.array : Array.from({ length: src.count }, (_, i) => i);+ return { pos, idx, faces: m === faceMesh };+ });+ return p.world;+ }++ /**+ * Deckel und Kontur an den aktuellen Stand anpassen: Deckel nur für sichtbare, deckende, geschlossene Körper. Transparente+ * Teile und Referenzen bekommen keinen (ihr Inneres ist ohnehin zu sehen), im Drahtgitter gibt es nur die Kontur.+ */+ private syncSection(): void {+ const on = this.clip.length > 0;+ let k = 0;+ for (const [id, p] of this.parts) {+ const mat = p.meshes[0]?.material as THREE.MeshStandardMaterial | undefined;+ const want = on && !this.wire && p.group.visible && p.meta.solid !== false && !this.ghosted.has(id) && !!mat && !mat.userData.baseTransparent;+ if (want && !p.cap) p.cap = this.makeCap(p);+ if (p.cap) {+ for (const s of p.cap.stencils) { s.visible = want; s.renderOrder = CAP_ORDER + 2 * k; }+ p.cap.plate.visible = want;+ p.cap.plate.renderOrder = CAP_ORDER + 2 * k + 1;+ }+ if (want) k++;+ }+ if (on) this.placeCaps();+ this.contourDirty = true;+ }++ /**+ * Gefüllte Schnittfläche nach dem Verfahren mit dem Schablonenpuffer: Die Rückseiten des geschnittenen Körpers zählen hoch,+ * die Vorderseiten herunter. Wo etwas übrig bleibt, liegt die Schnittebene im Material, dort zeichnet die Platte in der Ebene.+ * Sie setzt den Puffer dabei zurück, damit das nächste Bauteil von vorn zählt.+ */+ private makeCap(p: PartEntry): NonNullable<PartEntry['cap']> {+ const stencils: THREE.Mesh[] = [];+ for (const m of p.meshes) {+ for (const back of [true, false]) {+ const op = back ? THREE.IncrementWrapStencilOp : THREE.DecrementWrapStencilOp;+ const mat = new THREE.MeshBasicMaterial({+ side: back ? THREE.BackSide : THREE.FrontSide, depthWrite: false, depthTest: false, colorWrite: false,+ stencilWrite: true, stencilFunc: THREE.AlwaysStencilFunc, stencilFail: op, stencilZFail: op, stencilZPass: op,+ });+ mat.clippingPlanes = this.clip;+ const s = new THREE.Mesh(m.geometry, mat);+ s.raycast = () => {};+ m.add(s); // gleiche Lage wie das Netz, wird mit ihm freigegeben+ stencils.push(s);+ }+ }+ const base = (p.meshes[0].material as THREE.MeshStandardMaterial).color;+ const mat = new THREE.MeshBasicMaterial({+ color: base.clone().multiplyScalar(0.72), side: THREE.DoubleSide,+ polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1,+ stencilWrite: true, stencilRef: 0, stencilFunc: THREE.NotEqualStencilFunc,+ stencilFail: THREE.ReplaceStencilOp, stencilZFail: THREE.ReplaceStencilOp, stencilZPass: THREE.ReplaceStencilOp,+ });+ // Schraffur im Bildraum wie in Schnittzeichnungen, je Bauteil abwechselnd gekippt (gleiche Shader, eigene Werte)+ const dpr = window.devicePixelRatio || 1;+ const hatch = new THREE.Vector3(this.caps.children.length % 2 ? -1 : 1, 7 * dpr, 0.6 * dpr);+ mat.onBeforeCompile = (sh) => {+ sh.uniforms.uHatch = { value: hatch };+ sh.fragmentShader = 'uniform vec3 uHatch;\n' + sh.fragmentShader.replace('#include <dithering_fragment>', `#include <dithering_fragment>+ float hu = (gl_FragCoord.x * uHatch.x + gl_FragCoord.y) * 0.70710678;+ float hd = abs(mod(hu, uHatch.y) - 0.5 * uHatch.y);+ gl_FragColor.rgb *= 1.0 - 0.45 * smoothstep(0.5 * uHatch.y - uHatch.z - 0.6, 0.5 * uHatch.y - uHatch.z + 0.6, hd);`);+ };+ const plate = new THREE.Mesh(Viewer.plateGeometry, mat);+ plate.raycast = () => {};+ plate.onAfterRender = (r) => r.clearStencil();+ this.caps.add(plate);+ return { stencils, plate };+ }++ private static plateGeometry = new THREE.PlaneGeometry(1, 1);++ /** Platten in die Ebene legen, groß genug für das ganze Modell. */+ private placeCaps(): void {+ const at = this.plane.projectPoint(this.center, new THREE.Vector3());+ const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, 0, 1), this.plane.normal);+ const s = this.radius * 4;+ for (const o of this.caps.children) { o.position.copy(at); o.quaternion.copy(q); o.scale.set(s, s, 1); }+ }++ private clearCaps(): void {+ for (const p of this.parts.values()) {+ if (!p.cap) continue;+ for (const s of p.cap.stencils) { s.removeFromParent(); (s.material as THREE.Material).dispose(); }+ (p.cap.plate.material as THREE.Material).dispose();+ p.cap = undefined;+ }+ this.caps.clear();+ this.setContour(null);+ }++ /** Vor dem Zeichnen: Kontur neu berechnen, wenn sich Ebene oder Sichtbarkeit geändert haben. */+ private prepareSection(): void {+ if (!this.contourDirty) return;+ this.contourDirty = false;+ this.setContour(this.clip.length ? this.computeContour() : null);+ }++ /** Schnittlinien der Dreiecke mit der Ebene, je Segment mit Bauteil und Fläche. Transparente Teile bleiben ohne Kontur. */+ private computeContour(): { flat: number[]; of: { part: PartEntry; face: number }[] } {+ const n = this.plane.normal, c = this.plane.constant;+ const flat: number[] = [], of: { part: PartEntry; face: number }[] = [];+ const cross = (pos: Float32Array, i: number, j: number, di: number, dj: number) => {+ const t = di / (di - dj);+ flat.push(pos[i] + (pos[j] - pos[i]) * t, pos[i + 1] + (pos[j + 1] - pos[i + 1]) * t, pos[i + 2] + (pos[j + 2] - pos[i + 2]) * t);+ };+ for (const [id, p] of this.parts) {+ if (!p.group.visible || this.ghosted.has(id)) continue;+ for (const w of this.worldOf(p)) {+ const { pos, idx } = w;+ let face: FaceEntry | null = null;+ for (let t = 0; t + 2 < idx.length; t += 3) {+ const a = idx[t] * 3, b = idx[t + 1] * 3, cc = idx[t + 2] * 3;+ const da = n.x * pos[a] + n.y * pos[a + 1] + n.z * pos[a + 2] + c;+ const db = n.x * pos[b] + n.y * pos[b + 1] + n.z * pos[b + 2] + c;+ const dc = n.x * pos[cc] + n.y * pos[cc + 1] + n.z * pos[cc + 2] + c;+ const sa = da >= 0, sb = db >= 0, sc = dc >= 0;+ if (sa === sb && sb === sc) continue;+ // Genau zwei Kanten des Dreiecks kreuzen die Ebene+ if (sa !== sb) cross(pos, a, b, da, db);+ if (sb !== sc) cross(pos, b, cc, db, dc);+ if (sc !== sa) cross(pos, cc, a, dc, da);+ const tri = t / 3;+ if (w.faces && !(face && tri >= face.triStart && tri < face.triStart + face.triCount)) face = Viewer.faceOfTriangle(p.meta.faces, tri);+ of.push({ part: p, face: w.faces && face ? face.id : -1 });+ }+ }+ }+ return { flat, of };+ }++ private setContour(c: { flat: number[]; of: { part: PartEntry; face: number }[] } | null): void {+ if (this.contour) {+ this.scene.remove(this.contour);+ this.contour.geometry.dispose();+ this.lineMats.delete(this.contour.material);+ this.contour.material.dispose();+ this.contour = null;+ }+ this.contourOf = c?.of ?? [];+ if (!c || !c.flat.length) return;+ const g = new LineSegmentsGeometry();+ g.setPositions(c.flat);+ const m = new LineMaterial({ color: CONTOUR_COLOR, linewidth: 1.6 });+ m.resolution.set(this.container.clientWidth || 1, this.container.clientHeight || 1);+ this.lineMats.add(m);+ this.contour = new LineSegments2(g, m);+ this.contour.renderOrder = CONTOUR_ORDER;+ this.contour.raycast = () => {};+ this.scene.add(this.contour);+ }+// ---- Prüfhilfen (nur für Tests) -------------------------------------------------------------------------------facesOf(partId: string): FaceEntry[] { return this.parts.get(partId)?.meta.faces ?? []; }@@ -864,6 +1245,41 @@ export class Viewer {zoomToCursor: this.controls.zoomToCursor, animating: !!this.anim };}+ /** Stand des Schnitts, für Tests: Ebene, Bauteile mit Deckel, Segmente der Kontur, geschnittene Materialien. */+ sectionState() {+ this.prepareSection();+ const capped = [...this.parts.values()].filter((p) => p.cap?.plate.visible).map((p) => p.meta.partId);+ const clipped = [...this.parts.values()].every((p) => p.meshes.every((m) => (m.material as THREE.Material).clippingPlanes === this.clip));+ return { plane: this.section, capped, contour: this.contourOf.length, clipped, picking: !!this.planePick };+ }++ /**+ * Bildpunkte um eine Fensterposition, frisch gezeichnet, für Tests: mittlere Helligkeit und Spanne (Schraffur ergibt+ * eine große Spanne) sowie die mittlere Farbe.+ */+ pixels(x: number, y: number, half = 6): { mean: number; span: number; rgb: number[] } {+ this.prepareSection();+ this.renderer.render(this.scene, this.camera);+ const src = this.renderer.domElement, r = src.getBoundingClientRect();+ const c = document.createElement('canvas');+ c.width = src.width; c.height = src.height;+ const g = c.getContext('2d')!;+ g.drawImage(src, 0, 0);+ const k = src.width / r.width;+ const px = Math.round((x - r.left) * k), py = Math.round((y - r.top) * k), h = Math.round(half * k);+ const d = g.getImageData(px - h, py - h, 2 * h + 1, 2 * h + 1).data;+ let lo = 255, hi = 0, sum = 0;+ const rgb = [0, 0, 0];+ const n = d.length / 4;+ for (let i = 0; i < d.length; i += 4) {+ const l = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];+ lo = Math.min(lo, l); hi = Math.max(hi, l); sum += l;+ rgb[0] += d[i] / n; rgb[1] += d[i + 1] / n; rgb[2] += d[i + 2] / n;+ }+ this.requestRender();+ return { mean: sum / n, span: hi - lo, rgb: rgb.map(Math.round) };+ }+/** Bildschirmposition eines Punkts auf dem Ansichtswürfel, für Tests. */cubeScreen(p: number[]): { x: number; y: number } | null { return this.cube ? this.cube.screenOf(p) : null; }diff --git a/app/src/shared/editable.ts b/app/src/shared/editable.tsindex 96edaef..2748d3e 100644--- a/app/src/shared/editable.ts+++ b/app/src/shared/editable.ts@@ -7,6 +7,7 @@ export function readOnlyReason(rel: string): string | null {if (/^(AGENTS|CLAUDE)\.md$/i.test(p)) return 'Wird von der App verwaltet und bei Updates ersetzt. Eigene Wünsche und Regeln gehören in NOTES.md.';if (/^\.gitignore$/i.test(p)) return 'Wird von der App verwaltet.';if (/^(output|exports)\//i.test(p)) return 'Wird beim Bauen oder Exportieren neu erzeugt.';+ if (/^\.soma\/skills\//i.test(p)) return 'Kopie eines Skills. Ein- und ausschalten links unter „Skills“.';if (/^\.(soma|git)(\/|$)/i.test(p)) return 'Interne Daten der App und von Git.';return null;}diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex 2547909..12ef69f 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -83,6 +83,24 @@ export interface MeasurePair {export interface MeasureResult { build: string; a: MeasureInfo; b?: MeasureInfo; pair?: MeasurePair }/** `stale`: Die Anfrage gehört zu einem älteren Build, die Auswahl ist neu zu treffen. */export interface MeasureResponse { ok: boolean; result?: MeasureResult; error?: string; stale?: boolean }++/** Ein Skill (E17): Regelwerk für den Agenten, pro Modell zuschaltbar. */+export interface SkillInfo {+ id: string;+ /** Titel und Kurzbeschreibung für die Oberfläche, Themen aus den Zwischenüberschriften. */+ title: string; summary: string; topics: string[]; order: number;+ /** Bringt diese App mit (sonst liegt er nur im Projekt, etwa aus einer neueren App). */+ bundled: boolean;+ /** Laut project.json eingeschaltet. */+ active: boolean;+ /** Kopie im Projekt (`.soma/skills/<id>.md`), null wenn keine da ist. */+ file: string | null;+ /** Die Kopie im Projekt weicht von der mitgelieferten Fassung ab. */+ changed: boolean;+ /** Auffälligkeiten, nur gemeldet (E28). */+ problems: string[];+}+export interface SkillResult { ok: boolean; error?: string; warning?: string; backup?: string | null; skills: SkillInfo[] }/** Was vermessen wird: der aktuelle Stand oder die Vorschau eines alten Stands. */export type MeasureSource = 'live' | { preview: string };@@ -172,6 +190,8 @@ export interface SomaApi {agents: { detect(): Promise<AgentInfo[]> };/** Exakte Messung über den Python-Dienst (E9, E24). */measure: { query(source: MeasureSource, req: MeasureRequest): Promise<MeasureResponse> };+ /** Skills des offenen Modells (E17): auflisten, ein- und ausschalten. */+ skills: { list(): Promise<SkillInfo[]>; set(id: string, on: boolean): Promise<SkillResult> };/** Nativer Dialog mit Knöpfen, liefert den Index. Der letzte Knopf gilt als Abbrechen. Im Test über `test.answers` beantwortbar. */dialog: { choose(o: { title: string; message: string; detail?: string; buttons: string[] }): Promise<number> };}diff --git a/app/test/section.mjs b/app/test/section.mjsnew file mode 100644index 0000000..0cc8b58--- /dev/null+++ b/app/test/section.mjs@@ -0,0 +1,192 @@+// Test der Schnittansicht: Ebene senkrecht zu X/Y/Z oder parallel zu einer Fläche, Eingabe der Lage, Seite wechseln,+// Blick auf den Schnitt, gefüllte und schraffierte Schnittfläche, Klicks durch den Schnitt, Messen an der Schnittkontur,+// Text für den Agenten, neuer Build. Aufruf: npm run test:section (baut vorher). SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder ab.+import fs from 'node:fs';+import path from 'node:path';+import { APP, checker, cleanup, sleep, startApp } from './harness.mjs';++const t = checker();+const { check } = t;+let app;++// Offener Kasten 40 × 30 × 20 mit 4 mm Wand (innen x −16..16, y −11..11, Boden bis z = 4) und ein Block 16 × 16 × H+// bei x = 32..48 mit einer Bohrung Ø 6 von oben+const MODEL = (h) => `import cadquery as cq+from soma import add_part++box = cq.Workplane("XY").box(40, 30, 20, centered=(True, True, False)).faces(">Z").shell(-4)+block = (cq.Workplane("XY").box(16, 16, ${h}, centered=(True, True, False))+ .faces(">Z").workplane().hole(6).translate((40, 0, 0)))++add_part("Kasten", box)+add_part("Block", block, color=(0.85, 0.55, 0.25))+`;++const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps;+const vecNear = (a, b, eps = 1e-6) => !!a && a.every((x, i) => near(x, b[i], eps));++try {+ app = await startApp({ name: 'section' });+ const { ev, waitFor, domClick, page } = app;+ const shot = async (name) => {+ if (!process.env.SMOKE_SHOTS) return;+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });+ await sleep(900);+ await app.screenshot(path.join(APP, 'test', 'shots', `${name}.png`)).catch((e) => console.log('Screenshot:', e.message));+ };+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok' && window.__t.partCount() === 2);+ const proj = await ev(() => window.__t.project());+ fs.writeFileSync(path.join(proj.dir, 'model.py'), MODEL(10));+ await waitFor('Testmodell gebaut', () => window.__t.status().state === 'ok' && JSON.stringify(window.__t.treeNames()) === '["Kasten","Block"]', 60000);+ await ev(() => window.__t.viewer.setView('iso'));+ await sleep(300);+ const ids = await ev(() => Object.fromEntries(window.__t.parts().map((p) => [p.name, p.id])));+ const sec = () => ev(() => window.__t.section());+ const vs = () => ev(() => window.__t.viewer.sectionState());+ const screen = (p) => ev((q) => window.__t.viewer.screenAt(q), p);+ const clickAt = (p) => page.click(p.x, p.y);+ const setValue = (v) => ev((x) => {+ const i = document.getElementById('section-value');+ i.focus(); i.value = x;+ i.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ i.blur();+ }, v);+ const settle = () => waitFor('Kamera steht', () => !window.__t.viewer.viewState().animating, 5000).then(() => sleep(150));++ // 1) Einschalten: Ebene senkrecht zu X mitten durch das Modell (x −20..48), die Seite +X fällt weg+ await domClick('btn-section');+ let s = await sec();+ let v = await vs();+ check('„Schnitt": Karte offen, Ebene X in der Mitte (X = 14), weggeschnitten X > 14', s.active && s.axis === 'x' && near(s.value, 14, 1e-3)+ && vecNear(v.plane?.normal, [-1, 0, 0]) && near(v.plane.constant, 14, 1e-3) && s.text.includes('Weggeschnitten: X > 14,00 mm')+ && await ev(() => document.getElementById('btn-section').getAttribute('aria-pressed') === 'true'), JSON.stringify(v.plane));+ check('Alle Bauteile geschnitten, beide mit Deckel, Kontur vorhanden', v.clipped && v.capped.length === 2 && v.contour >= 8, JSON.stringify(v));++ // 2) Lage eingeben (Enter), Pfeiltasten in 1- und 10-mm-Schritten+ await setValue('0');+ s = await sec();+ check('Eingabe „0" + Enter: Ebene bei X = 0, das Feld zeigt danach „0,00"', near(s.value, 0) && near((await vs()).plane.constant, 0) && s.text.includes('X > 0,00 mm')+ && await ev(() => document.getElementById('section-value').value) === '0,00');+ await ev(() => {+ const i = document.getElementById('section-value');+ i.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true }));+ i.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', shiftKey: true, bubbles: true }));+ });+ s = await sec();+ check('Pfeil hoch: +1 mm, mit Umschalt +10 mm', near(s.value, 11), String(s.value));+ await setValue('−2,5');+ check('Eingabe mit Minuszeichen und Komma: „−2,5" ergibt X = −2.5', near((await sec()).value, -2.5), String((await sec()).value));+ await setValue('0');++ // 3) Blick auf den Schnitt: Kamera von der weggeschnittenen Seite (+X)+ await domClick('btn-section-look');+ await settle();+ const dir = (await ev(() => window.__t.viewer.viewState())).dir;+ check('„Blick auf den Schnitt": Kamera blickt von +X senkrecht auf die Ebene', vecNear(dir, [1, 0, 0], 1e-3), JSON.stringify(dir));+ await ev((id) => window.__t.viewer.setView('right', [id]), ids.Kasten);+ await sleep(300);+ await shot('schnitt-1-x');++ // 4) Schnittfläche gefüllt und schraffiert, durch den Hohlraum sieht man die innere Rückwand (gleichmäßig)+ const wall = await screen([0, 13, 10]);+ const hollow = await screen([0, 0, 12]);+ const capPx = await ev((p) => window.__t.viewer.pixels(p.x, p.y), wall);+ const hollowPx = await ev((p) => window.__t.viewer.pixels(p.x, p.y), hollow);+ check('Schnitt durch die Wand: gefüllt mit Schraffur (starke Helligkeitsspanne)', capPx.span > 25 && capPx.mean > 40, JSON.stringify(capPx));+ check('Durch den Hohlraum: innere Rückwand, ohne Schraffur', hollowPx.span < 12 && hollowPx.mean > 40, JSON.stringify(hollowPx));++ // 5) Klicks: auf die Schnittfläche wählt das Bauteil, durch den Hohlraum die innere Rückwand (x = −16)+ await clickAt(wall);+ await waitFor('Auswahl', () => window.__t.info().startsWith('Kasten'), 5000);+ let pk = await ev(() => window.__t.pick());+ check('Klick auf die Schnittfläche: Kasten gewählt, „Schnittfläche · ganzes Bauteil"', pk?.cut === true && pk.faceId == null+ && (await ev(() => window.__t.info())).includes('Schnittfläche · ganzes Bauteil'), JSON.stringify(pk));+ await clickAt(hollow);+ await waitFor('Fläche gewählt', () => window.__t.pick()?.faceId != null, 5000);+ pk = await ev(() => window.__t.pick());+ check('Klick in den Hohlraum geht durch den Schnitt: innere Rückwand bei x = −16', pk.surface === 'PLANE' && near(pk.point[0], -16, 0.01) && !pk.cut, JSON.stringify(pk));++ // 6) Messen im Schnitt: Kontur außen (y = 15) und innen (y = 11) anklicken ergibt die Wandstärke+ await domClick('btn-measure');+ await clickAt(await screen([0, 15, 10]));+ await waitFor('Messung A', () => !!window.__t.measure().result, 60000);+ let m = await ev(() => window.__t.measure());+ check('Messen: Klick auf die äußere Schnittkontur wählt die Außenfläche (eben)', m.a?.kind === 'face' && m.result?.a.type === 'PLANE', m.error || JSON.stringify(m.a));+ await clickAt(wall);+ await sleep(300);+ m = await ev(() => window.__t.measure());+ check('Klick auf die Schnittfläche selbst: Hinweis, die Messung bleibt', !!m.a && !m.b && m.text.includes('Schnittfläche selbst lässt sich nicht messen'), m.text.slice(0, 120));+ await clickAt(await screen([0, 11, 10]));+ await waitFor('Messung A–B', () => !!window.__t.measure().result?.pair, 60000);+ m = await ev(() => window.__t.measure());+ check('Innere Schnittkontur: Abstand der Ebenen 4,00 mm (Wandstärke)', near(m.result?.pair?.planes?.value ?? 0, 4, 1e-6) && m.text.includes('4,00 mm'), m.error || m.text.replace(/\s+/g, ' ').slice(0, 120));+ await shot('schnitt-2-messen');+ await domClick('btn-measure');++ // 7) Seite wechseln+ await domClick('btn-section-flip');+ v = await vs();+ check('„Seite wechseln": jetzt fällt X < 0 weg', vecNear(v.plane.normal, [1, 0, 0]) && near(v.plane.constant, 0) && (await sec()).text.includes('X < 0,00 mm'));+ check('Text für den Agenten nennt Ebene und weggeschnittene Seite', (await sec()).agent === 'Schnittansicht bei X = 0.000 mm, weggeschnitten ist X < 0.000', (await sec()).agent);++ // 8) An einer Fläche ausrichten: erst die Bohrung (nicht eben), dann die Oberseite des Blocks+ await ev(() => window.__t.viewer.setView('iso'));+ await sleep(300);+ await ev(() => document.querySelector('#section-axes [data-axis="face"]').click());+ s = await sec();+ check('„Fläche": wartet auf einen Klick, Hinweis in der Karte', s.picking && (await vs()).picking && s.text.includes('Ebene Fläche im Modell anklicken'));+ await ev(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })));+ s = await sec();+ check('Escape bricht das Anklicken ab, die Ebene bleibt bei X', !s.picking && !(await vs()).picking && s.axis === 'x');+ await ev(() => document.querySelector('#section-axes [data-axis="face"]').click());+ await clickAt(await screen([40, 3, 9]));+ await sleep(200);+ s = await sec();+ check('Klick in die Bohrung: „keine ebene Fläche", wartet weiter', s.picking && s.text.includes('keine ebene Fläche'), s.text.slice(0, 120));+ await clickAt(await screen([44, -4, 10]));+ await sleep(200);+ s = await sec();+ v = await vs();+ check('Oberseite des Blocks: Ebene parallel dazu, mitten durch den Block (z = 5, Tiefe 5 mm)', !s.picking && s.axis === 'face' && vecNear(s.face?.normal, [0, 0, 1])+ && vecNear(v.plane.normal, [0, 0, -1]) && near(v.plane.constant, 5, 1e-3) && near(s.shown, 5, 1e-3) && s.text.includes('Tiefe') && s.text.includes('„Block“'), JSON.stringify({ v: v.plane, s: s.face }));+ await setValue('2');+ v = await vs();+ check('Tiefe 2 mm: Ebene bei z = 8', near(v.plane.constant, 8, 1e-6), JSON.stringify(v.plane));+ check('Text für den Agenten: Ebene durch einen Punkt, Fläche, Richtung', /^Schnittansicht, Ebene durch \(40\.000, 0\.000, 8\.000\) mm parallel zu einer Fläche von "Block", weggeschnitten ist die Seite in Richtung \(0, 0, 1\)$/.test((await sec()).agent ?? ''), (await sec()).agent);+ await shot('schnitt-3-flaeche');++ // 9) Ebene Z+ await ev(() => document.querySelector('#section-axes [data-axis="z"]').click());+ v = await vs();+ check('Ebene Z: mitten durch das Modell (z = 10), oben fällt weg', vecNear(v.plane.normal, [0, 0, -1]) && near(v.plane.constant, 10, 1e-3) && (await sec()).text.includes('Z > 10,00 mm'), JSON.stringify(v.plane));++ // 10) Neuer Build: Der Schnitt bleibt, Deckel und Kontur passen zum neuen Modell+ fs.writeFileSync(path.join(proj.dir, 'model.py'), MODEL(14));+ await waitFor('Neuer Build', () => window.__t.status().state === 'ok' && window.__t.partSize('Block')?.[2] === 14, 60000);+ await sleep(300);+ v = await vs();+ s = await sec();+ check('Nach dem Build: Schnitt bei Z = 10 bleibt, beide Teile mit Deckel, Kontur neu', s.active && vecNear(v.plane.normal, [0, 0, -1]) && near(v.plane.constant, 10, 1e-3)+ && v.capped.length === 2 && v.contour >= 8 && v.clipped, JSON.stringify(v));++ // 11) Ausschalten: kein Schnitt mehr, die Außenwand ist wieder zu sehen+ await domClick('btn-section');+ v = await vs();+ s = await sec();+ check('„Schnitt" aus: keine Ebene, keine Deckel, keine Kontur, Karte zu', !s.active && !v.plane && !v.capped.length && !v.contour+ && await ev(() => document.getElementById('section-card').hidden), JSON.stringify(v));+ await ev((id) => { window.__t.viewer.setVisible(id, false); }, ids.Block); // stünde sonst vor der Wand+ await ev((id) => window.__t.viewer.setView('right', [id]), ids.Kasten);+ await sleep(300);+ const outerPx = await ev((p) => window.__t.viewer.pixels(p.x, p.y), await screen([0, 13, 10]));+ check('Ohne Schnitt an derselben Stelle: Außenwand, ohne Schraffur', outerPx.span < 12 && outerPx.mean > 40, JSON.stringify(outerPx));++ const relevant = page.errors.filter((e) => !/favicon/i.test(e));+ check('Keine Konsolenfehler im Renderer', relevant.length === 0, relevant.slice(0, 2).join(' | ').slice(0, 100));+} catch (e) {+ console.log('ABBRUCH:', e.message);+ t.fail();+}+if (app) { await app.stop(); cleanup(app.ud); }+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/skills.mjs b/app/test/skills.mjsnew file mode 100644index 0000000..efc6a08--- /dev/null+++ b/app/test/skills.mjs@@ -0,0 +1,158 @@+// Test der Skills (E17): Panel mit den mitgelieferten Skills, Ein- und Ausschalten (Kopie in .soma/skills/, project.json,+// Abschnitt in AGENTS.md), Ansehen und An Agent geben, geänderte Kopie wandert in die Sicherung, fehlende Dateien werden+// gemeldet statt repariert (E28), Skills im Snapshot und in der ZIP. Aufruf: npm run test:skills (baut vorher).+import { exec } from 'dugite';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import yauzl from 'yauzl';+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-skills-'));+const BUNDLED = path.join(APP, 'resources', 'skills');+const norm = (s) => s.replace(/\r\n?/g, '\n');++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();+}));++try {+ app = await startApp({ name: 'skills' });+ const { ev, waitFor, domClick, ud, page } = app;+ const shot = async (name) => {+ if (!process.env.SMOKE_SHOTS) return;+ fs.mkdirSync(path.join(APP, 'test', 'shots'), { recursive: true });+ await sleep(900);+ await app.screenshot(path.join(APP, 'test', 'shots', `${name}.png`)).catch((e) => console.log('Screenshot:', e.message));+ };+ await waitFor('Projekt und Build', () => !!window.__t && !!window.__t.project() && window.__t.status().state === 'ok' && window.__t.partCount() === 2);+ const proj = await ev(() => window.__t.project());+ const dir = proj.dir;+ const g = async (...args) => (await exec(args, dir)).stdout.trim();+ const read = (rel) => { try { return fs.readFileSync(path.join(dir, rel), 'utf8'); } catch { return null; } };+ const pj = () => JSON.parse(read('.soma/project.json'));+ const st = () => ev(() => window.__t.skills());+ const skill = async (id) => (await st()).skills.find((s) => s.id === id);+ const toggle = async (id, on) => {+ await ev((i) => document.querySelector(`#skills-list .sk-row[data-id="${i}"] .sk-switch`).click(), id);+ await waitFor(`Skill ${id} ${on ? 'an' : 'aus'}`, ([i, o]) => { const s = window.__t.skills(); return !s.busy.length && s.skills.find((x) => x.id === i)?.active === o; }, 10000, [id, on]);+ };+ const block = () => { const a = read('AGENTS.md') ?? ''; const m = /<!-- soma:skills -->([\s\S]*?)<!-- \/soma:skills -->/.exec(a); return m ? m[1] : null; };++ // 1) Panel: drei mitgelieferte Skills, alle aus. Die Vorlage hat den leeren Abschnitt in AGENTS.md+ check('Vorlage: AGENTS.md hat den Abschnitt „Skills" (noch keiner aktiv)', (block() ?? '').includes('No skills are active'), String(block()).slice(0, 80));+ await ev(() => document.querySelector('#rail [data-panel="skills"]').click());+ await waitFor('Skills geladen', () => window.__t.skills().skills.length >= 3, 10000);+ let s = await st();+ check('Panel „Skills": 3D-Druck, Toleranzen, Gehäusebau, alle aus', s.skills.map((x) => x.id).join(',') === '3d-druck,toleranzen,gehaeuse' && s.skills.every((x) => !x.active && !x.file && !x.problems.length)+ && s.text.includes('3D-Druck (FDM)') && s.text.includes('Gehäusebau'), s.skills.map((x) => `${x.id}:${x.active}`).join(','));+ await shot('skills-1-panel');++ // 2) Einschalten: Kopie, project.json (und App-Kopie), Abschnitt in AGENTS.md, als Änderung sichtbar+ await toggle('3d-druck', true);+ const copy = read('.soma/skills/3d-druck.md');+ check('3D-Druck an: Kopie in .soma/skills/ entspricht der mitgelieferten Fassung', copy !== null && norm(copy) === norm(fs.readFileSync(path.join(BUNDLED, '3d-druck.md'), 'utf8')));+ check('project.json und die Kopie in den App-Daten nennen den Skill', JSON.stringify(pj().skills) === '["3d-druck"]'+ && JSON.stringify(JSON.parse(fs.readFileSync(path.join(ud, 'projects', `${proj.id}.json`), 'utf8')).skills) === '["3d-druck"]');+ check('AGENTS.md führt ihn auf (Pfad und englischer Name), der Rest der Datei bleibt', (block() ?? '').includes('- `.soma/skills/3d-druck.md`: 3D printing (FDM)')+ && (read('AGENTS.md') ?? '').startsWith('# Instructions for the coding agent') && (read('AGENTS.md') ?? '').includes('## Version history (git)'), String(block()));+ check('Meldung: an, steht in AGENTS.md, Hinweis auf laufenden Agenten', (await ev(() => window.__t.toast())).text.includes('ist an und steht in AGENTS.md'));+ await waitFor('ungespeichert', () => window.__t.saveState()?.dirtyFiles >= 3, 10000).catch(() => {});+ check('Zählt als ungespeicherte Änderung (Kopie, project.json, AGENTS.md)', (await ev(() => window.__t.saveState())).dirtyFiles >= 3, String((await ev(() => window.__t.saveState())).dirtyFiles));++ // 3) Ansehen (nur lesen) und An Agent geben+ await ev(() => document.querySelector('#skills-list .sk-row[data-id="3d-druck"] .sk-more').click());+ await shot('skills-2-aktiv');+ await ev(() => [...document.querySelectorAll('#skills-list .sk-row[data-id="3d-druck"] .sk-actions button')].find((b) => b.textContent.includes('Ansehen')).click());+ await waitFor('Code-Panel', () => window.__t.editor.state().file === '.soma/skills/3d-druck.md', 10000);+ const ed = await ev(() => window.__t.editor.state());+ check('„Ansehen": Kopie im Code-Panel, nur lesen, mit Grund', ed.readOnly && ed.text.includes('# Skill: 3D printing (FDM)') && (ed.locked ?? '').includes('Skill'), JSON.stringify({ ro: ed.readOnly, locked: ed.locked }));+ await ev(() => window.__t.showPanel('skills'));+ await waitFor('Panel wieder offen', () => !!document.querySelector('#skills-list .sk-row[data-id="3d-druck"] .sk-actions'), 10000);+ // Eingefügten Text mitschneiden (im Terminal bricht die lange Eingabezeile um)+ await ev(() => { const tm = window.__t.terminals; const orig = tm.insert.bind(tm); tm.insert = (x) => { window.__inserted = x; return orig(x); }; });+ await ev(() => [...document.querySelectorAll('#skills-list .sk-row[data-id="3d-druck"] .sk-actions button')].find((b) => b.textContent.includes('An Agent')).click());+ await sleep(300);+ check('„An Agent geben" fügt [Skill: .soma/skills/3d-druck.md] ein', (await ev(() => window.__t.toast())).text.includes('In die Eingabe von')+ && await ev(() => window.__inserted) === '[Skill: .soma/skills/3d-druck.md] ', await ev(() => window.__inserted));++ // 4) Zweiter Skill: beide stehen in AGENTS.md, in der Reihenfolge des Einschaltens+ await toggle('toleranzen', true);+ const b2 = block() ?? '';+ check('Toleranzen dazu: AGENTS.md nennt beide, project.json auch', b2.indexOf('3d-druck.md') > 0 && b2.indexOf('toleranzen.md') > b2.indexOf('3d-druck.md') && JSON.stringify(pj().skills) === '["3d-druck","toleranzen"]', b2);++ // 5) Kopie geändert (etwa vom Agenten): gemeldet, beim Ausschalten in die Sicherung+ fs.appendFileSync(path.join(dir, '.soma', 'skills', '3d-druck.md'), '\n- Use PETG only.\n');+ await ev(() => window.__t.showPanel('files'));+ await ev(() => window.__t.showPanel('skills'));+ await waitFor('geändert erkannt', () => window.__t.skills().skills.find((x) => x.id === '3d-druck')?.changed === true, 10000);+ check('Geänderte Kopie: „weicht ab" in der Karte', (await st()).text.includes('weicht von der Fassung dieser App ab'));+ await toggle('3d-druck', false);+ const bdir = path.join(ud, 'workspace-backups', `${proj.id}-skills`);+ const backups = fs.existsSync(bdir) ? fs.readdirSync(bdir) : [];+ check('Ausschalten: Kopie weg, die geänderte Fassung liegt in der Sicherung', read('.soma/skills/3d-druck.md') === null && backups.length === 1+ && fs.readFileSync(path.join(bdir, backups[0]), 'utf8').includes('Use PETG only.'), backups.join(','));+ check('AGENTS.md und project.json ohne 3D-Druck, Toleranzen bleibt', !(block() ?? '').includes('3d-druck') && (block() ?? '').includes('toleranzen.md') && JSON.stringify(pj().skills) === '["toleranzen"]');+ check('Meldung nennt Sicherung und den laufenden Agenten', /ist aus\..*Sag ihm Bescheid.*Sicherung/.test((await ev(() => window.__t.toast())).text), (await ev(() => window.__t.toast())).text);++ // 6) Datei eines aktiven Skills fehlt: gemeldet, nicht neu angelegt (E28)+ fs.rmSync(path.join(dir, '.soma', 'skills', 'toleranzen.md'));+ await ev(() => window.__t.showPanel('files'));+ await ev(() => window.__t.showPanel('skills'));+ await waitFor('Problem gemeldet', () => window.__t.skills().skills.find((x) => x.id === 'toleranzen')?.problems.length > 0, 10000);+ const info = await ev(() => window.soma.project.current());+ check('Fehlende Kopie: Hinweis in der Karte und im Projekt-Check, nichts neu angelegt', (await skill('toleranzen')).problems[0].includes('fehlt')+ && info.problems.some((p) => p.includes('toleranzen')) && read('.soma/skills/toleranzen.md') === null, JSON.stringify(info.problems));+ await toggle('toleranzen', false);+ check('Ausschalten räumt auf: kein Problem mehr, Abschnitt „No skills are active"', !(await skill('toleranzen')).problems.length && (block() ?? '').includes('No skills are active') && JSON.stringify(pj().skills) === '[]');++ // 7) Älteres Projekt ohne Abschnitt in AGENTS.md: Er wird am Ende angehängt, nicht doppelt+ const agents = read('AGENTS.md');+ fs.writeFileSync(path.join(dir, 'AGENTS.md'), agents.replace(/\n*<!-- soma:skills -->[\s\S]*<!-- \/soma:skills -->\n?/, '\n'));+ await toggle('gehaeuse', true);+ const a2 = read('AGENTS.md');+ check('Ohne Abschnitt: am Ende angehängt, genau einmal', a2.trimEnd().endsWith('<!-- /soma:skills -->') && a2.split('<!-- soma:skills -->').length === 2 && (block() ?? '').includes('- `.soma/skills/gehaeuse.md`: Enclosure design'), String(block()));++ // 8) AGENTS.md fehlt ganz: Skill geht trotzdem an, Warnung, AGENTS.md wird nicht neu angelegt+ const keep = read('AGENTS.md');+ fs.rmSync(path.join(dir, 'AGENTS.md'));+ await toggle('3d-druck', true);+ check('Ohne AGENTS.md: Skill an, Warnung, keine neue AGENTS.md', read('AGENTS.md') === null && read('.soma/skills/3d-druck.md') !== null+ && (await ev(() => window.__t.toast())).text.includes('AGENTS.md fehlt') && (await ev(() => window.__t.toast())).error, (await ev(() => window.__t.toast())).text);+ fs.writeFileSync(path.join(dir, 'AGENTS.md'), keep);+ await ev(() => window.__t.showPanel('files'));+ await ev(() => window.__t.showPanel('skills'));+ await waitFor('Problem AGENTS.md', () => window.__t.skills().skills.find((x) => x.id === '3d-druck')?.problems.length > 0, 10000);+ check('AGENTS.md ohne Eintrag eines aktiven Skills: gemeldet', (await skill('3d-druck')).problems.some((p) => p.includes('AGENTS.md nennt')), JSON.stringify((await skill('3d-druck')).problems));+ await toggle('3d-druck', false);+ await toggle('3d-druck', true);+ check('Aus und wieder an trägt ihn ein', !(await skill('3d-druck')).problems.length && (block() ?? '').includes('3d-druck.md') && (block() ?? '').includes('gehaeuse.md'));++ // 9) Speichern: Skills im Snapshot und in der ZIP+ const zipPath = path.join(workDir, 'Skills.zip');+ await app.answers([zipPath]);+ await domClick('btn-save');+ await waitFor('gespeichert', () => window.__t.saveState() && !window.__t.saveState().unsaved && window.__t.saveState().zipPath, 60000)+ .catch(async (e) => { console.log('Stand:', JSON.stringify(await ev(() => ({ save: window.__t.saveState(), toast: window.__t.toast() })))); throw e; });+ const tracked = (await g('ls-files', '.soma/skills')).split('\n');+ check('Snapshot enthält die Skills (in Git)', tracked.includes('.soma/skills/3d-druck.md') && tracked.includes('.soma/skills/gehaeuse.md'), tracked.join(','));+ const names = await listZip(zipPath);+ check('ZIP enthält die Skills', names.includes('.soma/skills/3d-druck.md') && names.includes('.soma/skills/gehaeuse.md'));++ const relevant = page.errors.filter((e) => !/favicon/i.test(e));+ check('Keine Konsolenfehler im Renderer', relevant.length === 0, relevant.slice(0, 2).join(' | ').slice(0, 100));+} catch (e) {+ console.log('ABBRUCH:', e.message);+ t.fail();+}+if (app) { await app.stop(); cleanup(app.ud); }+cleanup(workDir);+console.log(t.fails ? `\n${t.fails} Prüfung(en) fehlgeschlagen` : '\nALLE PRÜFUNGEN BESTANDEN');+process.exit(t.fails ? 1 : 0);