import { app, BrowserWindow, ipcMain } from "electron"; import fsSync from "node:fs"; import os from "node:os"; import path from "node:path"; import { CH, type SendReq } from "../shared/ipc"; import { streamAssistant, type ChatMessage, type ChatSnapshot, type RunSummary, } from "../shared/chat"; app.setName("Chat Stream 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(), `chat61-${process.pid}`) : ""; if (tempData) app.setPath("userData", tempData); let win: BrowserWindow | null = null; let messages: ChatMessage[] = []; let runs: RunSummary[] = []; let running = false; let controller: AbortController | null = null; let lastPrompt = ""; let seq = 0; function log(kind: string, detail: string): void { process.stdout.write( `${JSON.stringify({ evt: "chat", kind, detail, at: Date.now() })}\n`, ); } function broadcast(): void { if (win && !win.isDestroyed()) { win.webContents.send("chat:changed", { at: Date.now() }); } } function snapshot(): ChatSnapshot { return { platform: process.platform, electronVersion: process.versions.electron, nodeVersion: process.versions.node, messages: messages.map((message) => ({ ...message, tool: message.tool ? { ...message.tool } : null, diff: message.diff ? { path: message.diff.path, lines: message.diff.lines.map((line) => ({ ...line })), } : null, })), running, lastRun: runs.at(-1) ? { ...(runs.at(-1) as RunSummary) } : null, runs: runs.map((run) => ({ ...run })), draft: lastPrompt, }; } function assertSendReq(value: unknown): asserts value is SendReq { if (typeof value !== "object" || value === null) throw new Error("BAD_REQ"); const request = value as SendReq; if (typeof request.text !== "string") throw new Error("BAD_TEXT"); const text = request.text.trim(); if (!request.retry && (text.length === 0 || text.length > 400)) { throw new Error("BAD_TEXT_LENGTH"); } if (request.retry !== undefined && typeof request.retry !== "boolean") { throw new Error("BAD_RETRY"); } if (request.paceMs !== undefined) { if ( typeof request.paceMs !== "number" || !Number.isFinite(request.paceMs) || request.paceMs < 4 || request.paceMs > 300 ) { throw new Error("BAD_PACE"); } } } function findAssistant(id: string): ChatMessage | undefined { return messages.find((message) => message.id === id); } function updateAssistant(id: string, patch: Partial): void { messages = messages.map((message) => message.id === id ? { ...message, ...patch } : message, ); broadcast(); } async function send(request: SendReq): Promise { if (running) throw new Error("RUN_IN_PROGRESS"); const text = (request.retry ? lastPrompt : request.text).trim(); if (!request.retry) lastPrompt = text; const attempt = request.retry ? (runs.filter((run) => run.prompt === text).length || 0) + 1 : 1; seq += 1; const assistantId = `m-${Date.now().toString(36)}-${seq}`; if (!request.retry) { seq += 1; messages = [ ...messages, { id: `m-${Date.now().toString(36)}-${seq}`, role: "user", text, streaming: false, attempt, tool: null, diff: null, error: null, at: Date.now(), }, ]; } messages = [ ...messages, { id: assistantId, role: "assistant", text: "", streaming: true, attempt, tool: null, diff: null, error: null, at: Date.now(), }, ]; running = true; controller = new AbortController(); broadcast(); log("start", `attempt=${attempt}`); const summary = await streamAssistant({ prompt: text, attempt, paceMs: request.paceMs ?? 24, signal: controller.signal, handlers: { onDelta: (chunk) => { const current = findAssistant(assistantId); if (!current) return; updateAssistant(assistantId, { text: current.text + chunk }); }, onTool: (tool) => { updateAssistant(assistantId, { tool }); }, onDiff: (diff) => { updateAssistant(assistantId, { diff }); }, onToolResult: (result) => { const current = findAssistant(assistantId); if (!current?.tool) return; updateAssistant(assistantId, { tool: { ...current.tool, status: "ok", result }, }); }, }, }); updateAssistant(assistantId, { streaming: false, error: summary.cancelled ? "STOPPED_BY_USER" : summary.error, }); runs = [...runs, summary].slice(-20); running = false; controller = null; broadcast(); log( "finish", `done=${summary.done} cancelled=${summary.cancelled} deltas=${summary.deltas}`, ); return summary; } 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", "chat 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 { return new Promise((resolve) => setTimeout(resolve, ms)); } async function evalRenderer( window: BrowserWindow, code: string, ): Promise { 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 { 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"); } type DemoState = { score: number; checks: number; passed: number; messages: number; assistantChars: number; deltas: number; toolCalls: number; diffLines: number; done: boolean; cancelled: boolean; retryAttempt: number; imeGuard: boolean; streaming: boolean; }; async function runSmoke(window: BrowserWindow): Promise { try { await waitForRenderer(window); await delay(500); 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.messages >= 4 && state.deltas >= 5 && state.toolCalls === 1 && state.diffLines === 4 && state.done && state.cancelled && state.retryAttempt >= 2 && state.imeGuard && !state.streaming, ...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 { 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 { try { const dir = path.resolve( process.cwd(), "../../../docs/assets/images/61-chat-ui-streaming", ); fsSync.mkdirSync(path.join(dir, "raw"), { recursive: true }); await waitForRenderer(window); await delay(500); await waitForRenderer(window); await evalRenderer(window, `window.__prepareShots("stream")`); await delay(700); await capture(window, dir, "61-01-stream.png"); await evalRenderer(window, `window.__prepareShots("tool")`); await delay(1800); await capture(window, dir, "61-02-tool-diff.png"); await evalRenderer(window, `window.__prepareShots("retry")`); await delay(900); await capture(window, dir, "61-03-retry.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.send, async (_event, raw: unknown) => { assertSendReq(raw); const summary = await send(raw); return { summary, snapshot: snapshot() }; }); ipcMain.handle(CH.stop, () => { controller?.abort(); log("stop", "abort requested"); return { ok: true }; }); ipcMain.handle(CH.reset, () => { controller?.abort(); messages = []; runs = []; running = false; controller = null; lastPrompt = ""; seq = 0; broadcast(); return snapshot(); }); app.whenReady().then(() => { log("load", "chat runtime 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", () => { if (tempData) { try { fsSync.rmSync(tempData, { recursive: true, force: true }); } catch { // 清理失败不影响退出。 } } }); app.on("window-all-closed", () => { if (process.platform !== "darwin") app.quit(); });