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: Hauptprozess für die neue Oberfläche

Kai-Jungsthoefel7fa5447c6ae7
diff --git a/app/src/main/build.ts b/app/src/main/build.ts
index d2d5c16..710dd76 100644
--- a/app/src/main/build.ts
+++ b/app/src/main/build.ts
@@ -27,9 +27,16 @@ export class BuildManager extends EventEmitter {
constructor(private readonly dir: string) { super(); }
- /** Dateiaenderung im Projekt gemeldet (nur relevant bei eingeschaltetem Auto-Build). */
+ /** Dateiaenderung im Projekt gemeldet. Ohne Auto-Build merkt sich der Stand nur, dass er veraltet ist. */
sourceChanged(): void {
if (this.autoBuild) this.schedule('Dateiänderung');
+ else if (!this.status.stale) this.setStatus({ ...this.status, stale: true });
+ }
+
+ /** Auto-Build umschalten. Wird er eingeschaltet, während der Stand veraltet ist, baut er gleich nach. */
+ setAuto(on: boolean): void {
+ this.autoBuild = on;
+ if (on && this.status.stale) this.schedule('Auto-Build eingeschaltet', 0);
}
schedule(reason: string, delay = DEBOUNCE_MS): void {
diff --git a/app/src/main/files.ts b/app/src/main/files.ts
index b9be8bb..23ce74e 100644
--- a/app/src/main/files.ts
+++ b/app/src/main/files.ts
@@ -1,10 +1,36 @@
import fs from 'node:fs';
import path from 'node:path';
-import type { FileNode } from '../shared/types';
+import type { FileNode, ImportResult } from '../shared/types';
const HIDDEN = new Set(['.git', '.cadide', '__pycache__', 'node_modules', '.venv', 'venv', 'env']);
const MAX_ENTRIES = 2000;
const MAX_DEPTH = 5;
+const MAX_IMPORT_BYTES = 500 * 1024 * 1024;
+
+/**
+ * Kopiert gezogene Dateien nach inputs/ (E33). Der Agent bindet sie danach im Skript ein.
+ * Nichts wird überschrieben: bei gleichem Namen entsteht „name (2).ext“. Ordner werden nicht übernommen.
+ */
+export function importInputs(root: string, sources: string[]): ImportResult {
+ const res: ImportResult = { files: [], errors: [] };
+ for (const src of sources) {
+ const base = path.basename(src);
+ try {
+ const st = fs.statSync(src);
+ if (!st.isFile()) { res.errors.push(`${base}: Nur einzelne Dateien lassen sich übernehmen, keine Ordner.`); continue; }
+ if (st.size > MAX_IMPORT_BYTES) { res.errors.push(`${base}: größer als 500 MB, nicht übernommen.`); continue; }
+ const dest = resolveInside(root, 'inputs');
+ fs.mkdirSync(dest, { recursive: true });
+ const ext = path.extname(base), stem = base.slice(0, base.length - ext.length);
+ let name = base;
+ for (let i = 2; fs.existsSync(path.join(dest, name)); i++) name = `${stem} (${i})${ext}`;
+ // COPYFILE_EXCL: falls zwischen Prüfung und Kopie doch eine Datei entsteht, schlägt die Kopie fehl statt zu überschreiben
+ fs.copyFileSync(src, resolveInside(root, `inputs/${name}`), fs.constants.COPYFILE_EXCL);
+ res.files.push(`inputs/${name}`);
+ } catch (e) { res.errors.push(`${base}: ${e instanceof Error ? e.message : String(e)}`); }
+ }
+ return res;
+}
/**
* Loest einen Pfad relativ zum Projektordner auf und lehnt alles ab, was ausserhalb landet
diff --git a/app/src/main/git.ts b/app/src/main/git.ts
index fa5f49c..ed4c3ef 100644
--- a/app/src/main/git.ts
+++ b/app/src/main/git.ts
@@ -3,10 +3,17 @@ import fs from 'node:fs';
import path from 'node:path';
import { resolveInside } from './files';
-export interface Commit { hash: string; short: string; author: string; date: string; subject: string }
+export interface Commit { hash: string; short: string; author: string; date: string; subject: string; byApp: boolean }
export interface RunResult { ok: boolean; code: number; out: string; err: string }
export interface GitStatus { dirty: boolean; changed: number; head: string | null }
+/**
+ * Markiert Commits der App, damit die Verlaufsleiste sie von Commits des Agenten unterscheiden kann. Der Autor taugt dafür
+ * nicht: Agent und App committen mit derselben Git-Identität. Ältere Projekte ohne Trailer erkennt die Leiste am Betreff.
+ */
+const APP_TRAILER = ['--trailer', 'Erstellt-von: CAD-IDE'];
+const APP_SUBJECT = /^(Neues Modell angelegt|Automatischer Snapshot beim Speichern|Sicherung vor Wiederherstellung|Stand wiederhergestellt: )/;
+
/** Gilt für jeden Aufruf: UTF-8-Pfade lesbar, keine Zeilenenden-Umwandlung (ZIPs wandern zwischen Systemen). */
const COMMON = ['-c', 'core.quotepath=false', '-c', 'core.autocrlf=false'];
/** `output/` zählt nicht als Änderung: STEP-Dateien sind nicht byte-stabil (Zeitstempel, teils Reihenfolge). */
@@ -68,7 +75,7 @@ export class GitRepo {
if (!name.out.trim()) await this.mustRun(['config', '--local', 'user.name', 'CAD-IDE'], true);
if (!email.out.trim()) await this.mustRun(['config', '--local', 'user.email', 'cadide@localhost'], true);
await this.mustRun(['add', '-A'], true);
- await this.mustRun(['commit', '--allow-empty', '--no-verify', '-m', message], true);
+ await this.mustRun(['commit', '--allow-empty', '--no-verify', '-m', message, ...APP_TRAILER], true);
return (await this.mustRun(['rev-parse', 'HEAD'])).trim();
});
}
@@ -89,18 +96,19 @@ export class GitRepo {
return this.serial(async () => {
if (!(await this.status()).dirty) return null;
await this.mustRun(['add', '-A'], true);
- await this.mustRun(['commit', '--no-verify', '-m', message], true);
+ await this.mustRun(['commit', '--no-verify', '-m', message, ...APP_TRAILER], true);
return (await this.mustRun(['rev-parse', 'HEAD'])).trim();
});
}
/** Verlauf, älteste zuerst. Ein kaputtes oder leeres Repository liefert eine leere Liste. */
async log(limit = 500): Promise<Commit[]> {
- const r = await this.run(['log', `-n${limit}`, '--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s%x1e', 'HEAD']);
+ const fmt = '--format=%H%x1f%h%x1f%an%x1f%aI%x1f%s%x1f%(trailers:key=Erstellt-von,valueonly,separator=%x2c)%x1e';
+ const r = await this.run(['log', `-n${limit}`, fmt, 'HEAD']);
if (!r.ok) return [];
return r.out.split('\x1e').map((e) => e.trim()).filter(Boolean).map((e) => {
- const [hash, short, author, date, subject] = e.split('\x1f');
- return { hash, short, author, date, subject };
+ const [hash, short, author, date, subject, by = ''] = e.split('\x1f');
+ return { hash, short, author, date, subject, byApp: by.includes('CAD-IDE') || APP_SUBJECT.test(subject) };
}).reverse();
}
@@ -137,7 +145,7 @@ export class GitRepo {
let safety: string | null = null;
if ((await this.status()).dirty) {
await this.mustRun(['add', '-A'], true);
- await this.mustRun(['commit', '--no-verify', '-m', 'Sicherung vor Wiederherstellung'], true);
+ await this.mustRun(['commit', '--no-verify', '-m', 'Sicherung vor Wiederherstellung', ...APP_TRAILER], true);
safety = (await this.mustRun(['rev-parse', 'HEAD'])).trim();
}
const target = new Set((await this.mustRun(['ls-tree', '-r', '-z', '--name-only', hash])).split('\0').filter(Boolean));
@@ -149,7 +157,7 @@ export class GitRepo {
await this.mustRun(['add', '-A'], true);
const diff = await this.run(['diff', '--cached', '--quiet']);
if (diff.ok) return { commit: null, safety }; // Stand war schon identisch
- await this.mustRun(['commit', '--no-verify', '-m', `Stand wiederhergestellt: ${subject} (${short})`], true);
+ await this.mustRun(['commit', '--no-verify', '-m', `Stand wiederhergestellt: ${subject} (${short})`, ...APP_TRAILER], true);
return { commit: (await this.mustRun(['rev-parse', 'HEAD'])).trim(), safety };
});
}
diff --git a/app/src/main/main.ts b/app/src/main/main.ts
index 007b0f0..ecb7cbb 100644
--- a/app/src/main/main.ts
+++ b/app/src/main/main.ts
@@ -3,10 +3,11 @@ import fs from 'node:fs';
import path from 'node:path';
import { detectAgents } from './agents';
import { setTestAnswers } from './dialogs';
-import { listFiles, resolveInside } from './files';
+import { importInputs, listFiles, resolveInside } from './files';
import { ProjectController } from './projects';
import { terminalEnv } from './terminals';
-import { createProject, getLastProject } from './workspace';
+import { thumbnailsDir } from './paths';
+import { createProject, getLastProject, isProjectId } from './workspace';
// App-Daten (Arbeitsordner, Caches) gehören auf die lokale Platte. Das Roaming-Profil (%APPDATA%) kann in Firmennetzen
// umgeleitet oder synchronisiert sein, das ist für Arbeitsordner und GPU-Cache ungeeignet. Tests leiten alles um.
@@ -25,6 +26,17 @@ function registerIpc(ctl: ProjectController): void {
ipcMain.handle('project:saveState', () => ctl.saveState());
ipcMain.handle('project:save', (_e, saveAs?: boolean) => ctl.save(!!saveAs));
ipcMain.handle('project:openZip', () => ctl.openZip());
+ ipcMain.handle('project:reveal', () => ctl.reveal());
+ ipcMain.handle('project:setThumb', (_e, dataUrl: string) => {
+ const m = /^data:image\/jpeg;base64,([A-Za-z0-9+/=]+)$/.exec(String(dataUrl));
+ if (!m || m[1].length > 2_000_000 || !ctl.session) return;
+ fs.mkdirSync(thumbnailsDir(), { recursive: true });
+ fs.writeFileSync(path.join(thumbnailsDir(), `${ctl.session.id}.jpg`), Buffer.from(m[1], 'base64'));
+ });
+ ipcMain.handle('project:thumb', (_e, id: string) => {
+ if (!isProjectId(String(id))) return null;
+ try { return `data:image/jpeg;base64,${fs.readFileSync(path.join(thumbnailsDir(), `${id}.jpg`)).toString('base64')}`; } catch { return null; }
+ });
ipcMain.handle('versions:log', () => ctl.gitLog());
ipcMain.handle('versions:preview', (_e, hash: string) => ctl.preview(hash));
@@ -32,10 +44,12 @@ function registerIpc(ctl: ProjectController): void {
ipcMain.handle('build:run', () => ctl.need().builds.start('manuell'));
ipcMain.handle('build:cancel', () => ctl.need().builds.cancel());
- ipcMain.handle('build:setAuto', (_e, on: boolean) => { ctl.need().builds.autoBuild = !!on; });
+ ipcMain.handle('build:setAuto', (_e, on: boolean) => ctl.need().builds.setAuto(!!on));
ipcMain.handle('build:status', () => ctl.need().builds.status);
+ ipcMain.handle('build:export', (_e, format: string, part: string | null) => ctl.exportModel(String(format), part ? String(part) : null));
ipcMain.handle('fs:list', () => listFiles(dir()));
+ ipcMain.handle('fs:import', (_e, paths: string[]) => importInputs(dir(), Array.isArray(paths) ? paths.map(String) : []));
ipcMain.handle('fs:readText', (_e, rel: string) => fs.readFileSync(resolveInside(dir(), rel), 'utf8'));
ipcMain.handle('fs:readBinary', (_e, rel: string) => {
const b = fs.readFileSync(resolveInside(dir(), rel));
@@ -79,7 +93,7 @@ const testWindowMode = process.env.CADIDE_HIDDEN;
function createWindow(): void {
win = new BrowserWindow({
- width: 1600, height: 950, title: 'CAD-IDE', backgroundColor: '#1e2227', show: testWindowMode !== '1' && testWindowMode !== 'offscreen',
+ width: 1600, height: 950, title: 'CAD-IDE', backgroundColor: '#121417', show: testWindowMode !== '1' && testWindowMode !== 'offscreen',
webPreferences: {
preload: path.join(__dirname, '..', 'preload', 'preload.js'),
contextIsolation: true, nodeIntegration: false, sandbox: true,
diff --git a/app/src/main/paths.ts b/app/src/main/paths.ts
index 41209ed..8bdf368 100644
--- a/app/src/main/paths.ts
+++ b/app/src/main/paths.ts
@@ -15,6 +15,8 @@ export const appStateFile = () => path.join(userDataDir(), 'state.json');
export const backupsDir = () => path.join(userDataDir(), 'workspace-backups');
/** Vorschauen alter Stände (aus dem Verlauf erzeugt, jederzeit neu erzeugbar). */
export const previewsDir = () => path.join(userDataDir(), 'previews');
+/** Vorschaubilder für die Startseite (vom Viewer nach dem Laden des Modells, jederzeit neu erzeugbar). */
+export const thumbnailsDir = () => path.join(userDataDir(), 'thumbnails');
/** Vorlage fuer neue Projekte (liegt neben dem Programm, spaeter im Installationspaket). */
export const templateDir = () => path.join(app.getAppPath(), 'resources', 'template');
diff --git a/app/src/main/projects.ts b/app/src/main/projects.ts
index af0ee2a..2b67a31 100644
--- a/app/src/main/projects.ts
+++ b/app/src/main/projects.ts
@@ -1,7 +1,7 @@
-import type { BrowserWindow, WebContents } from 'electron';
+import { shell, type BrowserWindow, type WebContents } from 'electron';
import fs from 'node:fs';
import path from 'node:path';
-import type { GitLog, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState } from '../shared/types';
+import type { ExportResult, GitLog, ModelMap, OpenResult, PreviewResult, ProjectInfo, RestoreResult, SaveResult, SaveState } from '../shared/types';
import { BuildManager, buildIsStale, newestSourceMtime, runCadide } from './build';
import { choose, choosePath } from './dialogs';
import { GitRepo } from './git';
@@ -110,7 +110,28 @@ export class ProjectController {
if (!app.zipPath) unsaved = true;
else if (hasRepo) unsaved = st.dirty || st.head !== (app.savedHead ?? null);
else unsaved = newestSourceMtime(s.dir) > (app.savedAt ?? 0); // ohne Git bleibt nur der Zeitvergleich
- return { zipPath: app.zipPath ?? null, savedHead: app.savedHead ?? null, head: st.head, dirtyFiles: st.changed, unsaved, hasRepo };
+ return { zipPath: app.zipPath ?? null, savedHead: app.savedHead ?? null, head: st.head, dirtyFiles: st.changed, unsaved, hasRepo, savedAt: app.zipPath ? app.savedAt ?? null : null };
+ }
+
+ /** ZIP im Dateimanager zeigen. Noch nicht gespeichert (oder ZIP verschwunden): den Arbeitsordner öffnen. */
+ async reveal(): Promise<void> {
+ const s = this.need();
+ const zip = getAppState(s.id).zipPath;
+ if (zip && fs.existsSync(zip)) shell.showItemInFolder(zip);
+ else await shell.openPath(s.dir);
+ }
+
+ /** Einzelexport über `cadide export` (E34). Der Export baut das Modell selbst, der Viewer bleibt davon unberührt. */
+ async exportModel(format: string, part: string | null): Promise<ExportResult> {
+ const s = this.need();
+ if (!/^[a-z0-9]{2,5}$/.test(format)) return { ok: false, files: [], error: `Unbekanntes Format: ${format}` };
+ // `--` vor dem Namen: Bauteilnamen dürfen mit einem Minus beginnen, ohne als Option zu gelten
+ const args = ['export', '--format', format, '--project', s.dir, ...(part ? ['--', part] : ['--all'])];
+ const r = await runCadide(args, s.dir, 5 * 60 * 1000);
+ const files = [...r.out.matchAll(/^exportiert: (.+)$/gm)].map((m) => m[1].trim());
+ if (r.ok) return { ok: true, files };
+ const msg = (r.err || r.out).trim().split(/\r?\n/).slice(-3).join('\n');
+ return { ok: false, files, error: msg || 'Export fehlgeschlagen' };
}
/** Speichern: Snapshot im Verlauf, dann ZIP. Fragt beim ersten Mal nach dem Ort. */
diff --git a/app/src/preload/preload.ts b/app/src/preload/preload.ts
index ca7f493..1088392 100644
--- a/app/src/preload/preload.ts
+++ b/app/src/preload/preload.ts
@@ -1,4 +1,4 @@
-import { contextBridge, ipcRenderer } from 'electron';
+import { contextBridge, ipcRenderer, webUtils } from 'electron';
import type { CadideApi } from '../shared/types';
/** Schmale, feste Schnittstelle zwischen Renderer und Hauptprozess. Der Renderer hat keinen Node-Zugriff. */
@@ -14,6 +14,9 @@ const api: CadideApi = {
save: (saveAs) => ipcRenderer.invoke('project:save', saveAs),
openZip: () => ipcRenderer.invoke('project:openZip'),
onSaveState: (cb) => { ipcRenderer.on('save:state', (_e, st) => cb(st)); },
+ reveal: () => ipcRenderer.invoke('project:reveal'),
+ setThumb: (dataUrl) => ipcRenderer.invoke('project:setThumb', dataUrl),
+ thumb: (id) => ipcRenderer.invoke('project:thumb', id),
},
versions: {
log: () => ipcRenderer.invoke('versions:log'),
@@ -27,12 +30,15 @@ const api: CadideApi = {
setAuto: (on) => ipcRenderer.invoke('build:setAuto', on),
status: () => ipcRenderer.invoke('build:status'),
onStatus: (cb) => { ipcRenderer.on('build:status', (_e, s) => cb(s)); },
+ export: (format, part) => ipcRenderer.invoke('build:export', format, part),
},
fs: {
list: () => ipcRenderer.invoke('fs:list'),
readText: (rel) => ipcRenderer.invoke('fs:readText', rel),
readBinary: (rel) => ipcRenderer.invoke('fs:readBinary', rel),
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)),
},
term: {
create: (opts) => ipcRenderer.invoke('term:create', opts),
diff --git a/app/src/shared/types.ts b/app/src/shared/types.ts
index 723d729..3f8d41e 100644
--- a/app/src/shared/types.ts
+++ b/app/src/shared/types.ts
@@ -22,7 +22,16 @@ export interface BuildResult {
}
export type BuildState = 'idle' | 'building' | 'ok' | 'error';
-export interface BuildStatus { state: BuildState; result?: BuildResult; startedAt?: number; queued?: boolean; reason?: string }
+export interface BuildStatus {
+ state: BuildState; result?: BuildResult; startedAt?: number; queued?: boolean; reason?: string;
+ /** Auto-Build ist aus und der Quelltext hat sich seit dem letzten Build geändert. */
+ stale?: boolean;
+}
+
+/** Einzelexport über `cadide export` (E34). `files` relativ zum Projekt. */
+export interface ExportResult { ok: boolean; files: string[]; error?: string }
+/** Dateien, die per Ziehen nach inputs/ kopiert wurden (E33). */
+export interface ImportResult { files: string[]; errors: string[] }
export interface FileNode { name: string; path: string; dir: boolean; children?: FileNode[] }
@@ -43,11 +52,14 @@ export interface SaveState {
dirtyFiles: number;
unsaved: boolean;
hasRepo: boolean;
+ /** Zeitpunkt des letzten Speicherns (ms seit 1970), null wenn noch nie gespeichert. */
+ savedAt: number | null;
}
export interface SaveResult { cancelled: boolean; zipPath?: string; snapshot?: string | null; files?: number; bytes?: number; warnings?: string[]; error?: string }
export interface OpenResult { cancelled: boolean; opened?: boolean; error?: string }
-export interface CommitInfo { hash: string; short: string; author: string; date: string; subject: string }
+/** `byApp`: Stand hat die App angelegt (Start, Snapshot, Wiederherstellen), sonst der Agent oder der Nutzer. */
+export interface CommitInfo { hash: string; short: string; author: string; date: string; subject: string; byApp: boolean }
export interface GitLog { commits: CommitInfo[]; problems: string[]; head: string | null; dirtyFiles: number }
export interface PreviewResult { commit: CommitInfo | null; glb: ArrayBuffer; map: ModelMap; error?: string }
export interface RestoreResult { cancelled: boolean; commit?: string | null; safety?: string | null; error?: string }
@@ -64,6 +76,11 @@ export interface CadideApi {
save(saveAs?: boolean): Promise<SaveResult>;
openZip(): Promise<OpenResult>;
onSaveState(cb: (s: SaveState) => void): void;
+ /** Zeigt die ZIP im Dateimanager (noch nicht gespeichert: den Arbeitsordner). */
+ reveal(): Promise<void>;
+ /** Vorschaubild des offenen Modells für die Startseite (JPEG als Data-URL). */
+ setThumb(dataUrl: string): Promise<void>;
+ thumb(id: string): Promise<string | null>;
};
versions: {
log(): Promise<GitLog>;
@@ -79,12 +96,16 @@ export interface CadideApi {
setAuto(on: boolean): Promise<void>;
status(): Promise<BuildStatus>;
onStatus(cb: (s: BuildStatus) => void): void;
+ /** `part` null = alle Bauteile ohne Referenzen. */
+ export(format: string, part: string | null): Promise<ExportResult>;
};
fs: {
list(): Promise<FileNode[]>;
readText(rel: string): Promise<string>;
readBinary(rel: string): Promise<ArrayBuffer>;
onChanged(cb: () => void): void;
+ /** Kopiert gezogene Dateien nach inputs/. Vorhandenes wird nie überschrieben. */
+ importFiles(files: File[]): Promise<ImportResult>;
};
term: {
create(opts?: { command?: string; title?: string }): Promise<number>;