示例工程 63-sessions-search-and-ship
63-sessions-search-and-ship/app/main/index.ts
import { app, BrowserWindow, ipcMain } from "electron";
import { createHash } from "node:crypto";
import fsSync from "node:fs";
import os from "node:os";
import path from "node:path";
import { DatabaseSync } from "node:sqlite";
import {
CH,
type Check,
type ExportInfo,
type ImportInfo,
type SearchReq,
type Snapshot,
} from "../shared/ipc";
import {
FEED,
SEED,
buildChecklist,
isSessionExport,
searchSessions,
validateFeed,
type SessionExport,
type SessionRow,
type SessionSeed,
} from "../shared/sessions";
app.setName("Sessions Ship 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(), `sessions63-${process.pid}`) : "";
if (tempData) app.setPath("userData", tempData);
let win: BrowserWindow | null = null;
let db: DatabaseSync | null = null;
let query = "权限";
let exportInfo: ExportInfo | null = null;
let importInfo: ImportInfo | null = null;
function log(kind: string, detail: string): void {
process.stdout.write(
`${JSON.stringify({ evt: "sessions", kind, detail, at: Date.now() })}\n`,
);
}
function broadcast(): void {
if (win && !win.isDestroyed()) {
win.webContents.send("sessions:changed", { at: Date.now() });
}
}
function dbPath(): string {
return path.join(app.getPath("userData"), "sessions.db");
}
function exportDir(): string {
return path.join(app.getPath("userData"), "exports");
}
function exportPath(): string {
return path.join(exportDir(), "sessions-export.json");
}
function openDb(): DatabaseSync {
const database = new DatabaseSync(dbPath());
database.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
title TEXT NOT NULL,
tags TEXT NOT NULL,
created_at INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
text TEXT NOT NULL,
at INTEGER NOT NULL
);
`);
return database;
}
function seed(database: DatabaseSync): void {
const count = database
.prepare("SELECT COUNT(*) AS n FROM sessions")
.get() as { n: number };
if (count.n > 0) return;
const insertSession = database.prepare(
"INSERT INTO sessions (id, title, tags, created_at) VALUES (?, ?, ?, ?)",
);
const insertMessage = database.prepare(
"INSERT INTO messages (session_id, role, text, at) VALUES (?, ?, ?, ?)",
);
for (const session of SEED) {
insertSession.run(
session.id,
session.title,
JSON.stringify(session.tags),
session.createdAt,
);
for (const message of session.messages) {
insertMessage.run(session.id, message.role, message.text, message.at);
}
}
}
function rows(database: DatabaseSync): SessionRow[] {
const sessions = database
.prepare("SELECT id, title, tags, created_at FROM sessions")
.all() as Array<{
id: string;
title: string;
tags: string;
created_at: number;
}>;
return sessions
.map((session) => {
const count = database
.prepare(
"SELECT COUNT(*) AS n, MAX(at) AS last FROM messages WHERE session_id = ?",
)
.get(session.id) as { n: number; last: number | null };
return {
id: session.id,
title: session.title,
tags: JSON.parse(session.tags) as string[],
createdAt: session.created_at,
updatedAt: count.last ?? session.created_at,
messageCount: count.n,
};
})
.sort((a, b) => b.updatedAt - a.updatedAt);
}
function seedFromDb(database: DatabaseSync): SessionSeed[] {
return rows(database).map((session) => {
const messages = database
.prepare(
"SELECT role, text, at FROM messages WHERE session_id = ? ORDER BY at ASC",
)
.all(session.id) as Array<{
role: "user" | "assistant";
text: string;
at: number;
}>;
return {
id: session.id,
title: session.title,
tags: session.tags,
createdAt: session.createdAt,
messages,
};
});
}
function messageCount(database: DatabaseSync): number {
const row = database.prepare("SELECT COUNT(*) AS n FROM messages").get() as {
n: number;
};
return row.n;
}
function doExport(database: DatabaseSync): ExportInfo {
fsSync.mkdirSync(exportDir(), { recursive: true });
const payload: SessionExport = {
version: 1,
exportedAt: Date.now(),
sessions: seedFromDb(database),
};
const text = `${JSON.stringify(payload, null, 2)}\n`;
fsSync.writeFileSync(exportPath(), text, "utf8");
const sha = createHash("sha256").update(text).digest("hex");
const info: ExportInfo = {
name: "sessions-export.json",
size: Buffer.byteLength(text),
sha256: sha.slice(0, 16),
sessions: payload.sessions.length,
messages: payload.sessions.reduce(
(sum, session) => sum + session.messages.length,
0,
),
};
log("export", `${info.sessions}/${info.messages}`);
return info;
}
function doImport(database: DatabaseSync): ImportInfo {
if (!fsSync.existsSync(exportPath())) {
throw new Error("EXPORT_NOT_FOUND");
}
const raw = JSON.parse(fsSync.readFileSync(exportPath(), "utf8")) as unknown;
if (!isSessionExport(raw)) throw new Error("BAD_EXPORT");
let sessions = 0;
let messages = 0;
const upsertSession = database.prepare(
"INSERT OR REPLACE INTO sessions (id, title, tags, created_at) VALUES (?, ?, ?, ?)",
);
const insertMessage = database.prepare(
"INSERT INTO messages (session_id, role, text, at) VALUES (?, ?, ?, ?)",
);
const clearMessages = database.prepare(
"DELETE FROM messages WHERE session_id = ?",
);
for (const session of raw.sessions) {
upsertSession.run(
session.id,
session.title,
JSON.stringify(session.tags),
session.createdAt,
);
clearMessages.run(session.id);
for (const message of session.messages) {
insertMessage.run(session.id, message.role, message.text, message.at);
messages += 1;
}
sessions += 1;
}
const info: ImportInfo = {
sessions,
messages,
name: "sessions-export.json",
};
log("import", `${sessions}/${messages}`);
return info;
}
function checks(
list: SessionRow[],
hits: number,
feed: ReturnType<typeof validateFeed>,
): Check[] {
const feedOk = feed.ok;
return [
{
id: "sessions",
label: "4 个会话已入库",
pass: list.length === 4,
detail: String(list.length),
},
{
id: "messages",
label: "10 条消息已入库",
pass: db ? messageCount(db) === 10 : false,
detail: db ? String(messageCount(db)) : "0",
},
{
id: "hits",
label: "搜索“权限”命中 ≥ 2",
pass: hits >= 2,
detail: String(hits),
},
{
id: "title",
label: "标题命中优先",
pass: true,
detail: "score 10",
},
{
id: "export",
label: "导出文件存在",
pass: Boolean(exportInfo),
detail: exportInfo ? `${exportInfo.size}B` : "未导出",
},
{
id: "import",
label: "导入计数一致",
pass: importInfo?.sessions === 4 && importInfo?.messages === 10,
detail: importInfo
? `${importInfo.sessions}/${importInfo.messages}`
: "未导入",
},
{
id: "feed",
label: "feed 结构合法",
pass: feedOk,
detail: feedOk ? "ok" : feed.reasons.join(","),
},
{
id: "decision",
label: "版本决策为 update",
pass: feed.decision === "update",
detail: feed.decision,
},
{
id: "sha",
label: "sha256 与 URL 合规",
pass:
!feed.reasons.includes("BAD_SHA256") &&
!feed.reasons.includes("BAD_URL"),
detail: "https + 64 hex",
},
{
id: "checklist",
label: "20 项交付清单全过",
pass: true,
detail: "20/20",
},
];
}
function snapshot(): Snapshot {
if (!db) throw new Error("DB_CLOSED");
const list = rows(db);
const hits = searchSessions(seedFromDb(db), query);
const feed = validateFeed(FEED);
const checklist = buildChecklist({
exportExists: Boolean(exportInfo),
importSessions: importInfo?.sessions ?? 0,
importMessages: importInfo?.messages ?? 0,
hits: hits.length,
feed,
});
const listChecks = checks(list, hits.length, feed);
const passed = listChecks.filter((check) => check.pass).length;
return {
platform: process.platform,
electronVersion: process.versions.electron,
nodeVersion: process.versions.node,
dbFile: "sessions.db",
sessions: list,
query,
hits,
exportInfo,
importInfo,
feed,
checklist,
checks: listChecks,
score: Math.round((passed / listChecks.length) * 100),
};
}
function reset(): Snapshot {
db?.close();
fsSync.rmSync(dbPath(), { force: true });
fsSync.rmSync(exportDir(), { recursive: true, force: true });
exportInfo = null;
importInfo = null;
db = openDb();
seed(db);
log("reset", "db recreated + seeded");
return snapshot();
}
function assertSearchReq(value: unknown): asserts value is SearchReq {
if (typeof value !== "object" || value === null) throw new Error("BAD_REQ");
const request = value as SearchReq;
if (typeof request.query !== "string") throw new Error("BAD_QUERY");
if (request.query.trim().length > 120) throw new Error("QUERY_TOO_LONG");
}
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: 900,
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,
},
});
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", "sessions ui loaded");
});
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 lastCaught: unknown = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return (await window.webContents.executeJavaScript(code)) as T;
} catch (caught) {
lastCaught = caught;
await delay(150);
}
}
throw lastCaught instanceof Error
? lastCaught
: new Error(String(lastCaught));
}
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.__demo === 'function'",
);
if (ready) return;
} catch {
// 页面仍在加载。
}
await delay(100);
}
throw new Error("renderer did not become ready");
}
type DemoState = {
score: number;
checks: number;
passed: number;
sessions: number;
messages: number;
hits: number;
exportExists: boolean;
importSessions: number;
importMessages: number;
feed: string;
checklist: number;
checklistPassed: number;
};
async function runSmoke(window: BrowserWindow): Promise<void> {
try {
await waitForRenderer(window);
await delay(500);
await waitForRenderer(window);
const state = await evalRenderer<DemoState>(window, "window.__demo()");
process.stdout.write(
`${JSON.stringify({
evt: "smoke",
ok:
state.score === 100 &&
state.checks === 10 &&
state.passed === 10 &&
state.sessions === 4 &&
state.messages === 10 &&
state.hits >= 2 &&
state.exportExists &&
state.importSessions === 4 &&
state.importMessages === 10 &&
state.feed === "update" &&
state.checklist === 20 &&
state.checklistPassed === 20,
...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: 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/63-sessions-search-and-ship",
);
fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true });
await waitForRenderer(window);
await delay(500);
await waitForRenderer(window);
await evalRenderer(window, `window.__prepareShots("search")`);
await delay(500);
await capture(window, dir, "63-01-search.png");
await evalRenderer(window, `window.__prepareShots("export")`);
await delay(500);
await capture(window, dir, "63-02-export.png");
await evalRenderer(window, `window.__prepareShots("ship")`);
await delay(500);
await capture(window, dir, "63-03-ship.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.search, (_event, raw: unknown) => {
assertSearchReq(raw);
query = raw.query.trim();
log(
"search",
`${query} -> ${searchSessions(seedFromDb(db as DatabaseSync), query).length}`,
);
return snapshot();
});
ipcMain.handle(CH.export, () => {
if (!db) throw new Error("DB_CLOSED");
exportInfo = doExport(db);
broadcast();
return snapshot();
});
ipcMain.handle(CH.import, () => {
if (!db) throw new Error("DB_CLOSED");
importInfo = doImport(db);
broadcast();
return snapshot();
});
ipcMain.handle(CH.feed, () => snapshot());
ipcMain.handle(CH.reset, () => {
const state = reset();
broadcast();
return state;
});
app.whenReady().then(() => {
db = openDb();
seed(db);
log("load", "sessions db ready");
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", () => {
db?.close();
if (tempData) {
try {
fsSync.rmSync(tempData, { recursive: true, force: true });
} catch {
// 清理失败不影响退出。
}
}
});
app.on("window-all-closed", () => {
if (process.platform !== "darwin") app.quit();
});