示例工程 43-project-local-knowledge-base

43-project-local-knowledge-base/app/main/index.ts

typescript · 15 KB

import {
  app,
  BrowserWindow,
  dialog,
  ipcMain,
  utilityProcess,
  type UtilityProcess,
} from "electron";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import {
  assertSearchReq,
  CH,
  type DocRow,
  type EventRow,
  type Hit,
  type IndexState,
  type Snapshot,
} from "../shared/ipc";
import { toFtsQuery } from "../shared/query";

app.setName("Local Knowledge Base");

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(),
        `knowledge-${isSmoke ? "smoke" : "shots"}-${process.pid}`,
      )
    : "";
if (tempData) app.setPath("userData", tempData);

const userData = app.getPath("userData");
const dbPath = path.join(userData, "knowledge", "kb.sqlite");
const knowledgeDir = app.isPackaged
  ? path.join(process.resourcesPath, "knowledge")
  : path.join(app.getAppPath(), "knowledge");
const indexerPath = path.join(knowledgeDir, "indexer.cjs");
const samplesDir = path.join(knowledgeDir, "samples");

let win: BrowserWindow | null = null;
let worker: UtilityProcess | null = null;
let workerPid = 0;
let index: IndexState = {
  status: "idle",
  current: 0,
  total: 0,
  progress: 0,
  lastError: "",
  indexedAt: 0,
  docs: 0,
  chunks: 0,
  dbBytes: 0,
};
let docs: DocRow[] = [];
let hits: Hit[] = [];
let lastQuery = "";
let searchMs = 0;
let searchError = "";
let events: EventRow[] = [];
let readyResolve: ((child: UtilityProcess) => void) | null = null;
let indexResolve: (() => void) | null = null;
let indexReject: ((error: Error) => void) | null = null;

function log(kind: string, detail: string): void {
  events = [{ at: Date.now(), kind, detail }, ...events].slice(0, 40);
  broadcast();
}

function broadcast(): void {
  if (win && !win.isDestroyed()) {
    win.webContents.send("knowledge:event", { at: Date.now() });
  }
}

function sampleFiles(): string[] {
  try {
    return fsSync
      .readdirSync(samplesDir)
      .filter((name) => name.endsWith(".md"))
      .sort()
      .map((name) => path.join(samplesDir, name));
  } catch {
    return [];
  }
}

function dbSize(): number {
  let bytes = 0;
  for (const file of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
    try {
      bytes += fsSync.statSync(file).size;
    } catch {
      // 文件不存在。
    }
  }
  return bytes;
}

function refreshStats(): void {
  docs = [];
  index.docs = 0;
  index.chunks = 0;
  index.dbBytes = dbSize();
  if (!fsSync.existsSync(dbPath)) return;
  try {
    const db = new DatabaseSync(dbPath);
    try {
      const rows = db
        .prepare(
          "SELECT id, path, title, bytes, chunks FROM docs ORDER BY title",
        )
        .all() as Array<{
        id: number;
        path: string;
        title: string;
        bytes: number;
        chunks: number;
      }>;
      docs = rows.map((row) => ({ ...row }));
      const counts = db
        .prepare(
          "SELECT (SELECT COUNT(*) FROM docs) AS docs, (SELECT COUNT(*) FROM chunks) AS chunks",
        )
        .get() as { docs?: number; chunks?: number } | undefined;
      index.docs = Number(counts?.docs ?? docs.length);
      index.chunks = Number(counts?.chunks ?? 0);
    } finally {
      db.close();
    }
    index.dbBytes = dbSize();
    if (index.status !== "indexing" && index.status !== "error") {
      index.status = "ready";
    }
    if (!index.indexedAt) {
      index.indexedAt = fsSync.statSync(dbPath).mtimeMs;
    }
  } catch (error) {
    index.lastError = error instanceof Error ? error.message : String(error);
  }
}

function snapshot(): Snapshot {
  return {
    platform: process.platform,
    electronVersion: process.versions.electron,
    nodeVersion: process.versions.node,
    worker: { running: worker !== null, pid: workerPid },
    index: { ...index },
    docs: docs.map((doc) => ({ ...doc })),
    samples: sampleFiles().map((file) => path.basename(file)),
    lastQuery,
    hits: hits.map((hit) => ({ ...hit })),
    searchMs,
    searchError,
    events: events.map((row) => ({ ...row })),
  };
}

function settleIndex(error?: Error): void {
  if (error) indexReject?.(error);
  else indexResolve?.();
  indexResolve = null;
  indexReject = null;
}

function handleWorkerMessage(message: Record<string, unknown>): void {
  if (message.type === "worker-ready") {
    workerPid = Number(message.pid ?? worker?.pid ?? 0);
    if (worker) readyResolve?.(worker);
    readyResolve = null;
    log("worker", `索引器就绪 · pid ${workerPid}`);
    return;
  }
  if (message.type === "progress") {
    const current = Number(message.current ?? 0);
    const total = Number(message.total ?? 0);
    index.current = current;
    index.total = total;
    index.progress = total > 0 ? Math.round((current / total) * 100) : 0;
    index.status = "indexing";
    log("progress", `${current}/${total} · ${String(message.file ?? "")}`);
    return;
  }
  if (message.type === "done") {
    index.status = "ready";
    index.current = Number(message.total ?? index.total);
    index.total = index.current;
    index.progress = 100;
    index.indexedAt = Date.now();
    index.lastError = "";
    log("done", `${message.docs} 篇 / ${message.chunks} 块 · ${message.ms}ms`);
    worker?.kill();
    worker = null;
    refreshStats();
    settleIndex();
    return;
  }
  if (message.type === "error") {
    index.status = "error";
    index.lastError = String(message.message ?? "INDEX_FAILED");
    log("error", index.lastError);
    worker?.kill();
    worker = null;
    refreshStats();
    settleIndex(new Error(index.lastError));
  }
}

function startWorker(): Promise<UtilityProcess> {
  const ready = new Promise<UtilityProcess>((resolve) => {
    readyResolve = resolve;
  });
  const child = utilityProcess.fork(indexerPath, [], {
    stdio: "pipe",
    serviceName: "knowledge-indexer",
  });
  worker = child;
  workerPid = child.pid ?? 0;
  child.on("message", (message) => {
    handleWorkerMessage(message as Record<string, unknown>);
  });
  child.stderr?.on("data", (chunk: Buffer) => {
    log("worker-stderr", chunk.toString().slice(0, 200));
  });
  child.on("exit", (code) => {
    if (worker === child) worker = null;
    if (index.status === "indexing") {
      index.status = "error";
      index.lastError = `INDEXER_EXIT:${code}`;
      settleIndex(new Error(index.lastError));
    }
  });
  return ready;
}

async function startIndex(files: string[]): Promise<void> {
  if (worker) throw new Error("INDEX_ALREADY_RUNNING");
  if (files.length === 0) throw new Error("NO_FILES");
  index = {
    ...index,
    status: "indexing",
    current: 0,
    total: files.length,
    progress: 0,
    lastError: "",
  };
  hits = [];
  lastQuery = "";
  searchError = "";
  broadcast();
  const ready = startWorker();
  const finished = new Promise<void>((resolve, reject) => {
    indexResolve = resolve;
    indexReject = reject;
  });
  const child = await ready;
  child.postMessage({
    type: "index",
    dbPath,
    files: files.map((file) => ({ path: file, title: path.basename(file) })),
  });
  log("index", `开始索引 ${files.length} 个文件`);
  return finished;
}

async function reindexSamples(): Promise<void> {
  await startIndex(sampleFiles());
}

async function pickFiles(): Promise<void> {
  if (!win) return;
  const result = await dialog.showOpenDialog(win, {
    title: "选择要索引的 Markdown / 文本",
    properties: ["openFile", "multiSelections"],
    filters: [{ name: "文本", extensions: ["md", "txt"] }],
  });
  if (result.canceled || result.filePaths.length === 0) return;
  await startIndex(result.filePaths);
}

function search(query: string): void {
  lastQuery = query;
  searchError = "";
  hits = [];
  const started = Date.now();
  const fts = toFtsQuery(query);
  if (!fts) {
    searchError = "EMPTY_QUERY";
    searchMs = Date.now() - started;
    return;
  }
  if (!fsSync.existsSync(dbPath)) {
    searchError = "NO_INDEX";
    searchMs = Date.now() - started;
    return;
  }
  try {
    const db = new DatabaseSync(dbPath);
    try {
      const rows = db
        .prepare(
          `SELECT chunks_fts.doc_id AS docId, chunks_fts.seq AS seq,
                  snippet(chunks_fts, 2, char(1), char(2), '…', 14) AS snippet,
                  bm25(chunks_fts) AS rank,
                  d.title AS title, d.path AS path
           FROM chunks_fts
           JOIN docs d ON d.id = chunks_fts.doc_id
           WHERE chunks_fts MATCH ?
           ORDER BY rank
           LIMIT 20`,
        )
        .all(fts) as Array<{
        docId: number;
        seq: number;
        snippet: string;
        rank: number;
        title: string;
        path: string;
      }>;
      hits = rows.map((row) => ({
        docId: row.docId,
        title: row.title,
        path: row.path,
        seq: row.seq,
        snippet: row.snippet,
        score: Number((-row.rank).toFixed(3)),
      }));
    } finally {
      db.close();
    }
    log("search", `${query} · ${hits.length} 条`);
  } catch (error) {
    searchError = error instanceof Error ? error.message : String(error);
    log("search-error", searchError);
  }
  searchMs = Date.now() - started;
}

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 window = new BrowserWindow({
    width: 1100,
    height: 860,
    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,
    },
  });
  window.once("ready-to-show", () => window.show());
  window.webContents.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: number): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

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

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

type SmokeResult = {
  docs: number;
  chunks: number;
  dbBytes: number;
  workerPid: number;
  status: string;
  progress: number;
  hits1: number;
  hits2: number;
  prefixHits: number;
  noHits: number;
  secondDocs: number;
  sampleCount: number;
  searchError: string;
  events: number;
};

async function runSmoke(window: BrowserWindow): Promise<void> {
  try {
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    const result = await evalRenderer<SmokeResult>(window, "window.__smoke()");
    process.stdout.write(
      `${JSON.stringify({
        evt: "smoke",
        ok:
          result.docs === 3 &&
          result.chunks >= 3 &&
          result.dbBytes > 0 &&
          result.workerPid > 0 &&
          result.status === "ready" &&
          result.progress === 100 &&
          result.hits1 >= 1 &&
          result.hits2 >= 1 &&
          result.prefixHits >= 1 &&
          result.noHits === 0 &&
          result.secondDocs === 3 &&
          result.sampleCount === 3 &&
          result.searchError === "" &&
          result.events >= 5,
        ...result,
      })}\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: BrowserWindow,
  dir: string,
  file: string,
): Promise<void> {
  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: BrowserWindow): Promise<void> {
  try {
    const dir = path.resolve(
      process.cwd(),
      "../../../docs/assets/images/43-project-local-knowledge-base",
    );
    fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
    await waitForRenderer(window);
    await delay(700);
    await waitForRenderer(window);
    await reindexSamples();
    await evalRenderer(window, `window.__prepareShots("index")`);
    await delay(300);
    await capture(window, dir, "43-01-index.png");
    await evalRenderer(window, `window.__prepareShots("search")`);
    await delay(500);
    await capture(window, dir, "43-02-search.png");
    void startIndex(sampleFiles()).catch(() => undefined);
    await evalRenderer(window, `window.__prepareShots("progress")`);
    await delay(400);
    await capture(window, dir, "43-03-progress.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.reindex, async () => {
  await reindexSamples();
  refreshStats();
  return snapshot();
});

ipcMain.handle(CH.startSamples, () => {
  void startIndex(sampleFiles()).catch((error) => {
    index.status = "error";
    index.lastError = error instanceof Error ? error.message : String(error);
    log("error", index.lastError);
  });
  return snapshot();
});

ipcMain.handle(CH.pick, async () => {
  await pickFiles();
  refreshStats();
  return snapshot();
});

ipcMain.handle(CH.search, (_event, raw: unknown) => {
  assertSearchReq(raw);
  search(raw.query);
  return snapshot();
});

ipcMain.handle(CH.refresh, () => {
  refreshStats();
  log("refresh", "刷新索引与文档状态");
  return snapshot();
});

app.whenReady().then(() => {
  refreshStats();
  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", () => {
  worker?.kill();
  worker = null;
  if (tempData) {
    try {
      fsSync.rmSync(tempData, { recursive: true, force: true });
    } catch {
      // 清理失败不影响退出。
    }
  }
});

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