[9] MCP-Brücke zur offenen App: KI-Zugriff (opt-in, Sitzungsschlüssel), gemeinsame Werkzeugliste, Protokoll und Pause
dossier-cli mcp --app spricht MCP über stdio und lauscht auf 127.0.0.1; die App verbindet sich nur mit „KI-Zugriff erlauben“ als WebSocket-Client (gegenseitige HMAC-Anmeldung). Werkzeuge für Datei und App aus einer Liste (core/aiToolDefs.ts, core/aiTools.ts), run_command über die Kern-Befehle, jede Änderung ein Undo-Schritt „KI: <werkzeug>“, KI-Protokoll mit Pause.
This commit is contained in:
25 files changed
+1594
-119
No files matched your search
@@ -136,6 +136,25 @@ Weitere Befehle: `section`, `elevation`, `dxf`, `dwg`, `step`, `glb`,
|
||||
`schedule`, `sun`, `validate`, `bench` und `mcp`, mit dem ein KI-Assistent das
|
||||
Projekt abfragen und ändern kann.
|
||||
|
||||
### KI-Assistent am offenen Projekt (MCP)
|
||||
|
||||
`dossier-cli … mcp` arbeitet auf einer Datei. Für das in der App **offene**
|
||||
Projekt: in Dossier unter *Fenster → Einstellungen → KI-Zugriff* „KI-Zugriff
|
||||
erlauben“ einschalten (aus per Vorgabe, nur 127.0.0.1) und die angezeigte Zeile
|
||||
im MCP-Client eintragen, z. B. in Claude Desktop (`claude_desktop_config.json`)
|
||||
bzw. mit `claude mcp add dossier -- node …/dossier-cli.mjs mcp --app --token …`:
|
||||
|
||||
```json
|
||||
{ "mcpServers": { "dossier": { "command": "node",
|
||||
"args": ["/pfad/zu/dist-cli/dossier-cli.mjs", "mcp", "--app", "--token", "<schlüssel>"] } } }
|
||||
```
|
||||
|
||||
Der Schlüssel gilt bis zum Beenden der App. Werkzeuge: Abfragen (Auswahl,
|
||||
Geschosse, Elemente, Kennzahlen, Listen), Befehle mit JSON-Parametern, Auswahl
|
||||
und Zoom, Export (SVG/PDF/IFC; Speichern nur über den Dialog). Jede Änderung ist
|
||||
ein Undo-Schritt „KI: …“ und steht im KI-Protokoll unten links, dort lässt sich
|
||||
die KI auch pausieren.
|
||||
|
||||
## Aufbau
|
||||
|
||||
```
|
||||
|
||||
@@ -1126,6 +1126,17 @@ Entscheid CLA vs. Verzicht auf Dual Licensing.
|
||||
Rest (nur Laden/Import/CLI) unter [K4] S3. · M
|
||||
29.10.: auch Laden/Import/CLI ohne Projekt-Differenz (`diffToOps` gelöscht); Öffnen/Neu leeren den Verlauf im Kern, ein Import = ein Schritt ([K4] S3/S4).
|
||||
- ◐ **[9] MCP-Brücke.** Headless `dossier-cli … mcp`; Brücke zum offenen Fenster fehlt. · M
|
||||
30.10.: Brücke zur offenen App. `dossier-cli mcp --app [--port 7979] --token …` spricht MCP (stdio) und lauscht auf
|
||||
127.0.0.1; die App verbindet sich als WebSocket-Client, nur mit „KI-Zugriff erlauben“ (Einstellungen, aus per Vorgabe,
|
||||
Sitzungsschlüssel, gegenseitige HMAC-Anmeldung ohne dass der Schlüssel reist) — kein eigener Server im Tauri-Host, kein
|
||||
Rust nötig. Eine Werkzeugliste für Datei und App (`core/aiToolDefs.ts`, Verteilung `core/aiTools.ts`): project_info,
|
||||
query, render_svg, apply_ops, run_command (Kern-Befehle `cmdOps` mit JSON), validate, kennzahlen, schedule; nur App:
|
||||
get_selection, select, zoom_to, export pdf, Speichern über den Dialog. Jede Änderung = ein Undo-Schritt „KI: <werkzeug>“,
|
||||
KI-Protokoll unten links mit „KI pausieren“ (`ui/AiActivityPanel.tsx`, `state/aiAccess.ts`). Tests: `aiTools.test.ts`,
|
||||
`mcpBridge.test.ts`, `aiAccess.test.ts`, e2e `aiBridge.spec.ts` (MCP-Client → Brücke → Browser-App).
|
||||
**Offen:** in Tauri/macOS und Electron nicht getestet (WebSocket aus `tauri://localhost` auf `ws://127.0.0.1` ungeprüft;
|
||||
CSP ist `null`); kein Ereignis-Strom (Auswahl/Änderungen an den Client); Undo/Redo und Ansichten (Schnitt/3D) als
|
||||
Werkzeuge; [C3] (`screenshot`, `ui_click`) bleibt offen.
|
||||
|
||||
### Daten
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// [9] MCP-Brücke Ende zu Ende: KI-Zugriff in den Einstellungen einschalten, `dossier-cli mcp --app`
|
||||
// mit dem angezeigten Schlüssel starten, über MCP (stdio) eine Wand zeichnen lassen, Protokoll,
|
||||
// Rückgängig („KI: run_command“) und Pause prüfen.
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import { createServer } from "node:net";
|
||||
import { expect, startNewProject, test } from "./app";
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolve) => {
|
||||
const s = createServer();
|
||||
s.listen(0, "127.0.0.1", () => {
|
||||
const a = s.address();
|
||||
const port = typeof a === "object" && a ? a.port : 0;
|
||||
s.close(() => resolve(port));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** MCP-Client über stdio: eine Anfrage je Zeile, Antworten nach id. */
|
||||
function mcpClient(proc: ChildProcessWithoutNullStreams) {
|
||||
let buf = "";
|
||||
const waiting = new Map<number, (v: unknown) => void>();
|
||||
proc.stdout.setEncoding("utf8");
|
||||
proc.stdout.on("data", (chunk: string) => {
|
||||
buf += chunk;
|
||||
let nl: number;
|
||||
while ((nl = buf.indexOf("\n")) >= 0) {
|
||||
const msg = JSON.parse(buf.slice(0, nl)) as { id: number };
|
||||
buf = buf.slice(nl + 1);
|
||||
waiting.get(msg.id)?.(msg);
|
||||
waiting.delete(msg.id);
|
||||
}
|
||||
});
|
||||
let id = 0;
|
||||
const request = (method: string, params: object = {}) =>
|
||||
new Promise<{ result: { isError?: boolean; content?: { text: string }[]; tools?: { name: string }[] } }>((resolve) => {
|
||||
const my = ++id;
|
||||
waiting.set(my, resolve as (v: unknown) => void);
|
||||
proc.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: my, method, params }) + "\n");
|
||||
});
|
||||
const call = async (name: string, args: object = {}) => (await request("tools/call", { name, arguments: args })).result;
|
||||
return { request, call };
|
||||
}
|
||||
|
||||
test("KI-Zugriff: MCP-Client zeichnet über die Brücke eine Wand in der offenen App", async ({ page }) => {
|
||||
const port = await freePort();
|
||||
await page.addInitScript((p) => localStorage.setItem("dossier.aiBridge.port", String(p)), port);
|
||||
await startNewProject(page);
|
||||
|
||||
// Aus per Vorgabe: kein Protokoll sichtbar. Einschalten in den Einstellungen.
|
||||
await expect(page.getByTestId("ai-activity")).toHaveCount(0);
|
||||
await page.getByRole("menubar").getByRole("button", { name: "Fenster", exact: true }).click();
|
||||
await page.getByRole("option", { name: "Einstellungen" }).click();
|
||||
await page.getByRole("checkbox", { name: "KI-Zugriff erlauben" }).check();
|
||||
const token = await page.getByTestId("ai-token").inputValue();
|
||||
expect(token).toMatch(/^[0-9a-f]{32}$/);
|
||||
|
||||
const proc = spawn("node", ["dist-cli/dossier-cli.mjs", "mcp", "--app", "--port", String(port), "--token", token]);
|
||||
try {
|
||||
const mcp = mcpClient(proc);
|
||||
await mcp.request("initialize", { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "e2e", version: "1" } });
|
||||
const tools = (await mcp.request("tools/list")).result.tools!.map((t) => t.name);
|
||||
expect(tools).toEqual(expect.arrayContaining(["run_command", "select", "zoom_to", "export"]));
|
||||
|
||||
await expect(page.getByTestId("ai-status")).toHaveText("Verbunden", { timeout: 15_000 });
|
||||
await page.getByRole("button", { name: "Schließen" }).first().click();
|
||||
|
||||
const before = JSON.parse((await mcp.call("project_info")).content![0].text).counts.walls ?? 0;
|
||||
const r = await mcp.call("run_command", { cmd: "wall", params: { pts: [[0, 0], [5, 0]] } });
|
||||
expect(r.isError, r.content?.[0]?.text).toBe(false);
|
||||
const added = JSON.parse(r.content![0].text).added as { collection: string; id: string }[];
|
||||
expect(added.map((a) => a.collection)).toEqual(["walls"]);
|
||||
expect(JSON.parse((await mcp.call("project_info")).content![0].text).counts.walls).toBe(before + 1);
|
||||
expect((await mcp.call("select", { ids: [added[0].id] })).isError).toBe(false);
|
||||
expect(JSON.parse((await mcp.call("get_selection")).content![0].text)).toEqual({ walls: [added[0].id] });
|
||||
|
||||
// Protokoll in der App: Änderung markiert
|
||||
const log = page.getByTestId("ai-log");
|
||||
await expect(log.locator("li.is-change")).toHaveCount(1);
|
||||
await expect(log).toContainText("run_command");
|
||||
|
||||
// Ein Undo-Schritt nimmt die ganze KI-Änderung zurück
|
||||
await page.keyboard.press("Escape");
|
||||
await page.keyboard.press("ControlOrMeta+z");
|
||||
await expect.poll(async () => JSON.parse((await mcp.call("project_info")).content![0].text).counts.walls ?? 0).toBe(before);
|
||||
|
||||
// Pause: Aufrufe abgewiesen
|
||||
await page.getByTestId("ai-pause").check();
|
||||
const paused = await mcp.call("project_info");
|
||||
expect(paused.isError).toBe(true);
|
||||
expect(paused.content![0].text).toContain("pausiert");
|
||||
} finally {
|
||||
proc.kill();
|
||||
}
|
||||
});
|
||||
@@ -12,6 +12,10 @@ const ALLOWED_CONSOLE_ERRORS: { re: RegExp; why: string }[] = [
|
||||
re: /createBuffer failed|wgpu-.*webgpu\.rs/,
|
||||
why: "render2d/render3d: SwiftShader verliert das WebGPU-Gerät beim Präsentieren, createBuffer(mappedAtCreation) wirft, wgpu paniert (nur headless). render2d baut dann neu auf bzw. fällt auf SVG zurück (planEngine.spec.ts).",
|
||||
},
|
||||
{
|
||||
re: /WebSocket connection to 'ws:\/\/127\.0\.0\.1:\d+\/' failed/,
|
||||
why: "[9] KI-Zugriff: die App sucht die MCP-Brücke alle 2 s auf 127.0.0.1, bis sie läuft; Chromium meldet jeden Fehlversuch (aiBridge.spec.ts).",
|
||||
},
|
||||
];
|
||||
|
||||
export const test = base.extend<{ errors: string[] }>({
|
||||
|
||||
+17
@@ -127,6 +127,8 @@ import { RoomStampEditor } from "./panels/RoomStampEditor";
|
||||
import { defaultRoomStamp } from "./model/roomStamp";
|
||||
import { StatusBar } from "./ui/StatusBar";
|
||||
import { isOffline, setOffline } from "./net/net";
|
||||
import { setAiAccessEnabled, setAiView, useAiAccess } from "./state/aiAccess";
|
||||
import { AiActivityPanel } from "./ui/AiActivityPanel";
|
||||
import { markSessionClean, markSessionStart } from "./state/startupGuard";
|
||||
import { getTool } from "./tools/tools";
|
||||
import { computeSnap } from "./tools/snapping";
|
||||
@@ -2765,6 +2767,16 @@ export default function App() {
|
||||
setOfflineState(v);
|
||||
};
|
||||
|
||||
// [9] KI-Zugriff (MCP-Brücke, Einstellungen → Allgemein): Stand für die Einstellungen; die
|
||||
// Planansicht für `zoom_to` anmelden.
|
||||
const aiAccessState = useAiAccess();
|
||||
const aiAccess = { enabled: aiAccessState.enabled, token: aiAccessState.token, port: aiAccessState.port, status: aiAccessState.status };
|
||||
useEffect(() => {
|
||||
setAiView({ fitBounds: (pts) => planViewRef.current?.fitBounds(pts) });
|
||||
return () => setAiView(null);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Hell/Dunkel (Einstellungen → Darstellung). Standard Hell (styles.css);
|
||||
// Dunkel ist Opt-in und persistiert in localStorage.
|
||||
const { themeMode, setThemeMode } = useThemeModeState();
|
||||
@@ -2782,6 +2794,7 @@ export default function App() {
|
||||
referenceElevationMasl: project.referenceElevationMasl,
|
||||
scaleLineWeights: project.scaleLineWeights === true,
|
||||
offline,
|
||||
aiAccess,
|
||||
layout,
|
||||
},
|
||||
{
|
||||
@@ -2791,6 +2804,7 @@ export default function App() {
|
||||
onReferenceElevationChange: (n) => applyChange((p) => setFieldIfChanged(p, "referenceElevationMasl", n)),
|
||||
onScaleLineWeightsChange: setScaleLineWeights,
|
||||
onOfflineChange,
|
||||
onAiAccessChange: setAiAccessEnabled,
|
||||
onApplyLayout: (l) => setLayout(reconcileLayout(l)),
|
||||
},
|
||||
);
|
||||
@@ -3954,6 +3968,7 @@ export default function App() {
|
||||
)}
|
||||
|
||||
<BusyOverlay />
|
||||
<AiActivityPanel />
|
||||
|
||||
{/* Modaler Import-Dialog (DXF/DWG) — offen, sobald eine Datei gewählt/
|
||||
fallengelassen wurde. Liefert eine strukturierte Entscheidung an
|
||||
@@ -4015,6 +4030,8 @@ export default function App() {
|
||||
onScaleLineWeightsChange={setScaleLineWeights}
|
||||
offline={offline}
|
||||
onOfflineChange={onOfflineChange}
|
||||
aiAccess={aiAccess}
|
||||
onAiAccessChange={setAiAccessEnabled}
|
||||
layout={layout}
|
||||
onApplyLayout={(l) => setLayout(reconcileLayout(l))}
|
||||
onAliasOverridesChange={setAliasOverrides}
|
||||
|
||||
+8
-4
@@ -21,13 +21,13 @@ const call = async (...a: string[]) => run([file, ...a]);
|
||||
describe("dossier-cli", () => {
|
||||
it("importiert ausschliesslich ../core", () => {
|
||||
const src = readFileSync(join(process.cwd(), "src", "cli", "main.ts"), "utf8");
|
||||
for (const f of ["main.ts", "mcp.ts"]) {
|
||||
for (const f of ["main.ts", "mcp.ts", "mcpBridge.ts"]) {
|
||||
const text = readFileSync(join(process.cwd(), "src", "cli", f), "utf8");
|
||||
const rel = [...text.matchAll(/from\s+"(\.[^"]+)"/g)].map((m) => m[1]);
|
||||
expect(rel.every((r) => r === "../core" || r === "./mcp"), f).toBe(true);
|
||||
expect(rel.every((r) => r === "../core" || r === "./mcp" || r === "./mcpBridge"), f).toBe(true);
|
||||
}
|
||||
expect(src.length).toBeGreaterThan(0);
|
||||
expect(readdirSync(join(process.cwd(), "src", "cli")).filter((f) => statSync(join(process.cwd(), "src", "cli", f)).isFile() && f.endsWith(".ts") && !f.endsWith(".test.ts")).sort()).toEqual(["main.ts", "mcp.ts"]);
|
||||
expect(readdirSync(join(process.cwd(), "src", "cli")).filter((f) => statSync(join(process.cwd(), "src", "cli", f)).isFile() && f.endsWith(".ts") && !f.endsWith(".test.ts")).sort()).toEqual(["main.ts", "mcp.ts", "mcpBridge.ts"]);
|
||||
});
|
||||
|
||||
it("info, validate, migrate", async () => {
|
||||
@@ -159,7 +159,11 @@ describe("MCP-Server", () => {
|
||||
const init = (await handleMessage(file, { jsonrpc: "2.0", id: 1, method: "initialize", params: {} })) as { result: { serverInfo: { name: string } } };
|
||||
expect(init.result.serverInfo.name).toBe("dossier");
|
||||
const list = (await handleMessage(file, { jsonrpc: "2.0", id: 2, method: "tools/list" })) as { result: { tools: Array<{ name: string }> } };
|
||||
expect(list.result.tools.map((t) => t.name)).toEqual(["project_info", "query", "render_svg", "apply_ops", "validate"]);
|
||||
// gemeinsame Liste (core/aiToolDefs.ts) ohne die App-Werkzeuge
|
||||
const names = list.result.tools.map((t) => t.name);
|
||||
expect(names.slice(0, 4)).toEqual(["project_info", "query", "render_svg", "apply_ops"]);
|
||||
expect(names).toContain("run_command");
|
||||
expect(names).not.toContain("select");
|
||||
expect(await handleMessage(file, { jsonrpc: "2.0", method: "notifications/initialized" })).toBeNull();
|
||||
|
||||
const call = async (name: string, args: Record<string, unknown>) =>
|
||||
|
||||
+28
-2
@@ -27,7 +27,8 @@
|
||||
// dossier-cli pdf-info <datei.pdf> [--page 1] Vektor-PDF lesen ([76]): Seiten, Pfade, Texte, BBox (pt) als JSON
|
||||
// dossier-cli convert plan.pdf plan.obp [--scale 100] [--page 1] [--no-text]
|
||||
// Vektor-PDF als 2D-Zeichnung (Ebenen nach Farbe/Strichstärke)
|
||||
// dossier-cli <projekt.obp> mcp MCP-Server (stdio): project_info, query, render_svg, apply_ops, validate
|
||||
// dossier-cli <projekt.obp> mcp MCP-Server (stdio) auf der Datei: Werkzeuge aus core/aiToolDefs.ts
|
||||
// dossier-cli mcp --app [--port 7979] [--token …] MCP-Brücke zur offenen App ([9], KI-Zugriff in den Einstellungen)
|
||||
// dossier-cli <projekt.obp> bench [--runs 10] Zeitprofil der Ableitungen (ms je Aufruf)
|
||||
//
|
||||
// Statt einer Datei nimmt `:beispiel` das eingebaute Demo-Haus (sampleProject).
|
||||
@@ -105,9 +106,11 @@ import {
|
||||
validateProject,
|
||||
projectWarnings,
|
||||
sampleProject,
|
||||
AI_BRIDGE_DEFAULT_PORT,
|
||||
} from "../core";
|
||||
import type { Project } from "../core";
|
||||
import { serveStdio } from "./mcp";
|
||||
import { startBridge } from "./mcpBridge";
|
||||
|
||||
type Args = { positional: string[]; flags: Map<string, string>; cmds: string[] };
|
||||
|
||||
@@ -299,6 +302,7 @@ export async function run(argv: string[]): Promise<number> {
|
||||
if (file === "bcf-info") return runBcfInfo(command);
|
||||
if (file === "pointcloud-info") return pointCloudInfo(args, command);
|
||||
if (file === "pdf-info") return runPdfInfo(args, command);
|
||||
if (file === "mcp" && args.flags.has("app")) return runAppBridge(args);
|
||||
if (!file || (!command && args.cmds.length === 0)) {
|
||||
process.stderr.write(
|
||||
"Aufruf: dossier-cli <projekt.obp> <info|validate|migrate|plan|section|elevation|dxf|dwg|ifc|import-ifc|import-mesh|step|obj|stl|glb|gltf|schedule|kennzahlen|raumprogramm|sun|model3d> [Optionen]\n" +
|
||||
@@ -306,7 +310,8 @@ export async function run(argv: string[]): Promise<number> {
|
||||
" dossier-cli <projekt.obp> --cmd \"befehl …\" [--cmd …] ({last} = zuletzt geschriebene Datei)\n" +
|
||||
" dossier-cli pointcloud-info <datei> [--voxel 0.05] [--max 2000000]\n" +
|
||||
" dossier-cli bcf-info <datei.bcfzip>\n" +
|
||||
" dossier-cli pdf-info <datei.pdf> [--page 1]\n",
|
||||
" dossier-cli pdf-info <datei.pdf> [--page 1]\n" +
|
||||
" dossier-cli mcp --app [--port 7979] [--token schlüssel] (MCP-Brücke zur offenen App)\n",
|
||||
);
|
||||
return 2;
|
||||
}
|
||||
@@ -323,6 +328,27 @@ export async function run(argv: string[]): Promise<number> {
|
||||
return code === 0 ? runCmds(project, file, args) : code;
|
||||
}
|
||||
|
||||
/**
|
||||
* [9] `dossier-cli mcp --app [--port 7979] [--token …]`: MCP über stdio, Werkzeuge laufen in der offenen App.
|
||||
* Schlüssel aus `--token` oder `DOSSIER_AI_TOKEN` (Einstellungen der App → KI-Zugriff).
|
||||
*/
|
||||
async function runAppBridge(args: Args): Promise<number> {
|
||||
const token = args.flags.get("token") ?? process.env.DOSSIER_AI_TOKEN ?? "";
|
||||
if (!token || token === "true") fail("mcp --app: Schlüssel fehlt (--token oder DOSSIER_AI_TOKEN, s. Einstellungen der App → KI-Zugriff)");
|
||||
const port = Number(args.flags.get("port") ?? AI_BRIDGE_DEFAULT_PORT);
|
||||
if (!Number.isInteger(port) || port < 1 || port > 65535) fail("--port: 1 bis 65535");
|
||||
let bridge;
|
||||
try {
|
||||
bridge = await startBridge({ port, token });
|
||||
} catch (e) {
|
||||
fail(`mcp --app: Port ${port} nicht verfügbar (${e instanceof Error ? e.message : String(e)})`);
|
||||
}
|
||||
process.stderr.write(`Dossier MCP-Brücke auf 127.0.0.1:${bridge.port} — wartet auf die App.\n`);
|
||||
await serveStdio(bridge.handle);
|
||||
await bridge.close();
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Endung (klein, ohne Punkt) eines Dateinamens. */
|
||||
const extOf = (path: string): string => (path.includes(".") ? (path.split(".").pop() ?? "").toLowerCase() : "");
|
||||
|
||||
|
||||
+51
-113
@@ -1,70 +1,28 @@
|
||||
// MCP-Server (stdio, JSON-RPC 2.0, newline-delimited) auf einer Projektdatei — lessons-bimcraft
|
||||
// [9] in der headless Variante: ein Agent liest, rendert und ändert das Projekt über dieselben
|
||||
// `CoreOp`s wie die UI (core/ops.ts). Änderungen werden validiert und atomar in die Datei
|
||||
// geschrieben. Start: `node dist-cli/dossier-cli.mjs projekt.obp mcp`.
|
||||
// Werkzeuge wie die Brücke zur laufenden App (`core/aiToolDefs.ts`, `core/aiTools.ts`; die
|
||||
// App-Werkzeuge fehlen hier). Änderungen werden validiert und atomar in die Datei geschrieben.
|
||||
// Start: `node dist-cli/dossier-cli.mjs projekt.obp mcp`.
|
||||
// Nur `../core` wird importiert (Wächter in cli.test.ts).
|
||||
|
||||
import { readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import {
|
||||
applyOps,
|
||||
computeSection,
|
||||
generateElevationPlan,
|
||||
generatePlan,
|
||||
generateSectionPlan,
|
||||
parseProjectFile,
|
||||
planToSvgString,
|
||||
serializeProject,
|
||||
validateOps,
|
||||
validateProject,
|
||||
projectWarnings,
|
||||
} from "../core";
|
||||
import type { CoreOp, Project } from "../core";
|
||||
import { AI_TOOLS, aiText, applyOps, callAiTool, parseProjectFile, serializeProject, validateOps } from "../core";
|
||||
import type { AiHost, AiToolDef, AiToolResult, Project } from "../core";
|
||||
|
||||
interface Rpc {
|
||||
export interface Rpc {
|
||||
jsonrpc: "2.0";
|
||||
id?: number | string | null;
|
||||
method?: string;
|
||||
params?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: "project_info",
|
||||
description: "Zählt Bauteile des Projekts und listet Geschosse/Schnitte/Ansichten.",
|
||||
inputSchema: { type: "object", properties: {} },
|
||||
},
|
||||
{
|
||||
name: "query",
|
||||
description: "Liest Elemente einer Liste (walls, ceilings, roofs, openings, stairs, rooms, drawings2d, extrudedSolids, …), optional eine id.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { collection: { type: "string" }, id: { type: "string" }, limit: { type: "number" } },
|
||||
required: ["collection"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "render_svg",
|
||||
description: "Rendert Grundriss (kind=floor), Schnitt (section) oder Ansicht (elevation) als SVG-Text.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { kind: { type: "string", enum: ["floor", "section", "elevation"] }, name: { type: "string" }, scale: { type: "number" } },
|
||||
required: ["kind"],
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "apply_ops",
|
||||
description:
|
||||
"Wendet CoreOps an (add/replace/remove/reorder/setField, JSON). Validiert (NaN, doppelte ids) und schreibt die Datei nur bei Erfolg.",
|
||||
inputSchema: {
|
||||
type: "object",
|
||||
properties: { ops: { type: "array", items: { type: "object" } } },
|
||||
required: ["ops"],
|
||||
},
|
||||
},
|
||||
{ name: "validate", description: "Prüft das gesamte Projekt auf nicht endliche Zahlen und doppelte ids.", inputSchema: { type: "object", properties: {} } },
|
||||
];
|
||||
|
||||
const text = (t: string, isError = false) => ({ content: [{ type: "text", text: t }], isError });
|
||||
/** Werkzeug für `tools/list` (ohne die internen Kennzeichen, mit MCP-Hinweisen). */
|
||||
export const mcpTool = (t: AiToolDef) => ({
|
||||
name: t.name,
|
||||
description: t.description,
|
||||
inputSchema: t.inputSchema,
|
||||
annotations: { readOnlyHint: !t.mutating },
|
||||
});
|
||||
|
||||
function load(file: string): Project {
|
||||
const r = parseProjectFile(readFileSync(file, "utf8"));
|
||||
@@ -78,63 +36,33 @@ function save(file: string, p: Project): void {
|
||||
renameSync(tmp, file); // atomar
|
||||
}
|
||||
|
||||
export async function callTool(file: string, name: string, args: Record<string, unknown>) {
|
||||
/** Host über eine Projektdatei: liest je Aufruf neu, schreibt nur angenommene Änderungen. */
|
||||
export function fileHost(file: string): AiHost {
|
||||
const project = load(file);
|
||||
const codes = new Set(project.layers.map((l) => l.code));
|
||||
switch (name) {
|
||||
case "project_info":
|
||||
return text(
|
||||
JSON.stringify({
|
||||
name: project.name,
|
||||
counts: Object.fromEntries(
|
||||
Object.entries(project as unknown as Record<string, unknown>)
|
||||
.filter(([, v]) => Array.isArray(v))
|
||||
.map(([k, v]) => [k, (v as unknown[]).length]),
|
||||
),
|
||||
levels: project.drawingLevels.map((l) => ({ id: l.id, name: l.name, kind: l.kind })),
|
||||
}),
|
||||
);
|
||||
case "query": {
|
||||
const list = (project as unknown as Record<string, unknown>)[String(args.collection)];
|
||||
if (!Array.isArray(list)) return text(`Keine Liste: ${String(args.collection)}`, true);
|
||||
const rows = args.id ? list.filter((e) => (e as { id?: string }).id === args.id) : list.slice(0, Number(args.limit ?? 50));
|
||||
return text(JSON.stringify(rows));
|
||||
}
|
||||
case "render_svg": {
|
||||
const kind = String(args.kind);
|
||||
const lvl = project.drawingLevels.find((l) => l.kind === kind && (!args.name || l.name === args.name || l.id === args.name));
|
||||
if (!lvl) return text(`Ebene nicht gefunden: ${kind} ${String(args.name ?? "")}`, true);
|
||||
const scale = Number(args.scale ?? 100);
|
||||
if (kind === "floor") return text(planToSvgString(generatePlan(project, lvl.id, codes), { scaleDenominator: scale }));
|
||||
if (kind === "section") {
|
||||
const o = await computeSection(project, lvl);
|
||||
if (!o) return text("keine gültige Schnittlinie", true);
|
||||
return text(planToSvgString(generateSectionPlan(o, false, { visibleCodes: codes }), { scaleDenominator: scale }));
|
||||
}
|
||||
const plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
|
||||
return plan ? text(planToSvgString(plan, { scaleDenominator: scale })) : text("keine gültige Ansichtslinie", true);
|
||||
}
|
||||
case "apply_ops": {
|
||||
const ops = args.ops as CoreOp[];
|
||||
if (!Array.isArray(ops)) return text("ops muss eine Liste sein", true);
|
||||
return {
|
||||
project: () => project,
|
||||
commit: (ops) => {
|
||||
const next = applyOps(project, ops);
|
||||
const problems = validateOps(next, ops, project);
|
||||
if (problems.length) return text(`Abgelehnt, nichts geschrieben: ${problems.join("; ")}`, true);
|
||||
if (problems.length) return problems.join("; ");
|
||||
save(file, next);
|
||||
return text(`ok: ${ops.length} Op(s) angewendet und gespeichert`);
|
||||
}
|
||||
case "validate": {
|
||||
const problems = validateProject(project);
|
||||
const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`);
|
||||
return text([...problems, ...warnings].join("\n") || "ok", problems.length > 0);
|
||||
}
|
||||
default:
|
||||
return text(`unbekanntes Werkzeug: ${name}`, true);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Behandelt EINE JSON-RPC-Nachricht; `null` = keine Antwort (Notification). */
|
||||
export async function handleMessage(file: string, msg: Rpc): Promise<object | null> {
|
||||
export async function callTool(file: string, name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
if (AI_TOOLS.find((t) => t.name === name)?.appOnly) return aiText(`${name}: nur mit der laufenden App (dossier-cli mcp --app)`, true);
|
||||
return callAiTool(fileHost(file), name, args);
|
||||
}
|
||||
|
||||
/** Behandelt EINE JSON-RPC-Nachricht mit Werkzeugliste `tools` und Ausführer `call`; `null` = keine Antwort. */
|
||||
export async function handleRpc(
|
||||
msg: Rpc,
|
||||
tools: AiToolDef[],
|
||||
call: (name: string, args: Record<string, unknown>) => Promise<AiToolResult>,
|
||||
serverName = "dossier",
|
||||
): Promise<object | null> {
|
||||
const reply = (result: unknown) => ({ jsonrpc: "2.0", id: msg.id ?? null, result });
|
||||
const error = (code: number, message: string) => ({ jsonrpc: "2.0", id: msg.id ?? null, error: { code, message } });
|
||||
if (msg.id === undefined) return null; // Notification (z. B. notifications/initialized)
|
||||
@@ -143,18 +71,18 @@ export async function handleMessage(file: string, msg: Rpc): Promise<object | nu
|
||||
return reply({
|
||||
protocolVersion: "2024-11-05",
|
||||
capabilities: { tools: {} },
|
||||
serverInfo: { name: "dossier", version: "0.1.0" },
|
||||
serverInfo: { name: serverName, version: "0.2.0" },
|
||||
});
|
||||
case "ping":
|
||||
return reply({});
|
||||
case "tools/list":
|
||||
return reply({ tools: TOOLS });
|
||||
return reply({ tools: tools.map(mcpTool) });
|
||||
case "tools/call": {
|
||||
const p = msg.params ?? {};
|
||||
try {
|
||||
return reply(await callTool(file, String(p.name), (p.arguments ?? {}) as Record<string, unknown>));
|
||||
return reply(await call(String(p.name), (p.arguments ?? {}) as Record<string, unknown>));
|
||||
} catch (e) {
|
||||
return reply(text(e instanceof Error ? e.message : String(e), true));
|
||||
return reply(aiText(e instanceof Error ? e.message : String(e), true));
|
||||
}
|
||||
}
|
||||
default:
|
||||
@@ -162,8 +90,18 @@ export async function handleMessage(file: string, msg: Rpc): Promise<object | nu
|
||||
}
|
||||
}
|
||||
|
||||
/** stdio-Schleife. */
|
||||
export async function serveStdio(file: string): Promise<void> {
|
||||
/** Headless: Werkzeuge ohne die App-Werkzeuge, auf der Datei. */
|
||||
export function handleMessage(file: string, msg: Rpc): Promise<object | null> {
|
||||
return handleRpc(
|
||||
msg,
|
||||
AI_TOOLS.filter((t) => !t.appOnly),
|
||||
(name, args) => callTool(file, name, args),
|
||||
);
|
||||
}
|
||||
|
||||
/** stdio-Schleife: jede Zeile eine JSON-RPC-Nachricht an `handle`. */
|
||||
export async function serveStdio(handle: string | ((msg: Rpc) => Promise<object | null>)): Promise<void> {
|
||||
const h = typeof handle === "string" ? (m: Rpc) => handleMessage(handle, m) : handle;
|
||||
let buf = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
for await (const chunk of process.stdin) {
|
||||
@@ -180,7 +118,7 @@ export async function serveStdio(file: string): Promise<void> {
|
||||
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error" } }) + "\n");
|
||||
continue;
|
||||
}
|
||||
const res = await handleMessage(file, msg);
|
||||
const res = await h(msg);
|
||||
if (res) process.stdout.write(JSON.stringify(res) + "\n");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
// [9] Brücke MCP ↔ laufende App: echte Brücke (WebSocket auf 127.0.0.1) gegen den echten App-Client
|
||||
// (`net/aiBridge.ts`) mit einem Host im Speicher statt des Stores.
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { startBridge, wsFrame, type Bridge } from "./mcpBridge";
|
||||
import { connectAiBridge, type AiBridgeStatus } from "../net/aiBridge";
|
||||
import { aiText, callAiTool, randomHex, type AiHost } from "../core";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
|
||||
const until = async (f: () => boolean, ms = 5000) => {
|
||||
const t0 = Date.now();
|
||||
while (!f()) {
|
||||
if (Date.now() - t0 > ms) throw new Error("Zeitüberschreitung");
|
||||
await new Promise((r) => setTimeout(r, 20));
|
||||
}
|
||||
};
|
||||
|
||||
let bridge: Bridge | null = null;
|
||||
let client: { close(): void } | null = null;
|
||||
afterEach(async () => {
|
||||
client?.close();
|
||||
client = null;
|
||||
await bridge?.close();
|
||||
bridge = null;
|
||||
});
|
||||
|
||||
const host: AiHost = { project: () => sampleProject, commit: () => null, select: () => {} };
|
||||
|
||||
describe("MCP-Brücke zur App", () => {
|
||||
it("ohne App: tools/list mit allen Werkzeugen, Aufruf meldet fehlende Verbindung", async () => {
|
||||
bridge = await startBridge({ port: 0, token: randomHex() });
|
||||
const list = (await bridge.handle({ jsonrpc: "2.0", id: 1, method: "tools/list" })) as { result: { tools: { name: string }[] } };
|
||||
expect(list.result.tools.map((t) => t.name)).toContain("zoom_to");
|
||||
const r = (await bridge.handle({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "project_info", arguments: {} } })) as {
|
||||
result: { isError: boolean; content: { text: string }[] };
|
||||
};
|
||||
expect(r.result.isError).toBe(true);
|
||||
expect(r.result.content[0].text).toContain("KI-Zugriff");
|
||||
});
|
||||
|
||||
it("App mit richtigem Schlüssel: Aufrufe laufen über die App", async () => {
|
||||
const token = randomHex();
|
||||
bridge = await startBridge({ port: 0, token });
|
||||
const seen: string[] = [];
|
||||
let status: AiBridgeStatus = "closed";
|
||||
client = connectAiBridge({
|
||||
port: bridge.port,
|
||||
token,
|
||||
retryMs: 50,
|
||||
onStatus: (s) => (status = s),
|
||||
call: (name, args) => {
|
||||
seen.push(name);
|
||||
return callAiTool(host, name, args);
|
||||
},
|
||||
});
|
||||
await until(() => bridge!.connected() && status === "connected");
|
||||
const r = (await bridge.handle({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "project_info", arguments: {} } })) as {
|
||||
result: { isError: boolean; content: { text: string }[] };
|
||||
};
|
||||
expect(r.result.isError).toBe(false);
|
||||
expect(JSON.parse(r.result.content[0].text).counts.walls).toBe(sampleProject.walls.length);
|
||||
// grosse Antwort (16-/64-Bit-Länge im Rahmen)
|
||||
const svg = await bridge.call("render_svg", { kind: "floor" });
|
||||
expect((svg.content[0] as { text: string }).text).toContain("<svg");
|
||||
expect(seen).toEqual(["project_info", "render_svg"]);
|
||||
});
|
||||
|
||||
it("falscher Schlüssel: keine Verbindung, Status auth-failed", async () => {
|
||||
bridge = await startBridge({ port: 0, token: randomHex() });
|
||||
let status: AiBridgeStatus = "closed";
|
||||
let called = false;
|
||||
client = connectAiBridge({
|
||||
port: bridge.port,
|
||||
token: randomHex(),
|
||||
retryMs: 50,
|
||||
onStatus: (s) => (status = s),
|
||||
call: async () => ((called = true), aiText("x")),
|
||||
});
|
||||
await until(() => status === "auth-failed");
|
||||
expect(bridge.connected()).toBe(false);
|
||||
expect((await bridge.call("project_info", {})).isError).toBe(true);
|
||||
expect(called).toBe(false);
|
||||
});
|
||||
|
||||
it("Fremder ohne Anmeldung wird getrennt und bekommt keine Aufrufe", async () => {
|
||||
bridge = await startBridge({ port: 0, token: randomHex() });
|
||||
const ws = new WebSocket(`ws://127.0.0.1:${bridge.port}`);
|
||||
const msgs: string[] = [];
|
||||
ws.onmessage = (e) => msgs.push(String(e.data));
|
||||
await new Promise((r) => (ws.onopen = r));
|
||||
ws.send(JSON.stringify({ type: "ready" }));
|
||||
await new Promise((r) => (ws.onclose = r));
|
||||
expect(bridge.connected()).toBe(false);
|
||||
expect(msgs.map((m) => JSON.parse(m).type)).toEqual(["hello"]);
|
||||
});
|
||||
|
||||
it("Rahmen-Längen 7/16/64 Bit", () => {
|
||||
expect(wsFrame(1, Buffer.alloc(5))[1]).toBe(5);
|
||||
expect(wsFrame(1, Buffer.alloc(300))[1]).toBe(126);
|
||||
expect(wsFrame(1, Buffer.alloc(70000))[1]).toBe(127);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
// [9] MCP-Brücke zur laufenden App: `dossier-cli mcp --app [--port 7979] [--token …]` spricht MCP über
|
||||
// stdio mit dem KI-Client und reicht die Werkzeug-Aufrufe an die App weiter. Die App verbindet sich
|
||||
// (nur mit „KI-Zugriff erlauben“) als WebSocket-Client mit dieser Brücke, die nur auf 127.0.0.1 lauscht;
|
||||
// beide Seiten melden sich per HMAC mit dem Sitzungsschlüssel aus den Einstellungen der App an
|
||||
// (`core/aiToolDefs.ts`). So braucht der App-Host (Tauri/Electron/Browser) keinen eigenen Server.
|
||||
// Der WebSocket-Server ist bewusst minimal (RFC 6455: Text, Ping/Pong, Schliessen; keine Erweiterungen).
|
||||
|
||||
import { createHash } from "node:crypto";
|
||||
import { createServer, type IncomingMessage } from "node:http";
|
||||
import type { Duplex } from "node:stream";
|
||||
import { AI_TOOLS, aiText, hmacHex, randomHex, sameMac } from "../core";
|
||||
import type { AiBridgeMsg, AiToolResult } from "../core";
|
||||
import { handleRpc, type Rpc } from "./mcp";
|
||||
|
||||
const WS_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
const MAX_MESSAGE = 64 * 1024 * 1024;
|
||||
|
||||
// ── WebSocket (Server-Seite, minimal) ─────────────────────────────────────────────────────────
|
||||
|
||||
interface WsConn {
|
||||
send(text: string): void;
|
||||
close(): void;
|
||||
onmessage?: (text: string) => void;
|
||||
onclose?: () => void;
|
||||
}
|
||||
|
||||
/** Rahmen (Server → Client: unmaskiert). */
|
||||
export function wsFrame(opcode: number, payload: Buffer): Buffer {
|
||||
const n = payload.length;
|
||||
const head = n < 126 ? Buffer.from([0x80 | opcode, n]) : n < 65536 ? Buffer.alloc(4) : Buffer.alloc(10);
|
||||
if (n >= 126 && n < 65536) {
|
||||
head[0] = 0x80 | opcode;
|
||||
head[1] = 126;
|
||||
head.writeUInt16BE(n, 2);
|
||||
} else if (n >= 65536) {
|
||||
head[0] = 0x80 | opcode;
|
||||
head[1] = 127;
|
||||
head.writeBigUInt64BE(BigInt(n), 2);
|
||||
}
|
||||
return Buffer.concat([head, payload]);
|
||||
}
|
||||
|
||||
function upgrade(req: IncomingMessage, socket: Duplex): WsConn | null {
|
||||
const key = req.headers["sec-websocket-key"];
|
||||
if (String(req.headers.upgrade).toLowerCase() !== "websocket" || typeof key !== "string" || req.headers["sec-websocket-version"] !== "13") {
|
||||
socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
|
||||
return null;
|
||||
}
|
||||
const accept = createHash("sha1").update(key + WS_GUID).digest("base64");
|
||||
socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`);
|
||||
let buf = Buffer.alloc(0);
|
||||
let parts: Buffer[] = [];
|
||||
let closed = false;
|
||||
const conn: WsConn = {
|
||||
send: (text) => {
|
||||
if (!closed) socket.write(wsFrame(1, Buffer.from(text, "utf8")));
|
||||
},
|
||||
close: () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
socket.end(wsFrame(8, Buffer.alloc(0)));
|
||||
conn.onclose?.();
|
||||
},
|
||||
};
|
||||
socket.on("data", (chunk: Buffer) => {
|
||||
buf = Buffer.concat([buf, chunk]);
|
||||
for (;;) {
|
||||
if (buf.length < 2) return;
|
||||
const fin = (buf[0] & 0x80) !== 0;
|
||||
const op = buf[0] & 0x0f;
|
||||
const masked = (buf[1] & 0x80) !== 0;
|
||||
let len = buf[1] & 0x7f;
|
||||
let off = 2;
|
||||
if (len === 126) {
|
||||
if (buf.length < 4) return;
|
||||
len = buf.readUInt16BE(2);
|
||||
off = 4;
|
||||
} else if (len === 127) {
|
||||
if (buf.length < 10) return;
|
||||
const big = buf.readBigUInt64BE(2);
|
||||
if (big > BigInt(MAX_MESSAGE)) return conn.close();
|
||||
len = Number(big);
|
||||
off = 10;
|
||||
}
|
||||
if (!masked || len > MAX_MESSAGE) return conn.close(); // Client-Rahmen müssen maskiert sein
|
||||
if (buf.length < off + 4 + len) return;
|
||||
const mask = buf.subarray(off, off + 4);
|
||||
const data = Buffer.from(buf.subarray(off + 4, off + 4 + len));
|
||||
for (let i = 0; i < data.length; i++) data[i] ^= mask[i & 3];
|
||||
buf = buf.subarray(off + 4 + len);
|
||||
if (op === 8) return conn.close();
|
||||
if (op === 9) socket.write(wsFrame(10, data));
|
||||
else if (op === 1 || op === 0) {
|
||||
parts.push(data);
|
||||
if (parts.reduce((s, p) => s + p.length, 0) > MAX_MESSAGE) return conn.close();
|
||||
if (fin) {
|
||||
const text = Buffer.concat(parts).toString("utf8");
|
||||
parts = [];
|
||||
conn.onmessage?.(text);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const end = () => {
|
||||
if (!closed) {
|
||||
closed = true;
|
||||
conn.onclose?.();
|
||||
}
|
||||
};
|
||||
socket.on("close", end);
|
||||
socket.on("error", end);
|
||||
return conn;
|
||||
}
|
||||
|
||||
// ── Brücke ───────────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface Bridge {
|
||||
port: number;
|
||||
connected(): boolean;
|
||||
call(name: string, args: Record<string, unknown>): Promise<AiToolResult>;
|
||||
handle(msg: Rpc): Promise<object | null>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Startet die Brücke auf 127.0.0.1:`port` (0 = frei wählen). */
|
||||
export function startBridge(opts: { port: number; token: string; callTimeoutMs?: number }): Promise<Bridge> {
|
||||
let app: WsConn | null = null;
|
||||
let nextId = 1;
|
||||
const pending = new Map<number, (r: AiToolResult) => void>();
|
||||
const server = createServer((_req, res) => {
|
||||
res.writeHead(426, { "Content-Type": "text/plain" });
|
||||
res.end("Dossier MCP-Brücke: nur WebSocket\n");
|
||||
});
|
||||
server.on("upgrade", (req, socket) => {
|
||||
const conn = upgrade(req, socket);
|
||||
if (!conn) return;
|
||||
const nonce = randomHex();
|
||||
let authed = false;
|
||||
let ready = false;
|
||||
conn.onmessage = async (text) => {
|
||||
let m: AiBridgeMsg;
|
||||
try {
|
||||
m = JSON.parse(text) as AiBridgeMsg;
|
||||
} catch {
|
||||
return conn.close();
|
||||
}
|
||||
if (!ready && m.type === "auth" && typeof m.nonce === "string") {
|
||||
if (authed || !sameMac(m.mac, await hmacHex(opts.token, `app:${nonce}`))) return conn.close();
|
||||
authed = true;
|
||||
conn.send(JSON.stringify({ type: "auth", mac: await hmacHex(opts.token, `bridge:${m.nonce}`) } satisfies AiBridgeMsg));
|
||||
} else if (authed && !ready && m.type === "ready") {
|
||||
if (app) return conn.close(); // nur eine App zugleich
|
||||
ready = true;
|
||||
app = conn;
|
||||
} else if (ready && m.type === "result") {
|
||||
pending.get(m.id)?.(m.result);
|
||||
pending.delete(m.id);
|
||||
} else if (!ready) conn.close();
|
||||
};
|
||||
conn.onclose = () => {
|
||||
if (app !== conn) return;
|
||||
app = null;
|
||||
for (const [id, done] of pending) {
|
||||
done(aiText("Verbindung zur App getrennt", true));
|
||||
pending.delete(id);
|
||||
}
|
||||
};
|
||||
conn.send(JSON.stringify({ type: "hello", nonce } satisfies AiBridgeMsg));
|
||||
});
|
||||
|
||||
const call = (name: string, args: Record<string, unknown>): Promise<AiToolResult> => {
|
||||
const conn = app;
|
||||
if (!conn)
|
||||
return Promise.resolve(
|
||||
aiText("Dossier ist nicht verbunden: in der App unter Einstellungen „KI-Zugriff erlauben“ einschalten und den Schlüssel als --token übergeben.", true),
|
||||
);
|
||||
const id = nextId++;
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
pending.delete(id);
|
||||
resolve(aiText("Zeitüberschreitung: keine Antwort der App", true));
|
||||
}, opts.callTimeoutMs ?? 300_000);
|
||||
pending.set(id, (r) => {
|
||||
clearTimeout(timer);
|
||||
resolve(r);
|
||||
});
|
||||
conn.send(JSON.stringify({ type: "call", id, name, args } satisfies AiBridgeMsg));
|
||||
});
|
||||
};
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(opts.port, "127.0.0.1", () => {
|
||||
const addr = server.address();
|
||||
resolve({
|
||||
port: typeof addr === "object" && addr ? addr.port : opts.port,
|
||||
connected: () => app !== null,
|
||||
call,
|
||||
handle: (msg) => handleRpc(msg, AI_TOOLS, call, "dossier-app"),
|
||||
close: () =>
|
||||
new Promise<void>((done) => {
|
||||
app?.close();
|
||||
server.close(() => done());
|
||||
server.closeAllConnections?.();
|
||||
}),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
// [9] KI-Werkzeuge: EINE Liste für den headless MCP-Server (`dossier-cli … mcp`) und die Brücke zur
|
||||
// laufenden App (`dossier-cli mcp --app`), dazu das Brücken-Protokoll (Nachrichten, gegenseitige
|
||||
// Anmeldung per HMAC). Bewusst ohne Importe: die Brücke und der e2e-Test laden nur diese Datei.
|
||||
|
||||
/** Beschreibung eines Werkzeugs (MCP `tools/list`) plus Dossier-Merkmale. */
|
||||
export interface AiToolDef {
|
||||
name: string;
|
||||
description: string;
|
||||
inputSchema: { type: "object"; properties: Record<string, unknown>; required?: string[] };
|
||||
/** Ändert das Projekt (in der App: ein Undo-Schritt „KI: <name>“, im Protokoll markiert). */
|
||||
mutating?: boolean;
|
||||
/** Braucht die laufende App (Auswahl, Ansicht, Speichern-Dialog). */
|
||||
appOnly?: boolean;
|
||||
}
|
||||
|
||||
const obj = (properties: Record<string, unknown> = {}, required?: string[]) =>
|
||||
({ type: "object", properties, ...(required ? { required } : {}) }) as AiToolDef["inputSchema"];
|
||||
const ids = { type: "array", items: { type: "string" } };
|
||||
|
||||
export const AI_TOOLS: AiToolDef[] = [
|
||||
{
|
||||
name: "project_info",
|
||||
description: "Zählt Bauteile des Projekts und listet Geschosse/Schnitte/Ansichten (in der App mit aktivem Geschoss).",
|
||||
inputSchema: obj(),
|
||||
},
|
||||
{
|
||||
name: "query",
|
||||
description:
|
||||
"Liest Elemente einer Liste (walls, ceilings, roofs, openings, stairs, rooms, columns, drawings2d, extrudedSolids, drawingLevels, …), optional nach id/ids gefiltert.",
|
||||
inputSchema: obj({ collection: { type: "string" }, id: { type: "string" }, ids, limit: { type: "number" } }, ["collection"]),
|
||||
},
|
||||
{
|
||||
name: "render_svg",
|
||||
description: "Rendert Grundriss (kind=floor), Schnitt (section) oder Ansicht (elevation) als SVG-Text.",
|
||||
inputSchema: obj({ kind: { type: "string", enum: ["floor", "section", "elevation"] }, name: { type: "string" }, scale: { type: "number" } }, ["kind"]),
|
||||
},
|
||||
{
|
||||
name: "apply_ops",
|
||||
description:
|
||||
"Wendet CoreOps an (add/replace/remove/reorder/setField, JSON). Der Kern prüft (NaN, doppelte ids); bei Fehler bleibt das Projekt unverändert.",
|
||||
inputSchema: obj({ ops: { type: "array", items: { type: "object" } } }, ["ops"]),
|
||||
mutating: true,
|
||||
},
|
||||
{
|
||||
name: "run_command",
|
||||
description:
|
||||
"Führt einen Kern-Befehl mit JSON-Parametern aus (dieselben wie die Befehle der Oberfläche): z. B. " +
|
||||
'{cmd:"wall", pts:[[0,0],[5,0]]}, {cmd:"room"|"ceiling"|"roof", pts:[…]}, {cmd:"column", at:[x,y]}, ' +
|
||||
'{cmd:"opening", wall:<id>, start, end (Wandachse), pos, width, height, sill, kind:"door"|"window"}, {cmd:"rect"|"polyline"|"circle", …}, {cmd:"transform", ids, …}, ' +
|
||||
'{cmd:"align"|"distribute", ids, mode|axis}, {cmd:"split", ids}. `level` = Geschoss-id (Standard: aktives bzw. erstes).',
|
||||
inputSchema: obj({ cmd: { type: "string" }, params: { type: "object" }, level: { type: "string" } }, ["cmd"]),
|
||||
mutating: true,
|
||||
},
|
||||
{ name: "validate", description: "Prüft das gesamte Projekt auf nicht endliche Zahlen und doppelte ids.", inputSchema: obj() },
|
||||
{
|
||||
name: "kennzahlen",
|
||||
description: "Kennzahlen (kind=kennzahlen: Flächen/Volumen, Raumprogramm, Baurecht), SIA-416-Flächentabelle (sia416) oder IVHB-Kennziffern (ivhb) als JSON.",
|
||||
inputSchema: obj({ kind: { type: "string", enum: ["kennzahlen", "sia416", "ivhb"] } }),
|
||||
},
|
||||
{
|
||||
name: "schedule",
|
||||
description: "Listen: Fenster/Türen (kind=openings, JSON), Bauteile mit U-Werten (elements, JSON) oder Bauteilliste (list, CSV).",
|
||||
inputSchema: obj({ kind: { type: "string", enum: ["openings", "elements", "list"] } }),
|
||||
},
|
||||
{ name: "get_selection", description: "Liefert die aktuelle Auswahl der App als {collection: [ids]}.", inputSchema: obj(), appOnly: true },
|
||||
{
|
||||
name: "select",
|
||||
description: "Wählt Elemente nach id in der App aus (ersetzt die Auswahl; leere Liste = Auswahl aufheben).",
|
||||
inputSchema: obj({ ids }, ["ids"]),
|
||||
appOnly: true,
|
||||
},
|
||||
{
|
||||
name: "zoom_to",
|
||||
description: "Wechselt aufs Geschoss der Elemente und passt die Planansicht der App auf sie ein.",
|
||||
inputSchema: obj({ ids }, ["ids"]),
|
||||
appOnly: true,
|
||||
},
|
||||
{
|
||||
name: "export",
|
||||
description:
|
||||
"Exportiert Grundriss als SVG (format=svg) oder PDF (pdf, nur App) bzw. das Modell als IFC (ifc). Liefert den Inhalt " +
|
||||
"(PDF base64); mit save=true öffnet die App den Speichern-Dialog und die Nutzerin wählt den Ort.",
|
||||
inputSchema: obj(
|
||||
{ format: { type: "string", enum: ["svg", "pdf", "ifc"] }, level: { type: "string" }, scale: { type: "number" }, save: { type: "boolean" } },
|
||||
["format"],
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
export const aiToolDef = (name: string): AiToolDef | undefined => AI_TOOLS.find((t) => t.name === name);
|
||||
|
||||
// ── Brücken-Protokoll (WebSocket, JSON je Nachricht) ─────────────────────────────────────────
|
||||
//
|
||||
// Die Brücke (`dossier-cli mcp --app`) lauscht auf 127.0.0.1:<port>; die App verbindet sich nur,
|
||||
// wenn „KI-Zugriff erlauben“ an ist. Anmeldung gegenseitig, ohne dass der Schlüssel reist:
|
||||
// Brücke → App {type:"hello", nonce:Nb}
|
||||
// App → Brücke {type:"auth", nonce:Na, mac:HMAC(token, "app:"+Nb)}
|
||||
// Brücke → App {type:"auth", mac:HMAC(token, "bridge:"+Na)} (sonst Abbruch)
|
||||
// App → Brücke {type:"ready"}
|
||||
// danach Brücke → App {type:"call", id, name, args}, App → Brücke {type:"result", id, result}.
|
||||
|
||||
export const AI_BRIDGE_DEFAULT_PORT = 7979;
|
||||
|
||||
export type AiBridgeMsg =
|
||||
| { type: "hello"; nonce: string }
|
||||
| { type: "auth"; nonce?: string; mac: string }
|
||||
| { type: "ready" }
|
||||
| { type: "call"; id: number; name: string; args: Record<string, unknown> }
|
||||
| { type: "result"; id: number; result: AiToolResult };
|
||||
|
||||
/** Ergebnis eines Werkzeugs (MCP `tools/call`). */
|
||||
export interface AiToolResult {
|
||||
content: ({ type: "text"; text: string } | { type: "resource"; resource: { uri: string; mimeType: string; blob: string } })[];
|
||||
isError: boolean;
|
||||
}
|
||||
|
||||
export const aiText = (text: string, isError = false): AiToolResult => ({ content: [{ type: "text", text }], isError });
|
||||
|
||||
const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
||||
|
||||
/** Zufällige Hex-Zeichenkette (`bytes` Bytes) aus dem Krypto-Zufall. */
|
||||
export function randomHex(bytes = 16): string {
|
||||
const b = new Uint8Array(bytes);
|
||||
globalThis.crypto.getRandomValues(b);
|
||||
return hex(b);
|
||||
}
|
||||
|
||||
/** HMAC-SHA256(token, msg) als Hex (WebCrypto: Browser, Tauri-WebView und Node). */
|
||||
export async function hmacHex(token: string, msg: string): Promise<string> {
|
||||
const enc = new TextEncoder();
|
||||
const key = await globalThis.crypto.subtle.importKey("raw", enc.encode(token), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
||||
return hex(new Uint8Array(await globalThis.crypto.subtle.sign("HMAC", key, enc.encode(msg))));
|
||||
}
|
||||
|
||||
/** Vergleich in konstanter Zeit (gleich lange Hex-Texte). */
|
||||
export function sameMac(a: unknown, b: string): boolean {
|
||||
if (typeof a !== "string" || a.length !== b.length) return false;
|
||||
let d = 0;
|
||||
for (let i = 0; i < a.length; i++) d |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
||||
return d === 0;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
// [9] Gemeinsame KI-Werkzeuge: Verteilung auf einen Host (App oder Datei) und Anmeldung der Brücke.
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { callAiTool, type AiHost } from "./aiTools";
|
||||
import { AI_TOOLS, hmacHex, randomHex, sameMac } from "./aiToolDefs";
|
||||
import { applyOps, validateOps, type CoreOp } from "./ops";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import type { Project } from "../model/types";
|
||||
|
||||
/** Host im Speicher, merkt sich Commits (Beschriftung) und Auswahl. */
|
||||
function fakeHost(withApp: boolean) {
|
||||
let project: Project = sampleProject;
|
||||
const labels: string[] = [];
|
||||
let selected: string[] = [];
|
||||
let zoomed: string[] = [];
|
||||
const host: AiHost = {
|
||||
project: () => project,
|
||||
commit: (ops: CoreOp[], label: string) => {
|
||||
const next = applyOps(project, ops);
|
||||
const problems = validateOps(next, ops, project);
|
||||
if (problems.length) return problems.join("; ");
|
||||
project = next;
|
||||
labels.push(label);
|
||||
return null;
|
||||
},
|
||||
...(withApp
|
||||
? {
|
||||
activeLevelId: () => sampleProject.drawingLevels.find((l) => l.kind === "floor")?.id,
|
||||
selection: () => ({ walls: selected }),
|
||||
select: (ids: string[]) => void (selected = ids),
|
||||
zoomTo: (ids: string[]) => ((zoomed = ids), true),
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
return { host, labels, get: () => project, sel: () => selected, zoom: () => zoomed };
|
||||
}
|
||||
|
||||
const textOf = (r: { content: { type: string; text?: string }[] }) => (r.content[0] as { text: string }).text;
|
||||
|
||||
describe("KI-Werkzeuge (gemeinsame Liste)", () => {
|
||||
it("Liste: eindeutige Namen, Schema je Werkzeug, Kennzeichen für App/Änderung", () => {
|
||||
const names = AI_TOOLS.map((t) => t.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
for (const n of ["project_info", "query", "render_svg", "apply_ops", "validate", "run_command", "select", "zoom_to", "export"]) expect(names).toContain(n);
|
||||
expect(AI_TOOLS.filter((t) => t.mutating).map((t) => t.name).sort()).toEqual(["apply_ops", "run_command"]);
|
||||
});
|
||||
|
||||
it("project_info und query lesen das Projekt des Hosts", async () => {
|
||||
const { host } = fakeHost(false);
|
||||
const info = JSON.parse(textOf(await callAiTool(host, "project_info", {})));
|
||||
expect(info.counts.walls).toBe(sampleProject.walls.length);
|
||||
const w = sampleProject.walls[1];
|
||||
const q = JSON.parse(textOf(await callAiTool(host, "query", { collection: "walls", ids: [w.id] })));
|
||||
expect(q.map((e: { id: string }) => e.id)).toEqual([w.id]);
|
||||
expect((await callAiTool(host, "query", { collection: "gibtsnicht" })).isError).toBe(true);
|
||||
});
|
||||
|
||||
it("run_command: Kern-Befehl mit JSON = ein Commit mit Beschriftung „KI: run_command“", async () => {
|
||||
const h = fakeHost(true);
|
||||
const before = h.get().walls.length;
|
||||
const r = await callAiTool(h.host, "run_command", { cmd: "wall", params: { pts: [[0, 0], [4, 0]] } });
|
||||
expect(r.isError).toBe(false);
|
||||
expect(h.get().walls.length).toBe(before + 1);
|
||||
expect(h.labels).toEqual(["KI: run_command"]);
|
||||
const added = h.get().walls.find((w) => !sampleProject.walls.some((o) => o.id === w.id))!;
|
||||
expect(added.floorId).toBe(h.host.activeLevelId!());
|
||||
expect(added.categoryCode).toBe(sampleProject.walls[0].categoryCode); // sichtbar wie in der Oberfläche
|
||||
expect(textOf(r)).toContain(added.id);
|
||||
// unbekannter Befehl → Fehler, kein Commit
|
||||
const bad = await callAiTool(h.host, "run_command", { cmd: "gibtsnicht" });
|
||||
expect(bad.isError).toBe(true);
|
||||
expect(h.labels.length).toBe(1);
|
||||
});
|
||||
|
||||
it("apply_ops: abgelehnte Ops melden den Grund, das Projekt bleibt", async () => {
|
||||
const h = fakeHost(false);
|
||||
const w = sampleProject.walls[0];
|
||||
const bad = await callAiTool(h.host, "apply_ops", { ops: [{ kind: "add", collection: "walls", items: [{ ...w }] }] });
|
||||
expect(bad.isError).toBe(true);
|
||||
expect(h.get()).toBe(sampleProject);
|
||||
expect((await callAiTool(h.host, "apply_ops", { ops: "x" })).isError).toBe(true);
|
||||
const ok = await callAiTool(h.host, "apply_ops", { ops: [{ kind: "replace", collection: "walls", entity: { ...w, height: 7 } }] });
|
||||
expect(ok.isError).toBe(false);
|
||||
expect(h.labels).toEqual(["KI: apply_ops"]);
|
||||
});
|
||||
|
||||
it("App-Werkzeuge: ohne App Fehler, mit App Auswahl/Zoom über den Host", async () => {
|
||||
const off = fakeHost(false);
|
||||
expect((await callAiTool(off.host, "select", { ids: ["a"] })).isError).toBe(true);
|
||||
const on = fakeHost(true);
|
||||
const id = sampleProject.walls[0].id;
|
||||
expect((await callAiTool(on.host, "select", { ids: [id] })).isError).toBe(false);
|
||||
expect(on.sel()).toEqual([id]);
|
||||
expect(JSON.parse(textOf(await callAiTool(on.host, "get_selection", {})))).toEqual({ walls: [id] });
|
||||
expect((await callAiTool(on.host, "zoom_to", { ids: [id] })).isError).toBe(false);
|
||||
expect(on.zoom()).toEqual([id]);
|
||||
expect((await callAiTool(on.host, "select", { ids: "x" })).isError).toBe(true);
|
||||
});
|
||||
|
||||
it("Auswertungen und Export ohne Dateizugriff", async () => {
|
||||
const { host } = fakeHost(false);
|
||||
expect(JSON.parse(textOf(await callAiTool(host, "kennzahlen", {}))).kennzahlen).toBeTruthy();
|
||||
expect(Array.isArray(JSON.parse(textOf(await callAiTool(host, "schedule", { kind: "openings" }))))).toBe(true);
|
||||
expect(textOf(await callAiTool(host, "export", { format: "svg" }))).toContain("<svg");
|
||||
expect((await callAiTool(host, "export", { format: "pdf" })).isError).toBe(true); // PDF nur in der App
|
||||
expect((await callAiTool(host, "export", { format: "svg", save: true })).isError).toBe(true); // Speichern nur mit Dialog
|
||||
expect((await callAiTool(host, "gibtsnicht", {})).isError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Brücken-Anmeldung", () => {
|
||||
it("HMAC ist deterministisch, schlüsselabhängig; Vergleich in konstanter Zeit", async () => {
|
||||
const tok = randomHex();
|
||||
expect(tok).toMatch(/^[0-9a-f]{32}$/);
|
||||
const a = await hmacHex(tok, "app:123");
|
||||
expect(a).toBe(await hmacHex(tok, "app:123"));
|
||||
expect(a).not.toBe(await hmacHex(tok, "bridge:123"));
|
||||
expect(a).not.toBe(await hmacHex(randomHex(), "app:123"));
|
||||
expect(sameMac(a, a)).toBe(true);
|
||||
expect(sameMac(a.slice(1), a)).toBe(false);
|
||||
expect(sameMac(undefined, a)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
// [9] Verteilung der KI-Werkzeuge (`aiToolDefs.ts`) auf einen Host: die Projektdatei (headless,
|
||||
// `dossier-cli … mcp`) oder die laufende App (Brücke, `state/aiBridge.ts`). Gemeinsam ist alles, was
|
||||
// nur das Projekt braucht; Auswahl, Ansicht, PDF und Speichern-Dialog liefert nur die App.
|
||||
// Änderungen gehen ausschliesslich als Ops an `host.commit` (ein Schritt, Beschriftung „KI: <tool>“).
|
||||
|
||||
import type { Project } from "../model/types";
|
||||
import type { Plan } from "../plan/generatePlan";
|
||||
import { generatePlan } from "../plan/generatePlan";
|
||||
import { computeSection, generateSectionPlan } from "../plan/toSection";
|
||||
import { generateElevationPlan } from "../plan/toElevation";
|
||||
import { planToSvgString } from "../export/planToSvgString";
|
||||
import { exportIfcSpf } from "../export/exportIfc";
|
||||
import { exportScheduleCsv } from "../export/exportSchedule";
|
||||
import { openingSchedule } from "../export/openingSchedule";
|
||||
import { elementSchedule } from "../export/elementSchedule";
|
||||
import { computeKennzahlen, checkRoomProgram } from "../analysis/kennzahlen";
|
||||
import { computeAreaTable, computeIvhb } from "../analysis/areaTable";
|
||||
import { checkSiteRules } from "../analysis/siteRules";
|
||||
import { loadFileio } from "../engine/fileioWasm";
|
||||
import { documentFor } from "./document";
|
||||
import { validateProject, projectWarnings, type CoreOp } from "./ops";
|
||||
import { aiText, aiToolDef, randomHex, type AiToolResult } from "./aiToolDefs";
|
||||
|
||||
/** Was ein Werkzeug vom Gegenüber braucht. Optionale Teile fehlen headless. */
|
||||
export interface AiHost {
|
||||
project(): Project;
|
||||
/** Ops als EIN Schritt anwenden (Beschriftung `label`); `null` = angenommen, sonst der Grund. */
|
||||
commit(ops: CoreOp[], label: string): string | null;
|
||||
activeLevelId?(): string | undefined;
|
||||
/** Vorgaben der Befehle wie in der Oberfläche (aktive Kategorie, Wandtyp). */
|
||||
commandDefaults?(): { cat?: string; wallType?: string };
|
||||
/** Auswahl je Liste (`walls`, `rooms`, …). */
|
||||
selection?(): Record<string, string[]>;
|
||||
select?(ids: string[]): void;
|
||||
/** Auf die Elemente einpassen; `false` = keine Geometrie gefunden. */
|
||||
zoomTo?(ids: string[]): boolean;
|
||||
planPdf?(plan: Plan, scale: number, title: string): Promise<Uint8Array>;
|
||||
/** Speichern-Dialog: die Nutzerin wählt den Ort; `false` = abgebrochen. */
|
||||
save?(data: string | Uint8Array, name: string, mime: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
const json = (v: unknown) => aiText(JSON.stringify(v));
|
||||
const err = (t: string) => aiText(t, true);
|
||||
|
||||
function strIds(v: unknown): string[] | null {
|
||||
return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : null;
|
||||
}
|
||||
|
||||
function b64(bytes: Uint8Array): string {
|
||||
let s = "";
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
return btoa(s);
|
||||
}
|
||||
|
||||
function floorLevel(project: Project, host: AiHost, want: unknown) {
|
||||
const floors = project.drawingLevels.filter((l) => l.kind === "floor");
|
||||
if (typeof want === "string" && want) return floors.find((l) => l.id === want || l.name === want);
|
||||
const active = host.activeLevelId?.();
|
||||
return floors.find((l) => l.id === active) ?? floors[0];
|
||||
}
|
||||
|
||||
const codesOf = (p: Project) => new Set(p.layers.map((l) => l.code));
|
||||
|
||||
/** Führt Werkzeug `name` mit `args` auf `host` aus (MCP-Ergebnis, Fehler als `isError`). */
|
||||
export async function callAiTool(host: AiHost, name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const def = aiToolDef(name);
|
||||
if (!def) return err(`unbekanntes Werkzeug: ${name}`);
|
||||
try {
|
||||
return await dispatch(host, name, args ?? {});
|
||||
} catch (e) {
|
||||
return err(e instanceof Error ? e.message : String(e));
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatch(host: AiHost, name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const project = host.project();
|
||||
const label = `KI: ${name}`;
|
||||
switch (name) {
|
||||
case "project_info":
|
||||
return json({
|
||||
name: project.name,
|
||||
counts: Object.fromEntries(
|
||||
Object.entries(project as unknown as Record<string, unknown>)
|
||||
.filter(([, v]) => Array.isArray(v))
|
||||
.map(([k, v]) => [k, (v as unknown[]).length]),
|
||||
),
|
||||
levels: project.drawingLevels.map((l) => ({ id: l.id, name: l.name, kind: l.kind })),
|
||||
...(host.activeLevelId ? { activeLevelId: host.activeLevelId() } : {}),
|
||||
});
|
||||
case "query": {
|
||||
const list = (project as unknown as Record<string, unknown>)[String(args.collection)];
|
||||
if (!Array.isArray(list)) return err(`Keine Liste: ${String(args.collection)}`);
|
||||
const want = strIds(args.ids) ?? (typeof args.id === "string" ? [args.id] : null);
|
||||
const rows = want ? list.filter((e) => want.includes((e as { id?: string }).id ?? "")) : list.slice(0, Number(args.limit ?? 50));
|
||||
return json(rows);
|
||||
}
|
||||
case "render_svg": {
|
||||
const kind = String(args.kind);
|
||||
const lvl = project.drawingLevels.find((l) => l.kind === kind && (!args.name || l.name === args.name || l.id === args.name));
|
||||
if (!lvl) return err(`Ebene nicht gefunden: ${kind} ${String(args.name ?? "")}`);
|
||||
const scale = Number(args.scale ?? 100);
|
||||
const codes = codesOf(project);
|
||||
if (kind === "floor") return aiText(planToSvgString(generatePlan(project, lvl.id, codes), { scaleDenominator: scale }));
|
||||
if (kind === "section") {
|
||||
const o = await computeSection(project, lvl);
|
||||
if (!o) return err("keine gültige Schnittlinie");
|
||||
return aiText(planToSvgString(generateSectionPlan(o, false, { visibleCodes: codes }), { scaleDenominator: scale }));
|
||||
}
|
||||
const plan = generateElevationPlan(project, lvl, { scaleDenominator: scale });
|
||||
return plan ? aiText(planToSvgString(plan, { scaleDenominator: scale })) : err("keine gültige Ansichtslinie");
|
||||
}
|
||||
case "apply_ops": {
|
||||
const ops = args.ops as CoreOp[];
|
||||
if (!Array.isArray(ops)) return err("ops muss eine Liste sein");
|
||||
const problem = host.commit(ops, label);
|
||||
return problem ? err(`Abgelehnt, nichts geändert: ${problem}`) : aiText(`ok: ${ops.length} Op(s) angewendet`);
|
||||
}
|
||||
case "run_command": {
|
||||
const cmd = args.cmd;
|
||||
if (typeof cmd !== "string" || !cmd) return err("cmd fehlt");
|
||||
const params = (args.params && typeof args.params === "object" ? args.params : {}) as Record<string, unknown>;
|
||||
const lvl = floorLevel(project, host, args.level);
|
||||
const d = host.commandDefaults?.() ?? {};
|
||||
const cat = d.cat ?? project.walls[0]?.categoryCode ?? project.layers[0]?.code ?? "";
|
||||
const ctx = { level: lvl?.id ?? "", floorHeight: lvl?.floorHeight ?? null, cat, wallType: d.wallType ?? "", ...((params.ctx as object) ?? {}) };
|
||||
const ops = documentFor(project).cmdOps({ ...params, cmd, ctx, stamp: `ki${Date.now().toString(36)}${randomHex(3)}` });
|
||||
if (ops.length === 0) return err(`Befehl „${cmd}“ ergab keine Änderung (Parameter prüfen)`);
|
||||
const problem = host.commit(ops, label);
|
||||
if (problem) return err(`Abgelehnt, nichts geändert: ${problem}`);
|
||||
const added = ops.flatMap((o) => (o.kind === "add" ? o.items.map((e) => ({ collection: o.collection, id: (e as { id?: string }).id })) : []));
|
||||
return json({ ok: true, ops: ops.length, added });
|
||||
}
|
||||
case "validate": {
|
||||
const problems = validateProject(project);
|
||||
const warnings = projectWarnings(project).map((w) => `Warnung: ${w}`);
|
||||
return aiText([...problems, ...warnings].join("\n") || "ok", problems.length > 0);
|
||||
}
|
||||
case "kennzahlen": {
|
||||
const kind = String(args.kind ?? "kennzahlen");
|
||||
if (kind === "sia416") return json(computeAreaTable(project));
|
||||
if (kind === "ivhb") return json(computeIvhb(project));
|
||||
return json({ kennzahlen: computeKennzahlen(project), raumprogramm: checkRoomProgram(project), baurecht: checkSiteRules(project) });
|
||||
}
|
||||
case "schedule": {
|
||||
const kind = String(args.kind ?? "openings");
|
||||
if (kind === "openings") return json(openingSchedule(project));
|
||||
if (kind === "elements") return json(elementSchedule(project));
|
||||
if (kind === "list") return aiText(exportScheduleCsv(project));
|
||||
return err(`schedule: unbekannte Art ${kind}`);
|
||||
}
|
||||
case "get_selection":
|
||||
return host.selection ? json(host.selection()) : appOnly(name);
|
||||
case "select": {
|
||||
if (!host.select) return appOnly(name);
|
||||
const ids = strIds(args.ids);
|
||||
if (!ids) return err("ids muss eine Liste von Texten sein");
|
||||
host.select(ids);
|
||||
return aiText(`ok: ${ids.length} gewählt`);
|
||||
}
|
||||
case "zoom_to": {
|
||||
if (!host.zoomTo) return appOnly(name);
|
||||
const ids = strIds(args.ids);
|
||||
if (!ids) return err("ids muss eine Liste von Texten sein");
|
||||
return host.zoomTo(ids) ? aiText("ok") : err("keine Geometrie zu diesen ids gefunden");
|
||||
}
|
||||
case "export":
|
||||
return exportTool(host, project, args);
|
||||
default:
|
||||
return err(`unbekanntes Werkzeug: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
const appOnly = (name: string) => err(`${name}: nur mit der laufenden App (dossier-cli mcp --app)`);
|
||||
|
||||
async function exportTool(host: AiHost, project: Project, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const format = String(args.format);
|
||||
const stem = project.name || "projekt";
|
||||
const scale = Number(args.scale ?? 100);
|
||||
if (args.save === true && !host.save) return err("save: Speichern nur in der App (Dialog, Ort wählt die Nutzerin)");
|
||||
let data: string | Uint8Array;
|
||||
let file: string;
|
||||
let mime: string;
|
||||
if (format === "ifc") {
|
||||
await loadFileio();
|
||||
data = exportIfcSpf(project);
|
||||
file = `${stem}.ifc`;
|
||||
mime = "application/x-step";
|
||||
} else if (format === "svg" || format === "pdf") {
|
||||
const lvl = floorLevel(project, host, args.level);
|
||||
if (!lvl) return err("kein Geschoss");
|
||||
const plan = generatePlan(project, lvl.id, codesOf(project));
|
||||
if (format === "svg") {
|
||||
data = planToSvgString(plan, { scaleDenominator: scale });
|
||||
mime = "image/svg+xml";
|
||||
} else {
|
||||
if (!host.planPdf) return appOnly("export pdf");
|
||||
data = await host.planPdf(plan, scale, `${stem} – ${lvl.name}`);
|
||||
mime = "application/pdf";
|
||||
}
|
||||
file = `${stem}-${lvl.name}.${format}`;
|
||||
} else return err(`export: unbekanntes Format ${format}`);
|
||||
if (args.save === true) {
|
||||
const ok = await host.save!(data, file, mime);
|
||||
return ok ? aiText(`gespeichert: ${file}`) : err("Speichern abgebrochen");
|
||||
}
|
||||
if (typeof data === "string") return aiText(data);
|
||||
return { content: [{ type: "resource", resource: { uri: `dossier:${file}`, mimeType: mime, blob: b64(data) } }], isError: false };
|
||||
}
|
||||
@@ -69,3 +69,7 @@ export { openingPreviewProject, openingPreviewSvgs } from "../plan/openingPrevie
|
||||
export type { OpeningPreviewSvgs } from "../plan/openingPreview";
|
||||
export { surfaceOpeningInfo, surfaceOpeningGrips, surfaceOpeningGripPatch } from "../plan/surfaceOpening";
|
||||
export type { SurfaceOpeningInfo } from "../plan/surfaceOpening";
|
||||
export { AI_TOOLS, AI_BRIDGE_DEFAULT_PORT, aiText, aiToolDef, hmacHex, randomHex, sameMac } from "./aiToolDefs";
|
||||
export type { AiToolDef, AiToolResult, AiBridgeMsg } from "./aiToolDefs";
|
||||
export { callAiTool } from "./aiTools";
|
||||
export type { AiHost } from "./aiTools";
|
||||
@@ -2270,6 +2270,23 @@ export const de = {
|
||||
"settings.section.network": "Netzwerk",
|
||||
"settings.offline": "Offline-Modus",
|
||||
"settings.offline.hint": "Sperrt alle Internet-Abrufe (Materialbibliothek, swisstopo, OpenStreetMap). Bereits geladene Daten bleiben nutzbar.",
|
||||
"settings.section.ai": "KI-Zugriff",
|
||||
"settings.ai.enable": "KI-Zugriff erlauben",
|
||||
"settings.ai.hint": "Ein KI-Assistent (MCP, z. B. Claude Desktop oder Claude Code) darf das offene Projekt über die lokale Brücke abfragen und ändern. Nur auf diesem Rechner (127.0.0.1); jede Änderung ist ein eigener Undo-Schritt „KI: …“. Der Schlüssel gilt bis zum Beenden der App.",
|
||||
"settings.ai.token": "Sitzungsschlüssel",
|
||||
"settings.ai.command": "Befehl für den MCP-Client",
|
||||
"settings.ai.copy": "Kopieren",
|
||||
"settings.ai.status.off": "Aus",
|
||||
"settings.ai.status.connecting": "Wartet auf die Brücke (dossier-cli mcp --app) …",
|
||||
"settings.ai.status.connected": "Verbunden",
|
||||
"settings.ai.status.auth-failed": "Brücke mit falschem Schlüssel — Befehl neu kopieren",
|
||||
"settings.ai.status.closed": "Getrennt",
|
||||
"ai.activity.title": "KI-Protokoll",
|
||||
"ai.activity.pause": "KI pausieren",
|
||||
"ai.activity.empty": "Noch keine Aufrufe.",
|
||||
"ai.activity.change": "Änderung",
|
||||
"ai.activity.error": "Fehler",
|
||||
"ai.activity.clear": "Leeren",
|
||||
"window.controls": "Fenster",
|
||||
"window.close": "Schliessen",
|
||||
"window.minimize": "Minimieren",
|
||||
|
||||
@@ -2220,6 +2220,23 @@ export const en: Record<TranslationKey, string> = {
|
||||
"settings.section.network": "Network",
|
||||
"settings.offline": "Offline mode",
|
||||
"settings.offline.hint": "Blocks all internet access (material library, swisstopo, OpenStreetMap). Already loaded data stays available.",
|
||||
"settings.section.ai": "AI access",
|
||||
"settings.ai.enable": "Allow AI access",
|
||||
"settings.ai.hint": "An AI assistant (MCP, e.g. Claude Desktop or Claude Code) may query and change the open project through the local bridge. This computer only (127.0.0.1); every change is its own undo step “KI: …”. The key is valid until the app quits.",
|
||||
"settings.ai.token": "Session key",
|
||||
"settings.ai.command": "Command for the MCP client",
|
||||
"settings.ai.copy": "Copy",
|
||||
"settings.ai.status.off": "Off",
|
||||
"settings.ai.status.connecting": "Waiting for the bridge (dossier-cli mcp --app) …",
|
||||
"settings.ai.status.connected": "Connected",
|
||||
"settings.ai.status.auth-failed": "Bridge has a wrong key — copy the command again",
|
||||
"settings.ai.status.closed": "Disconnected",
|
||||
"ai.activity.title": "AI log",
|
||||
"ai.activity.pause": "Pause AI",
|
||||
"ai.activity.empty": "No calls yet.",
|
||||
"ai.activity.change": "Change",
|
||||
"ai.activity.error": "Error",
|
||||
"ai.activity.clear": "Clear",
|
||||
"window.controls": "Window",
|
||||
"window.close": "Close",
|
||||
"window.minimize": "Minimize",
|
||||
|
||||
@@ -97,6 +97,8 @@ export function SettingsWindowApp() {
|
||||
onScaleLineWeightsChange={handlers.onScaleLineWeightsChange}
|
||||
offline={state.offline}
|
||||
onOfflineChange={handlers.onOfflineChange}
|
||||
aiAccess={state.aiAccess}
|
||||
onAiAccessChange={handlers.onAiAccessChange}
|
||||
layout={state.layout}
|
||||
onApplyLayout={handlers.onApplyLayout}
|
||||
onClose={onClose}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
//
|
||||
// Bezeichner englisch, Kommentare deutsch (CONVENTIONS.md).
|
||||
|
||||
import type { AiAccessView } from "../ui/AiAccessSection";
|
||||
import { useEffect, useRef } from "react";
|
||||
import { isTauriRuntime } from "./projectFile";
|
||||
import type { LayoutState } from "../panels/types";
|
||||
@@ -28,6 +29,8 @@ export interface SettingsSyncState {
|
||||
referenceElevationMasl: number | undefined;
|
||||
scaleLineWeights: boolean;
|
||||
offline: boolean;
|
||||
/** [9] KI-Zugriff (Schalter, Sitzungsschlüssel, Stand). */
|
||||
aiAccess: AiAccessView;
|
||||
layout: LayoutState;
|
||||
}
|
||||
|
||||
@@ -39,6 +42,7 @@ export interface SettingsCommandHandlers {
|
||||
onReferenceElevationChange: (n: number | undefined) => void;
|
||||
onScaleLineWeightsChange: (on: boolean) => void;
|
||||
onOfflineChange: (offline: boolean) => void;
|
||||
onAiAccessChange: (on: boolean) => void;
|
||||
onApplyLayout: (layout: LayoutState) => void;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
// [9] App-Seite der MCP-Brücke: verbindet sich (nur wenn „KI-Zugriff erlauben“ an ist) mit der Brücke
|
||||
// `dossier-cli mcp --app` auf 127.0.0.1, meldet sich gegenseitig per HMAC an (der Schlüssel reist nie,
|
||||
// s. `core/aiToolDefs.ts`) und beantwortet deren Werkzeug-Aufrufe über `call`. Kein Abruf ins Netz:
|
||||
// fest auf die lokale Schleife; versucht es bis `close()` alle `retryMs` erneut.
|
||||
|
||||
import { aiText, hmacHex, randomHex, sameMac, type AiBridgeMsg, type AiToolResult } from "../core/aiToolDefs";
|
||||
|
||||
export type AiBridgeStatus = "connecting" | "connected" | "auth-failed" | "closed";
|
||||
|
||||
export interface AiBridgeClientOptions {
|
||||
port: number;
|
||||
token: string;
|
||||
call: (name: string, args: Record<string, unknown>) => Promise<AiToolResult>;
|
||||
onStatus?: (s: AiBridgeStatus) => void;
|
||||
retryMs?: number;
|
||||
}
|
||||
|
||||
/** Startet die Verbindungsschleife; `close()` beendet sie und trennt. */
|
||||
export function connectAiBridge(o: AiBridgeClientOptions): { close(): void } {
|
||||
let stopped = false;
|
||||
let ws: WebSocket | null = null;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let failed = false; // nach falschem Schlüssel bleibt die Meldung stehen, bis eine Anmeldung gelingt
|
||||
const status = (s: AiBridgeStatus) => o.onStatus?.(s);
|
||||
|
||||
const retry = () => {
|
||||
if (stopped) return;
|
||||
timer = setTimeout(open, o.retryMs ?? 2000);
|
||||
};
|
||||
|
||||
function open(): void {
|
||||
if (stopped) return;
|
||||
if (!failed) status("connecting");
|
||||
let sock: WebSocket;
|
||||
try {
|
||||
sock = new WebSocket(`ws://127.0.0.1:${o.port}`);
|
||||
} catch {
|
||||
retry();
|
||||
return;
|
||||
}
|
||||
ws = sock;
|
||||
let stage: "hello" | "auth" | "ready" = "hello";
|
||||
let myNonce = "";
|
||||
const send = (m: AiBridgeMsg) => sock.send(JSON.stringify(m));
|
||||
sock.onmessage = async (ev) => {
|
||||
let m: AiBridgeMsg;
|
||||
try {
|
||||
m = JSON.parse(String(ev.data)) as AiBridgeMsg;
|
||||
} catch {
|
||||
sock.close();
|
||||
return;
|
||||
}
|
||||
if (stage === "hello" && m.type === "hello" && typeof m.nonce === "string") {
|
||||
myNonce = randomHex();
|
||||
stage = "auth";
|
||||
send({ type: "auth", nonce: myNonce, mac: await hmacHex(o.token, `app:${m.nonce}`) });
|
||||
} else if (stage === "auth" && m.type === "auth") {
|
||||
if (!sameMac(m.mac, await hmacHex(o.token, `bridge:${myNonce}`))) {
|
||||
failed = true;
|
||||
status("auth-failed");
|
||||
sock.close();
|
||||
return;
|
||||
}
|
||||
stage = "ready";
|
||||
send({ type: "ready" });
|
||||
failed = false;
|
||||
status("connected");
|
||||
} else if (stage === "ready" && m.type === "call" && typeof m.id === "number") {
|
||||
let result: AiToolResult;
|
||||
try {
|
||||
result = await o.call(String(m.name), m.args && typeof m.args === "object" ? m.args : {});
|
||||
} catch (e) {
|
||||
result = aiText(e instanceof Error ? e.message : String(e), true);
|
||||
}
|
||||
if (sock.readyState === WebSocket.OPEN) send({ type: "result", id: m.id, result });
|
||||
} else if (stage !== "ready") {
|
||||
// Unerwartete Nachricht vor der Anmeldung: kein Gespräch mit Unbekannten.
|
||||
sock.close();
|
||||
}
|
||||
};
|
||||
sock.onclose = () => {
|
||||
if (ws === sock) ws = null;
|
||||
if (stage === "ready") status("connecting");
|
||||
else if (stage === "auth") {
|
||||
// Die Brücke trennt nach unserer Anmeldung: sie kennt einen anderen Schlüssel.
|
||||
failed = true;
|
||||
status("auth-failed");
|
||||
}
|
||||
retry();
|
||||
};
|
||||
sock.onerror = () => {
|
||||
/* onclose folgt */
|
||||
};
|
||||
}
|
||||
|
||||
open();
|
||||
return {
|
||||
close() {
|
||||
stopped = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
ws?.close();
|
||||
ws = null;
|
||||
status("closed");
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// [9] KI-Zugriff in der App: Aufrufe gegen den echten Store (ein Undo-Schritt „KI: …“, Protokoll,
|
||||
// Pause, Auswahl, Zoom). Die Verbindung selbst prüft `cli/mcpBridge.test.ts`.
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { getState, setState } from "./appStore";
|
||||
import { sampleProject } from "../model/sampleProject";
|
||||
import { getAiAccess, handleAiCall, setAiAccessEnabled, setAiPaused, setAiView } from "./aiAccess";
|
||||
|
||||
beforeEach(() => {
|
||||
setState({ project: sampleProject, activeLevelId: "eg", undoDepth: 0, redoDepth: 0, canUndo: false, canRedo: false });
|
||||
getState().clearHistory();
|
||||
getState().clearSelection();
|
||||
setAiPaused(false);
|
||||
});
|
||||
|
||||
const text = (r: { content: { type: string }[] }) => (r.content[0] as unknown as { text: string }).text;
|
||||
|
||||
describe("KI-Zugriff (App-Host)", () => {
|
||||
it("aus per Vorgabe; Einschalten erzeugt einen Sitzungsschlüssel, der bleibt", () => {
|
||||
expect(getAiAccess().enabled).toBe(false);
|
||||
setAiAccessEnabled(true);
|
||||
const tok = getAiAccess().token;
|
||||
expect(tok).toMatch(/^[0-9a-f]{32}$/);
|
||||
setAiAccessEnabled(false);
|
||||
setAiAccessEnabled(true);
|
||||
expect(getAiAccess().token).toBe(tok);
|
||||
setAiAccessEnabled(false);
|
||||
expect(getAiAccess().status).toBe("off");
|
||||
});
|
||||
|
||||
it("run_command = ein Undo-Schritt „KI: run_command“, im Protokoll als Änderung", async () => {
|
||||
const n = getState().project.walls.length;
|
||||
const r = await handleAiCall("run_command", { cmd: "wall", params: { pts: [[0, 0], [3, 0], [3, 3]] } });
|
||||
expect(r.isError).toBe(false);
|
||||
expect(getState().project.walls.length).toBe(n + 2);
|
||||
expect(getState().historyEntries().undo).toEqual(["KI: run_command"]);
|
||||
getState().undo();
|
||||
expect(getState().project.walls.length).toBe(n);
|
||||
const last = getAiAccess().log[0];
|
||||
expect(last).toMatchObject({ tool: "run_command", mutating: true, ok: true });
|
||||
});
|
||||
|
||||
it("abgelehnte Ops: Fehler mit Grund, kein Schritt", async () => {
|
||||
const w = sampleProject.walls[0];
|
||||
const r = await handleAiCall("apply_ops", { ops: [{ kind: "add", collection: "walls", items: [{ ...w }] }] });
|
||||
expect(r.isError).toBe(true);
|
||||
expect(getState().historyEntries().undo).toEqual([]);
|
||||
expect(getAiAccess().log[0]).toMatchObject({ tool: "apply_ops", ok: false });
|
||||
});
|
||||
|
||||
it("Pause: jeder Aufruf wird abgewiesen und protokolliert", async () => {
|
||||
setAiPaused(true);
|
||||
const r = await handleAiCall("project_info", {});
|
||||
expect(r.isError).toBe(true);
|
||||
expect(text(r)).toContain("pausiert");
|
||||
expect(getAiAccess().log[0]).toMatchObject({ tool: "project_info", ok: false });
|
||||
});
|
||||
|
||||
it("select, get_selection und zoom_to über Store und Planansicht", async () => {
|
||||
const wall = sampleProject.walls[0];
|
||||
const room = sampleProject.rooms![0];
|
||||
expect((await handleAiCall("select", { ids: [wall.id, room.id, "gibtsnicht"] })).isError).toBe(false);
|
||||
expect(getState().selectedWallIds).toEqual([wall.id]);
|
||||
expect(getState().selectedRoomIds).toEqual([room.id]);
|
||||
expect(JSON.parse(text(await handleAiCall("get_selection", {})))).toMatchObject({ walls: [wall.id], rooms: [room.id] });
|
||||
let fitted: { x: number; y: number }[] = [];
|
||||
setAiView({ fitBounds: (pts) => (fitted = pts) });
|
||||
expect((await handleAiCall("zoom_to", { ids: [wall.id] })).isError).toBe(false);
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
expect(fitted.length).toBeGreaterThanOrEqual(2);
|
||||
expect(getState().activeLevelId).toBe(wall.floorId);
|
||||
expect((await handleAiCall("zoom_to", { ids: ["gibtsnicht"] })).isError).toBe(true);
|
||||
setAiView(null);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,222 @@
|
||||
// [9] KI-Zugriff auf das offene Projekt: Zustand (aus per Vorgabe, Sitzungsschlüssel, Pause, Protokoll),
|
||||
// die Verbindung zur MCP-Brücke (`net/aiBridge.ts`) und der Host, über den die gemeinsamen Werkzeuge
|
||||
// (`core/aiTools.ts`) den Store bedienen. Jede Änderung = ein Undo-Schritt „KI: <werkzeug>“; jeder Aufruf
|
||||
// steht im Protokoll (Anzeige `ui/AiActivityPanel.tsx`). Dateien schreibt nur der Speichern-Dialog.
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { AI_BRIDGE_DEFAULT_PORT, aiText, aiToolDef, applyOps, callAiTool, randomHex, validateOps } from "../core";
|
||||
import type { AiHost, AiToolResult, CoreOp, Project } from "../core";
|
||||
import type { Vec2 } from "../model/types";
|
||||
import { connectAiBridge, type AiBridgeStatus } from "../net/aiBridge";
|
||||
import { buildPlanPdf } from "../export/exportPdf";
|
||||
import { saveBinaryFile, saveTextFile } from "../native/saveFile";
|
||||
import { getState, setState } from "./appStore";
|
||||
|
||||
export interface AiLogEntry {
|
||||
at: number;
|
||||
tool: string;
|
||||
mutating: boolean;
|
||||
ok: boolean;
|
||||
/** Kurztext: Fehler oder Ergebnis-Anfang. */
|
||||
note: string;
|
||||
}
|
||||
|
||||
export interface AiAccessState {
|
||||
enabled: boolean;
|
||||
paused: boolean;
|
||||
/** Sitzungsschlüssel (leer, bis der Zugriff einmal eingeschaltet wurde). */
|
||||
token: string;
|
||||
port: number;
|
||||
status: AiBridgeStatus | "off";
|
||||
/** Neueste zuerst. */
|
||||
log: AiLogEntry[];
|
||||
}
|
||||
|
||||
const LOG_LIMIT = 50;
|
||||
const PORT_KEY = "dossier.aiBridge.port";
|
||||
|
||||
function storedPort(): number {
|
||||
try {
|
||||
const n = Number(globalThis.localStorage?.getItem(PORT_KEY));
|
||||
return Number.isInteger(n) && n > 0 && n < 65536 ? n : AI_BRIDGE_DEFAULT_PORT;
|
||||
} catch {
|
||||
return AI_BRIDGE_DEFAULT_PORT;
|
||||
}
|
||||
}
|
||||
|
||||
let state: AiAccessState = { enabled: false, paused: false, token: "", port: AI_BRIDGE_DEFAULT_PORT, status: "off", log: [] };
|
||||
const listeners = new Set<() => void>();
|
||||
let conn: { close(): void } | null = null;
|
||||
|
||||
function update(patch: Partial<AiAccessState>): void {
|
||||
state = { ...state, ...patch };
|
||||
for (const l of listeners) l();
|
||||
}
|
||||
|
||||
export const getAiAccess = (): AiAccessState => state;
|
||||
|
||||
export function useAiAccess(): AiAccessState {
|
||||
return useSyncExternalStore(
|
||||
(l) => (listeners.add(l), () => listeners.delete(l)),
|
||||
() => state,
|
||||
() => state,
|
||||
);
|
||||
}
|
||||
|
||||
/** „KI-Zugriff erlauben“: verbindet (bzw. trennt) die Brücke. Der Schlüssel gilt für die ganze Sitzung. */
|
||||
export function setAiAccessEnabled(on: boolean): void {
|
||||
if (on === state.enabled) return;
|
||||
conn?.close();
|
||||
conn = null;
|
||||
if (!on) {
|
||||
update({ enabled: false, status: "off" });
|
||||
return;
|
||||
}
|
||||
const token = state.token || randomHex();
|
||||
const port = storedPort();
|
||||
update({ enabled: true, token, port, status: "connecting" });
|
||||
if (typeof WebSocket === "undefined") return;
|
||||
conn = connectAiBridge({
|
||||
port,
|
||||
token,
|
||||
call: handleAiCall,
|
||||
onStatus: (s) => {
|
||||
if (state.enabled) update({ status: s });
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** „KI pausieren“: weist jeden Aufruf ab, die Verbindung bleibt. */
|
||||
export function setAiPaused(on: boolean): void {
|
||||
update({ paused: on });
|
||||
}
|
||||
|
||||
export function clearAiLog(): void {
|
||||
update({ log: [] });
|
||||
}
|
||||
|
||||
/** Planansicht für `zoom_to` (App meldet ihr Handle an, `null` beim Abbau). */
|
||||
let view: { fitBounds(pts: Vec2[]): void } | null = null;
|
||||
export function setAiView(v: { fitBounds(pts: Vec2[]): void } | null): void {
|
||||
view = v;
|
||||
}
|
||||
|
||||
// ── Host über den Store ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
type SelSetter = keyof Pick<
|
||||
ReturnType<typeof getState>,
|
||||
| "setSelectedWallIds"
|
||||
| "setSelectedDrawingIds"
|
||||
| "setSelectedCeilingIds"
|
||||
| "setSelectedOpeningIds"
|
||||
| "setSelectedStairIds"
|
||||
| "setSelectedRoomIds"
|
||||
| "setSelectedExtrudedSolidIds"
|
||||
| "setSelectedColumnIds"
|
||||
| "setSelectedRoofIds"
|
||||
| "setSelectedContextObjectIds"
|
||||
>;
|
||||
|
||||
/** Liste des Projekts → Auswahl-Kanal (Lesen, Setzen). */
|
||||
const CHANNELS: [keyof Project, string, SelSetter][] = [
|
||||
["walls", "selectedWallIds", "setSelectedWallIds"],
|
||||
["drawings2d", "selectedDrawingIds", "setSelectedDrawingIds"],
|
||||
["ceilings", "selectedCeilingIds", "setSelectedCeilingIds"],
|
||||
["openings", "selectedOpeningIds", "setSelectedOpeningIds"],
|
||||
["stairs", "selectedStairIds", "setSelectedStairIds"],
|
||||
["rooms", "selectedRoomIds", "setSelectedRoomIds"],
|
||||
["extrudedSolids", "selectedExtrudedSolidIds", "setSelectedExtrudedSolidIds"],
|
||||
["columns", "selectedColumnIds", "setSelectedColumnIds"],
|
||||
["roofs", "selectedRoofIds", "setSelectedRoofIds"],
|
||||
["context", "selectedContextObjectIds", "setSelectedContextObjectIds"],
|
||||
];
|
||||
|
||||
type Ent = Record<string, unknown> & { id?: string };
|
||||
const listOf = (p: Project, k: keyof Project) => ((p as unknown as Record<string, unknown>)[k] as Ent[] | undefined) ?? [];
|
||||
|
||||
function findEntity(p: Project, id: string): Ent | undefined {
|
||||
for (const [k] of CHANNELS) {
|
||||
const e = listOf(p, k).find((x) => x.id === id);
|
||||
if (e) return e;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Alle Punkte {x, y} bzw. [x, y] eines Elements (Grundriss-Meter), für das Einpassen. */
|
||||
function pointsOf(v: unknown, out: Vec2[], depth = 0): void {
|
||||
if (depth > 6 || v === null || typeof v !== "object") return;
|
||||
if (Array.isArray(v)) {
|
||||
if (v.length === 2 && typeof v[0] === "number" && typeof v[1] === "number") out.push({ x: v[0], y: v[1] });
|
||||
else for (const x of v) pointsOf(x, out, depth + 1);
|
||||
return;
|
||||
}
|
||||
const o = v as Record<string, unknown>;
|
||||
if (typeof o.x === "number" && typeof o.y === "number" && Number.isFinite(o.x) && Number.isFinite(o.y)) {
|
||||
out.push({ x: o.x, y: o.y });
|
||||
return;
|
||||
}
|
||||
for (const x of Object.values(o)) pointsOf(x, out, depth + 1);
|
||||
}
|
||||
|
||||
export const appHost: AiHost = {
|
||||
project: () => getState().project,
|
||||
activeLevelId: () => getState().activeLevelId,
|
||||
commandDefaults: () => ({ cat: getState().activeCategoryCode }),
|
||||
commit: (ops: CoreOp[], label: string) => {
|
||||
const s = getState();
|
||||
const before = s.project;
|
||||
// Vorprüfung für eine verständliche Antwort; der Store prüft beim Anwenden nochmals (Kern).
|
||||
const problems = validateOps(applyOps(before, ops), ops, before);
|
||||
if (problems.length) return problems.join("; ");
|
||||
s.groupChanges(() => getState().applyChange(ops), undefined, label);
|
||||
return getState().project === before ? "vom Kern abgelehnt" : null;
|
||||
},
|
||||
selection: () => {
|
||||
const s = getState() as unknown as Record<string, string[]>;
|
||||
return Object.fromEntries(CHANNELS.map(([k, sel]) => [k, s[sel] ?? []]).filter(([, ids]) => ids.length > 0));
|
||||
},
|
||||
select: (ids: string[]) => {
|
||||
const s = getState();
|
||||
const p = s.project;
|
||||
s.clearSelection();
|
||||
for (const [k, , set] of CHANNELS) {
|
||||
const have = new Set(listOf(p, k).map((e) => e.id));
|
||||
const mine = ids.filter((id) => have.has(id));
|
||||
if (mine.length) s[set](mine);
|
||||
}
|
||||
},
|
||||
zoomTo: (ids: string[]) => {
|
||||
const p = getState().project;
|
||||
const pts: Vec2[] = [];
|
||||
let level: string | undefined;
|
||||
for (const id of ids) {
|
||||
const e = findEntity(p, id);
|
||||
if (!e) continue;
|
||||
level ??= (e.floorId ?? e.levelId) as string | undefined;
|
||||
const before = pts.length;
|
||||
pointsOf(e, pts);
|
||||
if (pts.length === before && typeof e.wallId === "string") pointsOf(findEntity(p, e.wallId), pts);
|
||||
}
|
||||
if (pts.length === 0) return false;
|
||||
if (level && p.drawingLevels.some((l) => l.id === level)) setState({ activeLevelId: level });
|
||||
// Erst nach dem Geschosswechsel einpassen (neuer Plan).
|
||||
const v = view;
|
||||
if (v) setTimeout(() => v.fitBounds(pts), 0);
|
||||
return true;
|
||||
},
|
||||
planPdf: async (plan, scale, title) => {
|
||||
const doc = await buildPlanPdf(plan, { scaleDenominator: scale, paper: "a3", orientation: "landscape", title });
|
||||
return new Uint8Array(doc.output("arraybuffer"));
|
||||
},
|
||||
save: (data, name, mime) => (typeof data === "string" ? saveTextFile(data, name, mime) : saveBinaryFile(data, name, mime)),
|
||||
};
|
||||
|
||||
/** Ein Aufruf der Brücke: Pause prüfen, ausführen, protokollieren. */
|
||||
export async function handleAiCall(name: string, args: Record<string, unknown>): Promise<AiToolResult> {
|
||||
const mutating = aiToolDef(name)?.mutating === true;
|
||||
const result = state.paused ? aiText("KI-Zugriff ist in Dossier pausiert", true) : await callAiTool(appHost, name, args);
|
||||
const first = result.content[0];
|
||||
const note = first?.type === "text" ? first.text.slice(0, 120) : (first?.resource.uri ?? "");
|
||||
update({ log: [{ at: Date.now(), tool: name, mutating, ok: !result.isError, note }, ...state.log].slice(0, LOG_LIMIT) });
|
||||
return result;
|
||||
}
|
||||
@@ -8219,6 +8219,33 @@ body {
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
/* ── KI-Zugriff [9] (AiAccessSection, AiActivityPanel) ───────────────── */
|
||||
.ai-token-row { display: flex; gap: 6px; align-items: center; margin: 4px 0 8px; }
|
||||
.ai-token { flex: 1; min-width: 0; font-family: var(--font-mono); font-size: 11px; }
|
||||
.ai-cmd { flex: 1; min-width: 0; font-family: var(--font-mono); font-size: 11px; overflow-wrap: anywhere; user-select: all; }
|
||||
.ai-activity {
|
||||
position: fixed; left: 12px; bottom: 36px; z-index: 900; width: 260px; max-height: 40vh; overflow: auto;
|
||||
background: var(--panel); color: var(--ink); border: 1px solid var(--border); border-radius: 6px;
|
||||
font-size: 11px; box-shadow: 0 4px 14px rgba(0, 0, 0, 0.18); padding: 6px 8px;
|
||||
}
|
||||
.ai-activity.is-paused { border-color: var(--danger-light); }
|
||||
.ai-activity-head { display: flex; align-items: center; gap: 6px; }
|
||||
.ai-activity-title { flex: 1; text-align: left; background: none; border: 0; color: inherit; font-weight: 600; cursor: pointer; padding: 0; }
|
||||
.ai-count { margin-left: 4px; padding: 0 5px; border-radius: 8px; background: var(--active-dim); }
|
||||
.ai-pause { display: flex; align-items: center; gap: 4px; white-space: nowrap; }
|
||||
.ai-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--muted); flex: none; }
|
||||
.ai-dot-connected { background: #3a9a4a; }
|
||||
.ai-dot-auth-failed { background: var(--danger-light); }
|
||||
.ai-activity-empty { color: var(--muted); margin-top: 6px; }
|
||||
.ai-activity-log { list-style: none; margin: 6px 0 0; padding: 0; }
|
||||
.ai-activity-log li { display: flex; gap: 6px; padding: 2px 0; border-top: 1px solid var(--line); }
|
||||
.ai-activity-log li.is-change .ai-tool { font-weight: 600; }
|
||||
.ai-activity-log li.is-error { color: var(--danger-light); }
|
||||
.ai-time { color: var(--muted); font-family: var(--font-mono); }
|
||||
.ai-tool { flex: 1; }
|
||||
.ai-tag { color: var(--muted); }
|
||||
.ai-activity-clear { margin-top: 4px; font-size: 11px; }
|
||||
|
||||
/* ── BCF-Themen (BcfPanel) ───────────────────────────────────────────── */
|
||||
.bcf-panel {
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// [9] Einstellungen → Allgemein → KI-Zugriff: Schalter (aus per Vorgabe), Sitzungsschlüssel und die
|
||||
// Zeile für den MCP-Client. Rein darstellend (Werte über Props), damit sie auch im nativen
|
||||
// Einstellungs-Fenster läuft (Sync-Brücke, `native/settingsWindow.ts`).
|
||||
|
||||
import { t } from "../i18n";
|
||||
|
||||
/** Was die Einstellungen vom KI-Zugriff zeigen (über die Fenstergrenze serialisierbar). */
|
||||
export interface AiAccessView {
|
||||
enabled: boolean;
|
||||
token: string;
|
||||
port: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export function aiBridgeCommandLine(v: Pick<AiAccessView, "token" | "port">): string {
|
||||
const port = v.port === 7979 ? "" : ` --port ${v.port}`;
|
||||
return `dossier-cli mcp --app${port} --token ${v.token}`;
|
||||
}
|
||||
|
||||
export function AiAccessSection({ view, onChange }: { view: AiAccessView; onChange: (on: boolean) => void }) {
|
||||
const copy = (text: string) => void navigator.clipboard?.writeText(text).catch(() => {});
|
||||
return (
|
||||
<section className="imp-section" data-testid="ai-access">
|
||||
<div className="imp-section-title">{t("settings.section.ai")}</div>
|
||||
<label className="settings-check">
|
||||
<input type="checkbox" checked={view.enabled} onChange={(e) => onChange(e.target.checked)} />
|
||||
{t("settings.ai.enable")}
|
||||
</label>
|
||||
<div className="imp-note">{t("settings.ai.hint")}</div>
|
||||
{view.enabled && (
|
||||
<>
|
||||
<span className="settings-field-label">{t("settings.ai.token")}</span>
|
||||
<div className="ai-token-row">
|
||||
<input className="ai-token" readOnly value={view.token} data-testid="ai-token" onFocus={(e) => e.currentTarget.select()} />
|
||||
<button type="button" onClick={() => copy(view.token)}>{t("settings.ai.copy")}</button>
|
||||
</div>
|
||||
<span className="settings-field-label">{t("settings.ai.command")}</span>
|
||||
<div className="ai-token-row">
|
||||
<code className="ai-cmd">{aiBridgeCommandLine(view)}</code>
|
||||
<button type="button" onClick={() => copy(aiBridgeCommandLine(view))}>{t("settings.ai.copy")}</button>
|
||||
</div>
|
||||
<div className="imp-note" data-testid="ai-status">{t(`settings.ai.status.${view.status}`)}</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// [9] Kleines Protokoll der KI-Aufrufe (unten links, nur solange „KI-Zugriff erlauben“ an ist):
|
||||
// Verbindungsstand, Schalter „KI pausieren“, die letzten Aufrufe (Änderungen hervorgehoben).
|
||||
|
||||
import { useState } from "react";
|
||||
import { t } from "../i18n";
|
||||
import { clearAiLog, setAiPaused, useAiAccess } from "../state/aiAccess";
|
||||
|
||||
const time = (ms: number) => new Date(ms).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
|
||||
export function AiActivityPanel() {
|
||||
const ai = useAiAccess();
|
||||
const [open, setOpen] = useState(true);
|
||||
if (!ai.enabled) return null;
|
||||
const changes = ai.log.filter((e) => e.mutating && e.ok).length;
|
||||
return (
|
||||
<div className={`ai-activity${ai.paused ? " is-paused" : ""}`} data-testid="ai-activity" role="region" aria-label={t("ai.activity.title")}>
|
||||
<div className="ai-activity-head">
|
||||
<span className={`ai-dot ai-dot-${ai.status}`} title={t(`settings.ai.status.${ai.status}`)} />
|
||||
<button type="button" className="ai-activity-title" onClick={() => setOpen(!open)} aria-expanded={open}>
|
||||
{t("ai.activity.title")} {changes > 0 && <span className="ai-count">{changes}</span>}
|
||||
</button>
|
||||
<label className="ai-pause">
|
||||
<input type="checkbox" checked={ai.paused} onChange={(e) => setAiPaused(e.target.checked)} data-testid="ai-pause" />
|
||||
{t("ai.activity.pause")}
|
||||
</label>
|
||||
</div>
|
||||
{open && (
|
||||
<>
|
||||
{ai.log.length === 0 ? (
|
||||
<div className="ai-activity-empty">{t("ai.activity.empty")}</div>
|
||||
) : (
|
||||
<ul className="ai-activity-log" data-testid="ai-log">
|
||||
{ai.log.slice(0, 12).map((e, i) => (
|
||||
<li key={`${e.at}-${i}`} className={`${e.ok ? "" : "is-error"}${e.mutating ? " is-change" : ""}`} title={e.note}>
|
||||
<span className="ai-time">{time(e.at)}</span>
|
||||
<span className="ai-tool">{e.tool}</span>
|
||||
{e.mutating && <span className="ai-tag">{t("ai.activity.change")}</span>}
|
||||
{!e.ok && <span className="ai-tag">{t("ai.activity.error")}</span>}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
{ai.log.length > 0 && (
|
||||
<button type="button" className="ai-activity-clear" onClick={clearAiLog}>
|
||||
{t("ai.activity.clear")}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { t, type TranslationKey } from "../i18n";
|
||||
import { ACCENT_SWATCHES } from "../theme/accents";
|
||||
import { ColorHexField } from "./ColorHexField";
|
||||
import { LayoutMenu } from "./LayoutMenu";
|
||||
import { AiAccessSection, type AiAccessView } from "./AiAccessSection";
|
||||
import { APP_VERSION } from "./TopBar";
|
||||
import type { LayoutState } from "../panels/types";
|
||||
import type { ThemeMode } from "../theme/themeMode";
|
||||
@@ -79,6 +80,9 @@ export interface SettingsDialogProps {
|
||||
/** Offline-Modus: sperrt alle entfernten Abrufe (Materialbibliothek, swisstopo, OSM). */
|
||||
offline: boolean;
|
||||
onOfflineChange: (offline: boolean) => void;
|
||||
/** [9] KI-Zugriff (MCP-Brücke): Stand und Schalter; ohne Angabe keine Sektion. */
|
||||
aiAccess?: AiAccessView;
|
||||
onAiAccessChange?: (on: boolean) => void;
|
||||
/** Arbeitsumgebung (Fenster-/Dock-Layouts) — LayoutMenu wird HIER gerendert
|
||||
* (nicht mehr als vorgefertigtes ReactNode hereingereicht: JSX ist über eine
|
||||
* Fenstergrenze nicht serialisierbar, s. `windowed`). */
|
||||
@@ -124,6 +128,8 @@ export function SettingsDialog({
|
||||
onScaleLineWeightsChange,
|
||||
offline,
|
||||
onOfflineChange,
|
||||
aiAccess,
|
||||
onAiAccessChange,
|
||||
layout,
|
||||
onApplyLayout,
|
||||
onAliasOverridesChange,
|
||||
@@ -232,6 +238,8 @@ export function SettingsDialog({
|
||||
<div className="imp-note">{t("settings.offline.hint")}</div>
|
||||
</section>
|
||||
|
||||
{aiAccess && onAiAccessChange && <AiAccessSection view={aiAccess} onChange={onAiAccessChange} />}
|
||||
|
||||
<section className="imp-section">
|
||||
<div className="imp-section-title">{t("settings.section.display")}</div>
|
||||
<span className="settings-field-label">{t("settings.theme")}</span>
|
||||
|
||||
Reference in new issue
Block a user