示例工程 28-project-approval-panel

28-project-approval-panel/app/main/index.ts

typescript · 8.8 KB

import { app, BrowserWindow, ipcMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  assertDecideReq,
  assertRequestReq,
  CH,
  type ApprovalRecord,
  type ApprovalRequest,
  type ApprovalState,
  type Decision,
  type Risk,
  type Tool,
} from "../shared/ipc";

app.setName("Approval Panel");

const isSmoke =
  process.argv.includes("--smoke") || process.env.DEMO_SMOKE === "1";
const isShots = process.argv.includes("--shots");
const smokeData = isSmoke
  ? path.join(os.tmpdir(), `approval-panel-smoke-${process.pid}`)
  : "";
if (smokeData) app.setPath("userData", smokeData);

let sequence = 0;
let pending: ApprovalRequest[] = [];
let history: ApprovalRecord[] = [];
let policies: Tool[] = [];
const timers = new Map<string, ReturnType<typeof setTimeout>>();

function state(): ApprovalState {
  return {
    pending: [...pending],
    history: [...history],
    policies: [...policies],
    now: Date.now(),
  };
}

function broadcast(): void {
  const snapshot = state();
  for (const win of BrowserWindow.getAllWindows()) {
    if (!win.isDestroyed()) win.webContents.send(CH.changed, snapshot);
  }
}

function record(
  request: ApprovalRequest,
  outcome: ApprovalRecord["outcome"],
  auto: boolean,
): void {
  history = [
    {
      id: request.id,
      tool: request.tool,
      risk: request.risk,
      outcome,
      at: Date.now(),
      auto,
    },
    ...history,
  ].slice(0, 50);
}

function expire(id: string): void {
  const request = pending.find((item) => item.id === id);
  if (!request) return;
  pending = pending.filter((item) => item.id !== id);
  timers.delete(id);
  record(request, "expired", false);
  broadcast();
}

function enqueue(input: {
  tool: Tool;
  risk: Risk;
  detail: string;
  ttlMs: number;
}): ApprovalState {
  if (policies.includes(input.tool)) {
    record(
      {
        id: `auto-${++sequence}`,
        tool: input.tool,
        risk: input.risk,
        detail: input.detail,
        createdAt: Date.now(),
        expiresAt: Date.now(),
      },
      "allow",
      true,
    );
    broadcast();
    return state();
  }

  const request: ApprovalRequest = {
    id: `req-${++sequence}`,
    tool: input.tool,
    risk: input.risk,
    detail: input.detail,
    createdAt: Date.now(),
    expiresAt: Date.now() + input.ttlMs,
  };
  pending = [...pending, request].slice(-20);
  const timer = setTimeout(() => expire(request.id), input.ttlMs);
  timers.set(request.id, timer);
  broadcast();
  return state();
}

function decide(id: string, decision: Decision): ApprovalState {
  const request = pending.find((item) => item.id === id);
  if (!request) return state();
  const timer = timers.get(id);
  if (timer) clearTimeout(timer);
  timers.delete(id);
  pending = pending.filter((item) => item.id !== id);
  if (decision === "always") {
    policies = [...new Set([...policies, request.tool])];
  }
  record(request, decision, false);
  broadcast();
  return state();
}

function reset(): ApprovalState {
  for (const timer of timers.values()) clearTimeout(timer);
  timers.clear();
  pending = [];
  history = [];
  policies = [];
  broadcast();
  return state();
}

function resolvePreload(): string {
  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(): BrowserWindow {
  const win = new BrowserWindow({
    width: 1100,
    height: 820,
    show: false,
    title: "工具调用审批面板",
    backgroundColor: "#ffffff",
    webPreferences: {
      preload: resolvePreload(),
      contextIsolation: true,
      sandbox: true,
      nodeIntegration: false,
      webSecurity: true,
      allowRunningInsecureContent: false,
      experimentalFeatures: false,
      webviewTag: false,
      spellcheck: false,
      backgroundThrottling: true,
    },
  });
  win.once("ready-to-show", () => {
    if (!win.isDestroyed()) win.show();
  });
  if (MAIN_WINDOW_VITE_DEV_SERVER_URL) {
    void win.loadURL(MAIN_WINDOW_VITE_DEV_SERVER_URL);
  } else {
    void win.loadFile(
      path.join(__dirname, `../renderer/${MAIN_WINDOW_VITE_NAME}/index.html`),
    );
  }
  return win;
}

function delay(ms: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function evalRenderer<T>(win: BrowserWindow, code: string): Promise<T> {
  let lastError: unknown = null;
  for (let attempt = 0; attempt < 3; attempt += 1) {
    try {
      return (await win.webContents.executeJavaScript(code)) as T;
    } catch (error) {
      lastError = error;
      await delay(200);
    }
  }
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
}

async function waitForRenderer(win: BrowserWindow): Promise<void> {
  for (let attempt = 0; attempt < 160; attempt += 1) {
    if (win.isDestroyed()) return;
    try {
      const ready = await evalRenderer<boolean>(
        win,
        "typeof window.__smoke === 'function'",
      );
      if (ready) return;
    } catch {
      // 页面仍在加载。
    }
    await delay(100);
  }
  throw new Error("renderer did not become ready");
}

type SmokeResult = {
  allowOutcome: string;
  alwaysPolicy: boolean;
  autoApproved: boolean;
  expiredSeen: boolean;
  keyboardOutcome: string;
  viewsMatch: boolean;
  finalHistory: number;
  reactVersion: string;
  vueVersion: string;
  svelteVersion: string;
};

async function runSmoke(): Promise<void> {
  try {
    const win = createWindow();
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    const result = await evalRenderer<SmokeResult>(win, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.allowOutcome === "allow" &&
          result.alwaysPolicy &&
          result.autoApproved &&
          result.expiredSeen &&
          result.keyboardOutcome === "allow" &&
          result.viewsMatch &&
          result.finalHistory >= 4 &&
          result.reactVersion.startsWith("19.") &&
          result.vueVersion.startsWith("3.") &&
          result.svelteVersion.startsWith("5."),
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function capture(
  win: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  const image = await win.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(): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/28-project-approval-panel",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    const win = createWindow();
    await waitForRenderer(win);
    await delay(500);
    await waitForRenderer(win);
    await evalRenderer(win, `window.__prepareShots("react")`);
    await delay(500);
    await capture(win, dir, "28-01-react.png");
    await evalRenderer(win, `window.__prepareShots("vue")`);
    await delay(500);
    await capture(win, dir, "28-02-vue.png");
    await evalRenderer(win, `window.__prepareShots("svelte")`);
    await delay(500);
    await capture(win, dir, "28-03-svelte.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

ipcMain.handle(CH.get, () => state());

ipcMain.handle(CH.decide, (_event, raw: unknown) => {
  try {
    assertDecideReq(raw);
    return decide(raw.id, raw.decision);
  } catch {
    throw new Error("APPROVAL_DECIDE_FAILED");
  }
});

ipcMain.handle(CH.request, (_event, raw: unknown) => {
  try {
    assertRequestReq(raw);
    return enqueue(raw);
  } catch {
    throw new Error("APPROVAL_REQUEST_FAILED");
  }
});

ipcMain.handle(CH.reset, () => reset());

const ticker = setInterval(() => {
  if (pending.length > 0) broadcast();
}, 250);

app.whenReady().then(() => {
  if (isSmoke) {
    void runSmoke();
  } else if (isShots) {
    void runShots();
  } else {
    createWindow();
  }
  app.on("activate", () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("will-quit", () => {
  clearInterval(ticker);
  for (const timer of timers.values()) clearTimeout(timer);
  timers.clear();
  if (smokeData) {
    try {
      fsSync.rmSync(smokeData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

app.on("window-all-closed", () => {
  if (!isSmoke && !isShots && process.platform !== "darwin") app.quit();
});