import { app, BrowserWindow, ipcMain } from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { CH, } from "../shared/ipc"; import { EDGES, FAILURES, LAYERS, TOOLS, decide, validateArchitecture, } from "../shared/arch"; app.setName("Agent Arch Lab"); const isSmoke = process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1"; const isShots = process.argv.includes("--shots"); const tempData = isSmoke || isShots ? path.join(os.tmpdir(), `arch58-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); let win = null; let events = []; const modes = ["never", "once", "session", "always"]; function log(kind, detail) { events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40); broadcast(); } function broadcast() { if (win && !win.isDestroyed()) { win.webContents.send("arch:event", { at: Date.now() }); } } function matrix() { return TOOLS.map((tool) => ({ tool, decisions: modes.reduce((acc, mode) => { acc[mode] = decide(tool, mode); return acc; }, {}), })); } function checks() { const violations = validateArchitecture(EDGES); const rows = matrix(); const find = (id, mode) => rows.find((row) => row.tool.id === id)?.decisions[mode]; return [ { id: "layers", label: "架构分层 6 层", pass: LAYERS.length === 6, detail: LAYERS.map((layer) => layer.id).join("→"), }, { id: "edges", label: "数据流 8 条(5 允许 / 3 禁止)", pass: EDGES.length === 8 && EDGES.filter((edge) => edge.kind === "forbidden").length === 3, detail: `${EDGES.length} edges`, }, { id: "violations", label: "禁止边被校验器识别", pass: violations.includes("ui→system") && violations.includes("ui→provider") && violations.includes("preload→provider"), detail: violations.join(","), }, { id: "read", label: "受信工作区的 read 自动允许", pass: find("read", "never")?.allowed === true, detail: "READ_TRUSTED", }, { id: "write-never", label: "never 模式拒绝写入", pass: find("write", "never")?.allowed === false, detail: "POLICY_DENIED", }, { id: "write-once", label: "once 未授权需要审批", pass: find("write", "once")?.allowed === false && find("write", "once")?.needApproval === true, detail: "NEEDS_APPROVAL", }, { id: "write-session", label: "session 已授权放行", pass: decide(TOOLS[1], "session", true).allowed, detail: "APPROVED", }, { id: "write-always", label: "always + 受信工作区放行", pass: decide(TOOLS[1], "always", false, true).allowed, detail: "ALWAYS_TRUSTED", }, { id: "exec", label: "exec 永不自动放行", pass: decide(TOOLS[2], "always", true, true).needApproval === true && decide(TOOLS[2], "always", true, true).allowed === false, detail: "EXEC_ALWAYS_APPROVE", }, { id: "failures", label: "失败模式 6 类", pass: FAILURES.length === 6, detail: String(FAILURES.length), }, ]; } function snapshot() { const list = checks(); const passed = list.filter((check) => check.pass).length; return { platform: process.platform, electronVersion: process.versions.electron, nodeVersion: process.versions.node, layers: LAYERS.map((layer) => ({ ...layer, items: [...layer.items] })), edges: EDGES.map((edge) => ({ ...edge })), tools: TOOLS.map((tool) => ({ ...tool })), matrix: matrix(), failures: FAILURES.map((failure) => ({ ...failure })), violations: validateArchitecture(EDGES), checks: list, score: Math.round((passed / list.length) * 100), events: events.map((row) => ({ ...row })), }; } function resolvePreload() { const candidates = [ path.join(__dirname, "preload.cjs"), path.join(__dirname, "../preload/index.cjs"), path.join(__dirname, "preload.js"), ]; return (candidates.find((candidate) => fsSync.existsSync(candidate)) ?? candidates[0] ?? ""); } function createWindow() { const window = new BrowserWindow({ width: 1100, height: 860, show: false, title: "Agent 客户端架构规划", backgroundColor: "#ffffff", webPreferences: { preload: resolvePreload(), contextIsolation: true, sandbox: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false, experimentalFeatures: false, webviewTag: false, spellcheck: false, backgroundThrottling: true, }, }); const contents = window.webContents; contents.setWindowOpenHandler(() => ({ action: "deny" })); contents.on("will-navigate", (event, url) => { if (!url.startsWith("file://")) event.preventDefault(); }); contents.on("will-attach-webview", (event) => event.preventDefault()); window.once("ready-to-show", () => window.show()); contents.once("did-finish-load", () => { if (!window.isDestroyed() && !window.isVisible()) window.show(); log("ready", "架构界面已加载"); }); if (MAIN_WINDOW_VITE_DEV_SERVER_URL) { void window.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL); } else { void window.loadFile(path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`)); } win = window; return window; } function delay(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer(window, code) { let lastCaught = null; for (let attempt = 0; attempt < 3; attempt += 1) { try { return (await window.webContents.executeJavaScript(code)); } catch (caught) { lastCaught = caught; await delay(150); } } throw lastCaught instanceof Error ? lastCaught : new Error(String(lastCaught)); } async function waitForRenderer(window) { for (let attempt = 0; attempt < 160; attempt += 1) { if (window.isDestroyed()) return; try { const ready = await evalRenderer(window, "typeof window.__demo === 'function'"); if (ready) return; } catch { // 页面仍在加载。 } await delay(100); } throw new Error("renderer did not become ready"); } async function runSmoke(window) { try { await waitForRenderer(window); await delay(600); await waitForRenderer(window); const state = await evalRenderer(window, "window.__demo()"); process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: state.score === 100 && state.checks === 10 && state.passed === 10 && state.layers === 6 && state.edges === 8 && state.violations === 3 && state.tools === 4 && state.failures === 6 && state.readAllowed && state.writeNeverDenied && state.execNeedsApproval && state.matrix === 4, ...state, })}\n`); app.quit(); } catch (caught) { process.stdout.write(`${JSON.stringify({ evt: "smoke", ok: false, message: String(caught) })}\n`); app.exit(1); } } async function capture(window, dir, file) { const image = await window.webContents.capturePage(); if (image.isEmpty()) throw new Error(`empty capture: ${file}`); const png = image.toPNG(); fsSync.writeFileSync(path.join(dir, file), png); fsSync.writeFileSync(path.join(dir, "raw", file), png); } async function runShots(window) { try { const dir = path.resolve(process.cwd(), "../../../docs/assets/images/58-agent-app-architecture"); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(600); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("layers")`); await delay(250); await capture(window, dir, "58-01-layers.png"); await evalRenderer(window, `window.__prepareShots("permissions")`); await delay(250); await capture(window, dir, "58-02-permissions.png"); await evalRenderer(window, `window.__prepareShots("failures")`); await delay(250); await capture(window, dir, "58-03-failures.png"); app.quit(); } catch (caught) { process.stdout.write(`${JSON.stringify({ evt: "shots-error", message: String(caught) })}\n`); app.exit(1); } } ipcMain.handle(CH.snapshot, () => snapshot()); ipcMain.handle(CH.refresh, () => { log("refresh", "重新计算权限矩阵"); return snapshot(); }); app.whenReady().then(() => { log("load", `${LAYERS.length} layers / ${FAILURES.length} failures`); const window = createWindow(); if (isSmoke) { void runSmoke(window); } else if (isShots) { void runShots(window); } app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } else { win?.show(); win?.focus(); } }); }); app.on("will-quit", () => { if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); }); //# sourceMappingURL=index.js.map