Skip to content

armgit / SOMA

Public Imported from GitHub
0

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

App: Linie und Raster beim Markieren, Dateibrowser mit Menü, Einfügen ins laufende Terminal

Kai-Jungsthoefel6f7833785892
diff --git a/app/README.md b/app/README.md
index 1013489..d69d35f 100644
--- a/app/README.md
+++ b/app/README.md
@@ -15,8 +15,8 @@ Electron-App (TypeScript) für 3D-Modelle mit einem Coding-Agenten im Terminal.
npm install
npm start # baut und startet
npm run typecheck
-npm run test:unit # Bausteine ohne Electron: Dateien und Ordner nach inputs/, Markierung nach .soma/feedback/, Pfadschutz, Schreiben aus dem Editor mit Konfliktprüfung, App-Icon, Einstellungen, Kategorien und Standard der Skills (29 Prüfungen)
-npm run test:smoke # echte App, unsichtbar: Projekt, Viewer, Auswahl, Panels, Terminal, Übergabe an den Agenten, Markierung (Zeichnen, Auswählen, Verschieben, Drehen, Skalieren, Farben), Auto-Build, Fehlerfall, Export, Ansichtswürfel und Drehpunkt (61 Prüfungen)
+npm run test:unit # Bausteine ohne Electron: Dateien und Ordner nach inputs/, Anlegen, Umbenennen und Papierkorb im Dateibaum, Markierung nach .soma/feedback/, Pfadschutz, Schreiben aus dem Editor mit Konfliktprüfung, App-Icon, Einstellungen, Kategorien und Standard der Skills (42 Prüfungen)
+npm run test:smoke # echte App, unsichtbar: Projekt, Viewer, Auswahl, Panels, Terminal, Übergabe an den Agenten, Markierung (Zeichnen, Linie, Raster, Auswählen, Verschieben, Drehen, Skalieren, Farben, Bild aus dem Dateibaum), Dateibaum (Markierungen, Menü, Anlegen, Umbenennen, Papierkorb), Auto-Build, Fehlerfall, Export, Ansichtswürfel und Drehpunkt (76 Prüfungen)
npm run test:versions # Git-Verlauf, Speichern, Öffnen, Vorschau (auch markiert), Wiederherstellen, Störfälle (53 Prüfungen)
npm run test:editor # Editor: Höhe und Scrollen, Speichern nur auf Wunsch mit genau einem Build (nur bei Python und inputs/), Änderungen des Agenten, Konflikte mit Sicherung, Nur lesen, CRLF, Rückfragen bei Modellwechsel und Reiter schließen (29 Prüfungen)
npm run test:measure # Messen: Fläche, Kante, Punkt, Abstand paralleler Ebenen, zweier Bohrungen, zweier Punkte, Punkt zur Ebene, Verdecktes, neuer Build, Vorschau (21 Prüfungen)
diff --git a/app/src/main/files.ts b/app/src/main/files.ts
index 772b414..2c51400 100644
--- a/app/src/main/files.ts
+++ b/app/src/main/files.ts
@@ -1,7 +1,7 @@
import fs from 'node:fs';
import path from 'node:path';
-import { readOnlyReason } from '../shared/editable';
-import type { FeedbackResult, FileNode, ImportResult, WriteResult } from '../shared/types';
+import { fileOpBlockReason, readOnlyReason } from '../shared/editable';
+import type { FeedbackResult, FileNode, FileOpResult, ImportResult, WriteResult } from '../shared/types';
const HIDDEN = new Set(['.git', '.soma', '__pycache__', 'node_modules', '.venv', 'venv', 'env']);
const MAX_ENTRIES = 2000;
@@ -89,6 +89,113 @@ function scanFolder(src: string): FolderScan {
return scan;
}
+// ---- Dateibaum: anlegen, umbenennen, löschen, öffnen ---------------------------------------------------------
+
+/** Unter Windows verbotene Namen (auch mit Endung, etwa „con.txt“). */
+const RESERVED = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i;
+/**
+ * Dateien, die beim Öffnen mit dem Standardprogramm etwas ausführen würden. Der Arbeitsordner ist nicht vertrauenswürdig
+ * (der Agent schreibt dort), ein Klick im Dateibaum darf kein Programm starten. Python-Dateien öffnet das Code-Panel.
+ */
+const RUNNABLE = /\.(exe|com|bat|cmd|ps1|psm1|psd1|vbs|vbe|js|jse|mjs|wsf|wsh|msi|msp|scr|pif|lnk|url|hta|cpl|jar|reg|py|pyw|pyz|sh|appref-ms|application|msc|scf|inf|settingcontent-ms)$/i;
+
+const errMsg = (e: unknown) => (e instanceof Error ? e.message : String(e));
+
+/** Fehler im Namen einer neuen oder umbenannten Datei, sonst null. Nur ein Name, kein Pfad. */
+export function nameError(name: string): string | null {
+ if (!name.trim()) return 'Der Name ist leer.';
+ if (name !== name.trim()) return 'Der Name beginnt oder endet mit einem Leerzeichen.';
+ if (/[\\/:*?"<>|\x00-\x1f]/.test(name)) return 'Diese Zeichen gehen in Namen nicht: \\ / : * ? " < > |';
+ if (name === '.' || name === '..') return 'Dieser Name geht nicht.';
+ if (/\.$/.test(name)) return 'Der Name darf nicht mit einem Punkt enden.';
+ if (RESERVED.test(name)) return `„${name}“ ist unter Windows ein reservierter Name.`;
+ if (name.length > 200) return 'Der Name ist zu lang.';
+ return null;
+}
+
+/** Pfad aus dem Renderer in die feste Form „a/b“ bringen. „..“ wird abgelehnt, damit die Regeln nicht umgangen werden. */
+function cleanRel(rel: string): string {
+ // normalize nimmt „./“ vorne schon weg. Nur „.“ allein ist der Projektordner, „.soma“ bleibt „.soma“.
+ const p = path.posix.normalize(String(rel).replace(/\\/g, '/')).replace(/\/$/, '');
+ if (p === '.' || p === '') return '';
+ if (p === '..' || p.startsWith('../') || path.posix.isAbsolute(p) || /^[a-z]:/i.test(p)) throw new Error(`Pfad liegt ausserhalb des Projekts: ${rel}`);
+ return p;
+}
+
+const joinRel = (parent: string, name: string) => (parent ? `${parent}/${name}` : name);
+
+/** Neue, leere Datei oder neuer Ordner. Gibt es den Namen schon, wird nichts angelegt. */
+export function createEntry(root: string, parent: string, name: string, dir: boolean): FileOpResult {
+ try {
+ const base = cleanRel(parent);
+ const bad = nameError(name);
+ if (bad) return { ok: false, error: bad };
+ const rel = joinRel(base, name);
+ const block = fileOpBlockReason(base, 'create') ?? fileOpBlockReason(rel, 'create');
+ if (block) return { ok: false, error: `Hier lässt sich nichts anlegen. ${block}` };
+ const parentAbs = resolveInside(root, base || '.');
+ if (!fs.statSync(parentAbs).isDirectory()) return { ok: false, error: `${base} ist kein Ordner.` };
+ const abs = resolveInside(root, rel);
+ // Ohne recursive bzw. mit „wx“: Entsteht der Name gleichzeitig, schlägt das fehl statt zu überschreiben
+ if (dir) fs.mkdirSync(abs); else fs.writeFileSync(abs, '', { flag: 'wx' });
+ return { ok: true, path: rel };
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'EEXIST') return { ok: false, error: `„${name}“ gibt es dort schon.` };
+ return { ok: false, error: errMsg(e) };
+ }
+}
+
+/** Umbenennen im selben Ordner. Gibt es den neuen Namen schon, bleibt alles, wie es ist. Nur Groß-/Kleinschreibung ändern geht. */
+export function renameEntry(root: string, rel: string, name: string): FileOpResult {
+ try {
+ const from = cleanRel(rel);
+ const block = fileOpBlockReason(from, 'rename');
+ if (block) return { ok: false, error: `${from} lässt sich nicht umbenennen. ${block}` };
+ const bad = nameError(name);
+ if (bad) return { ok: false, error: bad };
+ const old = path.posix.basename(from);
+ const to = joinRel(path.posix.dirname(from) === '.' ? '' : path.posix.dirname(from), name);
+ if (name === old) return { ok: true, path: from };
+ const blockTo = fileOpBlockReason(to, 'create');
+ if (blockTo) return { ok: false, error: `Dieser Name geht hier nicht. ${blockTo}` };
+ const abs = resolveInside(root, from);
+ if (fs.lstatSync(abs).isSymbolicLink()) return { ok: false, error: 'Verknüpfungen lassen sich hier nicht umbenennen.' };
+ const target = resolveInside(root, to);
+ // Windows und macOS unterscheiden Groß und klein nicht: „Teil.py“ → „teil.py“ findet sich selbst als vorhanden
+ const caseOnly = name.toLowerCase() === old.toLowerCase();
+ if (!caseOnly && exists(target)) return { ok: false, error: `„${name}“ gibt es dort schon.` };
+ fs.renameSync(abs, target);
+ return { ok: true, path: to };
+ } catch (e) { return { ok: false, error: errMsg(e) }; }
+}
+
+/**
+ * Verschiebt in den Papierkorb (`trash`, im Hauptprozess `shell.trashItem`). Klappt das nicht, wird nichts gelöscht:
+ * endgültiges Löschen gibt es im Dateibaum nicht (Grundsatz: nichts still löschen).
+ */
+export async function trashEntry(root: string, rel: string, trash: (abs: string) => Promise<void>): Promise<FileOpResult> {
+ try {
+ const p = cleanRel(rel);
+ const block = fileOpBlockReason(p, 'delete');
+ if (block) return { ok: false, error: `${p} lässt sich nicht löschen. ${block}` };
+ const abs = resolveInside(root, p);
+ fs.lstatSync(abs);
+ try { await trash(abs); } catch (e) { return { ok: false, error: `${p} ließ sich nicht in den Papierkorb verschieben, es wurde nichts gelöscht: ${errMsg(e)}` }; }
+ return { ok: true, path: p };
+ } catch (e) { return { ok: false, error: errMsg(e) }; }
+}
+
+/** Prüft einen Pfad zum Zeigen oder Öffnen und gibt den absoluten Pfad zurück. */
+export function entryPath(root: string, rel: string, forOpen: boolean): { abs?: string; error?: string } {
+ try {
+ const p = cleanRel(rel);
+ const abs = resolveInside(root, p || '.');
+ const st = fs.statSync(abs);
+ if (forOpen && st.isFile() && RUNNABLE.test(p)) return { error: `${path.posix.basename(p)} könnte beim Öffnen ein Programm starten. SOMA öffnet solche Dateien nicht, „Im Explorer zeigen“ geht.` };
+ return { abs };
+ } catch (e) { return { error: errMsg(e) }; }
+}
+
/**
* Legt ein Bild der Markierung in .soma/feedback/ ab (E16). Dort ist es nicht in Git (E11), wandert aber mit der ZIP.
* Der Name trägt Datum und Uhrzeit, bei Gleichstand kommt „-2“ dazu. Vorhandenes wird nie überschrieben.
@@ -192,5 +299,14 @@ export function listFiles(root: string): FileNode[] {
}
return nodes.sort((a, b) => Number(b.dir) - Number(a.dir) || a.name.localeCompare(b.name));
};
- return walk(root, '', 0);
+ const nodes = walk(root, '', 0);
+ // Markierungen (E16) liegen versteckt in .soma/feedback/. Der Nutzer soll sie wiederfinden und erneut an den Agenten
+ // geben können, deshalb kommt nur dieser Ordner mit. Neueste zuerst (der Name beginnt mit Datum und Uhrzeit).
+ const fb = path.join(root, '.soma', 'feedback');
+ try {
+ if (fs.lstatSync(fb).isDirectory() && !fs.lstatSync(path.join(root, '.soma')).isSymbolicLink()) {
+ nodes.push({ name: 'feedback', path: '.soma/feedback', dir: true, children: walk(fb, '.soma/feedback', 1).reverse() });
+ }
+ } catch { /* noch keine Markierung */ }
+ return nodes;
}
diff --git a/app/src/main/main.ts b/app/src/main/main.ts
index 1c307b8..6021805 100644
--- a/app/src/main/main.ts
+++ b/app/src/main/main.ts
@@ -1,12 +1,14 @@
-import { app, BrowserWindow, dialog, ipcMain, type WebContents } from 'electron';
+import { app, BrowserWindow, dialog, ipcMain, shell, type WebContents } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
import { detectAgents } from './agents';
import { choose, setTestAnswers } from './dialogs';
-import { backupText, importInputs, listFiles, resolveInside, saveFeedbackImage, writeProjectText } from './files';
+import { backupText, createEntry, entryPath, importInputs, listFiles, renameEntry, resolveInside, saveFeedbackImage, trashEntry, writeProjectText } from './files';
import { ProjectController } from './projects';
import { terminalEnv } from './terminals';
import { appIcon, editBackupsDir, thumbnailsDir } from './paths';
+import { fileOpBlockReason } from '../shared/editable';
+import type { FileOpResult } from '../shared/types';
import { createProject, getLastProject, isProjectId } from './workspace';
// App-Daten (Arbeitsordner, Caches) gehören auf die lokale Platte. Das Roaming-Profil (%APPDATA%) kann in Firmennetzen
@@ -50,6 +52,39 @@ function registerIpc(ctl: ProjectController): void {
ipcMain.handle('fs:list', () => listFiles(dir()));
ipcMain.handle('fs:import', (_e, paths: string[]) => importInputs(dir(), Array.isArray(paths) ? paths.map(String) : []));
+ ipcMain.handle('fs:create', (_e, parent: string, name: string, isDir: boolean) => createEntry(dir(), String(parent ?? ''), String(name ?? ''), !!isDir));
+ ipcMain.handle('fs:rename', (_e, rel: string, name: string) => renameEntry(dir(), String(rel ?? ''), String(name ?? '')));
+ ipcMain.handle('fs:trash', async (_e, rel: string): Promise<FileOpResult> => {
+ const root = dir();
+ const r = entryPath(root, String(rel ?? ''), false);
+ if (!r.abs) return { ok: false, error: r.error };
+ // Gesperrtes gar nicht erst zur Rückfrage bringen (trashEntry prüft danach noch einmal mit bereinigtem Pfad)
+ const block = fileOpBlockReason(String(rel), 'delete');
+ if (block) return { ok: false, error: `${rel} lässt sich nicht löschen. ${block}` };
+ const isDir = fs.statSync(r.abs).isDirectory();
+ // Die Rückfrage stellt der Hauptprozess: So beantworten Tests sie wie alle anderen Dialoge (dialogs.ts)
+ const c = await choose(win, {
+ title: 'Löschen',
+ message: isDir ? `Den Ordner „${path.basename(r.abs)}“ mit allem darin in den Papierkorb verschieben?` : `„${path.basename(r.abs)}“ in den Papierkorb verschieben?`,
+ detail: 'Aus dem Papierkorb lässt es sich wiederherstellen. Gespeicherte Stände im Verlauf bleiben ohnehin erhalten.',
+ buttons: ['In den Papierkorb', 'Abbrechen'],
+ });
+ if (c !== 0) return { ok: false, canceled: true };
+ return trashEntry(root, String(rel), (abs) => trashItem(abs));
+ });
+ ipcMain.handle('fs:reveal', (_e, rel: string): FileOpResult => {
+ const r = entryPath(dir(), String(rel ?? ''), false);
+ if (!r.abs) return { ok: false, error: r.error };
+ if (process.env.SOMA_TEST !== '1') shell.showItemInFolder(r.abs);
+ return { ok: true, path: String(rel ?? '') };
+ });
+ ipcMain.handle('fs:openExternal', async (_e, rel: string): Promise<FileOpResult> => {
+ const r = entryPath(dir(), String(rel ?? ''), true);
+ if (!r.abs) return { ok: false, error: r.error };
+ if (process.env.SOMA_TEST === '1') return { ok: true, path: String(rel ?? '') };
+ const err = await shell.openPath(r.abs);
+ return err ? { ok: false, error: err } : { ok: true, path: String(rel ?? '') };
+ });
ipcMain.handle('fs:saveFeedback', (_e, png: unknown) => saveFeedbackImage(dir(), png));
ipcMain.handle('fs:writeText', (_e, id: string, rel: string, text: string, base: string | null, force?: boolean) => {
const s = ctl.session;
@@ -113,6 +148,17 @@ function onRendererGone(wc: WebContents, reason: string, exitCode: number): void
void wc;
}
+/**
+ * Papierkorb. Im Testmodus ein eigener Ordner in den App-Daten: Tests sollen den Papierkorb des Nutzers nicht füllen
+ * und prüfen können, was dort gelandet ist.
+ */
+async function trashItem(abs: string): Promise<void> {
+ if (process.env.SOMA_TEST !== '1') { await shell.trashItem(abs); return; }
+ const bin = path.join(app.getPath('userData'), 'test-papierkorb');
+ fs.mkdirSync(bin, { recursive: true });
+ fs.renameSync(abs, path.join(bin, `${Date.now()}-${path.basename(abs)}`));
+}
+
let editorReq = 0;
/**
* Fragt den Editor im Renderer: `status` (welche Dateien ungespeichert sind), `save` (speichern), `discard` (verwerfen,
diff --git a/app/src/main/terminals.ts b/app/src/main/terminals.ts
index 166b320..47b2f9d 100644
--- a/app/src/main/terminals.ts
+++ b/app/src/main/terminals.ts
@@ -16,10 +16,16 @@ export function terminalEnv(projectDir: string): NodeJS.ProcessEnv {
return env;
}
+/**
+ * Nummern der Terminals, fortlaufend über alle Projekte. Beim Modellwechsel endet die alte Shell erst nach dem Wechsel,
+ * ihre Daten und ihr „beendet“ kommen dann noch an. Finge jedes Projekt wieder bei 1 an, landeten sie beim neuen Terminal
+ * mit derselben Nummer: Es galt als beendet, und Auswahl oder Markierung ließen sich nicht mehr einfügen.
+ */
+let nextId = 1;
+
/** Verwaltet die Terminals eines Projekts. Jedes ist eine normale Shell im Projektordner (E19). */
export class TerminalManager {
private terms = new Map<number, pty.IPty>();
- private next = 1;
constructor(private readonly wc: WebContents, private readonly dir: string) {}
@@ -29,7 +35,7 @@ export class TerminalManager {
const p = pty.spawn(shell, win ? ['-NoLogo'] : [], {
name: 'xterm-256color', cols: 100, rows: 30, cwd: this.dir, env: terminalEnv(this.dir) as Record<string, string>,
});
- const id = this.next++;
+ const id = nextId++;
this.terms.set(id, p);
p.onData((d) => { if (!this.wc.isDestroyed()) this.wc.send('term:data', id, d); });
p.onExit(({ exitCode }) => {
diff --git a/app/src/main/watcher.ts b/app/src/main/watcher.ts
index cd93613..e32e655 100644
--- a/app/src/main/watcher.ts
+++ b/app/src/main/watcher.ts
@@ -5,6 +5,8 @@ import { affectsBuild } from '../shared/editable';
const IGNORED_TOP = new Set(['.git', '.soma', 'output', 'exports', '__pycache__', 'node_modules', '.venv', 'venv', 'env']);
const topSegment = (rel: string) => rel.split(/[\\/]/)[0] ?? '';
+/** Markierungen (E16) stehen im Dateibaum: Änderungen dort frischen die Liste auf, bauen aber nie. */
+const isFeedback = (rel: string) => /^\.soma[\\/]feedback([\\/]|$)/i.test(rel);
const isIgnored = (rel: string) => IGNORED_TOP.has(topSegment(rel)) || rel.split(/[\\/]/).includes('__pycache__');
/** Quelltext-Aenderung: dieselbe Regel wie beim Speichern im Editor (src/shared/editable.ts). */
const isSource = affectsBuild;
@@ -19,8 +21,8 @@ export function watchProject(dir: string, onSource: (rel: string | null) => void
try {
watcher = fs.watch(dir, { recursive: true }, (_evt, filename) => {
const rel = filename ? String(filename) : '';
- if (rel && isIgnored(rel)) return;
- if (!rel || isSource(rel)) onSource(rel || null);
+ if (rel && isIgnored(rel) && !isFeedback(rel)) return;
+ if (!rel || (isSource(rel) && !isFeedback(rel))) onSource(rel || null);
if (filesTimer) clearTimeout(filesTimer);
filesTimer = setTimeout(onFiles, 250);
});
diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.ts
index 450b7d0..7dc54bd 100644
--- a/app/src/preload/preload.ts
+++ b/app/src/preload/preload.ts
@@ -39,6 +39,11 @@ const api: SomaApi = {
onChanged: (cb) => { ipcRenderer.on('fs:changed', () => cb()); },
// Der Renderer kennt keine Dateipfade. Nur die Pfade gezogener Dateien gehen an den Hauptprozess, der prüft und kopiert.
importFiles: (files) => ipcRenderer.invoke('fs:import', files.map((f) => webUtils.getPathForFile(f)).filter(Boolean)),
+ create: (parent, name, dir) => ipcRenderer.invoke('fs:create', parent, name, dir),
+ rename: (rel, name) => ipcRenderer.invoke('fs:rename', rel, name),
+ trash: (rel) => ipcRenderer.invoke('fs:trash', rel),
+ reveal: (rel) => ipcRenderer.invoke('fs:reveal', rel),
+ openExternal: (rel) => ipcRenderer.invoke('fs:openExternal', rel),
saveFeedback: (png) => ipcRenderer.invoke('fs:saveFeedback', png),
writeText: (id, rel, text, base, force) => ipcRenderer.invoke('fs:writeText', id, rel, text, base, force),
backupText: (id, rel, text) => ipcRenderer.invoke('fs:backupText', id, rel, text),
diff --git a/app/src/renderer/code.ts b/app/src/renderer/code.ts
index 004cdde..aff0acc 100644
--- a/app/src/renderer/code.ts
+++ b/app/src/renderer/code.ts
@@ -203,6 +203,26 @@ export class CodePanel {
/** Dateien mit ungespeicherten Eingaben (auch solche mit Konflikt). */
unsaved(): string[] { return [...this.docs.values()].filter((d) => d.dirty || d.conflict).map((d) => d.file); }
+ /** Offene Dateien, die `rel` ist oder die in diesem Ordner liegen. */
+ openUnder(rel: string): string[] { return [...this.docs.keys()].filter((f) => f === rel || f.startsWith(`${rel}/`)); }
+
+ /**
+ * Schließt Reiter ohne Rückfrage, nachdem ihre Datei umbenannt oder gelöscht wurde. Nur für Reiter ohne ungespeicherte
+ * Eingaben: Der Dateibaum lehnt Umbenennen und Löschen vorher ab, solange hier etwas ungespeichert ist.
+ */
+ forget(rel: string): void {
+ const gone = this.openUnder(rel);
+ if (!gone.length) return;
+ for (const f of gone) this.docs.delete(f);
+ if (this.active && gone.includes(this.active)) {
+ this.active = null;
+ const next = [...this.docs.values()].pop();
+ if (next) this.activate(next); else this.view.setState(EditorState.create({ doc: '' }));
+ }
+ this.renderChrome();
+ this.deps.changed();
+ }
+
/**
* Ungespeicherte Dateien schreiben (Strg+S, Knöpfe, vor dem Bauen). `ok` ist false, wenn etwas nicht geschrieben
* werden konnte, etwa wegen eines Konflikts: Dann soll auch nicht gebaut oder als ZIP gespeichert werden.
diff --git a/app/src/renderer/filetree.ts b/app/src/renderer/filetree.ts
index c298148..ba30c6f 100644
--- a/app/src/renderer/filetree.ts
+++ b/app/src/renderer/filetree.ts
@@ -1,32 +1,115 @@
+import { fileOpBlockReason } from '../shared/editable';
import type { FileNode } from '../shared/types';
import { icon } from './icons';
-import { el } from './ui';
+import { el, menuItem, menus } from './ui';
/** Dateien, die die App verwaltet. Sie stehen eingeklappt unter „Vom Programm verwaltet“, damit der Baum ruhig bleibt. */
const MANAGED = new Set(['AGENTS.md', 'CLAUDE.md', '.gitignore']);
const TAGS: Record<string, string> = { 'model.py': 'Modell', 'output/model.step': 'Ergebnis', 'NOTES.md': 'Notizen', 'requirements.txt': 'Pakete' };
+/** Ordner der Markierungen. Der Hauptprozess liefert ihn als einzigen Teil von .soma/ mit. */
+const FEEDBACK = '.soma/feedback';
export const TEXT_EXT = /\.(py|md|txt|json|toml|cfg|ini|yml|yaml|gitignore|csv)$|^[^.]*$/i;
-/** Dateien-Panel: kompakter Baum, Ordner einklappbar. Ein Klick auf eine Textdatei öffnet sie im Code-Panel. */
+/** Was der Baum vom Rest der App braucht. Die Aktionen liefern true, wenn das Namensfeld zugehen darf. */
+export interface FileTreeDeps {
+ open(node: FileNode): void;
+ create(parent: string, name: string, dir: boolean): Promise<boolean>;
+ rename(rel: string, name: string): Promise<boolean>;
+ trash(rel: string): void;
+ reveal(rel: string): void;
+ openExternal(rel: string): void;
+ toAgent(rel: string): void;
+ copyPath(rel: string): void;
+}
+
+/** Offenes Namensfeld: neue Datei oder neuer Ordner in `parent`, oder Umbenennen von `node`. */
+type Edit = { mode: 'file' | 'dir'; parent: string } | { mode: 'rename'; node: FileNode };
+
+/**
+ * Symbol nach Dateityp, damit man Skripte, Tabellen, CAD-Dateien und Bilder auf einen Blick unterscheidet. Nur die Form
+ * unterscheidet sich, nicht die Farbe: Farben haben in der Oberfläche feste Bedeutungen (Aktion, Vorschau, Status).
+ */
+const FILE_ICONS: [RegExp, string][] = [
+ [/\.(py|pyw)$/i, 'f-py'],
+ [/\.(md|txt|rst|log)$|^[^.]*$/i, 'f-text'],
+ [/\.(csv|tsv|xlsx?|ods)$/i, 'f-table'],
+ [/\.(json|toml|ya?ml|ini|cfg|xml)$/i, 'f-data'],
+ [/\.(step|stp|iges|igs|brep|x_t|sat)$/i, 'f-cad'],
+ [/\.(stl|3mf|obj|glb|gltf|ply|amf)$/i, 'f-mesh'],
+ [/\.(dxf|dwg|svg)$/i, 'f-draw'],
+ [/\.(png|jpe?g|gif|webp|bmp|tiff?)$/i, 'f-image'],
+ [/\.pdf$/i, 'f-pdf'],
+ [/\.(zip|7z|rar|tar|gz)$/i, 'f-zip'],
+ [/^\.gitignore$/i, 'f-lock'],
+];
+export const fileIcon = (name: string) => FILE_ICONS.find(([re]) => re.test(name))?.[1] ?? 'file';
+
+const parentOf = (rel: string) => (rel.includes('/') ? rel.slice(0, rel.lastIndexOf('/')) : '');
+
+/**
+ * Dateien-Panel: kompakter Baum, Ordner einklappbar. Ein Klick auf eine Textdatei öffnet sie im Code-Panel.
+ * Rechtsklick (oder Umschalt+F10) öffnet das Menü mit Anlegen, Umbenennen (F2), Löschen (Entf), Öffnen und Pfad.
+ * Was gesperrt ist, regelt `fileOpBlockReason`, dieselbe Regel prüft der Hauptprozess noch einmal.
+ */
export class FileTree {
private collapsed = new Set<string>(['#managed']);
private nodes: FileNode[] = [];
+ private edit: Edit | null = null;
+ private input: HTMLInputElement | null = null;
+ /** Ein Name wird gerade angelegt oder umbenannt: kein zweites Absenden, auch nicht aus einem neu gezeichneten Feld. */
+ private submitting = false;
- constructor(private root: HTMLElement, private onOpen: (node: FileNode) => void) {}
+ constructor(private root: HTMLElement, private menu: HTMLElement, private deps: FileTreeDeps) {
+ root.addEventListener('contextmenu', (e) => {
+ e.preventDefault();
+ const row = (e.target as HTMLElement).closest<HTMLElement>('.frow[data-path]');
+ this.openMenu(row ? this.find(row.dataset.path!) : null, e.clientX, e.clientY);
+ });
+ root.addEventListener('keydown', (e) => {
+ if (e.target === this.input) return;
+ const row = (e.target as HTMLElement).closest<HTMLElement>('.frow[data-path]');
+ const n = row ? this.find(row.dataset.path!) : null;
+ if (!n) return;
+ if (e.key === 'F2') { e.preventDefault(); this.startRename(n); }
+ else if (e.key === 'Delete') { e.preventDefault(); if (!fileOpBlockReason(n.path, 'delete')) deps.trash(n.path); }
+ else if (e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey)) {
+ e.preventDefault();
+ const r = row!.getBoundingClientRect();
+ this.openMenu(n, r.left + 24, r.bottom);
+ }
+ });
+ }
render(nodes: FileNode[] = this.nodes): void {
this.nodes = nodes;
+ // Verschwindet die Datei, deren Name gerade bearbeitet wird (etwa durch den Agenten), geht das Feld zu
+ if (this.edit?.mode === 'rename' && !this.find(this.edit.node.path) && !this.submitting) { this.edit = null; this.input = null; }
const managed = nodes.filter((n) => !n.dir && MANAGED.has(n.name));
- const rest = nodes.filter((n) => !managed.includes(n));
+ const feedback = nodes.find((n) => n.path === FEEDBACK);
+ const rest = nodes.filter((n) => !managed.includes(n) && n !== feedback);
const rows: HTMLElement[] = [];
- const walk = (list: FileNode[], depth: number) => {
+ const ed = this.edit;
+ const walk = (list: FileNode[], depth: number, parent: string) => {
+ if (ed && ed.mode !== 'rename' && ed.parent === parent) rows.push(this.inputRow(depth, ed.mode === 'dir' ? 'folder' : 'file', ''));
for (const n of list) {
- rows.push(this.row(n, depth));
- if (n.dir && n.children && !this.collapsed.has(n.path)) walk(n.children, depth + 1);
+ rows.push(ed?.mode === 'rename' && ed.node.path === n.path ? this.inputRow(depth, n.dir ? 'folder' : fileIcon(n.name), n.name) : this.row(n, depth));
+ if (n.dir && n.children && !this.collapsed.has(n.path)) walk(n.children, depth + 1, n.path);
}
};
- walk(rest, 0);
- if (!rest.length) rows.push(el('div', { className: 'hint', textContent: 'Noch keine Dateien.' }));
+ walk(rest, 0, '');
+ if (!rest.length && !ed) rows.push(el('div', { className: 'hint', textContent: 'Noch keine Dateien.' }));
+ // Markierungen (E16) aus .soma/feedback/: eigene Gruppe, neueste zuerst. Zum Wiederfinden und erneut an den Agenten geben.
+ if (feedback?.children?.length) {
+ rows.push(el('div', { className: 'gap' }));
+ const open = !this.collapsed.has(FEEDBACK);
+ const head = this.button(0, open ? 'down' : 'right', 'image', 'Markierungen', String(feedback.children.length), 'dim');
+ head.title = 'Bilder aus „Markieren“, abgelegt in .soma/feedback/. Klick öffnet, Rechtsklick gibt den Pfad an den Agenten.';
+ head.setAttribute('aria-expanded', String(open));
+ head.dataset.path = FEEDBACK;
+ head.addEventListener('click', () => this.toggle(FEEDBACK));
+ rows.push(head);
+ if (open) walk(feedback.children, 1, FEEDBACK);
+ }
if (managed.length) {
rows.push(el('div', { className: 'gap' }));
const open = !this.collapsed.has('#managed');
@@ -37,7 +120,117 @@ export class FileTree {
rows.push(head);
if (open) for (const n of managed) rows.push(this.row(n, 1));
}
+ const hadFocus = !!this.input && document.activeElement === this.input;
this.root.replaceChildren(...rows);
+ // Neu gezeichnet, während getippt wird (Dateiänderung von außen): Fokus und Eingabe bleiben
+ if (hadFocus || this.input?.dataset.fresh) this.focusInput();
+ }
+
+ // ---- Anlegen und Umbenennen -----------------------------------------------------------------------------------
+
+ /** Namensfeld für eine neue Datei oder einen neuen Ordner in `parent` ('' = Projektordner). */
+ startCreate(parent: string, dir: boolean): void {
+ if (fileOpBlockReason(parent, 'create') || this.submitting) return;
+ this.edit = { mode: dir ? 'dir' : 'file', parent };
+ this.input = null;
+ if (parent) this.collapsed.delete(parent); // Ordner aufklappen, damit das Feld zu sehen ist
+ this.render();
+ }
+
+ startRename(n: FileNode): void {
+ if (fileOpBlockReason(n.path, 'rename') || this.submitting) return;
+ this.edit = { mode: 'rename', node: n };
+ this.input = null;
+ this.render();
+ }
+
+ private inputRow(depth: number, ico: string, value: string): HTMLElement {
+ const prev = this.input;
+ // Neu gezeichnet, während das Feld offen ist: das Getippte übernehmen
+ const input = el('input', { className: 'fedit', type: 'text', spellcheck: false, autocomplete: 'off', value: prev ? prev.value : value });
+ input.setAttribute('aria-label', this.edit?.mode === 'rename' ? 'Neuer Name' : this.edit?.mode === 'dir' ? 'Name des neuen Ordners' : 'Name der neuen Datei');
+ if (!prev) input.dataset.fresh = '1';
+ const finish = async (fromBlur: boolean) => {
+ if (this.submitting || this.input !== input) return;
+ const ed = this.edit;
+ const name = input.value;
+ // Unverändert oder leer: einfach zu
+ if (!ed || !name.trim() || (ed.mode === 'rename' && name === ed.node.name)) { this.cancelEdit(); return; }
+ this.submitting = true;
+ let ok = false;
+ try { ok = ed.mode === 'rename' ? await this.deps.rename(ed.node.path, name) : await this.deps.create(ed.parent, name, ed.mode === 'dir'); }
+ finally { this.submitting = false; }
+ if (this.edit !== ed) return;
+ // Abgelehnt nach Enter: Feld bleibt offen, damit der Name korrigiert werden kann. Nach dem Verlassen geht es zu.
+ if (ok || fromBlur) this.cancelEdit();
+ else this.input?.focus();
+ };
+ input.addEventListener('keydown', (e) => {
+ e.stopPropagation(); // Entf, F2 und Escape gehören hier dem Feld
+ if (e.key === 'Enter') { e.preventDefault(); void finish(false); }
+ else if (e.key === 'Escape') { e.preventDefault(); this.cancelEdit(); }
+ });
+ input.addEventListener('blur', () => { if (input.isConnected) void finish(true); });
+ this.input = input;
+ const row = el('div', { className: 'frow editing' }, el('span', { className: 'chev' }), el('span', { className: 'fi' }, icon(ico, 15)), input);
+ row.style.paddingLeft = `${8 + depth * 18}px`;
+ return row;
+ }
+
+ private focusInput(): void {
+ const t = this.input;
+ if (!t) return;
+ const fresh = !!t.dataset.fresh;
+ delete t.dataset.fresh;
+ t.focus();
+ // Beim Umbenennen den Namen ohne Endung markieren, wie im Explorer
+ if (fresh) { const dot = t.value.lastIndexOf('.'); t.setSelectionRange(0, dot > 0 && this.edit?.mode === 'rename' ? dot : t.value.length); }
+ }
+
+ private cancelEdit(): void {
+ const had = !!this.edit;
+ this.edit = null;
+ this.input = null;
+ if (had) this.render();
+ }
+
+ // ---- Menü -----------------------------------------------------------------------------------------------------
+
+ private openMenu(n: FileNode | null, x: number, y: number): void {
+ const d = this.deps;
+ const folder = n ? (n.dir ? n.path : parentOf(n.path)) : '';
+ const blockCreate = fileOpBlockReason(folder, 'create');
+ const blocked = (item: HTMLButtonElement, reason: string | null) => { if (reason) { item.disabled = true; item.title = reason; } return item; };
+ const items: HTMLElement[] = [el('div', { className: 'mh', textContent: n ? n.name : 'Projektordner' })];
+ if (n && !n.dir) {
+ if (TEXT_EXT.test(n.name)) items.push(menuItem('Öffnen', { icon: 'code', onClick: () => d.open(n) }));
+ items.push(menuItem('Mit Standardprogramm öffnen', { icon: 'openext', onClick: () => d.openExternal(n.path) }));
+ }
+ items.push(menuItem('Im Explorer zeigen', { icon: 'folder', onClick: () => d.reveal(n?.path ?? '') }));
+ if (n) {
+ items.push(el('div', { className: 'msep' }),
+ menuItem('Pfad an Agent geben', { icon: 'send', onClick: () => d.toAgent(n.path) }),
+ menuItem('Pfad kopieren', { icon: 'copy', onClick: () => d.copyPath(n.path) }));
+ }
+ items.push(el('div', { className: 'msep' }),
+ blocked(menuItem(n?.dir ? 'Neue Datei hier' : 'Neue Datei', { icon: 'fileplus', onClick: () => this.startCreate(folder, false) }), blockCreate),
+ blocked(menuItem(n?.dir ? 'Neuer Ordner hier' : 'Neuer Ordner', { icon: 'folderplus', onClick: () => this.startCreate(folder, true) }), blockCreate));
+ if (n) {
+ items.push(blocked(menuItem('Umbenennen', { icon: 'pen', kbd: 'F2', onClick: () => this.startRename(n) }), fileOpBlockReason(n.path, 'rename')),
+ blocked(menuItem('Löschen', { icon: 'trash', kbd: 'Entf', onClick: () => d.trash(n.path) }), fileOpBlockReason(n.path, 'delete')));
+ }
+ this.menu.replaceChildren(...items);
+ menus.at(this.menu, x, y);
+ }
+
+ // ---- Zeilen ---------------------------------------------------------------------------------------------------
+
+ private find(rel: string, list: FileNode[] = this.nodes): FileNode | null {
+ for (const n of list) {
+ if (n.path === rel) return n;
+ if (n.children) { const c = this.find(rel, n.children); if (c) return c; }
+ }
+ return null;
}
private toggle(key: string): void {
@@ -51,12 +244,14 @@ export class FileTree {
const b = this.button(depth, open ? 'down' : 'right', 'folder', n.name, '', 'dir');
b.setAttribute('aria-expanded', String(open));
b.title = n.path;
+ b.dataset.path = n.path;
b.addEventListener('click', () => this.toggle(n.path));
return b;
}
- const b = this.button(depth, null, 'file', n.name, TAGS[n.path] ?? '', '');
+ const b = this.button(depth, null, fileIcon(n.name), n.name, TAGS[n.path] ?? '', '');
b.title = TEXT_EXT.test(n.name) ? `${n.path} im Code-Panel öffnen` : n.path;
- b.addEventListener('click', () => this.onOpen(n));
+ b.dataset.path = n.path;
+ b.addEventListener('click', () => this.deps.open(n));
return b;
}
diff --git a/app/src/renderer/icons.ts b/app/src/renderer/icons.ts
index 74af133..b7cc717 100644
--- a/app/src/renderer/icons.ts
+++ b/app/src/renderer/icons.ts
@@ -29,6 +29,21 @@ const PATHS: Record<string, string> = {
image: '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5L5 20"/>',
alert: '<path d="M12 4 2 20h20z"/><path d="M12 10v4M12 17v.01"/>',
file: '<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/>',
+ // Dateitypen im Dateibaum: eine eigene, große Form je Typ, damit sie auch bei 15 px auseinanderzuhalten sind
+ 'f-py': '<path d="m8 7-5 5 5 5M16 7l5 5-5 5M13.5 4.5l-3 15"/>',
+ 'f-text': '<path d="M5 6h14M5 10h14M5 14h14M5 18h9"/>',
+ 'f-table': '<rect x="3.5" y="4.5" width="17" height="15" rx="1.5"/><path d="M3.5 9.5h17M3.5 14.5h17M10 9.5v10"/>',
+ 'f-data': '<path d="M9 4C7 4 6.5 5 6.5 7s0 3.5-2.5 5c2.5 1.5 2.5 3 2.5 5s.5 3 2.5 3M15 4c2 0 2.5 1 2.5 3s0 3.5 2.5 5c-2.5 1.5-2.5 3-2.5 5s-.5 3-2.5 3"/>',
+ 'f-cad': '<path d="M12 3 20 7.5v9L12 21l-8-4.5v-9z"/><path d="M4 7.5 12 12l8-4.5M12 12v9"/>',
+ 'f-mesh': '<path d="M12 3.5 21 19.5H3z"/><path d="M7.5 11.5h9M12 19.5l-4.5-8M12 19.5l4.5-8"/>',
+ 'f-draw': '<path d="M12 3 5.5 13.5 12 21l6.5-7.5z"/><circle cx="12" cy="13" r="2"/><path d="M12 3v8"/>',
+ 'f-image': '<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="9" cy="10" r="2"/><path d="m21 16-5-5L5 20"/>',
+ 'f-pdf': '<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4"/><path d="M9.5 18v-7H12a2 2 0 0 1 0 4H9.5"/>',
+ 'f-zip': '<rect x="3.5" y="4" width="17" height="5" rx="1"/><path d="M5 9v10.5h14V9M10 13h4"/>',
+ 'f-lock': '<rect x="5" y="11" width="14" height="9" rx="1.5"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/>',
+ fileplus: '<path d="M6 3h8l4 4v14H6z"/><path d="M14 3v4h4M12 11v6M9 14h6"/>',
+ folderplus: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><path d="M12 10.5v6M9 13.5h6"/>',
+ copy: '<rect x="8" y="8" width="12" height="12" rx="1.5"/><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"/>',
lock: '<rect x="5" y="11" width="14" height="9" rx="1.5"/><path d="M8 11V8a4 4 0 0 1 8 0v3"/>',
upload: '<path d="M12 16V4M7 9l5-5 5 5"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/>',
openext: '<path d="M14 4h6v6M20 4l-9 9"/><path d="M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',
@@ -40,7 +55,8 @@ const PATHS: Record<string, string> = {
pointer: '<path d="M6 3v16l4.2-4.1 2.9 6.2 2.6-1.2-2.9-6.1H18.5z"/>',
ghost: '<circle cx="12" cy="12" r="8"/><path d="M12 4a8 8 0 0 1 0 16z" fill="currentColor" fill-opacity=".45"/>',
trash: '<path d="M4 7h16M10 11v6M14 11v6"/><path d="M6 7l1 13h10l1-13M9 7V4h6v3"/>',
- pen: '<path d="M4 20h4L19 9l-4-4L4 16z"/>', arrow: '<path d="M5 19 19 5M9 5h10v10"/>',
+ pen: '<path d="M4 20h4L19 9l-4-4L4 16z"/>', arrow: '<path d="M5 19 19 5M9 5h10v10"/>', line: '<path d="M5 19 19 5"/>',
+ grid: '<rect x="3.5" y="3.5" width="17" height="17" rx="1.5"/><path d="M3.5 9.2h17M3.5 14.8h17M9.2 3.5v17M14.8 3.5v17"/>',
square: '<rect x="4" y="4" width="16" height="16" rx="1.5"/>', circle: '<circle cx="12" cy="12" r="8"/>',
text: '<path d="M5 6V4h14v2M12 4v16M9 20h6"/>', undo: '<path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>',
};
diff --git a/app/src/renderer/index.html b/app/src/renderer/index.html
index fdbdf78..33e45b2 100644
--- a/app/src/renderer/index.html
+++ b/app/src/renderer/index.html
@@ -43,6 +43,8 @@
<aside id="side" hidden>
<section id="panel-files" class="panel" aria-label="Dateien" hidden>
<div class="side-hd"><b>Dateien</b><span class="grow"></span>
+ <button id="btn-file-new" class="ibtn s" title="Neue Datei (Rechtsklick im Baum: auch in einem Ordner)" aria-label="Neue Datei"><i data-icon="fileplus" data-size="15"></i></button>
+ <button id="btn-folder-new" class="ibtn s" title="Neuer Ordner" aria-label="Neuer Ordner"><i data-icon="folderplus" data-size="15"></i></button>
<button id="btn-reveal" class="ibtn s" title="Im Explorer zeigen" aria-label="Im Explorer zeigen"><i data-icon="openext" data-size="15"></i></button>
<button class="ibtn s side-close" aria-label="Dateien schließen"><i data-icon="x" data-size="15" data-stroke="2"></i></button></div>
<div id="tab-files" class="ftree"></div>
@@ -179,7 +181,8 @@
<span class="mk-title"><i data-icon="camera" data-size="15"></i><b>Markieren</b></span><span class="vsep"></span>
<button data-tool="select" aria-pressed="false" aria-label="Auswählen" title="Auswählen: Form anklicken und ziehen. Ecken skalieren (Umschalt: Seitenverhältnis), der Punkt oben dreht (Umschalt: 15°-Schritte), Entf löscht, Doppelklick bearbeitet Text"><i data-icon="pointer"></i></button>
<button data-tool="pen" aria-pressed="true" aria-label="Stift" title="Stift: frei zeichnen"><i data-icon="pen"></i></button>
- <button data-tool="arrow" aria-pressed="false" aria-label="Pfeil" title="Pfeil: vom Anfang zur Spitze ziehen"><i data-icon="arrow"></i></button>
+ <button data-tool="line" aria-pressed="false" aria-label="Linie" title="Linie: vom Anfang zum Ende ziehen (mit Umschalt: in 15°-Schritten)"><i data-icon="line"></i></button>
+ <button data-tool="arrow" aria-pressed="false" aria-label="Pfeil" title="Pfeil: vom Anfang zur Spitze ziehen (mit Umschalt: in 15°-Schritten)"><i data-icon="arrow"></i></button>
<button data-tool="rect" aria-pressed="false" aria-label="Rechteck" title="Rechteck (mit Umschalt: Quadrat)"><i data-icon="square"></i></button>
<button data-tool="ellipse" aria-pressed="false" aria-label="Kreis" title="Kreis oder Ellipse (mit Umschalt: Kreis)"><i data-icon="circle"></i></button>
<button data-tool="text" aria-pressed="false" aria-label="Text" title="Text: an die Stelle klicken, schreiben, Enter. Klick auf einen Text bearbeitet ihn"><i data-icon="text"></i></button>
@@ -189,6 +192,7 @@
<button id="btn-mark-undo" aria-label="Rückgängig" title="Rückgängig (Strg Z), wiederholen mit Strg Y" disabled><i data-icon="undo"></i></button>
<button id="btn-mark-delete" aria-label="Löschen" title="Ausgewählte Form löschen (Entf)" disabled><i data-icon="trash"></i></button>
<span class="vsep"></span>
+ <button id="btn-mark-grid" aria-pressed="false" title="Raster ein- und ausschalten. Es steht mit im Bild, Linien, Pfeile und Formen rasten ein (Alt beim Ziehen: frei)"><i data-icon="grid"></i><span class="lbl">Raster</span></button>
<button id="btn-mark-blank" aria-pressed="false" title="Auf leerer Fläche zeichnen statt auf dem Viewer-Bild"><i data-icon="image"></i><span class="lbl">Leere Fläche</span></button>
</div>
<div id="mark-hint" class="float mk-hint"></div>
diff --git a/app/src/renderer/main.ts b/app/src/renderer/main.ts
index c04a303..4413f34 100644
--- a/app/src/renderer/main.ts
+++ b/app/src/renderer/main.ts
@@ -95,18 +95,71 @@ const skills = new SkillsPanel($('skills-list'), {
changed: () => { filesDirty = true; textCache.clear(); void refreshSaveState(); void code.refresh(); },
});
-const files = new FileTree($('tab-files'), (n) => {
- if (TEXT_EXT.test(n.name)) void openCode(n.path);
- else if (/\.(step|stp)$/i.test(n.name)) toast('Fremde STEP-Dateien im Viewer ansehen kommt in einem späteren Schritt. Der Agent kann sie schon jetzt im Skript einbinden.', 'info');
- else toast('Für diesen Dateityp gibt es keine Ansicht in der App.', 'info');
+const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|svg)$/i;
+
+const files = new FileTree($('tab-files'), $('menu-ctx'), {
+ open: (n) => {
+ if (TEXT_EXT.test(n.name)) void openCode(n.path);
+ // Bilder (etwa Markierungen und Skizzen) zeigt das Bildprogramm des Systems
+ else if (IMAGE_EXT.test(n.name)) void openExternal(n.path);
+ else if (/\.(step|stp)$/i.test(n.name)) toast('Fremde STEP-Dateien im Viewer ansehen kommt in einem späteren Schritt. Der Agent kann sie schon jetzt im Skript einbinden.', 'info');
+ else toast('Für diesen Dateityp gibt es keine Ansicht in der App. Rechtsklick: „Mit Standardprogramm öffnen“.', 'info');
+ },
+ create: async (parent, name, dir) => {
+ const r = await api.fs.create(parent, name, dir);
+ if (!r.ok || !r.path) { toast(r.error ?? `${name} ließ sich nicht anlegen.`, 'error'); return false; }
+ await refreshFiles();
+ if (!dir && TEXT_EXT.test(name)) void openCode(r.path);
+ return true;
+ },
+ rename: async (rel, name) => {
+ if (!fileOpAllowed(rel, 'umbenennen')) return true;
+ const wasOpen = code.openUnder(rel);
+ const r = await api.fs.rename(rel, name);
+ if (!r.ok || !r.path) { toast(r.error ?? `${rel} ließ sich nicht umbenennen.`, 'error'); return false; }
+ // Reiter wandern mit: der alte zu, die Datei unter neuem Namen wieder auf (ohne das Panel zu wechseln)
+ code.forget(rel);
+ for (const f of wasOpen) void code.open(r.path + f.slice(rel.length), undefined, false);
+ await refreshFiles();
+ return true;
+ },
+ trash: (rel) => void (async () => {
+ if (!fileOpAllowed(rel, 'löschen')) return;
+ const r = await api.fs.trash(rel);
+ if (r.canceled) return;
+ if (!r.ok) { toast(r.error ?? `${rel} ließ sich nicht löschen.`, 'error'); return; }
+ code.forget(rel);
+ await refreshFiles();
+ toast(`${rel} liegt im Papierkorb.`);
+ })(),
+ reveal: (rel) => void api.fs.reveal(rel).then((r) => { if (!r.ok) toast(r.error ?? 'Der Explorer ließ sich nicht öffnen.', 'error'); }),
+ openExternal: (rel) => void openExternal(rel),
+ toAgent: (rel) => insertToAgent(`[Datei: ${rel}] `),
+ copyPath: (rel) => void navigator.clipboard.writeText(rel).then(() => toast(`Pfad kopiert: ${rel}`), (e) => toast(`Der Pfad ließ sich nicht kopieren: ${e instanceof Error ? e.message : String(e)}`, 'error')),
});
+async function openExternal(rel: string): Promise<void> {
+ const r = await api.fs.openExternal(rel);
+ if (!r.ok) toast(r.error ?? `${rel} ließ sich nicht öffnen.`, 'error');
+}
+
+/** Umbenennen und Löschen nur ohne ungespeicherte Eingaben im Editor, sonst gingen sie unter dem alten Namen verloren. */
+function fileOpAllowed(rel: string, what: string): boolean {
+ const open = code.unsaved().filter((f) => f === rel || f.startsWith(`${rel}/`));
+ if (!open.length) return true;
+ toast(`Zum ${what === 'löschen' ? 'Löschen' : 'Umbenennen'} erst speichern oder die Änderungen verwerfen: ${open.join(', ')}`, 'error');
+ return false;
+}
+
async function refreshFiles(): Promise<void> {
if (panel !== 'files') { filesDirty = true; return; }
filesDirty = false;
try { files.render(await api.fs.list()); } catch { /* Projekt wechselt gerade */ }
}
+$('btn-file-new').addEventListener('click', () => files.startCreate('', false));
+$('btn-folder-new').addEventListener('click', () => files.startCreate('', true));
+
// Dateien und Ordner ziehen: überall im Fenster ablegen landet in inputs/. Ohne das würde Electron die Datei als Seite öffnen.
let dragDepth = 0;
const hasFiles = (e: DragEvent) => !!e.dataTransfer && [...e.dataTransfer.types].includes('Files');
@@ -228,7 +281,7 @@ function insertToAgent(text: string | null, done?: string): void {
setAgentCollapsed(false);
const title = terminals.insert(text);
if (title) toast(`${pre}In die Eingabe von ${title} eingefügt. Enter schickt ab.`);
- else toast(`${pre}Das Terminal ist beendet. Öffne über + ein neues.`, 'error');
+ else toast(`${pre}Alle Terminals sind beendet. Öffne über + ein neues.`, 'error');
}
// ---- Messen (E9) ------------------------------------------------------------------------------------------------
@@ -257,7 +310,7 @@ const sectionTool = new SectionTool({
const markup = new Markup({
viewer: $('viewer'), layer: $('markup'), canvas: $<HTMLCanvasElement>('mark-canvas'), text: $<HTMLInputElement>('mark-text'),
hint: $('mark-hint'), tools: $('mark-tools'), undo: $<HTMLButtonElement>('btn-mark-undo'), del: $<HTMLButtonElement>('btn-mark-delete'),
- blank: $<HTMLButtonElement>('btn-mark-blank'), colorBtn: $<HTMLButtonElement>('btn-mark-color'), colorSwatch: $('mark-color-sw'),
+ blank: $<HTMLButtonElement>('btn-mark-blank'), grid: $<HTMLButtonElement>('btn-mark-grid'), colorBtn: $<HTMLButtonElement>('btn-mark-color'), colorSwatch: $('mark-color-sw'),
palette: $('menu-mark-color'), custom: $<HTMLInputElement>('mark-color-custom'),
});
@@ -278,6 +331,7 @@ async function sendMarkup(): Promise<void> {
if (!r.ok || !r.path) { toast(`Die Markierung ließ sich nicht speichern: ${r.error ?? 'unbekannter Fehler'}`, 'error'); return; }
const old = versions.previewed;
markup.close();
+ void refreshFiles(); // die neue Markierung steht gleich im Dateibaum
// Zeigt das Bild einen alten Stand oder einen Schnitt, soll der Agent das wissen (sonst vergleicht er es mit dem aktuellen Code
// oder hält die Schnittfläche für eine echte Fläche)
const cut = sectionTool.agentText();
diff --git a/app/src/renderer/markup.ts b/app/src/renderer/markup.ts
index 3f8ec38..e309ace 100644
--- a/app/src/renderer/markup.ts
+++ b/app/src/renderer/markup.ts
@@ -1,7 +1,7 @@
import { el, fmtWhen, menus, toast } from './ui';
/** Werkzeuge der Markierung (E16). Nichts ist maßhaltig, Maße schreibt man als Text daneben. */
-export type MarkTool = 'select' | 'pen' | 'arrow' | 'rect' | 'ellipse' | 'text';
+export type MarkTool = 'select' | 'pen' | 'line' | 'arrow' | 'rect' | 'ellipse' | 'text';
type DrawTool = Exclude<MarkTool, 'select'>;
type Pt = [number, number];
@@ -29,6 +29,8 @@ interface Ui {
undo: HTMLButtonElement;
del: HTMLButtonElement;
blank: HTMLButtonElement;
+ /** Raster ein und aus. */
+ grid: HTMLButtonElement;
/** Knopf mit der aktuellen Farbe, darunter das Menü mit Knöpfen `[data-color]` und der eigenen Farbe. */
colorBtn: HTMLButtonElement;
colorSwatch: HTMLElement;
@@ -42,6 +44,8 @@ const FONT = 19;
const TEXT_PAD: Pt = [5, 3];
/** Abstand des Auswahlrahmens zur Form, Abstand des Drehgriffs über dem Rahmen, Fangradius der Griffe und der Linien (CSS-Pixel). */
const SEL_PAD = 6, ROT_GAP = 24, GRAB = 9, TOL = 6;
+/** Rasterweite in CSS-Pixeln, jede fünfte Linie kräftiger. */
+const GRID = 20, GRID_MAJOR = 5;
const css = (name: string) => getComputedStyle(document.documentElement).getPropertyValue(name).trim();
const clone = <T>(v: T): T => structuredClone(v);
const turn = (a: number, u: number, v: number): Pt => [u * Math.cos(a) - v * Math.sin(a), u * Math.sin(a) + v * Math.cos(a)];
@@ -67,6 +71,8 @@ export class Markup {
private colorName: string | null = 'orange';
private bg: HTMLCanvasElement | null = null;
private blankBg = false;
+ /** Raster an: Es steht im Bild (wie Karopapier) und Linien, Pfeile und Formen rasten an den Kreuzungen ein. Bleibt für die nächste Markierung. */
+ private grid = false;
private scale = 1;
private size: Pt = [0, 0];
private takenAt = Date.now();
@@ -88,6 +94,7 @@ export class Markup {
ui.undo.addEventListener('click', () => this.undo());
ui.del.addEventListener('click', () => this.removeSelected());
ui.blank.addEventListener('click', () => { this.blankBg = !this.blankBg || !this.bg; this.renderUi(); this.draw(); });
+ ui.grid.addEventListener('click', () => { this.grid = !this.grid; this.renderUi(); this.draw(); });
this.installPointer();
ui.text.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); this.commitText(); }
@@ -261,9 +268,9 @@ export class Markup {
return [s.x + u, s.y + v];
}
- /** Punkte auf der Zeichenfläche: die Linie (Stift, Pfeil) bzw. der geschlossene Umriss (Rechteck, Ellipse). */
+ /** Punkte auf der Zeichenfläche: die Linie (Stift, Linie, Pfeil) bzw. der geschlossene Umriss (Rechteck, Ellipse). */
private outline(s: Shape): Pt[] {
- if (s.tool === 'pen' || s.tool === 'arrow') return s.pts.map((p) => this.world(s, p));
+ if (s.tool === 'pen' || s.tool === 'line' || s.tool === 'arrow') return s.pts.map((p) => this.world(s, p));
const [x0, y0, x1, y1] = this.bounds(s);
if (s.tool === 'rect') return ([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]] as Pt[]).map((p) => this.world(s, p));
// Die Ellipse als Vieleck: So bleibt die Strichstärke beim Skalieren gleich
@@ -347,20 +354,20 @@ export class Markup {
const t = this.hit(p);
if (t?.tool === 'text') this.editText(t); else this.openText(p);
return;
- } else this.drag = { kind: 'draw', tool: this.tool, color: this.color, raw: [p] };
+ } else this.drag = { kind: 'draw', tool: this.tool, color: this.color, raw: [this.tool === 'pen' ? p : this.snap(p, e.altKey)] };
if (this.drag) try { c.setPointerCapture(e.pointerId); } catch { /* synthetische Ereignisse (Tests) haben keinen aktiven Zeiger */ }
this.draw();
});
c.addEventListener('pointermove', (e) => {
const p = this.at(e);
if (!this.drag) { if (this.tool === 'select') c.style.cursor = this.cursorAt(p); return; }
- this.dragTo(p, e.shiftKey);
+ this.dragTo(p, e.shiftKey, e.altKey);
this.draw();
});
c.addEventListener('pointerup', (e) => {
const d = this.drag;
if (!d) return;
- this.dragTo(this.at(e), e.shiftKey);
+ this.dragTo(this.at(e), e.shiftKey, e.altKey);
this.drag = null;
if (d.kind === 'draw') {
const [a, b = a] = d.raw;
@@ -397,11 +404,17 @@ export class Markup {
this.renderUi();
}
- private dragTo(p: Pt, shift: boolean): void {
+ /**
+ * Ziehen. Linie und Pfeil mit Umschalt: Winkel in 15-Grad-Schritten (waagerecht, senkrecht, 45° …). Rechteck und
+ * Ellipse mit Umschalt: Quadrat bzw. Kreis. Bei eingeschaltetem Raster rasten die Endpunkte ein, Alt hebt das auf.
+ */
+ private dragTo(p: Pt, shift: boolean, alt = false): void {
const d = this.drag!;
if (d.kind === 'draw') {
if (d.tool === 'pen') { if (dist(p, d.raw[d.raw.length - 1]) >= 1.5) d.raw.push(p); }
- else d.raw[1] = shift && (d.tool === 'rect' || d.tool === 'ellipse') ? square(d.raw[0], p) : p;
+ else if (shift && (d.tool === 'line' || d.tool === 'arrow')) d.raw[1] = angled(d.raw[0], p);
+ else if (shift) d.raw[1] = square(d.raw[0], this.snap(p, alt));
+ else d.raw[1] = this.snap(p, alt);
return;
}
const s = this.shapes.find((x) => x.id === d.id);
@@ -416,6 +429,13 @@ export class Markup {
} else this.scaleTo(s, o, d.corner, p, shift);
}
+ /** Nächste Rasterkreuzung, solange das Raster an ist und Alt nicht gedrückt. Bleibt auf der Zeichenfläche. */
+ private snap(p: Pt, alt: boolean): Pt {
+ if (!this.grid || alt) return p;
+ const r = (v: number, max: number) => Math.max(0, Math.min(max, Math.round(v / GRID) * GRID));
+ return [r(p[0], this.size[0]), r(p[1], this.size[1])];
+ }
+
private cursorAt(p: Pt): string {
const s = this.sel();
const h = s ? this.handleAt(s, p) : null;
@@ -501,6 +521,7 @@ export class Markup {
if (this.bg && !this.blankBg) g.drawImage(this.bg, 0, 0);
else { g.fillStyle = css('--s2') || '#1b1e23'; g.fillRect(0, 0, c.width, c.height); }
g.setTransform(this.scale, 0, 0, this.scale, 0, 0);
+ if (this.grid) this.paintGrid(g);
for (const s of this.shapes) if (s.id !== this.editing?.id) this.paint(g, s);
const d = this.drag;
if (d?.kind === 'draw') this.paint(g, this.makeShape(d.tool, d.color, d.raw));
@@ -538,6 +559,8 @@ export class Markup {
// Durch die Mittelpunkte geglättet, sonst wirkt Freihand eckig
for (let i = 1; i < p.length - 1; i++) g.quadraticCurveTo(p[i][0], p[i][1], (p[i][0] + p[i + 1][0]) / 2, (p[i][1] + p[i + 1][1]) / 2);
if (p.length > 1) g.lineTo(p[p.length - 1][0], p[p.length - 1][1]);
+ } else if (s.tool === 'line') {
+ g.lineTo(b[0], b[1]);
} else if (s.tool === 'arrow') {
const ang = Math.atan2(b[1] - a[1], b[0] - a[0]);
const head = Math.min(16, dist(a, b) * 0.4);
@@ -551,6 +574,26 @@ export class Markup {
g.restore();
}
+ /**
+ * Raster wie Karopapier. Es kommt mit ins Bild: Der Agent sieht dann dieselben Kästchen wie der Nutzer und kann
+ * Größenverhältnisse daran abzählen. Halbtransparent, damit es auf dunklem und hellem Grund zu sehen ist, ohne das Modell zu verdecken.
+ */
+ private paintGrid(g: CanvasRenderingContext2D): void {
+ const [w, h] = this.size;
+ g.save();
+ // Auf halbe Gerätepixel gelegt, damit dünne Linien scharf bleiben
+ const crisp = (v: number) => (Math.round(v * this.scale) + 0.5) / this.scale;
+ for (const major of [false, true]) {
+ g.beginPath();
+ for (let i = 0; i * GRID <= w; i++) if ((i % GRID_MAJOR === 0) === major) { const x = crisp(i * GRID); g.moveTo(x, 0); g.lineTo(x, h); }
+ for (let i = 0; i * GRID <= h; i++) if ((i % GRID_MAJOR === 0) === major) { const y = crisp(i * GRID); g.moveTo(0, y); g.lineTo(w, y); }
+ g.strokeStyle = major ? 'rgba(150,158,170,.42)' : 'rgba(150,158,170,.2)';
+ g.lineWidth = 1 / this.scale;
+ g.stroke();
+ }
+ g.restore();
+ }
+
/** Rahmen, Eckgriffe (skalieren) und Drehgriff. Kommt nie ins Bild für den Agenten. */
private paintSelection(g: CanvasRenderingContext2D, s: Shape): void {
const f = this.frame(s);
@@ -584,6 +627,7 @@ export class Markup {
u.undo.disabled = !this.history.length && !this.editing;
u.del.disabled = this.selected == null;
u.blank.setAttribute('aria-pressed', String(this.blankBg));
+ u.grid.setAttribute('aria-pressed', String(this.grid));
u.canvas.style.cursor = this.tool === 'select' ? 'default' : this.tool === 'text' ? 'text' : 'crosshair';
u.hint.replaceChildren(this.blankBg ? 'Leere Fläche. Das Bild landet in ' : `Bild des Viewers von ${fmtWhen(this.takenAt)}. Es landet in `,
el('code', { textContent: '.soma/feedback/' }), ', der Pfad in der Eingabe des Agenten.');
@@ -594,7 +638,7 @@ export class Markup {
state() {
const r = (v: number, n = 2) => +v.toFixed(n);
return {
- active: this.active, tool: this.tool, color: this.color, blank: this.blankBg, size: this.size, pixels: [this.ui.canvas.width, this.ui.canvas.height],
+ active: this.active, tool: this.tool, color: this.color, blank: this.blankBg, grid: this.grid, size: this.size, pixels: [this.ui.canvas.width, this.ui.canvas.height],
shapes: this.shapes.map((s) => s.tool),
items: this.shapes.map((s) => ({ tool: s.tool, color: s.color, text: s.text ?? null, x: r(s.x), y: r(s.y), rot: r(s.rot, 4), sx: r(s.sx, 3), sy: r(s.sy, 3) })),
selected: this.shapes.findIndex((s) => s.id === this.selected), editing: !!this.editing, undo: this.history.length, redo: this.future.length,
@@ -622,6 +666,13 @@ function square(a: Pt, p: Pt): Pt {
return [a[0] + Math.sign(p[0] - a[0] || 1) * d, a[1] + Math.sign(p[1] - a[1] || 1) * d];
}
+/** Mit Umschalt bei Linie und Pfeil: Richtung auf 15-Grad-Schritte gerundet, Länge bleibt. */
+function angled(a: Pt, p: Pt): Pt {
+ const step = Math.PI / 12;
+ const ang = Math.round(Math.atan2(p[1] - a[1], p[0] - a[0]) / step) * step, len = dist(a, p);
+ return [a[0] + len * Math.cos(ang), a[1] + len * Math.sin(ang)];
+}
+
/** Abstand eines Punkts von einer Strecke. */
function segDist(p: Pt, a: Pt, b: Pt): number {
const dx = b[0] - a[0], dy = b[1] - a[1], len = dx * dx + dy * dy;
diff --git a/app/src/renderer/style.css b/app/src/renderer/style.css
index 2426aba..ad17eb4 100644
--- a/app/src/renderer/style.css
+++ b/app/src/renderer/style.css
@@ -108,6 +108,10 @@ code { font-family:var(--mono); font-size:.95em; }
.frow.dim { color:var(--tx2); }
.ftree .gap { height:8px; }
.ftree .hint { color:var(--tx3); padding:6px 14px; }
+.frow.editing { cursor:default; }
+.frow.editing:hover { background:none; }
+.fedit { flex:1; min-width:0; height:22px; padding:0 6px; border:1px solid var(--acc-line); border-radius:4px; background:var(--s1); color:var(--tx); font:inherit; outline:none; }
+.fedit:focus { border-color:var(--acc); }
/* Skills (E17): eine Karte je Skill mit Schalter. Eingeschaltet in Orange (Auswahl), Auffälligkeiten in Gelb. */
.sk-intro { padding:10px 14px 4px; font-size:12px; color:var(--tx2); }
.sk-intro code, .sk-row code { font:11.5px var(--mono); color:var(--tx); }
@@ -364,7 +368,7 @@ code { font-family:var(--mono); font-size:.95em; }
.mk-frame { position:absolute; inset:6px; border:2px dashed var(--acc-line); border-radius:8px; pointer-events:none; }
.mk-tools { left:12px; top:12px; }
.mk-title { display:flex; align-items:center; gap:7px; padding:0 10px 0 8px; color:var(--acc-tx); }
-.mk-tools [data-tool][aria-pressed=true], #btn-mark-blank[aria-pressed=true] { background:var(--acc-tint); color:var(--acc-tx); font-weight:500; }
+.mk-tools [data-tool][aria-pressed=true], #btn-mark-blank[aria-pressed=true], #btn-mark-grid[aria-pressed=true] { background:var(--acc-tint); color:var(--acc-tx); font-weight:500; }
.mk-tools .mk-colorbtn { gap:5px; padding:0 7px 0 9px; }
.mk-tools .swatch { width:16px; height:16px; border-radius:50%; background:var(--c); box-shadow:inset 0 0 0 1px rgba(255,255,255,.25); }
.mk-palette { display:grid; grid-template-columns:repeat(5, 28px); gap:10px; padding:6px 10px 10px; }
diff --git a/app/src/renderer/terminals.ts b/app/src/renderer/terminals.ts
index 9be70f1..d869a33 100644
--- a/app/src/renderer/terminals.ts
+++ b/app/src/renderer/terminals.ts
@@ -12,6 +12,8 @@ interface Tab { id: number; term: Terminal; fit: FitAddon; pane: HTMLElement; ta
export class TerminalTabs {
private tabs = new Map<number, Tab>();
private active: number | null = null;
+ /** Reihenfolge des Aktivierens (zuletzt aktiviert hinten), damit Einfügen das zuletzt benutzte Terminal findet. */
+ private used: number[] = [];
/** Klick auf einen Tab der eingeklappten Leiste: der Bereich soll aufgehen. */
onStripClick: () => void = () => {};
@@ -66,6 +68,7 @@ export class TerminalTabs {
t.tab.classList.toggle('on', on);
}
this.active = id;
+ this.used = [...this.used.filter((x) => x !== id), id];
this.renderStrip();
requestAnimationFrame(() => { this.fitActive(); this.tabs.get(id)?.term.focus(); });
}
@@ -76,6 +79,7 @@ export class TerminalTabs {
window.soma.term.kill(id);
t.term.dispose(); t.pane.remove(); t.tab.remove();
this.tabs.delete(id);
+ this.used = this.used.filter((x) => x !== id);
if (this.active === id) {
const next = [...this.tabs.keys()].pop();
this.active = null;
@@ -89,13 +93,20 @@ export class TerminalTabs {
get activeId(): number | null { return this.active; }
get activeTitle(): string | null { return this.active != null ? this.tabs.get(this.active)?.title ?? null : null; }
+ /** Laufende Terminals, zuletzt benutztes zuerst: das aktive, dann die übrigen in umgekehrter Reihenfolge des Aktivierens. */
+ private live(): Tab[] {
+ return [...this.used].reverse().map((id) => this.tabs.get(id)).filter((t): t is Tab => !!t && !t.exited);
+ }
+
/**
- * Text in die Eingabezeile des aktiven Terminals einfügen, ohne abzuschicken (E11). Läuft als Einfügen (bracketed paste),
- * damit Agenten den Text nicht als Tastenkürzel deuten. Liefert den Tab-Titel oder null, wenn kein Terminal offen ist.
+ * Text in die Eingabezeile einfügen, ohne abzuschicken (E11). Läuft als Einfügen (bracketed paste), damit Agenten den
+ * Text nicht als Tastenkürzel deuten. Ziel ist das aktive Terminal. Ist es beendet, das zuletzt benutzte, das noch läuft:
+ * Es kommt nach vorn, damit man sieht, wo der Text gelandet ist. Liefert den Tab-Titel oder null, wenn keines mehr läuft.
*/
insert(text: string): string | null {
- const t = this.active != null ? this.tabs.get(this.active) : undefined;
- if (!t || t.exited) return null;
+ const t = this.live()[0];
+ if (!t) return null;
+ if (t.id !== this.active) this.activate(t.id);
t.term.paste(text);
t.term.focus();
return t.title;
diff --git a/app/src/shared/editable.ts b/app/src/shared/editable.ts
index 2748d3e..345e5d4 100644
--- a/app/src/shared/editable.ts
+++ b/app/src/shared/editable.ts
@@ -12,6 +12,25 @@ export function readOnlyReason(rel: string): string | null {
return null;
}
+/**
+ * Grund, warum der Dateibaum hier nicht anlegen, umbenennen oder löschen darf, sonst null. Bei `create` ist `rel` der neue
+ * Pfad (auch das Ziel einer Umbenennung). App-Dateien, Ergebnisse und interne Daten bleiben unangetastet, `model.py`
+ * ist der feste Einstiegspunkt (E6), `inputs/` und `parts/` sind Ordner, die `AGENTS.md` dem Agenten nennt.
+ */
+export function fileOpBlockReason(rel: string, op: 'create' | 'rename' | 'delete'): string | null {
+ const p = rel.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/$/, '');
+ if (!p) return op === 'create' ? null : 'Der Projektordner selbst lässt sich hier nicht ändern.';
+ if (/^(AGENTS|CLAUDE)\.md$/i.test(p) || /^\.gitignore$/i.test(p)) return 'Wird von der App verwaltet.';
+ if (/^output(\/|$)/i.test(p)) return 'Wird beim Bauen neu erzeugt.';
+ // Markierungen (E16) gehören dem Nutzer: aufräumen und umbenennen ja. Neues legt dort nur „An Agent geben“ ab, das
+ // sperrt die Prüfung des Ordners selbst (.soma/feedback fällt unter die nächste Regel).
+ if (/^\.soma\/feedback\/[^/]+$/i.test(p)) return null;
+ if (/^\.(soma|git)(\/|$)/i.test(p)) return 'Interne Daten der App und von Git.';
+ if (op !== 'create' && /^model\.py$/i.test(p)) return 'model.py ist der feste Einstiegspunkt des Modells.';
+ if (op === 'rename' && /^(inputs|parts)$/i.test(p)) return 'Der Agent sucht diesen Ordner unter seinem Namen.';
+ 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.
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index 6cdb731..bd36b9a 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -40,6 +40,9 @@ export interface WriteResult { ok: boolean; conflict?: boolean; disk?: string |
/** Gespeicherte Markierung (E16). `path` relativ zum Projekt, z. B. `.soma/feedback/markierung-20260930-1405.png`. */
export interface FeedbackResult { ok: boolean; path?: string; error?: string }
+/** Anlegen, Umbenennen oder Löschen im Dateibaum. `path` relativ zum Projekt (neuer Pfad), `canceled`: Rückfrage abgelehnt. */
+export interface FileOpResult { ok: boolean; path?: string; error?: string; canceled?: boolean }
+
export interface FileNode { name: string; path: string; dir: boolean; children?: FileNode[] }
export interface AgentInfo { id: string; label: string; command: string; found: boolean }
@@ -188,6 +191,16 @@ export interface SomaApi {
onChanged(cb: () => void): void;
/** Kopiert gezogene Dateien nach inputs/. Vorhandenes wird nie überschrieben. */
importFiles(files: File[]): Promise<ImportResult>;
+ /** Neue, leere Datei oder neuer Ordner in `parent` ('' = Projektordner). Vorhandenes wird nie überschrieben. */
+ create(parent: string, name: string, dir: boolean): Promise<FileOpResult>;
+ /** Benennt eine Datei oder einen Ordner im selben Ordner um. Vorhandenes wird nie überschrieben. */
+ rename(rel: string, name: string): Promise<FileOpResult>;
+ /** Fragt nach und verschiebt dann in den Papierkorb. Endgültig gelöscht wird nie. */
+ trash(rel: string): Promise<FileOpResult>;
+ /** Zeigt die Datei im Explorer ('' = Projektordner). */
+ reveal(rel: string): Promise<FileOpResult>;
+ /** Öffnet die Datei mit dem Standardprogramm des Systems. Ausführbares lehnt der Hauptprozess ab. */
+ openExternal(rel: string): Promise<FileOpResult>;
/** Legt ein PNG der Markierung in .soma/feedback/ ab. Vorhandenes wird nie überschrieben. */
saveFeedback(png: Uint8Array): Promise<FeedbackResult>;
/**
diff --git a/app/test/smoke.mjs b/app/test/smoke.mjs
index 3338e32..ebd2a28 100644
--- a/app/test/smoke.mjs
+++ b/app/test/smoke.mjs
@@ -168,6 +168,20 @@ try {
await key('Escape');
check('Escape hebt zuerst nur die Auswahl auf', (await mk()).selected === -1 && (await mk()).active);
+ // Linie und Raster: Das Raster steht im Bild, Linien rasten an den Kreuzungen ein
+ const gridOff = await ev(() => window.__t.markPixel(600, 10));
+ await domClick('btn-mark-grid');
+ const gridOn = await ev(() => window.__t.markPixel(600, 10));
+ await tool('line'); await drag([[101, 203], [150, 205], [189, 207]]);
+ st = await mk();
+ const ln = st.items[st.items.length - 1];
+ await shot('7f-markieren-raster');
+ check('Raster an: im Bild zu sehen, Knopf gedrückt', st.grid && gridOn.slice(0, 3).join() !== gridOff.slice(0, 3).join()
+ && await ev(() => document.getElementById('btn-mark-grid').getAttribute('aria-pressed')) === 'true', `${gridOff.slice(0, 3)} → ${gridOn.slice(0, 3)}`);
+ check('Linie: gerade, Endpunkte am Raster (100,200 bis 180,200)', st.shapes.length === 5 && ln.tool === 'line' && ln.x === 140 && ln.y === 200, `${ln.tool} ${ln.x},${ln.y}`);
+ await domClick('btn-mark-grid');
+ check('Raster wieder aus: Bild ohne Raster', !(await mk()).grid && (await ev(() => window.__t.markPixel(600, 10))).slice(0, 3).join() === gridOff.slice(0, 3).join());
+
await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
check('Escape mit Zeichnung verwirft nicht sofort (erst beim zweiten Mal)', (await ev(() => window.__t.markup())).active && (await ev(() => window.__t.toast())).text.includes('Noch einmal Escape'));
const px = (await ev(() => window.__t.markup())).pixels;
@@ -192,6 +206,55 @@ try {
await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
check('„Markierung" in der Übergabeleiste öffnet die Zeichenfläche, Escape ohne Zeichnung schließt', viaHandoff && !(await ev(() => window.__t.markup().active)) && fs.readdirSync(fbDir).length === 1);
+ // Dateibaum: Markierungen sichtbar, anlegen, umbenennen, löschen über Menü und Tasten
+ await ev(() => window.__t.showPanel('files'));
+ await waitFor('Markierungen im Dateibaum', (f) => window.__t.fileRows().includes(f), 10000, fbFiles[0]).catch(() => {});
+ const rows2 = await ev(() => window.__t.fileRows());
+ check('Dateibaum: Gruppe „Markierungen“ mit dem Bild aus .soma/feedback/, sonst nichts aus .soma', rows2.includes('Markierungen') && rows2.includes(fbFiles[0]) && !rows2.includes('project.json'), rows2.slice(-6).join(','));
+ const ctx = (rel) => ev((rel) => {
+ const row = document.querySelector(`#tab-files .frow[data-path="${CSS.escape(rel)}"]`);
+ if (!row) return null;
+ const r = row.getBoundingClientRect();
+ row.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: r.left + 20, clientY: r.top + 5 }));
+ return [...document.querySelectorAll('#menu-ctx .mi')].map((b) => (b.disabled ? '-' : '') + b.textContent.replace(/(F2|Entf)$/, ''));
+ }, rel);
+ const menuItemClick = (label) => ev((l) => [...document.querySelectorAll('#menu-ctx .mi')].find((b) => b.textContent.startsWith(l))?.click(), label);
+ const typeName = (name) => ev((n) => { const t = document.querySelector('#tab-files .fedit'); if (!t) return false; t.value = n; t.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true })); return true; }, name);
+ const modelMenu = await ctx('model.py');
+ check('Menü auf model.py: Öffnen, Explorer, Pfad, Anlegen; Umbenennen und Löschen gesperrt', ['Öffnen', 'Im Explorer zeigen', 'Pfad an Agent geben', 'Pfad kopieren', 'Neue Datei', '-Umbenennen', '-Löschen'].every((x) => modelMenu?.includes(x)), modelMenu?.join(','));
+ await ev(() => document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));
+ await domClick('btn-file-new');
+ await sleep(50);
+ const typed = await typeName('notiz.txt');
+ const notiz = path.join(proj.dir, 'notiz.txt');
+ await waitFor('Datei angelegt und offen', () => window.__t.editor.state().file === 'notiz.txt', 5000).catch(() => {});
+ check('„Neue Datei“: Namensfeld im Baum, Enter legt sie an und öffnet sie im Editor', typed && fs.existsSync(notiz) && (await ev(() => window.__t.editor.state())).file === 'notiz.txt');
+ await ev(() => window.__t.showPanel('files'));
+ await waitFor('notiz.txt im Baum', () => window.__t.fileRows().includes('notiz.txt'), 5000).catch(() => {});
+ await ctx('notiz.txt'); await menuItemClick('Umbenennen'); await sleep(50);
+ await typeName('model.py'); await sleep(300);
+ const dupErr = await ev(() => ({ toast: window.__t.toast().text, open: !!document.querySelector('#tab-files .fedit') }));
+ check('Umbenennen auf vorhandenen Namen: Meldung, Feld bleibt offen, nichts überschrieben', dupErr.open && dupErr.toast.includes('gibt es dort schon') && fs.existsSync(notiz)
+ && fs.readFileSync(path.join(proj.dir, 'model.py'), 'utf8').includes('add_part'), dupErr.toast.slice(0, 60));
+ await typeName('skizze.txt');
+ const skizze = path.join(proj.dir, 'skizze.txt');
+ await waitFor('umbenannt', () => window.__t.editor.state().files.includes('skizze.txt'), 5000).catch(() => {});
+ const es = await ev(() => window.__t.editor.state());
+ check('Umbenennen: Datei heißt neu, der offene Reiter zieht mit', fs.existsSync(skizze) && !fs.existsSync(notiz) && es.files.includes('skizze.txt') && !es.files.includes('notiz.txt'), es.files.join(','));
+ await waitFor('skizze.txt im Baum', () => window.__t.fileRows().includes('skizze.txt'), 5000).catch(() => {});
+ await app.answers([0]);
+ await ev(() => { const r = document.querySelector('#tab-files .frow[data-path="skizze.txt"]'); r.focus(); r.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })); });
+ await waitFor('gelöscht', () => !window.__t.fileRows().includes('skizze.txt'), 5000).catch(() => {});
+ const bin = path.join(ud, 'test-papierkorb');
+ check('Entf mit Rückfrage: in den Papierkorb, Reiter zu', !fs.existsSync(skizze) && fs.existsSync(bin) && fs.readdirSync(bin).some((f) => f.endsWith('skizze.txt'))
+ && !(await ev(() => window.__t.editor.state())).files.includes('skizze.txt'), fs.existsSync(bin) ? fs.readdirSync(bin).join(',') : 'kein Papierkorb');
+ await ctx(`.soma/feedback/${fbFiles[0]}`); await menuItemClick('Pfad an Agent geben');
+ await waitFor('Pfad der Markierung im Terminal', (f) => window.__t.termText(f[0]).includes(`[Datei: .soma/feedback/${f[1]}]`), 5000, [tid, fbFiles[0]]).catch(() => {});
+ check('Markierung: Rechtsklick „Pfad an Agent geben“ fügt den Pfad ein', (await ev((id) => window.__t.termText(id), tid)).includes(`[Datei: .soma/feedback/${fbFiles[0]}]`));
+ await ev((id) => window.soma.term.write(id, '\x03'), tid);
+ await shot('3b-dateien-menue');
+ await ev(() => window.__t.showPanel(null));
+
// 4) Auto-Build: Änderung an model.py -> neuer Build -> drittes Bauteil
const modelPy = path.join(proj.dir, 'model.py');
const original = fs.readFileSync(modelPy, 'utf8');
@@ -288,6 +351,26 @@ try {
check('„Neu" legt ein zweites Projekt mit eigener UUID an', p2.id !== proj.id, p2.id.slice(0, 8));
await sleep(600);
check('Projektwechsel: genau ein frisches Terminal', await ev(() => window.__t.terminals.count) === 1);
+ // Die alte Shell meldet ihr Ende erst nach dem Wechsel. Das darf das neue Terminal nicht als beendet markieren,
+ // sonst lässt sich nichts mehr einfügen („Das Terminal ist beendet“), obwohl darin ein Agent läuft.
+ await sleep(2500);
+ await ev(() => window.__t.insert('[Test nach Wechsel] '));
+ const afterSwitch = await ev(() => window.__t.toast());
+ check('Nach dem Wechsel: Einfügen ins neue Terminal geht', !afterSwitch.error && afterSwitch.text.includes('In die Eingabe von Terminal eingefügt'), afterSwitch.text.slice(0, 60));
+ await ev(() => window.soma.term.write(window.__t.terminals.activeId, '\x03'));
+ // Aktives Terminal beendet, ein anderes läuft noch: Der Text geht dorthin, und dieses kommt nach vorn
+ const firstTid = await ev(() => window.__t.terminals.activeId);
+ const secondTid = await ev(() => window.__t.terminals.add({ title: 'Zweites' }));
+ await sleep(1500);
+ await ev((id) => window.soma.term.write(id, 'exit\r'), secondTid);
+ await waitFor('zweites Terminal beendet', (id) => window.__t.termText(id).includes('Prozess beendet'), 10000, secondTid).catch(() => {});
+ await ev(() => window.__t.insert('[Test Ersatzterminal] '));
+ const fallback = await ev(() => window.__t.toast());
+ await waitFor('Text im ersten Terminal', (id) => window.__t.termText(id).includes('[Test Ersatzterminal]'), 5000, firstTid).catch(() => {});
+ check('Aktives Terminal beendet: Text geht ins zuletzt benutzte laufende, das nach vorn kommt', !fallback.error && await ev(() => window.__t.terminals.activeId) === firstTid
+ && (await ev((id) => window.__t.termText(id), firstTid)).includes('[Test Ersatzterminal]'), fallback.text.slice(0, 60));
+ await ev((id) => window.soma.term.write(id, '\x03'), firstTid);
+ await ev((id) => window.__t.terminals.close(id), secondTid);
check('Beide Arbeitsordner existieren getrennt', fs.existsSync(proj.dir) && fs.existsSync(p2.dir) && proj.dir !== p2.dir);
if (app.visible) { await sleep(500); await page.screenshot(path.join(APP, 'test', 'smoke.png')); }
diff --git a/app/test/unit.mjs b/app/test/unit.mjs
index 041a904..ffeb6af 100644
--- a/app/test/unit.mjs
+++ b/app/test/unit.mjs
@@ -14,7 +14,7 @@ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'soma-unit-'));
try {
const out = path.join(tmp, 'files.mjs');
await build({ entryPoints: [path.join(APP, 'src', 'main', 'files.ts')], outfile: out, bundle: true, platform: 'node', format: 'esm', logLevel: 'silent' });
- const { importInputs, saveFeedbackImage, writeProjectText, backupText } = await import(pathToFileURL(out).href);
+ const { importInputs, saveFeedbackImage, writeProjectText, backupText, createEntry, renameEntry, trashEntry, entryPath, listFiles } = await import(pathToFileURL(out).href);
const proj = path.join(tmp, 'projekt');
const src = path.join(tmp, 'quelle');
@@ -86,6 +86,56 @@ try {
check('.soma zeigt nach außen: Markierung abgelehnt, draußen landet nichts', !r3.ok && fs.readdirSync(outside).length === 0, r3.error?.slice(0, 70) ?? '');
} else check('.soma als Verweis nach außen (übersprungen, Verweis nicht anlegbar)', true);
+ // Dateibaum: anlegen, umbenennen, Papierkorb, öffnen. Nichts überschrieben, App-Dateien gesperrt, nie endgültig gelöscht.
+ const ops = path.join(tmp, 'ops');
+ fs.mkdirSync(path.join(ops, 'parts'), { recursive: true });
+ fs.mkdirSync(path.join(ops, '.soma', 'feedback'), { recursive: true });
+ fs.writeFileSync(path.join(ops, 'model.py'), 'M');
+ fs.writeFileSync(path.join(ops, 'AGENTS.md'), 'A');
+ fs.writeFileSync(path.join(ops, '.soma', 'feedback', 'markierung-20260930-1405.png'), 'P');
+ let o = createEntry(ops, 'parts', 'deckel.py', false);
+ const o2 = createEntry(ops, '', 'skizzen', true);
+ check('Neue Datei und neuer Ordner', o.ok && o.path === 'parts/deckel.py' && fs.readFileSync(path.join(ops, 'parts', 'deckel.py'), 'utf8') === ''
+ && o2.ok && fs.statSync(path.join(ops, 'skizzen')).isDirectory(), `${o.path} ${o2.path}`);
+ fs.writeFileSync(path.join(ops, 'parts', 'deckel.py'), 'INHALT');
+ o = createEntry(ops, 'parts', 'deckel.py', false);
+ check('Neue Datei mit vorhandenem Namen: abgelehnt, Inhalt bleibt', !o.ok && /schon/.test(o.error) && fs.readFileSync(path.join(ops, 'parts', 'deckel.py'), 'utf8') === 'INHALT', o.error);
+ const badNames = ['', ' x', 'a/b', 'a:b', 'con', 'NUL.txt', 'x.', '..'].map((n) => createEntry(ops, '', n, false));
+ check('Ungültige Namen (leer, Leerzeichen, / : , reservierte Namen, Punkt am Ende) abgelehnt', badNames.every((x) => !x.ok), badNames.map((x) => x.error).join(' | ').slice(0, 90));
+ const blockedCreate = [createEntry(ops, 'output', 'x.step', false), createEntry(ops, '.soma', 'x', false), createEntry(ops, '.soma/feedback', 'x.png', false), createEntry(ops, '', 'AGENTS.md', false), createEntry(ops, '../draussen', 'x', false)];
+ check('Anlegen in output/, .soma/ und außerhalb sowie als App-Datei: abgelehnt', blockedCreate.every((x) => !x.ok) && !fs.existsSync(path.join(tmp, 'draussen', 'x')), blockedCreate.map((x) => x.error).join(' | ').slice(0, 90));
+
+ o = renameEntry(ops, 'parts/deckel.py', 'lid.py');
+ check('Umbenennen im selben Ordner', o.ok && o.path === 'parts/lid.py' && fs.readFileSync(path.join(ops, 'parts', 'lid.py'), 'utf8') === 'INHALT' && !fs.existsSync(path.join(ops, 'parts', 'deckel.py')), o.path ?? o.error);
+ fs.writeFileSync(path.join(ops, 'parts', 'body.py'), 'BODY');
+ o = renameEntry(ops, 'parts/lid.py', 'body.py');
+ check('Umbenennen auf vorhandenen Namen: abgelehnt, beide bleiben', !o.ok && fs.readFileSync(path.join(ops, 'parts', 'body.py'), 'utf8') === 'BODY' && fs.existsSync(path.join(ops, 'parts', 'lid.py')), o.error);
+ o = renameEntry(ops, 'parts/lid.py', 'Lid.py');
+ check('Nur Groß-/Kleinschreibung ändern geht', o.ok && fs.readdirSync(path.join(ops, 'parts')).includes('Lid.py'), fs.readdirSync(path.join(ops, 'parts')).join(','));
+ const blockedRename = [renameEntry(ops, 'model.py', 'haupt.py'), renameEntry(ops, 'AGENTS.md', 'x.md'), renameEntry(ops, 'parts', 'teile'), renameEntry(ops, 'parts/../model.py', 'x.py'), renameEntry(ops, 'skizzen', 'AGENTS.md')];
+ check('Umbenennen gesperrt: model.py, App-Dateien, parts/, Umweg über „..“, App-Name als Ziel', blockedRename.every((x) => !x.ok) && fs.existsSync(path.join(ops, 'model.py')) && fs.existsSync(path.join(ops, 'parts')),
+ blockedRename.map((x) => x.error).join(' | ').slice(0, 90));
+ o = renameEntry(ops, '.soma/feedback/markierung-20260930-1405.png', 'griff-zu-dick.png');
+ check('Markierung in .soma/feedback/ lässt sich umbenennen', o.ok && fs.existsSync(path.join(ops, '.soma', 'feedback', 'griff-zu-dick.png')), o.path ?? o.error);
+
+ const binned = [];
+ const fakeTrash = async (abs) => { binned.push(path.basename(abs)); fs.rmSync(abs, { recursive: true }); };
+ o = await trashEntry(ops, 'skizzen', fakeTrash);
+ const o3 = await trashEntry(ops, 'model.py', fakeTrash), o4 = await trashEntry(ops, 'AGENTS.md', fakeTrash), o5 = await trashEntry(ops, '.soma', fakeTrash);
+ check('Löschen geht in den Papierkorb, model.py, App-Dateien und .soma gesperrt', o.ok && !fs.existsSync(path.join(ops, 'skizzen')) && JSON.stringify(binned) === '["skizzen"]'
+ && !o3.ok && !o4.ok && !o5.ok && fs.existsSync(path.join(ops, 'model.py')), binned.join(','));
+ o = await trashEntry(ops, 'parts/body.py', async () => { throw new Error('Papierkorb nicht erreichbar'); });
+ check('Papierkorb klappt nicht: nichts gelöscht, Meldung', !o.ok && fs.existsSync(path.join(ops, 'parts', 'body.py')) && /nichts gelöscht/.test(o.error), o.error?.slice(0, 80));
+
+ fs.writeFileSync(path.join(ops, 'start.bat'), '@echo off');
+ fs.writeFileSync(path.join(ops, 'parts', 'foto.png'), 'P');
+ const runnable = [entryPath(ops, 'start.bat', true), entryPath(ops, 'parts/Lid.py', true)], fine = entryPath(ops, 'parts/foto.png', true), shown = entryPath(ops, 'start.bat', false);
+ check('Mit Standardprogramm öffnen: Ausführbares (.bat, .py) abgelehnt, Bild und Zeigen im Explorer gehen', runnable.every((x) => !x.abs && x.error) && !!fine.abs && !!shown.abs, runnable[0].error?.slice(0, 70));
+ const tree2 = listFiles(ops);
+ const fbNode = tree2.find((n) => n.path === '.soma/feedback');
+ check('Dateiliste: .soma/feedback/ als einziger Teil von .soma, sonst bleibt .soma verborgen', !!fbNode && fbNode.children.map((c) => c.name).join() === 'griff-zu-dick.png'
+ && !tree2.some((n) => n.path === '.soma'), tree2.map((n) => n.path).join(','));
+
// Editor: schreiben nur, wenn die Platte noch dem gelesenen Stand entspricht (der Agent schreibt an denselben Dateien)
const bdir = path.join(tmp, 'sicherungen');
const mp = path.join(proj, 'model.py');