示例工程 18-streaming-ui

18-streaming-ui/app/main/index.ts

typescript · 10 KB

import { app, BrowserWindow, ipcMain, MessageChannelMain } from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import {
  CH,
  type StartResult,
  type StreamMessage,
  type StreamOptions,
} from "../shared/ipc";

app.setName("Streaming UI Lab");

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

type Active = {
  id: string;
  timer: NodeJS.Timeout;
  port: Electron.MessagePortMain;
  sent: number;
};

let active: Active | null = null;
let seq = 0;

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: 760,
    show: false,
    title: "流式 UI 工作台",
    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 < 120; 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");
}

function closeActive(reason: string): void {
  if (!active) return;
  clearInterval(active.timer);
  try {
    active.port.postMessage({ type: "cancelled", sent: active.sent });
  } catch {
    // 端口可能已关闭。
  }
  const port = active.port;
  setTimeout(() => {
    try {
      port.close();
    } catch {
      // 已关闭。
    }
  }, 100);
  active = null;
  if (reason) {
    // 预留日志钩子。
  }
}

function shuffle(values: number[]): number[] {
  const copy = [...values];
  for (let index = copy.length - 1; index > 0; index -= 1) {
    const swap = Math.floor(Math.random() * (index + 1));
    const left = copy[index];
    const right = copy[swap];
    if (left !== undefined && right !== undefined) {
      copy[index] = right;
      copy[swap] = left;
    }
  }
  return copy;
}

ipcMain.handle(CH.start, (event, raw: unknown): StartResult => {
  const options = raw as Partial<StreamOptions> | undefined;
  if (
    !options ||
    !Number.isInteger(options.chunks) ||
    (options.chunks ?? 0) < 1 ||
    (options.chunks ?? 0) > 1000 ||
    !Number.isInteger(options.intervalMs) ||
    (options.intervalMs ?? -1) < 0 ||
    (options.intervalMs ?? 0) > 1000
  ) {
    return { ok: false, code: "BAD_OPTIONS" };
  }
  closeActive("replaced");
  seq += 1;
  const id = `stream-${seq}`;
  const from = Math.max(1, options.from ?? 1);
  const to = from + (options.chunks ?? 0) - 1;
  const channel = new MessageChannelMain();
  const port = channel.port1;
  port.start();
  const values = Array.from(
    { length: to - from + 1 },
    (_, index) => from + index,
  );
  const order = options.shuffle ? shuffle(values) : values;
  const state: Active = {
    id,
    timer: setInterval(() => {}, 1000),
    port,
    sent: 0,
  };
  clearInterval(state.timer);
  let cursor = 0;
  state.timer = setInterval(
    () => {
      const next = order[cursor];
      if (next === undefined) {
        clearInterval(state.timer);
        try {
          port.postMessage({
            type: "done",
            total: order.length,
            lastSeq: to,
          } satisfies StreamMessage);
        } catch {
          // 页面可能已关闭。
        }
        const current = state.port;
        setTimeout(() => {
          try {
            current.close();
          } catch {
            // 已关闭。
          }
        }, 120);
        if (active === state) active = null;
        return;
      }
      cursor += 1;
      state.sent += 1;
      try {
        port.postMessage({
          type: "chunk",
          seq: next,
          token: `${next} `,
          at: Date.now(),
        } satisfies StreamMessage);
      } catch {
        // 端口已关闭。
      }
    },
    Math.max(1, options.intervalMs ?? 20),
  );
  active = state;
  event.sender.postMessage(CH.port, { streamId: id }, [channel.port2]);
  return { ok: true, streamId: id, from, to };
});

ipcMain.handle(CH.cancel, () => {
  if (!active) return { ok: false };
  closeActive("cancelled");
  return { ok: true };
});

async function runDiagnostics(): Promise<void> {
  try {
    const win = createWindow();
    await waitForRenderer(win);
    const result = await evalRenderer<{
      ok: boolean;
      name?: string;
      message?: string;
      stack?: string[];
    }>(
      win,
      `(() => {
        try {
          const box = document.querySelector('[data-testid="missing-scroll-box"]');
          box.scrollTop = 0;
          return { ok: true };
        } catch (error) {
          return {
            ok: false,
            name: error.name,
            message: error.message,
            stack: String(error.stack || "").split("\\n").slice(0, 3),
          };
        }
      })()`,
    );
    process.stdout.write(
      `${JSON.stringify({ evt: "diagnostics", ...result })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "diagnostics", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

type SmokeResult = {
  naiveCommits: number;
  batchedCommits: number;
  sameText: boolean;
  reorderApplied: number;
  reorderBuffered: number;
  cancelled: boolean;
  scrollPaused: boolean;
  scrollResumed: boolean;
};

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.naiveCommits > result.batchedCommits &&
          result.batchedCommits > 0 &&
          result.sameText &&
          result.reorderApplied === 20 &&
          result.reorderBuffered === 0 &&
          result.cancelled &&
          result.scrollPaused &&
          result.scrollResumed,
        ...result,
      })}\n`,
    );
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "smoke", ok: false, message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

async function setTab(win: BrowserWindow, tab: string): Promise<void> {
  await evalRenderer(
    win,
    `window.__setTab && window.__setTab(${JSON.stringify(tab)})`,
  );
}

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/18-streaming-ui",
    );
    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()");
    await setTab(win, "compare");
    await delay(250);
    await capture(win, dir, "18-01-render-compare.png");
    await setTab(win, "reorder");
    await evalRenderer(win, "window.__startReorder()");
    await delay(350);
    await capture(win, dir, "18-02-reorder.png");
    await evalRenderer(win, "window.__cancel()");
    await setTab(win, "scroll");
    await evalRenderer(win, "window.__fillScroll()");
    await evalRenderer(win, "window.__pauseScroll()");
    await delay(250);
    await capture(win, dir, "18-03-scroll.png");
    app.quit();
  } catch (error) {
    process.stdout.write(
      `${JSON.stringify({ evt: "shots-error", message: String(error) })}\n`,
    );
    app.exit(1);
  }
}

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

app.on("will-quit", () => {
  closeActive("quit");
  if (smokeData) {
    try {
      fsSync.rmSync(smokeData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

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