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
Parameter-Panel: Werte aus param(), eigene Werte getrennt vom Code (E74)
Kai-Jungsthoefel6155d921ef9c
diff --git a/app/package.json b/app/package.jsonindex b05213b..77f6584 100644--- a/app/package.json+++ b/app/package.json@@ -17,6 +17,7 @@"test:section": "npm run build && node test/section.mjs","test:explode": "npm run build && node test/explode.mjs","test:skills": "npm run build && node test/skills.mjs",+ "test:params": "npm run build && node test/params.mjs","test:fasteners": "npm run build && node test/fasteners.mjs","test:animation": "npm run build && node test/animation.mjs","test:packages": "npm run build && node test/packages.mjs",diff --git a/app/resources/skills/cadquery.md b/app/resources/skills/cadquery.mdindex 4fcd310..43a24fb 100644--- a/app/resources/skills/cadquery.md+++ b/app/resources/skills/cadquery.md@@ -14,6 +14,8 @@ topics: Parameters and structure; Order of operations; Selectors; Typical errors- Base dimensions are named constants at the top of `model.py`, everything else is derived (`INNER_W = WIDTH - 2 *WALL`). Never type the same number twice.+- The base dimensions the user would want to change themselves become `param()` with a range in which the model works+ (`WIDTH = param(40.0, "Width", min=20, max=80, unit="mm")`), see AGENTS.md. Derived values never do.- One function per part (`def make_lid(): ... return lid`), the `add_part` calls at the end of `model.py`. Move partsinto `parts/` when `model.py` grows beyond about 200 lines. The constants then move to `parts/params.py`, importedby `model.py` and the part modules.diff --git a/app/resources/template/AGENTS.md b/app/resources/template/AGENTS.mdindex 194fa23..181d358 100644--- a/app/resources/template/AGENTS.md+++ b/app/resources/template/AGENTS.md@@ -11,6 +11,7 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes| `model.py` | Entry point. Builds the model and registers every part. Small models live only here || `parts/` | Optional. Move parts into modules here when `model.py` gets long, import them from `model.py` || `inputs/` | Files the user brought (STEP, images). Never modify them, load them from `model.py` |+| `parameters.json` | Values the user set in the app's Parameters panel (rule 7). Written by the app || `output/model.step` | Main result with all parts, written by `soma build`. Never write it yourself || `exports/` | Single-part exports written by `soma export` || `animations/` | Optional. Motion, camera flights and captions in Python (`soma.anim`), one file per topic. The skill for animation explains them |@@ -20,14 +21,15 @@ The app shows the result in a 3D viewer next to this terminal. Notes and wishes## Rules for model.py-1. `from soma import add_part, import_step, import_assembly`+1. `from soma import add_part, param, import_step, import_assembly`2. **Register every part**: `add_part("Name", workplane_or_shape)`. Unregistered geometry is invisible in the viewer and missing from exports.3. Names are unique. Umlauts are fine, they are shown as written.4. Group related parts with `group`: `add_part("Screw front", screw, group="Housing/Screws")` (nested with `/`). Groups show up in the part tree of the app and as sub-assemblies in `output/model.step`.5. Mark a part the user brought (for example a circuit board) with `role="reference"`: it is shown semi-transparent and skipped by `soma export --all`. Cut clearances around it, but do not export it.6. Units are millimetres, Z is up. Put dimensions in named constants at the top of `model.py` so the user can ask for changes ("make the wall 3 mm"). Once parts live in `parts/`, the constants go to `parts/params.py`, and `model.py` and the part modules import them from there.-7. Load user files with `import_step("inputs/board.step")`: this merges the whole file into one shape. If the file has several parts or sub-assemblies, keep them with `asm = import_assembly("inputs/board.step")` and `add_part("Board", asm, role="reference")`: every body becomes its own part with its name and color, the sub-assemblies become groups under "Board". Move an assembly with `asm.loc = cq.Location((x, y, z))`. STEP files often have their origin in a corner: check the bounding box and move the part deliberately.-8. Prefer simple, readable CadQuery. Check that operations produced solids. Do not use `show_object` or `cq_editor`.+7. **Parameters for the user**: make the values the user would want to change themselves with `param()`: `BORE = param(38.0, "Cylinder bore", min=30, max=42, step=0.5, unit="mm", group="Crank train")`. They appear in the app's Parameters panel, where the user changes them without you. Good parameters are main dimensions, counts, options and positions (`CRANK = param(0, "Crank angle", min=0, max=360, unit="deg")`), usually 3 to 15 per model. Helper and derived values stay plain constants. Choose `min` and `max` so that the model builds and makes sense over the whole range. The default decides the field: `param(18, ...)` whole numbers, `param(True, ...)` a switch, `param("M3", ..., options=["M3", "M4"])` a choice. The user's values are kept in `parameters.json` and take the place of the defaults in the code, `soma build` lists them ("set by the user in the app"). So the number in the code is not always the one in the model. Do not edit `parameters.json` unless the user asks. If the user asks you for a new value of a parameter they set in the panel, change the default in the code and remove its entry from `parameters.json`, so that the code's value applies again.+8. Load user files with `import_step("inputs/board.step")`: this merges the whole file into one shape. If the file has several parts or sub-assemblies, keep them with `asm = import_assembly("inputs/board.step")` and `add_part("Board", asm, role="reference")`: every body becomes its own part with its name and color, the sub-assemblies become groups under "Board". Move an assembly with `asm.loc = cq.Location((x, y, z))`. STEP files often have their origin in a corner: check the bounding box and move the part deliberately.+9. Prefer simple, readable CadQuery. Check that operations produced solids. Do not use `show_object` or `cq_editor`.## Commands@@ -68,6 +70,7 @@ The app pastes short notes into your input. The user adds their own words and se- `[Markup: .soma/feedback/markup-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 `shows the older version <hash>`, the picture shows that older commit, not the current code (`git show <hash>:model.py`). Leave the images where they are.- `[Selection: part "…", model.py line …]`: the part the user clicked, with the lines of its `add_part` call and the clicked face.- `[Build error: …]`: the message of the last failed build.+- `[Parameter: "Cylinder bore" (BORE) = 40 mm, set in the app, code default 38 mm, model.py line 12]`: a parameter from the Parameters panel, with the user's value if they set one.- `[Animation: "Name" (animations/x.py) at 1.50 s]`, `[Video: renders/x.mp4 at 00:03.20]`: a moment in an animation or a video. A markup can name it too (`drawn on renders/x.mp4 at 00:03.20`).- `[Result: "Wall thickness" (.soma/results/…), part "…": 0.80 mm at (x, y, z) mm]`: a spot in the colours of an analysis.- `[Skill: .soma/skills/<name>.md]`: the user points you to this rule set, switched it on or changed its settings (the note may list them, they are already written into the file). Read the file again now and follow it from here on. When the user switches a skill off, it disappears from the list below: stop applying it.diff --git a/app/resources/template/model.py b/app/resources/template/model.pyindex eb65fe1..def9d35 100644--- a/app/resources/template/model.py+++ b/app/resources/template/model.py@@ -4,13 +4,13 @@ Rules (see AGENTS.md): every part must be registered with add_part(), names mustbuild with `soma build`. Units are millimetres, Z is up."""import cadquery as cq-from soma import add_part+from soma import add_part, param-# --- parameters --------------------------------------------------------------------------LENGTH = 60.0-WIDTH = 40.0-HEIGHT = 25.0-WALL = 2.0+# --- parameters: the user can change param() values in the app (Parameters panel) ------+LENGTH = param(60.0, "Length", min=30, max=200, unit="mm")+WIDTH = param(40.0, "Width", min=20, max=150, unit="mm")+HEIGHT = param(25.0, "Height", min=10, max=100, unit="mm")+WALL = param(2.0, "Wall", min=1.2, max=4.0, step=0.1, unit="mm")# --- body: a box, hollowed out from the top ---------------------------------------------body = (diff --git a/app/src/main/build.ts b/app/src/main/build.tsindex 5bb6ac0..ee73b31 100644--- a/app/src/main/build.ts+++ b/app/src/main/build.ts@@ -3,7 +3,7 @@ import fs from 'node:fs';import path from 'node:path';import { EventEmitter } from 'node:events';import { affectsBuild } from '../shared/editable';-import type { BuildResult, BuildStatus } from '../shared/types';+import type { BuildResult, BuildStatus, ParamInfo } from '../shared/types';import { pythonExe, warmDir } from './paths';import { IGNORED_TOP } from './watcher';@@ -38,8 +38,27 @@ export class BuildManager extends EventEmitter {private installing: string[] | null = null;private afterInstall = false;private packageError: string | null = null;+ /**+ * Parameter des Modells aus dem letzten Build, der sie kannte (null: noch keiner). Scheitert ein Build, bevor der Code+ * seine Parameter anlegt, bleibt die Liste des vorigen stehen (`paramsStale`): Das Panel soll gerade dann bedienbar+ * bleiben, denn oft war ein Wert daraus die Ursache.+ */+ params: ParamInfo[] | null = null;+ paramsStale = false;++ constructor(private readonly dir: string) {+ super();+ // Bis zum ersten Build dieser Sitzung: die Liste des letzten Builds auf der Platte+ const last = readLastBuild(dir);+ if (Array.isArray(last?.params)) this.params = last.params;+ }- constructor(private readonly dir: string) { super(); }+ private takeParams(result: BuildResult): void {+ const list = Array.isArray(result.params) ? result.params : null;+ if (result.status === 'ok') { this.params = list ?? []; this.paramsStale = false; }+ else if (list?.length || !this.params) { this.params = list; this.paramsStale = false; }+ else this.paramsStale = true;+ }/*** Dateiaenderung im Projekt gemeldet. Ohne Auto-Build merkt sich der Stand nur, dass er veraltet ist.@@ -94,6 +113,7 @@ export class BuildManager extends EventEmitter {clearTimeout(timeout);this.proc = null;if (this.disposed) return;+ this.takeParams(result);this.setStatus({ state: result.status === 'ok' ? 'ok' : 'error', result, seconds: (Date.now() - startedAt) / 1000, builtAt: Date.now() });if (this.rerun) { this.rerun = false; this.start('change during the build'); }};@@ -117,7 +137,8 @@ export class BuildManager extends EventEmitter {*/adopt(last: LastBuild): void {if (this.disposed || this.busy) return;- const result: BuildResult = { status: 'ok', parts: last.parts, timings: last.timings, warnings: last.warnings };+ const result: BuildResult = { status: 'ok', parts: last.parts, timings: last.timings, warnings: last.warnings, params: last.params };+ this.takeParams(result);const seconds = typeof last.started === 'number' && typeof last.finished === 'number' ? Math.max(0, last.finished - last.started) : undefined;const builtAt = typeof last.finished === 'number' ? last.finished * 1000 : undefined;this.setStatus({ state: 'ok', result, reason: 'last build', seconds, builtAt });@@ -283,7 +304,7 @@ export function runSoma(args: string[], cwd: string, timeoutMs = 120000): Promis// ---- Stand des letzten Builds ----------------------------------------------------------------------------------------/** Neuester Änderungszeitpunkt von Einstiegspunkt, parts/ und inputs/ (Quelltext des Modells). */+/** Neuester Änderungszeitpunkt von Einstiegspunkt, parts/, inputs/ und parameters.json (Quelltext des Modells). */export function newestSourceMtime(dir: string): number {let newest = 0;const walk = (d: string, depth: number) => {@@ -298,7 +319,7 @@ export function newestSourceMtime(dir: string): number {}};for (const top of ['parts', 'inputs']) walk(path.join(dir, top), 0);- for (const f of fs.readdirSync(dir)) if (f.endsWith('.py')) try { newest = Math.max(newest, fs.statSync(path.join(dir, f)).mtimeMs); } catch { /* weg */ }+ for (const f of fs.readdirSync(dir)) if (f.endsWith('.py') || f === 'parameters.json') try { newest = Math.max(newest, fs.statSync(path.join(dir, f)).mtimeMs); } catch { /* weg */ }return newest;}diff --git a/app/src/main/main.ts b/app/src/main/main.tsindex 00e307b..6f17f59 100644--- a/app/src/main/main.ts+++ b/app/src/main/main.ts@@ -126,6 +126,9 @@ function registerIpc(ctl: ProjectController): void {ipcMain.handle('measure:query', (_e, source: unknown, req: unknown) => ctl.measure(source, req));ipcMain.handle('measure:start', () => ctl.measureStart());ipcMain.handle('measure:prepare', (_e, source: unknown, build: unknown) => ctl.measurePrepare(source, build));+ ipcMain.handle('params:state', () => ctl.paramState());+ ipcMain.handle('params:set', (_e, values: unknown) => ctl.setParams(values));+ ipcMain.handle('params:resetAll', () => ctl.resetAllParams());ipcMain.handle('skills:list', () => ctl.skills());ipcMain.handle('skills:set', (_e, id: unknown, mode: unknown) => ctl.setSkill(id, mode));ipcMain.handle('skills:configure', (_e, id: unknown, values: unknown) => ctl.configureSkill(id, values));diff --git a/app/src/main/params.ts b/app/src/main/params.tsnew file mode 100644index 0000000..6ee90c1--- /dev/null+++ b/app/src/main/params.ts@@ -0,0 +1,92 @@+import fs from 'node:fs';+import path from 'node:path';+import type { ParamInfo, ParamValue } from '../shared/types';++/**+ * Werte des Nutzers aus dem Parameter-Panel. Die Werte des Agenten stehen im Code (`param(38.0, …)`), die des Nutzers in+ * dieser Datei im Projektordner. So bleibt der Wert des Agenten erhalten, und „Zurücksetzen“ entfernt nur den Eintrag.+ * Die Datei liegt in Git und in der ZIP, `soma build` liest sie (python/soma/params.py, gleicher Aufbau).+ */+export const PARAMS_FILE = 'parameters.json';+const NOTE = 'Values the user set in the Parameters panel of SOMA. They take the place of the defaults of param() in the code.';+const NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;+const MAX_TEXT = 1000;++export interface UserParams {+ /** Inhalt der Datei ohne `values` (etwa die Notiz). Bleibt beim Schreiben erhalten. */+ rest: Record<string, unknown>;+ values: Record<string, ParamValue>;+ /** Die Datei ist da, aber nicht lesbar: dann wird nichts geschrieben (nichts still überschreiben). */+ error?: string;+}++const isObject = (x: unknown): x is Record<string, unknown> => typeof x === 'object' && x !== null && !Array.isArray(x);+const msg = (e: unknown) => (e instanceof Error ? e.message : String(e));++/** Ein Wert, wie er in der Datei stehen darf. Was nicht passt, lässt die App weg, `soma build` meldet es. */+export function isParamValue(v: unknown): v is ParamValue {+ return typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= MAX_TEXT);+}++export function readUserParams(dir: string): UserParams {+ let text: string;+ try { text = fs.readFileSync(path.join(dir, PARAMS_FILE), 'utf8'); } catch (e) {+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return { rest: {}, values: {} };+ return { rest: {}, values: {}, error: `${PARAMS_FILE} cannot be read: ${msg(e)}` };+ }+ let data: unknown;+ try { data = JSON.parse(text.replace(/^/, '')); } catch (e) {+ return { rest: {}, values: {}, error: `${PARAMS_FILE} is not valid JSON (${msg(e)}). The defaults from the code apply. Ask the agent to fix the file.` };+ }+ if (!isObject(data) || !isObject(data.values)) return { rest: {}, values: {}, error: `${PARAMS_FILE} has no “values” object. The defaults from the code apply. Ask the agent to fix the file.` };+ const { values, ...rest } = data;+ const out: Record<string, ParamValue> = {};+ for (const [k, v] of Object.entries(values)) if (isParamValue(v)) out[k] = v;+ return { rest, values: out };+}++/**+ * Passt der Wert zum Parameter? Bereichsgrenzen zählen nicht: Ein Wert außerhalb wird eingetragen und gebaut, die+ * Oberfläche und `soma build` melden ihn (melden statt reparieren, E28). Ohne Definition (noch kein Build) nur der Typ.+ */+export function checkParamValue(p: ParamInfo | undefined, v: ParamValue): string | null {+ if (!p) return isParamValue(v) ? null : 'This value cannot be stored.';+ switch (p.kind) {+ case 'number': return typeof v === 'number' && Number.isFinite(v) ? null : `${p.label} needs a number.`;+ case 'int': return typeof v === 'number' && Number.isInteger(v) ? null : `${p.label} needs a whole number.`;+ case 'bool': return typeof v === 'boolean' ? null : `${p.label} is on or off.`;+ case 'text': return typeof v === 'string' && v.length <= MAX_TEXT ? null : `${p.label} needs a text of at most ${MAX_TEXT} characters.`;+ case 'choice': return p.options?.some((o) => o.value === v) ? null : `${p.label}: this is not one of the options.`;+ default: return null;+ }+}++/**+ * Werte setzen (null: Eintrag entfernen, dann gilt der Wert aus dem Code). Ohne Einträge und ohne weiteren Inhalt+ * verschwindet die Datei, so bleibt ein Modell ohne eigene Werte wie die Vorlage. Gibt einen Fehlertext zurück oder null.+ */+export function writeUserParams(dir: string, changes: Record<string, ParamValue | null>): string | null {+ const cur = readUserParams(dir);+ if (cur.error) return `${cur.error} Nothing was changed.`;+ const values = { ...cur.values };+ for (const [k, v] of Object.entries(changes)) {+ if (!NAME.test(k)) return `“${k}” is not a parameter name.`;+ if (v === null) delete values[k];+ else values[k] = v;+ }+ const file = path.join(dir, PARAMS_FILE);+ const rest = Object.fromEntries(Object.entries(cur.rest).filter(([k]) => k !== 'note'));+ try {+ if (!Object.keys(values).length && !Object.keys(rest).length) {+ fs.rmSync(file, { force: true });+ return null;+ }+ // Erst vollständig schreiben, dann ersetzen: Ein halber Inhalt würde den nächsten Build alle Werte verlieren lassen+ const tmp = `${file}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, `${JSON.stringify({ note: NOTE, ...rest, values }, null, 2)}\n`, 'utf8');+ fs.renameSync(tmp, file);+ return null;+ } catch (e) {+ return `${PARAMS_FILE} could not be written: ${msg(e)}`;+ }+}diff --git a/app/src/main/projects.ts b/app/src/main/projects.tsindex 1a1b596..1242886 100644--- a/app/src/main/projects.ts+++ b/app/src/main/projects.ts@@ -4,7 +4,7 @@ import os from 'node:os';import path from 'node:path';import type {AnimBuildResult, AnimList, ExportResult, GitLog, MeasureEntity, MeasurePrepared, MeasureRequest, MeasureResponse, ModelMap, OpenResult, PreviewResult,- ProjectInfo, RemoveResult, RenderResult, RestoreResult, ResultEntry, SaveResult, SaveState, SkillInfo, SkillResult,+ ParamResult, ParamState, ParamValue, ProjectInfo, RemoveResult, RenderResult, RestoreResult, ResultEntry, SaveResult, SaveState, SkillInfo, SkillResult,} from '../shared/types';import { affectsAnimation } from '../shared/editable';import { AnimBuilder, listResults, readAnimList, rerunResult, samePath } from './animations';@@ -14,6 +14,7 @@ import { choose, chooseExportTarget, choosePath, documentsDir, trashItem } fromimport { GitRepo, type GitStatus } from './git';import { MeasureService } from './measure';import { ensureEnv, envIsCurrent, installMissing, missingPackages } from './packages';+import { checkParamValue, isParamValue, readUserParams, writeUserParams } from './params';import { previewsDir, skillBackupsDir, skillsDir } from './paths';import { storeBuildAsPreview } from './previews';import {@@ -563,6 +564,46 @@ 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.*/+ // ---- Parameter (param() im Code, Werte des Nutzers in parameters.json) -------------------------------------------++ paramState(): ParamState {+ const s = this.need();+ const u = readUserParams(s.dir);+ return { params: s.builds.params, values: u.values, ...(u.error ? { error: u.error } : {}), ...(s.builds.paramsStale ? { stale: true } : {}) };+ }++ /**+ * Werte des Nutzers setzen (null: zurück auf den Wert aus dem Code) und gleich bauen, wie Strg+S im Editor (E39), auch+ * ohne Auto-Build: Der Nutzer hat ausdrücklich etwas geändert und will das Ergebnis sehen. Erst alles prüfen, dann schreiben.+ */+ setParams(values: unknown): ParamResult {+ const s = this.need();+ const fail = (message: string): ParamResult => ({ ok: false, message, ...this.paramState() });+ if (typeof values !== 'object' || values === null || Array.isArray(values)) return fail('No values given.');+ const defs = new Map((s.builds.params ?? []).map((p) => [p.name, p]));+ const changes: Record<string, ParamValue | null> = {};+ for (const [name, v] of Object.entries(values as Record<string, unknown>)) {+ if (v === null) { changes[name] = null; continue; }+ if (!isParamValue(v)) return fail(`The value for ${name} cannot be stored.`);+ const why = checkParamValue(defs.get(name), v);+ if (why) return fail(why);+ changes[name] = v;+ }+ if (!Object.keys(changes).length) return { ok: true, ...this.paramState() };+ const err = writeUserParams(s.dir, changes);+ if (err) return fail(err);+ s.builds.start('parameter changed');+ return { ok: true, ...this.paramState() };+ }++ /** Alle Werte des Nutzers entfernen. */+ resetAllParams(): ParamResult {+ const s = this.need();+ const u = readUserParams(s.dir);+ if (u.error) return { ok: false, message: `${u.error} Nothing was changed.`, ...this.paramState() };+ return this.setParams(Object.fromEntries(Object.keys(u.values).map((k) => [k, null])));+ }+// ---- Skills (E17) -----------------------------------------------------------------------------------------------skills(): SkillInfo[] {diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.tsindex 7c9b9c5..1b24b01 100644--- a/app/src/preload/preload.ts+++ b/app/src/preload/preload.ts@@ -67,6 +67,11 @@ const api: SomaApi = {start: () => ipcRenderer.invoke('measure:start'),prepare: (source, build) => ipcRenderer.invoke('measure:prepare', source, build),},+ params: {+ state: () => ipcRenderer.invoke('params:state'),+ set: (values) => ipcRenderer.invoke('params:set', values),+ resetAll: () => ipcRenderer.invoke('params:resetAll'),+ },skills: {list: () => ipcRenderer.invoke('skills:list'),set: (id, mode) => ipcRenderer.invoke('skills:set', id, mode),diff --git a/app/src/renderer/icons.ts b/app/src/renderer/icons.tsindex 4d12613..407e3ea 100644--- a/app/src/renderer/icons.ts+++ b/app/src/renderer/icons.ts@@ -13,6 +13,10 @@ const PATHS: Record<string, string> = {pkg: '<path d="M21 8 12 3 3 8v8l9 5 9-5z"/><path d="M3 8l9 5 9-5M12 13v8"/>',help: '<circle cx="12" cy="12" r="9"/><path d="M9.5 9a2.5 2.5 0 1 1 3.5 2.3c-.6.3-1 .9-1 1.6V14M12 17.5v.01"/>',sliders: '<path d="M4 6h9M17 6h3M4 12h3M11 12h9M4 18h11M19 18h1"/><circle cx="15" cy="6" r="2"/><circle cx="9" cy="12" r="2"/><circle cx="17" cy="18" r="2"/>',+ // Zahnrad für „Options“ (Entwurf 2, cogPath), seit „sliders“ für die Parameter steht+ cog: '<path d="M21.42 10.17L21.42 13.83L18.89 14.11L18.36 15.38L19.96 17.37L17.37 19.96L15.38 18.36L14.11 18.89L13.83 21.42L10.17 21.42L9.89 18.89L8.62 18.36L6.63 19.96L4.04 17.37L5.64 15.38L5.11 14.11L2.58 13.83L2.58 10.17L5.11 9.89L5.64 8.62L4.04 6.63L6.63 4.04L8.62 5.64L9.89 5.11L10.17 2.58L13.83 2.58L14.11 5.11L15.38 5.64L17.37 4.04L19.96 6.63L18.36 8.62L18.89 9.89Z"/><circle cx="12" cy="12" r="3"/>',+ // Zurück auf den Wert aus dem Code (Parameter, Entwurf 2)+ reset: '<path d="M4 12a8 8 0 1 0 2.3-5.7L4 8.5"/><path d="M4 3.5v5h5"/>',search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',eye: '<path d="M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',eyeoff: '<path d="M3 3l18 18"/><path d="M10.6 5.1A10 10 0 0 1 12 5c6.4 0 10 7 10 7a17 17 0 0 1-3.2 4.1M6.6 6.6A17 17 0 0 0 2 12s3.6 7 10 7a9.7 9.7 0 0 0 5.4-1.6"/>',diff --git a/app/src/renderer/index.html b/app/src/renderer/index.htmlindex 722bcbe..136d808 100644--- a/app/src/renderer/index.html+++ b/app/src/renderer/index.html@@ -37,11 +37,12 @@<div id="body"><nav id="rail" aria-label="Sidebars"><button data-panel="parts" aria-pressed="false" title="Parts of the model: select, hide and show, make transparent"><i data-icon="cube" data-size="20" data-stroke="1.7"></i><span>Parts</span></button>+ <button data-panel="params" aria-pressed="false" title="Parameters: values of the model you can change, such as sizes, counts or angles"><i data-icon="sliders" data-size="20" data-stroke="1.7"></i><span>Parameters</span></button><button data-panel="files" aria-pressed="false" title="Files of the model. Click a file to open it in the code next to it."><i data-icon="folder" data-size="20" data-stroke="1.7"></i><span>Files</span></button><button data-panel="skills" aria-pressed="false" title="Skills: rules for the agent, set per model (3D printing, tolerances …)"><i data-icon="book" data-size="20" data-stroke="1.7"></i><span>Skills</span></button><span class="grow"></span><button disabled title="Help is coming in a later version"><i data-icon="help" data-size="20" data-stroke="1.7"></i><span>Help</span></button>- <button disabled title="Options are coming in a later version"><i data-icon="sliders" data-size="20" data-stroke="1.7"></i><span>Options</span></button>+ <button disabled title="Options are coming in a later version"><i data-icon="cog" data-size="20" data-stroke="1.6"></i><span>Options</span></button></nav><aside id="side" hidden>@@ -53,6 +54,14 @@<input id="parts-filter" class="filter" type="search" placeholder="Search part" aria-label="Search part" hidden><div id="tab-model" class="list ptree"></div></section>+ <!-- Parameter (Entwurf 2, Bild 6): Werte, die der Agent mit param() freigibt. Der Wert im Code bleibt, die des Nutzers stehen in parameters.json -->+ <section id="panel-params" class="panel" aria-label="Parameters" hidden>+ <div class="side-hd"><b>Parameters</b><span id="params-count" class="c3 hd-count"></span><span class="grow"></span>+ <button id="btn-params-info" class="ibtn s" aria-label="What are parameters?" title="Parameters are values of the model you can change here. The agent creates them in the code with param() and decides which ones. Your values are kept in parameters.json and take the place of the values in the code. Resetting brings back the agent’s value."><i data-icon="info" data-size="15" data-stroke="1.9"></i></button>+ <button class="ibtn s side-close" aria-label="Close sidebar"><i data-icon="x" data-size="15" data-stroke="2"></i></button></div>+ <div id="params-list" class="pm-list"></div>+ <div id="params-foot" class="pfoot" hidden></div>+ </section><section id="panel-files" class="panel" aria-label="Files" hidden><div class="side-hd"><b>Files</b><span class="grow"></span><button id="btn-file-new" class="ibtn s" title="New file (right-click in the tree: also inside a folder)" aria-label="New file"><i data-icon="fileplus" data-size="15"></i></button>diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.tsindex 30280b8..5676e0a 100644--- a/app/src/renderer/main.ts+++ b/app/src/renderer/main.ts@@ -12,6 +12,7 @@ import { MeasureTool } from './measuretool';import { SectionTool } from './sectiontool';import { ExplodeTool } from './explodetool';import { SkillsPanel } from './skills';+import { ParamsPanel } from './params';import { DRAG_PART, PartsCard } from './parts';import { ResultTool } from './resulttool';import { ResultLayer } from './resultview';@@ -58,9 +59,10 @@ const SURFACE: Record<string, string> = {const surfaceName = (s: string | null) => (s ? SURFACE[s] ?? s.toLowerCase() : 'face');const ERROR_KIND: Record<string, string> = { Timeout: 'Time limit exceeded', PythonStart: 'Python could not be started', NoResult: 'Build without result' };-// ---- Seitenleiste (Bauteile, Dateien, Skills) und Code-Spalte (Entwurf 2) -----------------------------------------+// ---- Seitenleiste (Bauteile, Parameter, Dateien, Skills) und Code-Spalte (Entwurf 2) -------------------------------type PanelName = 'parts' | 'files' | 'skills';+type PanelName = 'parts' | 'params' | 'files' | 'skills';+const PANELS: PanelName[] = ['parts', 'params', 'files', 'skills'];let panel: PanelName | null = null;/** Zuletzt gezeigte Ansicht der Seitenleiste: Der Schalter oben bringt sie wieder. */let lastPanel: PanelName = 'parts';@@ -75,10 +77,12 @@ function showPanel(p: PanelName | null): void {$('side').hidden = !p;$('split-side').hidden = !p;$('panel-parts').hidden = p !== 'parts';+ $('panel-params').hidden = p !== 'params';$('panel-files').hidden = p !== 'files';$('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 === 'params') void paramsPanel.refresh();if (p === 'skills') void skills.refresh();else skills.closeDetail();store.set('soma.side', p ?? '');@@ -158,6 +162,15 @@ const skills = new SkillsPanel({ list: $('skills-list'), sum: $('skills-sum'), dchanged: () => { filesDirty = true; textCache.clear(); void refreshSaveState(); void code.refresh(); },});+const paramsPanel = new ParamsPanel({ list: $('params-list'), foot: $('params-foot'), count: $('params-count') }, {+ state: () => api.params.state(),+ set: (values) => api.params.set(values),+ resetAll: () => api.params.resetAll(),+ openCode: (file, line, label) => void openCode(file, { from: line, to: line, label }),+ insert: (text) => insertToAgent(text),+ toast,+});+const files = new FileTree($('tab-files'), $('menu-ctx'), {open: (n) => {if (TEXT_EXT.test(n.name) || isPdf(n.name)) void openCode(n.path);@@ -749,6 +762,8 @@ async function onProject(p: ProjectInfo): Promise<void> {code.reset();skills.reset();if (panel === 'skills') void skills.refresh();+ paramsPanel.reset();+ if (panel === 'params') void paramsPanel.refresh();if (codeOpen) void code.open('model.py'); // die Code-Spalte bleibt offen, dann nicht leerresetViewLists();selection = null;@@ -1269,10 +1284,13 @@ let buildStarts = 0; // Prüfhilfe: Wie oft hat ein Build begonnen?api.build.onStatus((s) => {if (s.state === 'building' && buildStatus.state !== 'building') buildStarts++;renderBuild(s);+ paramsPanel.setBuild(s);if (s.state === 'ok' && !s.stale) { void loadModel(); void refreshFiles(); void refreshViewLists(); }+ // Nach jedem Build (auch einem gescheiterten): Liste und Werte neu, der Build kennt die Parameter des Codes+ if (panel === 'params' && s.state !== 'building') void paramsPanel.refresh();});// Auch bei geschlossenem Code abgleichen: Offene Dateien können ungesicherte Eingaben enthalten-api.fs.onChanged(() => { textCache.clear(); void refreshFiles(); void code.refresh(); scheduleViewLists(); });+api.fs.onChanged(() => { textCache.clear(); void refreshFiles(); void code.refresh(); scheduleViewLists(); if (panel === 'params') void paramsPanel.refresh(); });// Beim Beenden fragt der Hauptprozess, was im Editor ungespeichert ist, und lässt speichern oder verwerfenapi.fs.onEditorRequest(async (action) => {if (action === 'status') return { dirty: code.unsaved() };@@ -1299,7 +1317,7 @@ if (store.get('soma.agentCollapsed') === '1') setAgentCollapsed(true);// Seitenleiste wie beim letzten Mal, beim ersten Start mit den Bauteilen{const side = store.get('soma.side');- showPanel(side === null ? 'parts' : side === 'parts' || side === 'files' || side === 'skills' ? side : null);+ showPanel(side === null ? 'parts' : PANELS.includes(side as PanelName) ? side as PanelName : null);}// Die App beginnt auf der Startseite (E69), der Hauptprozess öffnet kein Modell. Nur im Testmodus öffnet er gleich eins.if (api.startsHome) void showStart(true);@@ -1338,6 +1356,8 @@ if (api.testMode) {videoOpen: (rel: string) => videoView.open(rel),videoSeek: (t: number) => videoView.testSeek(t),skills: () => skills.state(),+ params: () => paramsPanel.state(),+ paramsRefresh: () => paramsPanel.refresh(),pick: () => selection?.pick ?? null,markPixel: (x: number, y: number) => markup.pixel(x, y),markHandles: () => markup.handles(),diff --git a/app/src/renderer/params.ts b/app/src/renderer/params.tsnew file mode 100644index 0000000..9fee2f6--- /dev/null+++ b/app/src/renderer/params.ts@@ -0,0 +1,379 @@+import type { BuildStatus, ParamInfo, ParamResult, ParamState, ParamValue } from '../shared/types';+import { icon } from './icons';+import { el } from './ui';++interface Deps {+ state(): Promise<ParamState>;+ /** Werte setzen (null: zurück auf den Wert aus dem Code). Der Hauptprozess schreibt parameters.json und baut. */+ set(values: Record<string, ParamValue | null>): Promise<ParamResult>;+ resetAll(): Promise<ParamResult>;+ /** Stelle im Code zeigen, an der der Parameter angelegt ist. */+ openCode(file: string, line: number, label: string): void;+ /** Text in die Eingabe des Agenten einfügen (E11). */+ insert(text: string): void;+ toast(text: string, kind?: 'ok' | 'info' | 'error'): void;+}++interface Ui {+ list: HTMLElement;+ /** Zeile unter der Liste: wie viele Werte vom Code abweichen, „Reset all“. */+ foot: HTMLElement;+ count: HTMLElement;+}++/** Zahl zum Lesen und Wiedereinlesen: Punkt, ohne Tausendertrennung (1500 darf nicht als „1,500“ zurückkommen). */+const numText = (v: number) => v.toLocaleString('en-US', { maximumFractionDigits: 6, useGrouping: false });+const unitOf = (p: ParamInfo) => (p.unit && (p.kind === 'number' || p.kind === 'int') ? (/^[°%]$/.test(p.unit) ? p.unit : ` ${p.unit}`) : '');+/** Wert für die Oberfläche: Zahl mit Einheit, Schalter als on/off, Auswahl mit ihrem Namen. */+export function shownValue(p: ParamInfo, v: ParamValue): string {+ if (typeof v === 'number') return `${numText(v)}${unitOf(p)}`;+ if (typeof v === 'boolean') return v ? 'on' : 'off';+ if (p.kind === 'choice') return p.options?.find((o) => o.value === v)?.label ?? String(v);+ return `“${v}”`;+}+/** Für den Agenten: Zahlen mit Punkt, Texte in Anführungszeichen, Schalter wie in Python. */+const forAgent = (p: ParamInfo, v: ParamValue) => (typeof v === 'boolean' ? (v ? 'True' : 'False') : typeof v === 'string' ? JSON.stringify(v) : `${numText(v)}${unitOf(p)}`);++/** Passt ein Wert aus parameters.json zum Parameter? Gleiche Regeln wie soma build (python/soma/params.py, _coerce). */+function usable(p: ParamInfo, v: ParamValue): boolean {+ switch (p.kind) {+ case 'number': return typeof v === 'number' && Number.isFinite(v);+ case 'int': return typeof v === 'number' && Number.isInteger(v);+ case 'bool': return typeof v === 'boolean';+ case 'text': return typeof v === 'string';+ default: return !!p.options?.some((o) => o.value === v);+ }+}+const outside = (p: ParamInfo, v: ParamValue) => typeof v === 'number' && ((p.min != null && v < p.min) || (p.max != null && v > p.max));+const rangeText = (p: ParamInfo) => `${p.min != null ? shownValue(p, p.min) : '…'} to ${p.max != null ? shownValue(p, p.max) : '…'}`;++/** Text für die Eingabe des Agenten: Name, Wert, ggf. der Wert aus dem Code, Stelle im Code. */+export function paramNote(p: ParamInfo, v: ParamValue, changed: boolean): string {+ return `[Parameter: "${p.label}" (${p.name}) = ${forAgent(p, v)}${changed ? `, set in the app, code default ${forAgent(p, p.default)}` : ''}, ${p.file} line ${p.line}] `;+}++/**+ * Seitenleiste „Parameters“ (Entwurf 2, Bild 6): die Werte, die der Agent mit `param()` freigegeben hat, gruppiert wie im+ * Code. Ändern schreibt den Wert nach parameters.json und baut, der Wert im Code (der des Agenten) bleibt. Abweichende+ * Werte sind orange und einzeln oder alle zusammen zurückzusetzen. Werte außerhalb des Bereichs werden gemeldet und+ * trotzdem gebaut (E28), abgelehnt wird nur, was nicht zum Typ passt.+ */+export class ParamsPanel {+ private st: ParamState | null = null;+ private loadError = '';+ private openName: string | null = null;+ private collapsed = new Set<string>();+ private busy = false;+ private build: BuildStatus = { state: 'idle' };+ /**+ * Letzte Änderung: Scheitert der Build danach, bietet das Panel den Wert davor an (null: Wert aus dem Code). Den Build+ * startet der Hauptprozess schon beim Schreiben, seine Meldung „building“ kann vor der Antwort hier ankommen.+ */+ private last: { name: string; before: ParamValue | null; after: ParamValue | null } | null = null;+ /** Neu zeichnen erst, wenn kein Feld mehr in Bearbeitung ist: sonst wären Eingabe und Fokus weg. */+ private deferred = false;+ private commitTimer: ReturnType<typeof setTimeout> | undefined;++ constructor(private ui: Ui, private deps: Deps) {+ ui.list.addEventListener('focusout', () => setTimeout(() => {+ if (this.deferred && !this.editing()) { this.deferred = false; this.render(); }+ }, 0));+ }++ async refresh(): Promise<void> {+ try { this.st = await this.deps.state(); this.loadError = ''; } catch (e) { this.loadError = e instanceof Error ? e.message : String(e); }+ this.render();+ }++ /** Neues Modell: alte Liste weg. */+ reset(): void { this.st = null; this.openName = null; this.last = null; this.collapsed.clear(); this.render(); }++ /** Stand des Builds: für den Hinweis, wenn ein Build nach einer Änderung scheitert. */+ setBuild(s: BuildStatus): void { this.build = s; }++ private editing(): boolean {+ const a = document.activeElement;+ return !!a && this.ui.list.contains(a) && (a.tagName === 'INPUT' || a.tagName === 'SELECT');+ }++ private userValue(p: ParamInfo): ParamValue | undefined {+ const v = this.st?.values[p.name];+ return v !== undefined && usable(p, v) ? v : undefined;+ }++ private current(p: ParamInfo): ParamValue { return this.userValue(p) ?? p.default; }++ /** Wert übernehmen. Gleich dem Wert im Code: Eintrag entfernen, dann folgt der Parameter wieder dem Code. */+ private async commit(p: ParamInfo, v: ParamValue | null): Promise<void> {+ clearTimeout(this.commitTimer);+ const next = v === null || v === p.default ? null : v;+ const before = this.userValue(p) ?? null;+ if (next === before && this.st?.values[p.name] === (before ?? undefined)) { this.render(); return; }+ this.busy = true;+ let r: ParamResult;+ try { r = await this.deps.set({ [p.name]: next }); } catch (e) { r = { ok: false, message: e instanceof Error ? e.message : String(e), ...(this.st ?? { params: null, values: {} }) }; }+ this.busy = false;+ this.st = r;+ if (!r.ok) { this.deps.toast(r.message ?? `${p.label} could not be changed.`, 'error'); this.render(); return; }+ this.last = { name: p.name, before, after: next };+ this.render();+ }++ /** Zahlen aus Pfeiltasten und Stepper kurz sammeln, damit nicht jeder Druck einen Build anstößt. */+ private commitSoon(p: ParamInfo, v: ParamValue): void {+ clearTimeout(this.commitTimer);+ this.commitTimer = setTimeout(() => void this.commit(p, v), 450);+ }++ private async resetAll(): Promise<void> {+ this.busy = true;+ let r: ParamResult;+ try { r = await this.deps.resetAll(); } catch (e) { r = { ok: false, message: e instanceof Error ? e.message : String(e), ...(this.st ?? { params: null, values: {} }) }; }+ this.busy = false;+ this.st = r;+ this.last = null;+ this.render();+ if (!r.ok) this.deps.toast(r.message ?? 'The values could not be reset.', 'error');+ else this.deps.toast('All parameters are back at the values from the code.');+ }++ render(): void {+ if (this.editing()) { this.deferred = true; return; }+ const { list, foot, count } = this.ui;+ const st = this.st;+ const params = st?.params ?? null;+ count.textContent = params?.length ? String(params.length) : '';+ const out: HTMLElement[] = [];+ if (this.loadError) out.push(el('div', { className: 'pm-warn', textContent: `Parameters not readable: ${this.loadError}` }));+ if (st?.error) out.push(el('div', { className: 'pm-warn' }, icon('alert', 14, 2), el('span', { textContent: st.error })));+ if (!st && !this.loadError) out.push(el('div', { className: 'hint', textContent: 'Loading …' }));+ else if (st && params === null) {+ out.push(el('div', { className: 'hint', textContent: this.build.state === 'building' ? 'The parameters appear after the build …' : 'The parameters appear after the first successful build.' }));+ } else if (params && !params.length) out.push(this.empty());+ if (params?.length) {+ if (st?.stale) out.push(el('div', { className: 'pm-note', textContent: 'The last build failed before it reached the parameters. The list is from an earlier build.' }));+ const failed = this.failedHint(params);+ if (failed) out.push(failed);+ const groups = new Map<string, ParamInfo[]>();+ for (const p of params) {+ const g = p.group ?? '';+ if (!groups.has(g)) groups.set(g, []);+ groups.get(g)!.push(p);+ }+ // Ohne Gruppe zuerst und ohne Überschrift, danach die Gruppen in der Reihenfolge des Codes+ const order = [...groups.keys()].sort((a, b) => Number(a !== '') - Number(b !== ''));+ for (const g of order) {+ const items = groups.get(g)!;+ if (g) {+ const closed = this.collapsed.has(g);+ const changed = items.filter((p) => this.st?.values[p.name] !== undefined).length;+ const h = el('button', { className: 'pg', title: closed ? 'Expand group' : 'Collapse group' }, icon(closed ? 'right' : 'down', 12, 2), el('span', { textContent: g }),+ closed ? el('span', { className: 'src', textContent: `· ${items.length}${changed ? `, ${changed} changed` : ''}` }) : null);+ h.setAttribute('aria-expanded', String(!closed));+ h.addEventListener('click', () => { if (closed) this.collapsed.delete(g); else this.collapsed.add(g); this.render(); });+ out.push(h);+ if (closed) continue;+ }+ for (const p of items) out.push(this.row(p));+ }+ }+ // Werte ohne Parameter, auch wenn das Modell gar keine (mehr) hat. Nicht bei einer Liste von früher: Neue Parameter+ // des gescheiterten Builds kennt sie nicht+ if (params && !st?.stale) {+ const known = new Set(params.map((p) => p.name));+ const orphans = Object.entries(st?.values ?? {}).filter(([k]) => !known.has(k));+ if (orphans.length) out.push(this.orphans(orphans));+ }+ list.replaceChildren(...out);+ // Fußzeile: wie viele Werte vom Code abweichen+ const n = params ? Object.keys(st?.values ?? {}).length : 0;+ foot.hidden = !n;+ if (n) {+ const b = el('button', { className: 'btn sm', disabled: this.busy, title: 'Remove all your values: every parameter takes the value from the code again' }, icon('reset', 14, 1.9), 'Reset all');+ b.addEventListener('click', () => void this.resetAll());+ foot.replaceChildren(el('span', { className: 'dot' }), el('span', { className: 'pf-t', textContent: `${n} changed`, title: `${n} value${n === 1 ? '' : 's'} of yours in parameters.json, in place of the values from the code` }), el('span', { className: 'grow' }), b);+ }+ }++ /** Leerer Zustand (Entwurf 2, Bild 7): was Parameter sind und wie man zu ihnen kommt. */+ private empty(): HTMLElement {+ const ask = el('button', { className: 'btn sm acc', title: 'Add a request to the agent’s input. Enter sends it.' }, icon('send', 14, 1.9), 'Ask the agent');+ ask.addEventListener('click', () => this.deps.insert('Make the main dimensions of the model adjustable with param(), so I can change them in the Parameters panel. '));+ return el('div', { className: 'pm-empty' }, el('span', { className: 'c3' }, icon('sliders', 22, 1.6)), el('b', { textContent: 'This model has no parameters yet' }),+ el('span', { className: 'c2 small', textContent: 'Parameters are values of the model you can change here, such as a size, a count or an angle. The agent decides which ones, for example when you ask: “Make bore and stroke adjustable”.' }),+ ask);+ }++ /** Der Build nach der letzten Änderung ist gescheitert: den Wert davor anbieten (nicht selbst zurücknehmen, E28). */+ private failedHint(params: ParamInfo[]): HTMLElement | null {+ const l = this.last;+ if (!l || this.build.state !== 'error') return null;+ const p = params.find((x) => x.name === l.name);+ if (!p) return null;+ const after = l.after ?? p.default;+ const back = el('button', { className: 'btn sm', disabled: this.busy }, icon('undo', 14, 2), `Back to ${shownValue(p, l.before ?? p.default)}`);+ back.addEventListener('click', () => void this.commit(p, l.before));+ const send = el('button', { className: 'btn sm acc', title: 'Add the parameter to the agent’s input. The error is in the card in the viewer.' }, icon('send', 14, 1.9), 'Send to agent');+ send.addEventListener('click', () => this.deps.insert(`${paramNote(p, after, l.after !== null)}The build fails with this value. `));+ return el('div', { className: 'pm-fail' }, el('div', { className: 'pm-fail-t' }, icon('alert', 15, 2), el('span', { textContent: `The build failed after ${p.label} was set to ${shownValue(p, after)}.` })),+ el('div', { className: 'pm-acts' }, back, send));+ }++ private orphans(entries: [string, ParamValue][]): HTMLElement {+ const box = el('div', { className: 'pm-orph' }, el('div', { className: 'pg static', textContent: 'Not in the model anymore' }),+ el('div', { className: 'pm-note', textContent: 'You set these values, but the code has no parameter with this name (anymore). They are not used.' }));+ for (const [name, v] of entries) {+ const rm = el('button', { className: 'btn sm', disabled: this.busy, title: `Remove ${name} from parameters.json` }, 'Remove');+ rm.addEventListener('click', () => void (async () => {+ const r = await this.deps.set({ [name]: null }).catch((e: unknown) => ({ ok: false, message: e instanceof Error ? e.message : String(e), params: null, values: {} }) as ParamResult);+ if (!r.ok) this.deps.toast(r.message ?? `${name} could not be removed.`, 'error');+ else this.st = r;+ this.render();+ })());+ const row = el('div', { className: 'pm-orow' }, el('span', { className: 'mono', textContent: name }), el('span', { className: 'c3', textContent: typeof v === 'string' ? `“${v}”` : String(v) }), el('span', { className: 'grow' }), rm);+ row.dataset.name = name;+ box.append(row);+ }+ return box;+ }++ private row(p: ParamInfo): HTMLElement {+ const raw = this.st?.values[p.name];+ const user = this.userValue(p);+ const v = user ?? p.default;+ const changed = raw !== undefined;+ const bad = raw !== undefined && user === undefined; // in der Datei, passt aber nicht zum Parameter+ const out = outside(p, v);+ const open = this.openName === p.name;+ const cls = ['prm', changed && 'chg', (out || bad) && 'err', open && 'open'].filter(Boolean).join(' ');+ const lb = el('button', { className: 'lb', title: `${p.label} (${p.name})${p.help ? `\n${p.help}` : ''}` }, el('span', { className: 'lt', textContent: p.label }), el('span', { className: 'cn', textContent: p.name }));+ lb.setAttribute('aria-expanded', String(open));+ lb.addEventListener('click', () => { this.openName = open ? null : p.name; this.render(); });+ const rst = el('button', { className: 'rst', disabled: this.busy, title: `Back to the value from the code (${shownValue(p, p.default)})` }, icon('reset', 13, 2));+ rst.setAttribute('aria-label', `Reset ${p.label}`);+ // Unsichtbar statt ausgeblendet: Die Felder aller Zeilen bleiben bündig+ rst.classList.toggle('off', !changed);+ rst.tabIndex = changed ? 0 : -1;+ rst.addEventListener('click', () => void this.commit(p, null));+ const r = el('div', { className: 'r' }, lb, this.control(p, v), rst);+ const row = el('div', { className: cls }, r);+ row.dataset.name = p.name;+ if (out) row.title = `Outside the range ${rangeText(p)} from the code`;+ if (open) row.append(this.details(p, v, changed, out, bad));+ return row;+ }++ /** Aufgeklappt: Schieber, Erklärung, Wert im Code, Hinweise, Sprung in den Code und „Send to agent“. */+ private details(p: ParamInfo, v: ParamValue, changed: boolean, out: boolean, bad: boolean): HTMLElement {+ const x = el('div', { className: 'x' });+ if ((p.kind === 'number' || p.kind === 'int') && p.min != null && p.max != null && p.max > p.min) x.append(this.slider(p, v as number));+ if (p.help) x.append(el('div', { className: 'c2 small', textContent: p.help }));+ const facts = [`Code: ${shownValue(p, p.default)}`];+ if ((p.kind === 'number' || p.kind === 'int') && (p.min != null || p.max != null)) facts.push(`range ${rangeText(p)}`);+ if (p.step != null) facts.push(`step ${numText(p.step)}`);+ x.append(el('div', { className: 'c3 small', textContent: facts.join(' · ') }));+ if (out) x.append(el('div', { className: 'pm-err small', textContent: `${shownValue(p, v)} lies outside the range from the code. It is used anyway, the agent chose the range so the model works within it.` }));+ if (bad) x.append(el('div', { className: 'pm-err small', textContent: `parameters.json holds ${JSON.stringify(this.st?.values[p.name])}, which does not fit this parameter. The value from the code applies.` }));+ const code = el('button', { className: 'lnk', title: 'Show the place in the code' }, icon('code', 13, 2), `${p.file}, line ${p.line}`);+ code.addEventListener('click', () => this.deps.openCode(p.file, p.line, p.label));+ const send = el('button', { className: 'lnk', title: 'Add this parameter to the agent’s input' }, icon('send', 13, 2), 'Send to agent');+ send.addEventListener('click', () => this.deps.insert(paramNote(p, v, changed)));+ x.append(el('div', { className: 'pm-links' }, code, el('span', { className: 'grow' }), send));+ return x;+ }++ private slider(p: ParamInfo, v: number): HTMLElement {+ const min = p.min!, max = p.max!;+ // Ohne step: ein Zweihundertstel des Bereichs, auf eine runde Zahl von Stellen+ const step = p.step ?? (p.kind === 'int' ? 1 : 10 ** Math.floor(Math.log10((max - min) / 200)));+ const digits = Math.max(0, Math.min(6, -Math.floor(Math.log10(step) + 1e-9)));+ const round = (n: number) => (p.kind === 'int' ? Math.round(n) : Number(n.toFixed(digits)));+ const range = el('input', { type: 'range', className: 'pm-range', min: String(min), max: String(max), step: String(step), value: String(Math.min(max, Math.max(min, v))), disabled: this.busy });+ range.setAttribute('aria-label', `${p.label}, slider`);+ // Beim Ziehen nur die Zahl mitführen, gebaut wird beim Loslassen+ range.addEventListener('input', () => {+ const f = range.closest('.prm')?.querySelector<HTMLInputElement>('.pm-num');+ if (f) f.value = numText(round(Number(range.value)));+ });+ range.addEventListener('change', () => { range.blur(); void this.commit(p, round(Number(range.value))); });+ return el('div', { className: 'slider' }, el('span', { className: 'c3', textContent: numText(min) }), range, el('span', { className: 'c3', textContent: numText(max) }));+ }++ private control(p: ParamInfo, v: ParamValue): HTMLElement {+ const id = `pm-${p.name}`;+ if (p.kind === 'bool') {+ const sw = el('button', { id, className: 'pm-switch', disabled: this.busy, title: v ? 'On' : 'Off' }, el('span'));+ sw.setAttribute('role', 'switch');+ sw.setAttribute('aria-checked', String(v === true));+ sw.setAttribute('aria-label', p.label);+ sw.addEventListener('click', () => void this.commit(p, !(v === true)));+ return el('span', { className: 'pm-ctl' }, sw);+ }+ if (p.kind === 'choice') {+ const sel = el('select', { id, className: 'pm-select', disabled: this.busy }, ...(p.options ?? []).map((o, i) => el('option', { value: String(i), textContent: o.label })));+ sel.value = String(Math.max(0, (p.options ?? []).findIndex((o) => o.value === v)));+ sel.setAttribute('aria-label', p.label);+ sel.addEventListener('change', () => { const o = p.options?.[Number(sel.value)]; sel.blur(); if (o) void this.commit(p, o.value); });+ return el('span', { className: 'pm-ctl' }, sel);+ }+ const isNum = p.kind === 'number' || p.kind === 'int';+ const shown = typeof v === 'number' ? numText(v) : String(v);+ const inp = el('input', { id, className: isNum ? 'pm-num' : 'pm-text', type: 'text', value: shown, spellcheck: false, autocomplete: 'off', disabled: this.busy });+ inp.setAttribute('aria-label', p.label);+ if (isNum) inp.inputMode = p.kind === 'int' ? 'numeric' : 'decimal';+ const parse = (): ParamValue | null => {+ if (!isNum) return inp.value;+ const n = Number(inp.value.trim().replace(',', '.'));+ if (!inp.value.trim() || !Number.isFinite(n)) { this.deps.toast(`${p.label} needs a number, for example ${numText(p.default as number)}.`, 'error'); return null; }+ if (p.kind === 'int' && !Number.isInteger(n)) { this.deps.toast(`${p.label} needs a whole number.`, 'error'); return null; }+ return n;+ };+ const apply = () => {+ if (inp.value.trim() === shown) return;+ const n = parse();+ if (n === null) { inp.value = shown; return; }+ void this.commit(p, n);+ };+ const nudge = (dir: 1 | -1) => {+ const cur = parse();+ if (typeof cur !== 'number') return;+ const step = p.step ?? (p.kind === 'int' ? 1 : 10 ** Math.floor(Math.log10(Math.max(Math.abs(cur), 1e-6))) / 10);+ const next = Number((cur + dir * step).toFixed(6));+ inp.value = numText(next);+ this.commitSoon(p, next);+ };+ inp.addEventListener('change', apply);+ inp.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); apply(); inp.blur(); }+ else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); inp.value = shown; inp.blur(); }+ else if (isNum && (e.key === 'ArrowUp' || e.key === 'ArrowDown')) { e.preventDefault(); nudge(e.key === 'ArrowUp' ? 1 : -1); }+ });+ const box = el('span', { className: `pm-ctl valbox${isNum ? '' : ' wide'}` });+ if (p.kind === 'int') {+ const minus = el('button', { className: 'stp', disabled: this.busy, title: `Less (${p.label})` }, icon('minus', 12, 2));+ const plus = el('button', { className: 'stp', disabled: this.busy, title: `More (${p.label})` }, icon('plus', 12, 2));+ minus.setAttribute('aria-label', `${p.label} minus`);+ plus.setAttribute('aria-label', `${p.label} plus`);+ minus.addEventListener('click', () => nudge(-1));+ plus.addEventListener('click', () => nudge(1));+ box.classList.add('stepper');+ box.append(minus, inp, plus);+ } else box.append(inp);+ if (isNum && p.unit) box.append(el('span', { className: 'u', textContent: p.unit }));+ return box;+ }++ /** Für Tests. */+ state() {+ const params = this.st?.params ?? null;+ return {+ names: params?.map((p) => p.name) ?? null,+ shown: Object.fromEntries((params ?? []).map((p) => [p.name, shownValue(p, this.current(p))])),+ values: { ...(this.st?.values ?? {}) },+ changed: [...this.ui.list.querySelectorAll<HTMLElement>('.prm.chg')].map((x) => x.dataset.name),+ errors: [...this.ui.list.querySelectorAll<HTMLElement>('.prm.err')].map((x) => x.dataset.name),+ stale: !!this.st?.stale, error: this.st?.error ?? null, busy: this.busy, open: this.openName,+ text: this.ui.list.innerText, foot: this.ui.foot.hidden ? '' : this.ui.foot.innerText,+ };+ }+}diff --git a/app/src/renderer/style.css b/app/src/renderer/style.cssindex e013cae..ed62923 100644--- a/app/src/renderer/style.css+++ b/app/src/renderer/style.css@@ -185,6 +185,69 @@ code { font-family:var(--mono); font-size:.95em; }.sk-reset { width:22px; height:22px; display:flex; align-items:center; justify-content:center; border-radius:5px; color:var(--tx3); flex-shrink:0; }.sk-reset:hover { background:var(--s3); color:var(--tx); }.sk-reset[hidden] { display:flex; visibility:hidden; }++/* Parameter (Entwurf 2, Bild 6): Werte aus param() im Code. Orange = weicht vom Wert im Code ab, Rot = außerhalb des+ Bereichs oder unbrauchbar. Die aktive Zeile klappt auf: Schieber, Wert im Code, Sprung in den Code */+.pm-list { flex:1; overflow:auto; padding:2px 0 10px; }+.pm-list .hint { color:var(--tx3); padding:8px 14px; }+.pm-note { padding:6px 14px; font-size:12px; color:var(--tx3); line-height:1.45; }+.pm-warn { display:flex; gap:8px; align-items:flex-start; margin:8px 10px 2px; padding:8px 10px; border-radius:7px; background:rgba(232,197,71,.1); color:var(--warn); font-size:12px; line-height:1.45; }+.pm-warn svg { margin-top:1px; }+.pg { display:flex; align-items:center; gap:6px; width:100%; padding:12px 14px 4px 10px; font-size:11px; letter-spacing:.06em; text-transform:uppercase; color:var(--tx3); text-align:left; }+.pg:hover:not(.static) { color:var(--tx2); }+.pg .src { letter-spacing:0; text-transform:none; font-size:11.5px; }+.pg.static { padding-left:14px; }+.prm { position:relative; margin:0 6px; border-radius:7px; }+.prm:hover:not(.open) { background:var(--s2); }+.prm .r { display:flex; align-items:center; gap:6px; height:32px; padding:0 2px 0 14px; }+.prm .lb { flex:1; min-width:0; height:100%; display:flex; align-items:center; gap:7px; white-space:nowrap; overflow:hidden; text-align:left; }+.prm .lb .lt { overflow:hidden; text-overflow:ellipsis; min-width:24px; }+.prm .lb .cn { font-family:var(--mono); font-size:10.5px; color:var(--tx3); overflow:hidden; text-overflow:ellipsis; flex-shrink:3; min-width:0; }+.prm.chg::before { content:""; position:absolute; left:4px; top:13px; width:6px; height:6px; border-radius:50%; background:var(--acc); }+.prm.chg.err::before { background:var(--err); }+.prm.open { background:var(--s2); box-shadow:inset 0 0 0 1px var(--line2); }+.pm-ctl { flex-shrink:0; display:flex; align-items:center; justify-content:flex-end; width:104px; }+.valbox { height:26px; padding:0 6px; gap:4px; border:1px solid var(--line2); border-radius:5px; background:var(--term); }+.valbox:focus-within { border-color:var(--acc); }+.valbox input { flex:1; min-width:0; width:100%; height:100%; padding:0; border:0; outline:none; background:none; color:inherit; font:12px var(--mono); text-align:right; }+.valbox .u { color:var(--tx3); font-size:11px; white-space:nowrap; }+.valbox.wide { width:124px; }+.valbox.wide input { text-align:left; font-family:var(--sans); }+.valbox.stepper { padding:0; }+.valbox.stepper input { text-align:center; }+.valbox.stepper .stp { width:22px; height:100%; display:flex; align-items:center; justify-content:center; color:var(--tx3); flex-shrink:0; }+.valbox.stepper .stp:hover:not(:disabled) { color:var(--tx); background:var(--s3); }+.valbox.stepper .u { padding-right:6px; }+.pm-select { width:104px; height:26px; padding:0 4px; border-radius:5px; border:1px solid var(--line2); background:var(--term); color:var(--tx); font:12px var(--sans); }+.pm-switch { width:32px; height:18px; border-radius:9px; background:var(--s3); box-shadow:inset 0 0 0 1px var(--line2); position:relative; flex-shrink:0; }+.pm-switch span { position:absolute; top:3px; left:3px; width:12px; height:12px; border-radius:50%; background:var(--tx2); transition:left .12s; }+.pm-switch[aria-checked=true] { background:var(--acc-tint); box-shadow:inset 0 0 0 1px var(--acc-line); }+.pm-switch[aria-checked=true] span { left:17px; background:var(--acc); }+.prm.chg .valbox, .prm.chg .pm-select { border-color:var(--acc-line); color:var(--acc-tx); }+.prm.err .valbox, .prm.err .pm-select { border-color:rgba(240,116,112,.6); color:#ffb8b3; }+.prm .rst { width:22px; height:22px; display:flex; align-items:center; justify-content:center; border-radius:5px; color:var(--tx3); flex-shrink:0; }+.prm .rst:hover:not(:disabled) { background:var(--s3); color:var(--tx); }+.prm .rst.off { visibility:hidden; }+.prm .x { padding:2px 12px 12px 14px; display:flex; flex-direction:column; gap:9px; }+.prm .x .slider { display:flex; align-items:center; gap:8px; }+.prm .x .slider .c3 { font:11px var(--mono); }+.pm-range { flex:1; min-width:0; accent-color:var(--acc); height:18px; }+.pm-err { color:#ffb8b3; line-height:1.45; }+.pm-links { display:flex; align-items:center; gap:12px; }+.pm-links .lnk { display:flex; align-items:center; gap:6px; font-size:12px; color:var(--tx2); }+.pm-links .lnk:hover { color:var(--tx); }+.pm-fail { margin:8px 10px 4px; padding:10px; border:1px solid rgba(240,116,112,.45); border-radius:8px; background:var(--err-tint); }+.pm-fail-t { display:flex; gap:8px; align-items:flex-start; color:#ffb8b3; font-size:12.5px; line-height:1.45; }+.pm-fail-t svg { margin-top:1px; }+.pm-acts { display:flex; flex-wrap:wrap; gap:8px; margin-top:8px; }+.pm-empty { margin:12px 10px; padding:16px; border:1px solid var(--line); border-radius:10px; background:var(--s2); display:flex; flex-direction:column; gap:10px; line-height:1.5; }+.pm-empty .btn { align-self:flex-start; }+.pm-orph { margin-top:6px; }+.pm-orow { display:flex; align-items:center; gap:8px; min-height:32px; padding:0 8px 0 14px; margin:0 6px; font-size:12px; }+.pm-orow .mono { font-family:var(--mono); }+.pfoot { flex-shrink:0; display:flex; align-items:center; gap:8px; padding:8px 10px 8px 14px; border-top:1px solid var(--line); font-size:12px; color:var(--tx2); }+.pfoot .dot { width:7px; height:7px; background:var(--acc); }+.pfoot .pf-t { white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }.dropzone { margin:10px 12px 12px; padding:9px 12px; border:1px dashed var(--line2); border-radius:8px; display:flex; align-items:center; gap:10px; color:var(--tx3); font-size:12px; flex-shrink:0; }.dropzone b { color:var(--tx2); font-weight:500; }.dropzone.over, body.dragging .dropzone { border-color:var(--acc); background:var(--acc-tint); }diff --git a/app/src/shared/editable.ts b/app/src/shared/editable.tsindex e082cef..b932ca4 100644--- a/app/src/shared/editable.ts+++ b/app/src/shared/editable.ts@@ -5,6 +5,7 @@export function readOnlyReason(rel: string): string | null {const p = rel.replace(/\\/g, '/').replace(/^\.\//, '');if (/^(AGENTS|CLAUDE)\.md$/i.test(p)) return 'Managed by the app and replaced on updates. Your own wishes and rules belong in NOTES.md.';+ if (/^parameters\.json$/i.test(p)) return 'Your values from the Parameters panel. Change them there, on the left under “Parameters”.';if (/^\.gitignore$/i.test(p)) return 'Managed by the app.';if (/^(output|exports)\//i.test(p)) return 'Recreated on every build or export.';if (/^\.soma\/skills\//i.test(p)) return 'Copy of a skill. Change it on the left under “Skills”.';@@ -28,17 +29,19 @@ export function fileOpBlockReason(rel: string, op: 'create' | 'rename' | 'deleteif (/^\.(soma|git)(\/|$)/i.test(p)) return 'Internal data of the app and of Git.';if (op !== 'create' && /^model\.py$/i.test(p)) return 'model.py is the fixed entry point of the model.';if (op === 'rename' && /^(inputs|parts)$/i.test(p)) return 'The agent looks for this folder by its name.';+ if (op === 'rename' && /^parameters\.json$/i.test(p)) return 'The app and soma build look for this file by its name.';return null;}/**- * Betrifft eine Änderung an dieser Datei das Modell? Python-Dateien und alles in inputs/ (mitgebrachte STEP-Dateien,- * Tabellen, die model.py einliest). Notizen wie NOTES.md nicht: Nach ihrem Speichern wird nicht gebaut.+ * Betrifft eine Änderung an dieser Datei das Modell? Python-Dateien, alles in inputs/ (mitgebrachte STEP-Dateien,+ * Tabellen, die model.py einliest) und die Werte aus dem Parameter-Panel. Notizen wie NOTES.md nicht: Nach ihrem+ * Speichern wird nicht gebaut.*/export function affectsBuild(rel: string): boolean {const p = rel.replace(/\\/g, '/');if (affectsAnimation(p)) return false;- return /\.py$/i.test(p) || /^inputs\//i.test(p);+ return /\.py$/i.test(p) || /^inputs\//i.test(p) || /^parameters\.json$/i.test(p);}/** Eine Animationsdatei (E58): Ihre Änderung baut die Animation neu, nicht das Modell. */diff --git a/app/src/shared/types.ts b/app/src/shared/types.tsindex 61383b4..810a4cd 100644--- a/app/src/shared/types.ts+++ b/app/src/shared/types.ts@@ -22,8 +22,31 @@ export interface BuildResult {error?: BuildError;timings?: Record<string, number>;warnings?: string[];+ /** Parameter des Modells (`param()` im Code), auch nach einem Fehler: die bis dahin angelegten. */+ params?: ParamInfo[];}+/** Wert eines Parameters: Zahl, Schalter oder Text. */+export type ParamValue = number | boolean | string;+/**+ * Ein Parameter aus `soma.param()`, so wie ihn der letzte Build kennt. `default` steht im Code (der Wert des Agenten),+ * `value` hat der Build verwendet, `source` sagt, woher er kam (`user`: aus parameters.json).+ */+export interface ParamInfo {+ name: string; label: string; kind: 'number' | 'int' | 'bool' | 'choice' | 'text';+ default: ParamValue; value: ParamValue; source: 'code' | 'user';+ min: number | null; max: number | null; step: number | null; unit: string | null;+ options: { value: ParamValue; label: string }[] | null;+ group: string | null; help: string | null; file: string; line: number;+}+/**+ * Stand des Parameter-Panels. `params`: Parameter aus dem letzten Build, der sie kannte (null: noch keiner).+ * `values`: Werte des Nutzers aus parameters.json, gelten vor den Werten im Code. `error`: Die Datei ist nicht lesbar.+ * `stale`: Die Liste stammt von einem früheren Build, weil der letzte vor den Parametern scheiterte.+ */+export interface ParamState { params: ParamInfo[] | null; values: Record<string, ParamValue>; error?: string; stale?: boolean }+export interface ParamResult extends ParamState { ok: boolean; message?: string }+export type BuildState = 'idle' | 'building' | 'ok' | 'error';export interface BuildStatus {state: BuildState; result?: BuildResult; startedAt?: number; queued?: boolean; reason?: string;@@ -307,6 +330,14 @@ export interface SomaApi {/** Den Stand vorab in den Messdienst laden, damit der erste Klick nicht darauf wartet (große Baugruppen: Sekunden). */prepare(source: MeasureSource, build: string): Promise<MeasurePrepared>;};+ /** Parameter des Modells (`param()` im Code) und die Werte des Nutzers in parameters.json. */+ params: {+ state(): Promise<ParamState>;+ /** Wert des Nutzers setzen (null: zurück auf den Wert aus dem Code) und bauen. */+ set(values: Record<string, ParamValue | null>): Promise<ParamResult>;+ /** Alle Werte des Nutzers entfernen: Es gelten wieder die Werte aus dem Code. */+ resetAll(): Promise<ParamResult>;+ };/** Skills des offenen Modells (E17): auflisten, Stufe wählen (E55). */skills: {list(): Promise<SkillInfo[]>;diff --git a/app/test/editor.mjs b/app/test/editor.mjsindex 31d5d30..5d62c74 100644--- a/app/test/editor.mjs+++ b/app/test/editor.mjs@@ -92,10 +92,10 @@ try {// 3) Tippen speichert nicht und baut nichtconst b0 = await builds();- await replace('LENGTH = 60.0', 'LENGTH = 70.0');+ await replace('LENGTH = param(60.0', 'LENGTH = param(70.0');await sleep(2500);s = await ed();- check('Tippen: Platte unverändert, kein Build', s.dirty && disk().includes('LENGTH = 60.0') && await builds() === b0 && await body() === 60, `${await builds() - b0} Builds`);+ check('Tippen: Platte unverändert, kein Build', s.dirty && disk().includes('LENGTH = param(60.0') && await builds() === b0 && await body() === 60, `${await builds() - b0} Builds`);check('Anzeige: Punkt am Reiter, „Not saved · Ctrl+S" und Knopf „Save and build"', await ev(() => !!document.querySelector('#code-tabs .ctab.on .dirty')&& document.getElementById('code-info').textContent.includes('Not saved · Ctrl+S') && document.getElementById('btn-code-save')?.textContent === 'Save and build'));await shot('8-editor-ungespeichert');@@ -103,49 +103,49 @@ try {// 4) Strg+S im Editor: speichern, dann genau ein Buildawait ctrlS();await waitFor('Build mit 70', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] === 70, 60000).catch(() => {});- check('Strg+S im Editor: Datei gespeichert und gebaut (Body 70 mm lang)', disk().includes('LENGTH = 70.0') && !(await ed()).dirty && await body() === 70);+ check('Strg+S im Editor: Datei gespeichert und gebaut (Body 70 mm lang)', disk().includes('LENGTH = param(70.0') && !(await ed()).dirty && await body() === 70);await sleep(2000);check('Genau ein Build nach dem Speichern (die Dateiüberwachung baut nicht noch einmal)', await builds() === b0 + 1, `${await builds() - b0} Builds`);check('Strg+S im Editor schreibt keine ZIP (das macht „Speichern" oben)', !(await ev(() => window.__t.saveState()))?.zipPath);// 5) Knopf „Speichern und bauen"- await replace('LENGTH = 70.0', 'LENGTH = 72.0');+ await replace('LENGTH = param(70.0', 'LENGTH = param(72.0');await domClick('btn-code-save');await waitFor('Build mit 72', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] === 72, 60000).catch(() => {});- check('Knopf „Save and build": gespeichert und gebaut (72 mm), Knopf wieder weg', disk().includes('LENGTH = 72.0') && await body() === 72 && await ev(() => !document.getElementById('btn-code-save')?.isConnected));+ check('Knopf „Save and build": gespeichert und gebaut (72 mm), Knopf wieder weg', disk().includes('LENGTH = param(72.0') && await body() === 72 && await ev(() => !document.getElementById('btn-code-save')?.isConnected));// 6) Änderung von außen ohne eigene Eingaben: Der Editor übernimmt sie- fs.writeFileSync(modelPy, disk().replace('LENGTH = 72.0', 'LENGTH = 75.0'));- await waitFor('Editor übernimmt', () => window.__t.editor.state().text.includes('LENGTH = 75.0'), 10000).catch(() => {});+ fs.writeFileSync(modelPy, disk().replace('LENGTH = param(72.0', 'LENGTH = param(75.0'));+ await waitFor('Editor übernimmt', () => window.__t.editor.state().text.includes('LENGTH = param(75.0'), 10000).catch(() => {});s = await ed();- check('Änderung von außen (Agent) erscheint im Editor, ohne als eigene Eingabe zu gelten', s.text.includes('LENGTH = 75.0') && !s.dirty && !s.conflict);+ check('Änderung von außen (Agent) erscheint im Editor, ohne als eigene Eingabe zu gelten', s.text.includes('LENGTH = param(75.0') && !s.dirty && !s.conflict);await idle();// 7) Konflikt: ungespeicherte Eingabe, und der Agent ändert dieselbe Datei. Nichts wird überschrieben.- await replace('LENGTH = 75.0', 'LENGTH = 76.0');- fs.writeFileSync(modelPy, disk().replace('LENGTH = 75.0', 'LENGTH = 77.0'));+ await replace('LENGTH = param(75.0', 'LENGTH = param(76.0');+ fs.writeFileSync(modelPy, disk().replace('LENGTH = param(75.0', 'LENGTH = param(77.0'));await waitFor('Konflikt', () => window.__t.editor.state().conflict === 'changed', 10000).catch(() => {});s = await ed();- check('Gleichzeitige Änderung: Hinweis im Editor, die Platte bleibt beim Agenten', s.conflict === 'changed' && disk().includes('LENGTH = 77.0') && s.text.includes('LENGTH = 76.0')+ check('Gleichzeitige Änderung: Hinweis im Editor, die Platte bleibt beim Agenten', s.conflict === 'changed' && disk().includes('LENGTH = param(77.0') && s.text.includes('LENGTH = param(76.0')&& await ev(() => !document.getElementById('code-banner').hidden && !!document.querySelector('#code-tabs .dirty.warn')));await ctrlS();await sleep(300);- check('Strg+S bei Konflikt: nichts geschrieben, Meldung', disk().includes('LENGTH = 77.0') && (await ev(() => window.__t.toast())).text.includes('Not everything could be saved'));+ check('Strg+S bei Konflikt: nichts geschrieben, Meldung', disk().includes('LENGTH = param(77.0') && (await ev(() => window.__t.toast())).text.includes('Not everything could be saved'));await shot('9-editor-konflikt');await idle();const b1 = await builds();await ev(() => window.__t.editor.keepMine());- await until('eigene Fassung auf der Platte', () => disk().includes('LENGTH = 76.0'));+ await until('eigene Fassung auf der Platte', () => disk().includes('LENGTH = param(76.0'));await waitFor('Build mit 76', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] === 76, 60000).catch(() => {});check('„Meine Fassung behalten": gespeichert und gebaut, die Fassung von außen liegt in der Sicherung',- disk().includes('LENGTH = 76.0') && await body() === 76 && await builds() > b1 && backups().some((b) => b.includes('LENGTH = 77.0')) && !(await ed()).conflict);- await replace('LENGTH = 76.0', 'LENGTH = 78.0');- fs.writeFileSync(modelPy, disk().replace('LENGTH = 76.0', 'LENGTH = 79.0'));+ disk().includes('LENGTH = param(76.0') && await body() === 76 && await builds() > b1 && backups().some((b) => b.includes('LENGTH = param(77.0')) && !(await ed()).conflict);+ await replace('LENGTH = param(76.0', 'LENGTH = param(78.0');+ fs.writeFileSync(modelPy, disk().replace('LENGTH = param(76.0', 'LENGTH = param(79.0'));await waitFor('zweiter Konflikt', () => window.__t.editor.state().conflict === 'changed', 10000).catch(() => {});await ev(() => window.__t.editor.takeTheirs());s = await ed();check('„Fassung von außen laden": Editor zeigt sie, die eigene Eingabe liegt in der Sicherung',- s.text.includes('LENGTH = 79.0') && !s.dirty && !s.conflict && disk().includes('LENGTH = 79.0') && backups().some((b) => b.includes('LENGTH = 78.0')));+ s.text.includes('LENGTH = param(79.0') && !s.dirty && !s.conflict && disk().includes('LENGTH = param(79.0') && backups().some((b) => b.includes('LENGTH = param(78.0')));await idle();// 8) Dateien der App: nur lesen, mit Begründung@@ -250,27 +250,27 @@ try {// 10) Build-Fehler: „Code öffnen" markiert die Zeile rotawait open('model.py');- await replace('LENGTH = 79.0', 'LENGTH = 79.0 +');+ await replace('LENGTH = param(79.0', 'LENGTH = param(79.0 +');await ctrlS();await waitFor('Fehler', () => window.__t.status().state === 'error', 60000).catch(() => {});await domClick('btn-err-code');await waitFor('Fehlerzeile', () => window.__t.editor.state().marked.some((m) => m.startsWith('er:')), 10000).catch(() => {});s = await ed();- check('Fehlerkarte „Code öffnen": Fehlerzeile im Editor rot markiert', s.marked.some((m) => m.startsWith('er:') && m.includes('LENGTH = 79.0 +')), s.marked.join(' | ').slice(0, 60));+ check('Fehlerkarte „Code öffnen": Fehlerzeile im Editor rot markiert', s.marked.some((m) => m.startsWith('er:') && m.includes('LENGTH = param(79.0 +')), s.marked.join(' | ').slice(0, 60));await shot('10-editor-fehler');- await replace('LENGTH = 79.0 +', 'LENGTH = 79.0');+ await replace('LENGTH = param(79.0 +', 'LENGTH = param(79.0');await ctrlS();await waitFor('wieder gebaut', () => window.__t.status().state === 'ok', 60000).catch(() => {});// 11) „Speichern" oben: speichert auch die Eingaben im Editor, dann Snapshot und ZIP- await replace('LENGTH = 79.0', 'LENGTH = 81.0');+ await replace('LENGTH = param(79.0', 'LENGTH = param(81.0');const zipPath = path.join(ud, 'Editortest.zip');await app.answers([zipPath]);await domClick('btn-save');await waitFor('gespeichert', () => !!window.__t.saveState()?.zipPath && !window.__t.saveState().unsaved, 60000).catch(() => {});const inHead = (await exec(['show', 'HEAD:model.py'], proj.dir)).stdout;- check('„Speichern" oben: Eingabe aus dem Editor ist im Snapshot und in der ZIP', inHead.includes('LENGTH = 81.0') && fs.existsSync(zipPath) && !(await ed()).dirty);- await replace('LENGTH = 81.0', 'LENGTH = 82.0');+ check('„Speichern" oben: Eingabe aus dem Editor ist im Snapshot und in der ZIP', inHead.includes('LENGTH = param(81.0') && fs.existsSync(zipPath) && !(await ed()).dirty);+ await replace('LENGTH = param(81.0', 'LENGTH = param(82.0');check('Ungespeicherte Eingabe im Editor: Speicherstand oben zeigt „Not saved"', await ev(() => document.getElementById('save-badge').textContent.startsWith('Not saved')),await ev(() => document.getElementById('save-badge').textContent));@@ -278,31 +278,31 @@ try {await app.answers([2]);await domClick('btn-new');await sleep(1500);- check('Neues Modell, Rückfrage „Abbrechen": Modell bleibt, Eingabe bleibt ungespeichert', (await ev(() => window.__t.project())).id === proj.id && (await ed()).dirty && disk().includes('LENGTH = 81.0'));+ check('Neues Modell, Rückfrage „Abbrechen": Modell bleibt, Eingabe bleibt ungespeichert', (await ev(() => window.__t.project())).id === proj.id && (await ed()).dirty && disk().includes('LENGTH = param(81.0'));await app.answers([0]);await domClick('btn-new');await waitFor('neues Modell', (old) => window.__t.project().id !== old && window.__t.status().state === 'ok' && window.__t.partCount() === 2, 90000, proj.id).catch(() => {});const p2 = await ev(() => window.__t.project());const model2 = path.join(p2.dir, 'model.py');- check('Rückfrage „Speichern": Eingabe steht im alten Modell, das neue ist unberührt', p2.id !== proj.id && disk().includes('LENGTH = 82.0') && fs.readFileSync(model2, 'utf8').includes('LENGTH = 60.0'));+ check('Rückfrage „Speichern": Eingabe steht im alten Modell, das neue ist unberührt', p2.id !== proj.id && disk().includes('LENGTH = param(82.0') && fs.readFileSync(model2, 'utf8').includes('LENGTH = param(60.0'));// Die Code-Spalte bleibt offen und zeigt dann model.py des neuen Modells (nicht leer), Reiter des alten sind wegawait waitFor('model.py des neuen Modells', () => window.__t.editor.state().file === 'model.py', 10000).catch(() => {});const ed2 = await ed();- check('Nach dem Wechsel: keine Reiter des alten Modells, die Code-Spalte zeigt model.py des neuen', ed2.files.join(',') === 'model.py' && ed2.text.includes('LENGTH = 60.0') && !ed2.dirty, ed2.files.join(','));+ check('Nach dem Wechsel: keine Reiter des alten Modells, die Code-Spalte zeigt model.py des neuen', ed2.files.join(',') === 'model.py' && ed2.text.includes('LENGTH = param(60.0') && !ed2.dirty, ed2.files.join(','));// 13) Reiter mit ungespeicherter Eingabe schließen: „Verwerfen" legt sie als Sicherung abawait open('model.py');- await replace('LENGTH = 60.0', 'LENGTH = 65.0');+ await replace('LENGTH = param(60.0', 'LENGTH = param(65.0');await app.answers([1]);await ev(() => document.querySelector('#code-tabs .ctab.on .x').click());await waitFor('Reiter zu', () => window.__t.editor.state().files.length === 0, 10000).catch(() => {});const bdir2 = path.join(ud, 'workspace-backups', `${p2.id}-editor`);const back2 = fs.existsSync(bdir2) ? fs.readdirSync(bdir2).map((f) => fs.readFileSync(path.join(bdir2, f), 'utf8')) : [];- check('Reiter schließen, „Verwerfen": Datei unverändert, Eingabe in der Sicherung', fs.readFileSync(model2, 'utf8').includes('LENGTH = 60.0') && back2.some((b) => b.includes('LENGTH = 65.0')));+ check('Reiter schließen, „Verwerfen": Datei unverändert, Eingabe in der Sicherung', fs.readFileSync(model2, 'utf8').includes('LENGTH = param(60.0') && back2.some((b) => b.includes('LENGTH = param(65.0')));// 14) Späte Schreibanfrage für ein schon gewechseltes Modell: nicht ins neue schreiben, sondern sichernconst late = await ev((id) => window.soma.fs.writeText(id, 'model.py', 'X = 1\n', null, true), proj.id);- check('Späte Eingabe für das alte Modell: nicht ins neue geschrieben, sondern gesichert', !late.ok && /backup/.test(late.error ?? '') && fs.readFileSync(model2, 'utf8').includes('LENGTH = 60.0')+ check('Späte Eingabe für das alte Modell: nicht ins neue geschrieben, sondern gesichert', !late.ok && /backup/.test(late.error ?? '') && fs.readFileSync(model2, 'utf8').includes('LENGTH = param(60.0')&& backups().includes('X = 1\n'), (late.error ?? '').slice(0, 60));const relevant = page.errors.filter((e) => !/favicon/i.test(e));diff --git a/app/test/params.mjs b/app/test/params.mjsnew file mode 100644index 0000000..94425d7--- /dev/null+++ b/app/test/params.mjs@@ -0,0 +1,294 @@+// Test des Parameter-Panels: param() im Code (Wert des Agenten), Werte des Nutzers in parameters.json, Zurücksetzen einzeln+// und alle, Bereich (melden, trotzdem bauen), Typen (Zahl, ganze Zahl, Schalter, Auswahl, Text), Gruppen, Werte ohne+// Parameter, gescheiterter Build mit Angebot „Back to“, Fehler vor den Parametern, kaputte Datei (melden, nicht+// überschreiben), leerer Zustand, Snapshot und ZIP. Aufruf: node test/run-all.mjs params (nach npm run build).+// SMOKE_VISIBLE=offscreen SMOKE_SHOTS=1 legt Bilder in test/shots/ ab.+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-params-'));++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();+}));++// Ein Modell, wie es ein Agent schreiben könnte: Gruppen, alle Arten von Parametern und eine Grenze, an der der Code scheitert+const AGENT_MODEL = `import cadquery as cq+from soma import add_part, param++SIZE = param(40.0, "Size", min=20, max=80, unit="mm", group="Frame")+PLATES = param(2, "Plates", min=1, max=4, group="Frame", help="Number of plates stacked on the frame.")+LID = param(True, "With lid", group="Options")+FINISH = param("matte", "Finish", options={"matte": "Matte", "gloss": "Glossy"}, group="Options")+LABEL = param("SOMA", "Label")+assert SIZE <= 70, "SIZE above 70 mm does not fit the frame"++add_part("Frame", cq.Workplane("XY").box(SIZE, SIZE, 5))+for i in range(PLATES):+ add_part(f"Plate {i + 1}", cq.Workplane("XY").box(SIZE - 4, SIZE - 4, 2).translate((0, 0, 4 + 3 * i)))+if LID:+ add_part("Lid", cq.Workplane("XY").box(SIZE, SIZE, 1).translate((0, 0, 20)))+`;++try {+ app = await startApp({ name: 'params' });+ 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());+ const dir = proj.dir;+ const g = async (...args) => (await exec(args, dir)).stdout.trim();+ const modelPy = path.join(dir, 'model.py');+ const pfile = path.join(dir, 'parameters.json');+ const disk = () => fs.readFileSync(modelPy, 'utf8');+ const userFile = () => { try { return JSON.parse(fs.readFileSync(pfile, 'utf8')); } catch { return null; } };+ const vals = () => userFile()?.values ?? {};+ const ps = () => ev(() => window.__t.params());+ const builds = () => ev(() => window.__t.buildStarts());+ const size = async (name) => (await ev((n) => window.__t.partSize(n), name))?.[0];+ const buildState = () => ev(() => window.soma.build.status());+ /** Wartet auf den Build, der nach `b0` begonnen hat, und darauf, dass das Panel ihn kennt. */+ const built = async (b0, what) => {+ await waitFor(`Build nach ${what}`, (b) => window.__t.buildStarts() > b && window.__t.status().state !== 'building', 60000, b0);+ await sleep(400);+ await ev(() => window.__t.paramsRefresh());+ };+ /** Wert eingeben wie der Nutzer: ins Feld schreiben, Enter. */+ const typeValue = (name, text) => ev(([n, v]) => {+ const f = document.getElementById(`pm-${n}`);+ f.focus(); f.value = v;+ f.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));+ }, [name, text]);+ const row = (name) => `#params-list .prm[data-name="${name}"]`;+ const click = (sel) => ev((s) => document.querySelector(s).click(), sel);+ const clickText = (sel, text) => ev(([s, x]) => [...document.querySelectorAll(s)].find((b) => b.textContent.includes(x)).click(), [sel, text]);++ // 1) Leiste „Parameters“: die vier Parameter der Vorlage, alle auf dem Wert aus dem Code+ await click('#rail [data-panel="params"]');+ await waitFor('Parameter geladen', () => window.__t.params().names?.length === 4, 20000);+ let s = await ps();+ check('Leiste „Parameters“: Vorlage mit LENGTH, WIDTH, HEIGHT, WALL, Werte aus dem Code, nichts geändert',+ s.names.join(',') === 'LENGTH,WIDTH,HEIGHT,WALL' && s.shown.LENGTH === '60 mm' && s.shown.WALL === '2 mm' && !s.changed.length && !s.foot && !fs.existsSync(pfile), JSON.stringify(s.shown));+ check('Zeile: Name, Name im Code, Feld mit Einheit', s.text.includes('Length') && s.text.includes('LENGTH') && await ev(() => document.querySelector('#pm-LENGTH')?.closest('.valbox')?.textContent === 'mm'));+ await shot('params-1-panel');++ // 2) Wert ändern: landet in parameters.json, baut, der Code bleibt beim Wert des Agenten+ let b0 = await builds();+ await typeValue('LENGTH', '80');+ await built(b0, 'Length 80');+ await waitFor('Body 80 mm', () => window.__t.partSize('Body')?.[0] === 80, 20000).catch(() => {});+ s = await ps();+ check('Length 80: in parameters.json, gebaut (Body 80 mm), model.py unverändert, Zeile orange, Fußzeile',+ vals().LENGTH === 80 && await size('Body') === 80 && disk().includes('LENGTH = param(60.0') && s.changed.join(',') === 'LENGTH' && s.foot.includes('1 changed'), JSON.stringify(userFile()));+ check('parameters.json erklärt sich selbst (Notiz für den Agenten)', /Parameters panel/.test(userFile()?.note ?? ''));+ const res = (await buildState()).result;+ check('Build kennt die Parameter mit Wert und Herkunft', res?.params?.find((p) => p.name === 'LENGTH')?.value === 80 && res.params.find((p) => p.name === 'LENGTH').source === 'user'+ && res.params.find((p) => p.name === 'WIDTH').source === 'code');++ b0 = await builds();+ await typeValue('WALL', '2,5');+ await built(b0, 'Wall 2,5');+ check('Komma wird gelesen: Wall 2.5 mm', vals().WALL === 2.5 && (await ps()).shown.WALL === '2.5 mm', JSON.stringify(vals()));++ b0 = await builds();+ await typeValue('WIDTH', '40.0');+ await sleep(1500);+ check('Wert gleich dem Code: kein Eintrag, kein Build', !('WIDTH' in vals()) && await builds() === b0);++ await typeValue('HEIGHT', 'abc');+ await sleep(500);+ check('Keine Zahl: Meldung, Feld zurück, nichts geschrieben', (await ev(() => window.__t.toast())).text.includes('Height needs a number') && !('HEIGHT' in vals())+ && await ev(() => document.getElementById('pm-HEIGHT').value) === '25');++ // 3) Zurücksetzen einer Zeile: wieder der Wert des Agenten+ b0 = await builds();+ await click(`${row('LENGTH')} .rst`);+ await built(b0, 'Reset Length');+ await waitFor('Body 60 mm', () => window.__t.partSize('Body')?.[0] === 60, 20000).catch(() => {});+ check('Zurücksetzen (Zeile): Eintrag entfernt, Body wieder 60 mm, Wall bleibt 2.5', !('LENGTH' in vals()) && vals().WALL === 2.5 && await size('Body') === 60, JSON.stringify(vals()));++ // 4) Außerhalb des Bereichs: eingetragen und gebaut, rot gemeldet (E28)+ b0 = await builds();+ await typeValue('LENGTH', '250');+ await built(b0, 'Length 250');+ await click(`${row('LENGTH')} .lb`);+ s = await ps();+ check('Length 250 außerhalb 30 bis 200: gebaut, Zeile rot, Hinweis beim Aufklappen', vals().LENGTH === 250 && await size('Body') === 250 && s.errors.includes('LENGTH')+ && s.text.includes('lies outside the range') && s.open === 'LENGTH', s.text.slice(0, 300));+ check('soma build meldet den Wert außerhalb des Bereichs', ((await buildState()).result?.warnings ?? []).some((w) => w.includes('LENGTH = 250 mm (set in the app) lies outside the range 30 mm to 200 mm')));+ check('Aufgeklappt: Schieber, Wert im Code und Bereich, Stelle im Code', await ev((r) => !!document.querySelector(`${r} input[type=range]`), row('LENGTH'))+ && s.text.includes('Code: 60 mm · range 30 mm to 200 mm') && s.text.includes('model.py, line 10'), s.text.slice(0, 300));+ await shot('params-2-outside');++ b0 = await builds();+ await ev((r) => { const x = document.querySelector(`${r} input[type=range]`); x.value = '100'; x.dispatchEvent(new Event('input')); x.dispatchEvent(new Event('change')); }, row('LENGTH'));+ await built(b0, 'Schieber');+ check('Schieber: Loslassen übernimmt 100 mm', vals().LENGTH === 100 && !(await ps()).errors.includes('LENGTH'), JSON.stringify(vals()));++ await clickText(`${row('LENGTH')} .lnk`, 'line');+ await waitFor('Code offen', () => window.__t.editor.state().file === 'model.py', 10000).catch(() => {});+ const es = await ev(() => window.__t.editor.state());+ check('Sprung in den Code: model.py, Zeile von LENGTH markiert', es.file === 'model.py' && es.marked.some((m) => m.includes('LENGTH = param(60.0')), es.marked.join(' | '));+ await ev(() => { const tm = window.__t.terminals; const orig = tm.insert.bind(tm); tm.insert = (x) => { window.__inserted = x; return orig(x); }; });+ await clickText(`${row('LENGTH')} .lnk`, 'Send to agent');+ check('„Send to agent": Wert, Wert im Code und Stelle', await ev(() => window.__inserted) === '[Parameter: "Length" (LENGTH) = 100 mm, set in the app, code default 60 mm, model.py line 10] ',+ await ev(() => window.__inserted));+ await ev(() => window.__t.showCode(false));++ // 5) Alle zurücksetzen: die Datei verschwindet, das Modell ist wieder das des Agenten+ b0 = await builds();+ await clickText('#params-foot button', 'Reset all');+ await built(b0, 'Reset all');+ s = await ps();+ check('„Reset all": parameters.json entfernt, alles auf dem Wert aus dem Code, Fußzeile weg', !fs.existsSync(pfile) && !s.changed.length && !s.foot && await size('Body') === 60);++ // 6) Der Agent schreibt ein anderes Modell. Vorher von Hand: ein Wert, der nicht passt, und einer ohne Parameter+ fs.writeFileSync(pfile, JSON.stringify({ values: { PLATES: 2.5, OLD: 7 } }));+ b0 = await builds();+ fs.writeFileSync(modelPy, AGENT_MODEL);+ await waitFor('neue Parameter', (b) => window.__t.buildStarts() > b && window.__t.status().state === 'ok' && window.__t.params().names?.join(',') === 'SIZE,PLATES,LID,FINISH,LABEL', 60000, b0)+ .catch(async (e) => { console.log(JSON.stringify(await ev(() => ({ st: window.__t.status(), p: window.__t.params() })))); throw e; });+ await waitFor('4 Bauteile', () => window.__t.partCount() === 4, 20000).catch(() => {});+ s = await ps();+ const heads = await ev(() => [...document.querySelectorAll('#params-list .pg')].map((h) => h.textContent).join(','));+ check('Gruppen wie im Code, ohne Gruppe zuerst', heads === 'Frame,Options,Not in the model anymore' && s.text.indexOf('Label') < s.text.indexOf('Size'), heads);+ check('Feld nach Typ: Stepper (int), Schalter (bool), Auswahl, Textfeld', await ev(() => !!document.getElementById('pm-PLATES')?.closest('.stepper')+ && document.getElementById('pm-LID')?.getAttribute('role') === 'switch' && document.getElementById('pm-LID')?.getAttribute('aria-checked') === 'true'+ && [...document.getElementById('pm-FINISH').options].map((o) => o.textContent).join(',') === 'Matte,Glossy' && document.getElementById('pm-LABEL')?.classList.contains('pm-text')));+ check('Unpassender Wert (2.5 für eine ganze Zahl): Zeile rot, der Wert aus dem Code gilt', s.errors.includes('PLATES') && s.shown.PLATES === '2' && (await buildState()).result.warnings.some((w) => w.includes('2.5 for PLATES is not a whole number')));+ check('Wert ohne Parameter: eigener Abschnitt mit „Remove“, soma build meldet ihn', s.text.includes('OLD') && (await buildState()).result.warnings.some((w) => w.includes('no parameter OLD')));+ await shot('params-3-types');++ await clickText('#params-list .pm-orow button', 'Remove');+ await waitFor('OLD entfernt', () => !('OLD' in window.__t.params().values), 10000);+ check('„Remove": OLD aus parameters.json, PLATES bleibt', !('OLD' in vals()) && vals().PLATES === 2.5, JSON.stringify(vals()));+ b0 = await builds();+ await click(`${row('PLATES')} .rst`);+ await built(b0, 'Reset Plates');+ check('Unpassenden Wert zurücksetzen: letzter Eintrag weg, Datei weg', !fs.existsSync(pfile));++ b0 = await builds();+ await click('#pm-LID');+ await built(b0, 'Lid aus');+ await waitFor('3 Bauteile', () => window.__t.partCount() === 3, 20000).catch(() => {});+ check('Schalter aus: LID false, Deckel weg (3 Bauteile)', vals().LID === false && await ev(() => window.__t.partCount()) === 3);++ b0 = await builds();+ await ev(() => { const f = document.getElementById('pm-FINISH'); f.value = '1'; f.dispatchEvent(new Event('change')); });+ await built(b0, 'Finish');+ check('Auswahl „Glossy“: FINISH gloss, angezeigt mit Namen', vals().FINISH === 'gloss' && (await ps()).shown.FINISH === 'Glossy');++ b0 = await builds();+ await ev(() => document.querySelector('#params-list .prm[data-name="PLATES"] .stp[aria-label$="plus"]').click());+ await built(b0, 'Plates +1');+ await waitFor('4 Bauteile', () => window.__t.partCount() === 4, 20000).catch(() => {});+ check('Stepper +: PLATES 3, drei Platten ohne Deckel', vals().PLATES === 3 && await ev(() => window.__t.partCount()) === 4, JSON.stringify(vals()));++ b0 = await builds();+ await typeValue('LABEL', 'Hallo Welt');+ await built(b0, 'Label');+ check('Text: LABEL steht als Text in parameters.json', vals().LABEL === 'Hallo Welt');++ await clickText('#params-list .pg', 'Frame');+ s = await ps();+ check('Gruppe einklappen: Zeilen weg, Kopf nennt Anzahl und Änderungen', !s.text.includes('Size') && (await ev(() => [...document.querySelectorAll('#params-list .pg')].map((h) => h.textContent).join('|'))).includes('Frame· 2, 1 changed'));+ await clickText('#params-list .pg', 'Frame');++ // 7) Build scheitert nach einer Änderung: Panel bleibt bedienbar und bietet den Wert davor an (nicht selbst zurücknehmen)+ b0 = await builds();+ await typeValue('SIZE', '75');+ await built(b0, 'Size 75');+ s = await ps();+ check('Size 75: Build scheitert, Panel zeigt die Parameter weiter und bietet „Back to 40 mm“', (await ev(() => window.__t.status().state)) === 'error' && vals().SIZE === 75+ && s.names?.length === 5 && s.text.includes('The build failed after Size was set to 75 mm.') && s.text.includes('Back to 40 mm'), s.text.slice(0, 200));+ await shot('params-4-failed');+ b0 = await builds();+ await clickText('#params-list .pm-fail button', 'Back to');+ await built(b0, 'Back to');+ check('„Back to 40 mm": Eintrag weg, Build wieder ok, Hinweis weg', !('SIZE' in vals()) && (await ev(() => window.__t.status().state)) === 'ok' && !(await ps()).text.includes('The build failed'));++ // 8) Fehler im Code vor den Parametern: Die Liste des vorigen Builds bleibt, mit Hinweis+ b0 = await builds();+ fs.writeFileSync(modelPy, `x = (\n${AGENT_MODEL}`);+ await waitFor('Fehler', (b) => window.__t.buildStarts() > b && window.__t.status().state === 'error', 60000, b0);+ await sleep(400);+ await ev(() => window.__t.paramsRefresh());+ s = await ps();+ check('Syntaxfehler vor den Parametern: Liste bleibt (stale), Werte weiter änderbar', s.stale && s.names?.length === 5 && s.text.includes('The list is from an earlier build') && !!(await ev(() => document.getElementById('pm-SIZE'))));+ b0 = await builds();+ fs.writeFileSync(modelPy, AGENT_MODEL);+ await waitFor('wieder ok', (b) => window.__t.buildStarts() > b && window.__t.status().state === 'ok', 60000, b0);+ await ev(() => window.__t.paramsRefresh());+ check('Code wieder in Ordnung: Hinweis weg', !(await ps()).stale);++ // 9) Kaputte parameters.json (etwa von Hand): melden, nicht überschreiben (E28)+ const before = '{ "values": { "SIZE": 50, } }';+ b0 = await builds();+ fs.writeFileSync(pfile, before);+ await waitFor('Build nach kaputter Datei', (b) => window.__t.buildStarts() > b && window.__t.status().state !== 'building', 60000, b0);+ await ev(() => window.__t.paramsRefresh());+ s = await ps();+ check('Kaputte Datei: Hinweis im Panel, soma build meldet sie, Werte aus dem Code', /not valid JSON/.test(s.error ?? '') && s.text.includes('not valid JSON')+ && ((await buildState()).result?.warnings ?? []).some((w) => w.includes('parameters.json cannot be read')), s.error ?? '');+ await typeValue('SIZE', '30');+ await sleep(600);+ check('Ändern bei kaputter Datei: abgelehnt mit Meldung, Datei unverändert', fs.readFileSync(pfile, 'utf8') === before && (await ev(() => window.__t.toast())).text.includes('Nothing was changed'));+ b0 = await builds();+ fs.rmSync(pfile);+ await waitFor('Build nach Löschen', (b) => window.__t.buildStarts() > b && window.__t.status().state !== 'building', 60000, b0);+ await ev(() => window.__t.paramsRefresh());+ check('Datei gelöscht (Nutzer): Hinweis weg, Werte aus dem Code', !(await ps()).error && !Object.keys((await ps()).values).length);++ // 10) Speichern: parameters.json im Snapshot und in der ZIP+ b0 = await builds();+ await typeValue('SIZE', '50');+ await built(b0, 'Size 50');+ const zipPath = path.join(workDir, 'Parameter.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; });+ check('Snapshot enthält parameters.json mit dem Wert', JSON.parse(await g('show', 'HEAD:parameters.json')).values.SIZE === 50);+ check('ZIP enthält parameters.json', (await listZip(zipPath)).includes('parameters.json'));+ b0 = await builds();+ await typeValue('SIZE', '55');+ await built(b0, 'Size 55');+ check('Geänderter Wert zählt als ungespeicherte Änderung', await waitFor('ungespeichert', () => window.__t.saveState()?.unsaved, 10000).catch(() => false));++ // 11) Modell ohne Parameter: leerer Zustand mit Bitte an den Agenten+ b0 = await builds();+ fs.writeFileSync(modelPy, 'import cadquery as cq\nfrom soma import add_part\n\nadd_part("Block", cq.Workplane("XY").box(10, 10, 10))\n');+ await waitFor('ohne Parameter', (b) => window.__t.buildStarts() > b && window.__t.status().state === 'ok' && window.__t.params().names?.length === 0, 60000, b0);+ s = await ps();+ check('Ohne Parameter: leerer Zustand mit Erklärung, SIZE als Wert ohne Parameter', s.text.includes('This model has no parameters yet') && s.text.includes('Ask the agent') && s.text.includes('SIZE'));+ await clickText('#params-list .pm-empty button', 'Ask the agent');+ check('„Ask the agent" fügt die Bitte in die Eingabe ein', (await ev(() => window.__inserted)).startsWith('Make the main dimensions of the model adjustable with param()'));+ await shot('params-5-empty');++ 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);+ if (app) console.log(app.log().slice(-1500));+ t.fail();+}+if (app) { await app.stop(); cleanup(app.ud); }+cleanup(workDir);+console.log(t.fails ? `\n${t.fails} Prüfung(en) fehlgeschlagen` : '\nALLE PRÜFUNGEN BESTANDEN');+process.exit(t.fails ? 1 : 0);diff --git a/app/test/run-all.mjs b/app/test/run-all.mjsindex b5d0a2f..f51d07b 100644--- a/app/test/run-all.mjs+++ b/app/test/run-all.mjs@@ -9,7 +9,7 @@ import path from 'node:path';const DIR = import.meta.dirname;// Längste zuerst, damit sie nicht am Ende allein laufen-const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'explode', 'fasteners', 'section', 'measure', 'groups', 'packages', 'unit'];+const ALL = ['animation', 'fem', 'versions', 'smoke', 'editor', 'skills', 'params', 'explode', 'fasteners', 'section', 'measure', 'groups', 'packages', 'unit'];const wanted = process.argv.slice(2);const unknown = wanted.filter((s) => !ALL.includes(s));if (unknown.length) { console.log(`Unbekannte Suite: ${unknown.join(', ')}. Vorhanden: ${ALL.join(', ')}`); process.exit(2); }diff --git a/app/test/unit.mjs b/app/test/unit.mjsindex 1d077b5..18f6f08 100644--- a/app/test/unit.mjs+++ b/app/test/unit.mjs@@ -218,10 +218,42 @@ try {// Animationsdateien (E58): bauen die Animation neu, nicht das Modellconst ed = path.join(tmp, 'editable.mjs');await build({ entryPoints: [path.join(APP, 'src', 'shared', 'editable.ts')], outfile: ed, bundle: true, platform: 'node', format: 'esm', logLevel: 'silent' });- const { affectsBuild, affectsAnimation } = await import(pathToFileURL(ed).href);+ const { affectsBuild, affectsAnimation, readOnlyReason, fileOpBlockReason } = await import(pathToFileURL(ed).href);check('animations/*.py: Animation, kein Model-Build. model.py, parts/, inputs/ bauen das Modell', affectsAnimation('animations/deckel.py') && affectsAnimation('animations\\x.py')&& !affectsBuild('animations/deckel.py') && affectsBuild('model.py') && affectsBuild('parts/lid.py') && affectsBuild('inputs/a.step')&& !affectsAnimation('animations/sub/x.py') && !affectsAnimation('model.py') && !affectsAnimation('animations/notes.md'));+ check('parameters.json baut das Modell, ist im Editor nur lesbar, Umbenennen gesperrt, Löschen erlaubt', affectsBuild('parameters.json') && !affectsBuild('parts/parameters.json')+ && !!readOnlyReason('parameters.json') && !!fileOpBlockReason('parameters.json', 'rename') && fileOpBlockReason('parameters.json', 'delete') === null);++ // Werte aus dem Parameter-Panel (parameters.json): lesen, prüfen, schreiben, beim letzten Eintrag die Datei entfernen+ const pmOut = path.join(tmp, 'params.mjs');+ await build({ entryPoints: [path.join(APP, 'src', 'main', 'params.ts')], outfile: pmOut, bundle: true, platform: 'node', format: 'esm', logLevel: 'silent' });+ const { readUserParams, writeUserParams, checkParamValue } = await import(pathToFileURL(pmOut).href);+ const pdir = path.join(tmp, 'params-projekt');+ fs.mkdirSync(pdir);+ const pfile = path.join(pdir, 'parameters.json');+ check('Ohne parameters.json: keine Werte, kein Fehler', JSON.stringify(readUserParams(pdir)) === '{"rest":{},"values":{}}');+ let perr = writeUserParams(pdir, { BORE: 40, LID: false, NAME: 'Grüße' });+ let pj = JSON.parse(fs.readFileSync(pfile, 'utf8'));+ check('Schreiben: Werte unter „values“, Notiz für den Agenten, keine Zwischendatei', perr === null && pj.values.BORE === 40 && pj.values.LID === false && pj.values.NAME === 'Grüße'+ && /Parameters panel/.test(pj.note) && fs.readdirSync(pdir).join(',') === 'parameters.json', JSON.stringify(pj));+ fs.writeFileSync(pfile, '' + JSON.stringify({ note: 'x', variants: { a: 1 }, values: { BORE: 40, BAD: [1], N: Infinity } }));+ check('Lesen: BOM erlaubt, unbrauchbare Werte fallen weg, fremde Schlüssel bleiben', JSON.stringify(readUserParams(pdir).values) === '{"BORE":40}' && readUserParams(pdir).rest.variants?.a === 1);+ perr = writeUserParams(pdir, { BORE: null });+ pj = JSON.parse(fs.readFileSync(pfile, 'utf8'));+ check('Letzter Wert entfernt, aber fremder Inhalt: Datei bleibt mit leeren Werten', perr === null && JSON.stringify(pj.values) === '{}' && pj.variants?.a === 1);+ fs.writeFileSync(pfile, JSON.stringify({ values: { A: 1 } }));+ check('Letzter Wert entfernt, sonst nichts: Datei verschwindet', writeUserParams(pdir, { A: null }) === null && !fs.existsSync(pfile));+ fs.writeFileSync(pfile, '{ kaputt');+ perr = writeUserParams(pdir, { A: 2 });+ check('Kaputte Datei: gemeldet, nicht überschrieben (melden statt reparieren)', /not valid JSON/.test(readUserParams(pdir).error ?? '') && /Nothing was changed/.test(perr ?? '')+ && fs.readFileSync(pfile, 'utf8') === '{ kaputt', perr ?? '');+ check('Ungültiger Name wird abgelehnt', /not a parameter name/.test(writeUserParams(path.join(tmp, 'leer-' + process.pid), { 'a-b': 1 }) ?? ''));+ const def = (kind, extra = {}) => ({ name: 'X', label: 'X', kind, default: 1, value: 1, source: 'code', min: null, max: null, step: null, unit: null, options: null, group: null, help: null, file: 'model.py', line: 1, ...extra });+ check('Prüfung nach Typ: Zahl, ganze Zahl, Schalter, Auswahl, Text; Bereich zählt nicht', checkParamValue(def('number', { max: 5 }), 99) === null && !!checkParamValue(def('number'), 'a')+ && !!checkParamValue(def('int'), 1.5) && checkParamValue(def('int'), 3) === null && !!checkParamValue(def('bool'), 1) && checkParamValue(def('bool'), true) === null+ && checkParamValue(def('choice', { options: [{ value: 'a', label: 'A' }] }), 'a') === null && !!checkParamValue(def('choice', { options: [{ value: 'a', label: 'A' }] }), 'b')+ && checkParamValue(def('text'), 'hallo') === null && !!checkParamValue(def('text'), 5));// Zwischenergebnisse der App (Ergebnisse von soma analyze bis 70 MB) nicht in Snapshot und ZIP, auch in älteren// Projekten ohne die Einträge in der .gitignore. dugite (und die CommonJS-Pakete für ZIP) bleiben extern, das Bündeldiff --git a/app/test/versions.mjs b/app/test/versions.mjsindex 15949fb..674c956 100644--- a/app/test/versions.mjs+++ b/app/test/versions.mjs@@ -54,7 +54,7 @@ try {// ---- 2) Agent committet selbst ----const src = fs.readFileSync(modelPy, 'utf8');- fs.writeFileSync(modelPy, src.replace('LENGTH = 60.0', 'LENGTH = 80.0'));+ fs.writeFileSync(modelPy, src.replace('LENGTH = param(60.0', 'LENGTH = param(80.0'));await waitFor('Build mit Länge 80', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] > 79);check('Änderung am Modell erscheint im Viewer (Body 80 mm lang)', (await ev(() => window.__t.partSize('Body')))[0] === 80);await waitFor('ungesicherte Änderung', () => window.__t.versions().dirtyFiles === 1);@@ -117,7 +117,7 @@ try {await sleep(800); // capturePage liefert bei unsichtbaren Fenstern sonst ein etwas älteres Bildconst shot = await app.screenshot(path.join(import.meta.dirname, 'versions.png')).catch((e) => ({ error: String(e) }));check('Screenshot der Vorschau (Verlaufsleiste sichtbar)', !!shot.width, shot.width ? `${shot.width}x${shot.height}` : shot.error);- check('Arbeitsordner blieb unberührt (model.py hat weiter 80)', fs.readFileSync(modelPy, 'utf8').includes('LENGTH = 80.0'));+ check('Arbeitsordner blieb unberührt (model.py hat weiter 80)', fs.readFileSync(modelPy, 'utf8').includes('LENGTH = param(80.0'));check('Kein neuer Commit durch die Vorschau', (await g('rev-list', '--count', 'HEAD')) === commitsBefore);fs.appendFileSync(modelPy, '\n# Kommentar während der Vorschau\n');await sleep(4000);@@ -142,7 +142,7 @@ try {check('Gleich nach dem Wiederherstellen ist der wiederhergestellte Stand zu sehen (Body 60, nicht 80)', (await ev(() => window.__t.partSize('Body')))[0] === 60);check('Wiederherstellen legt einen NEUEN Commit an', (await g('log', '-1', '--format=%s')).startsWith('Restored version: New model created'));check('Verlauf blieb vollständig (alter Startcommit unverändert vorhanden)', (await g('cat-file', '-t', first)) === 'commit' && (await g('rev-list', '--count', 'HEAD')) > commitsBefore);- check('Dateien sind zurück: model.py mit 60, Notiz-Wunsch entfernt', fs.readFileSync(modelPy, 'utf8').includes('LENGTH = 60.0') && !fs.readFileSync(path.join(dir, 'NOTES.md'), 'utf8').includes('Wunsch'));+ check('Dateien sind zurück: model.py mit 60, Notiz-Wunsch entfernt', fs.readFileSync(modelPy, 'utf8').includes('LENGTH = param(60.0') && !fs.readFileSync(path.join(dir, 'NOTES.md'), 'utf8').includes('Wunsch'));await waitFor('Build nach Wiederherstellung', () => window.__t.status().state === 'ok' && (window.__t.partSize('Body') || [0])[0] === 60);check('Live-Ansicht zeigt wieder den (wiederhergestellten) Stand, Body 60 mm', true);check('Kein HEAD-Umbau: Branch ist weiter main, nicht detached', (await g('symbolic-ref', '--short', 'HEAD')) === 'main');@@ -194,7 +194,7 @@ try {await app.answers([zipPath]);await domClick('btn-open');await waitFor('entpackt und geöffnet', (id) => window.__t.project().id === id && window.__t.status().state === 'ok' && window.__t.versions().count > 1, 90000, proj.id);- check('Arbeitsordner fehlt (anderer Rechner): ZIP wird entpackt und geöffnet', fs.existsSync(modelPy) && fs.readFileSync(modelPy, 'utf8').includes('LENGTH = 60.0'));+ check('Arbeitsordner fehlt (anderer Rechner): ZIP wird entpackt und geöffnet', fs.existsSync(modelPy) && fs.readFileSync(modelPy, 'utf8').includes('LENGTH = param(60.0'));check('Der Verlauf ist mitgekommen (gleiche Commits wie vorher)', (await g('log', '--format=%s')) === logBefore);// Der Build ist oft schneller da als der Speicherstand des neuen Modells (bis dahin gilt noch der des vorherigen)await waitFor('Speicherstand', () => window.__t.saveState() && !window.__t.saveState().unsaved, 15000).catch(() => {});