| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469 |
- import { execFile } from "node:child_process"
- import { stat, readFile, writeFile, rename, rm } from "node:fs/promises"
- import { createWriteStream } from "node:fs"
- import { Readable } from "node:stream"
- import { pipeline } from "node:stream/promises"
- import { basename } from "node:path"
- import { app, BrowserWindow, clipboard, dialog, ipcMain, shell, safeStorage } from "electron"
- import type { IpcMainEvent, IpcMainInvokeEvent } from "electron"
- import type { DesktopMenuAction } from "@opencode-ai/app/desktop-menu"
- import type { FatalRendererError, ServerReadyData, TitlebarTheme } from "../preload/types"
- import { runDesktopMenuAction } from "./desktop-menu-actions"
- import { setForceFocus } from "./debug"
- import { assertAttachmentBudget, createPickedFileAuthorizations } from "./attachment-picker"
- import { getStore, removeStoreFileIfEmpty } from "./store"
- import {
- getPinchZoomEnabled,
- getWindowID,
- openExternalURL,
- openLocalFileURL,
- setPinchZoomEnabled,
- setTitlebar,
- updateTitlebar,
- } from "./windows"
- import type { UpdaterController } from "./updater-controller"
- import { createUpdaterSubscriptions } from "./updater-subscriptions"
- import { createPaasConnections } from "./paas"
- import { createPaasConnectionStorage } from "./paas-connection-storage"
- const pickerFilters = (ext?: string[]) => {
- if (!ext || ext.length === 0) return undefined
- return [{ name: "Files", extensions: ext }]
- }
- const pickedFiles = createPickedFileAuthorizations()
- type Deps = {
- killSidecar: () => Promise<void> | void
- relaunch: () => void
- awaitInitialization: () => Promise<ServerReadyData>
- consumeInitialDeepLinks: () => Promise<string[]> | string[]
- getDefaultServerUrl: () => Promise<string | null> | string | null
- setDefaultServerUrl: (url: string | null) => Promise<void> | void
- isFirstLaunchOnboardingPending: () => Promise<boolean> | boolean
- finishFirstLaunchOnboarding: (createDefaultProject: boolean) => Promise<string | null> | string | null
- isOldLayoutEligible: () => Promise<boolean> | boolean
- getDisplayBackend: () => Promise<string | null>
- setDisplayBackend: (backend: string | null) => Promise<void> | void
- checkAppExists: (appName: string) => Promise<boolean> | boolean
- resolveAppPath: (appName: string) => Promise<string | null>
- updater: UpdaterController
- showUpdater: () => Promise<void> | void
- setBackgroundColor: (color: string) => void
- exportDebugLogs: () => Promise<string>
- recordFatalRendererError: (error: FatalRendererError) => Promise<void> | void
- }
- export function registerIpcHandlers(deps: Deps) {
- const paas = createPaasConnections()
- const selections = new Map<number, Map<string, { path: string; connection: unknown }>>()
- const connectionStorage = createPaasConnectionStorage({
- secure: () =>
- safeStorage.isEncryptionAvailable() &&
- (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"),
- read: () => getStore("lambda-scientist.connection").get("connection"),
- write: (value) => getStore("lambda-scientist.connection").set("connection", value),
- remove: () => getStore("lambda-scientist.connection").delete("connection"),
- encrypt: (value) => safeStorage.encryptString(value).toString("base64"),
- decrypt: (value) => safeStorage.decryptString(Buffer.from(value, "base64")),
- })
- const owners = new Set<number>()
- ipcMain.handle("paas-connect", async (event, input) => {
- const owner = event.sender.id
- if (!owners.has(owner)) {
- owners.add(owner)
- event.sender.once("destroyed", () => {
- paas.disconnect(owner)
- selections.delete(owner)
- owners.delete(owner)
- })
- }
- input ??= connectionStorage.load()
- const result = await paas.connect(owner, input)
- const remembered = input ? connectionStorage.save({ ...input, url: result.url }) : false
- return { ...result, remembered }
- })
- ipcMain.handle("paas-disconnect", (event, forget) => {
- paas.disconnect(event.sender.id)
- selections.delete(event.sender.id)
- if (forget === true) connectionStorage.clear()
- })
- ipcMain.handle("paas-select-files", async (event) => {
- const owner = event.sender.id
- const connection = paas.identity(owner)
- if (!connection) throw new Error("请先连接平台。")
- const selected = await dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], title: "选择研究材料" })
- if (selected.canceled) return []
- if (paas.identity(owner) !== connection) throw new Error("连接已改变,请重新选择材料。")
- const owned = selections.get(owner) || new Map<string, { path: string; connection: unknown }>()
- selections.set(owner, owned)
- return Promise.all(
- selected.filePaths.map(async (path) => {
- const size = (await stat(path)).size
- const selectionID = crypto.randomUUID()
- owned.set(selectionID, { path, connection })
- return { selectionID, name: basename(path), size }
- }),
- )
- })
- ipcMain.handle("paas-upload-files", async (event, input) => {
- const connection = paas.identity(event.sender.id)
- const selected = await dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], title: "选择研究材料" })
- if (selected.canceled) return []
- const capabilities = await paas.request(event.sender.id, { action: "file-capabilities" }).catch(() => undefined)
- const advertised =
- capabilities && typeof capabilities === "object" && "direct_upload_max_bytes" in capabilities
- ? capabilities.direct_upload_max_bytes
- : undefined
- const limit = typeof advertised === "number" && advertised > 0 ? advertised : 256 * 1024 * 1024
- for (const path of selected.filePaths) {
- if ((await stat(path)).size > limit)
- throw new Error(`${basename(path)} 超过当前平台直接上传额度(${Math.floor(limit / 1024 / 1024)} MB)。`)
- }
- const files = []
- for (const path of selected.filePaths) {
- if (!connection || paas.identity(event.sender.id) !== connection)
- throw new Error("平台连接已改变,请重新选择材料。")
- const data = new Uint8Array(await readFile(path))
- if (paas.identity(event.sender.id) !== connection) throw new Error("平台连接已改变,请重新选择材料。")
- const file = await paas.request(event.sender.id, {
- action: "upload-file",
- agentID: input.agentID,
- threadID: input.threadID,
- name: basename(path),
- data,
- })
- files.push(file)
- }
- return files
- })
- ipcMain.handle("paas-request", async (event, input) => {
- if (input?.action === "export-report") {
- if (typeof input.text !== "string" || typeof input.name !== "string") throw new Error("报告内容无效。")
- const format: string = input.format ?? "md"
- if (!["md", "docx", "pdf"].includes(format)) throw new Error("不支持的报告格式。")
- const selected = await dialog.showSaveDialog({
- title: "导出研究报告",
- defaultPath: `${basename(input.name).replace(/\.(md|docx|pdf)$/i, "") || "研究报告"}.${format}`,
- filters: [
- { name: format === "docx" ? "Word 文档" : format === "pdf" ? "PDF 文档" : "Markdown", extensions: [format] },
- ],
- })
- if (selected.canceled || !selected.filePath) return { saved: false }
- const temporary = `${selected.filePath}.${crypto.randomUUID()}.export`
- try {
- const contents = await (async () => {
- if (format === "md") return input.text
- const { reportDOCX, reportHTML } = await import("./report-document")
- if (format === "docx") return reportDOCX(input.name, input.text)
- const preview = new BrowserWindow({
- show: false,
- webPreferences: {
- sandbox: true,
- contextIsolation: true,
- nodeIntegration: false,
- javascript: false,
- partition: `report-${crypto.randomUUID()}`,
- },
- })
- preview.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
- preview.webContents.on("will-navigate", (event) => event.preventDefault())
- try {
- await preview.loadURL(
- `data:text/html;charset=utf-8,${encodeURIComponent(reportHTML(input.name, input.text))}`,
- )
- return await preview.webContents.printToPDF({
- pageSize: "A4",
- printBackground: true,
- margins: { top: 0.55, bottom: 0.55, left: 0.6, right: 0.6 },
- })
- } finally {
- preview.destroy()
- }
- })()
- await writeFile(temporary, contents, { flag: "wx" })
- await rename(temporary, selected.filePath)
- } finally {
- await rm(temporary, { force: true })
- }
- return { saved: true, name: basename(selected.filePath), path: selected.filePath }
- }
- if (input?.action === "upload-selected") {
- const selected = selections.get(event.sender.id)?.get(input.selectionID)
- if (!selected || paas.identity(event.sender.id) !== selected.connection)
- throw new Error("该材料的本地选择已失效,请重新选择文件。")
- const capabilities = await paas.request(event.sender.id, { action: "file-capabilities" }).catch(() => undefined)
- const advertised =
- capabilities && typeof capabilities === "object" && "direct_upload_max_bytes" in capabilities
- ? Number(capabilities.direct_upload_max_bytes)
- : 256 * 1024 * 1024
- const maximum = Number.isFinite(advertised) && advertised > 0 ? advertised : 256 * 1024 * 1024
- if ((await stat(selected.path)).size > maximum) throw new Error("该文件超过当前平台直接上传额度。")
- const data = new Uint8Array(await readFile(selected.path))
- if (paas.identity(event.sender.id) !== selected.connection) throw new Error("平台连接已改变,请重新选择材料。")
- input = { ...input, action: "upload-file", name: basename(selected.path), data }
- }
- if (input?.action === "download") {
- const connection = paas.identity(event.sender.id)
- const selected = await dialog.showSaveDialog({
- title: "保存研究成果",
- defaultPath: basename(input.name || "研究成果"),
- })
- if (selected.canceled || !selected.filePath) return { saved: false }
- if (!connection || paas.identity(event.sender.id) !== connection) throw new Error("平台连接已改变,请重新下载。")
- const response = await paas.request(event.sender.id, input)
- if (!(response instanceof Response) || !response.body) throw new Error("平台未返回文件。")
- const temporary = `${selected.filePath}.${crypto.randomUUID()}.download`
- try {
- await pipeline(
- Readable.fromWeb(response.body as import("node:stream/web").ReadableStream),
- createWriteStream(temporary, { flags: "wx" }),
- )
- await rename(temporary, selected.filePath)
- } finally {
- await rm(temporary, { force: true })
- }
- return { saved: true, name: basename(selected.filePath), path: selected.filePath }
- }
- return paas.request(
- event.sender.id,
- input,
- (progress) => {
- if (!event.sender.isDestroyed()) event.sender.send("paas-progress", progress)
- },
- (progress) => {
- if (!event.sender.isDestroyed()) event.sender.send("paas-upload-progress", progress)
- },
- )
- })
- const updaterSubscriptions = createUpdaterSubscriptions()
- app.once("will-quit", updaterSubscriptions.clear)
- ipcMain.handle("kill-sidecar", () => deps.killSidecar())
- ipcMain.handle("await-initialization", () => deps.awaitInitialization())
- ipcMain.handle("consume-initial-deep-links", () => deps.consumeInitialDeepLinks())
- ipcMain.handle("get-default-server-url", () => deps.getDefaultServerUrl())
- ipcMain.handle("set-default-server-url", (_event: IpcMainInvokeEvent, url: string | null) =>
- deps.setDefaultServerUrl(url),
- )
- ipcMain.handle("is-first-launch-onboarding-pending", () => deps.isFirstLaunchOnboardingPending())
- ipcMain.handle("finish-first-launch-onboarding", (_event: IpcMainInvokeEvent, createDefaultProject: boolean) =>
- deps.finishFirstLaunchOnboarding(createDefaultProject),
- )
- ipcMain.handle("is-old-layout-eligible", () => deps.isOldLayoutEligible())
- ipcMain.handle("get-display-backend", () => deps.getDisplayBackend())
- ipcMain.handle("set-display-backend", (_event: IpcMainInvokeEvent, backend: string | null) =>
- deps.setDisplayBackend(backend),
- )
- ipcMain.handle("check-app-exists", (_event: IpcMainInvokeEvent, appName: string) => deps.checkAppExists(appName))
- ipcMain.handle("resolve-app-path", (_event: IpcMainInvokeEvent, appName: string) => deps.resolveAppPath(appName))
- ipcMain.handle("updater-subscribe", (event) => {
- const id = event.sender.id
- updaterSubscriptions.set(
- id,
- deps.updater.subscribe((state) => {
- if (event.sender.isDestroyed()) return updaterSubscriptions.delete(id)
- event.sender.send("updater-state", state)
- }),
- )
- event.sender.once("destroyed", () => updaterSubscriptions.delete(id))
- })
- ipcMain.handle("updater-unsubscribe", (event) => updaterSubscriptions.delete(event.sender.id))
- ipcMain.handle("updater-check", () => deps.updater.check())
- ipcMain.handle("updater-install", () => deps.updater.install())
- ipcMain.handle("set-background-color", (_event: IpcMainInvokeEvent, color: string) => deps.setBackgroundColor(color))
- ipcMain.handle("export-debug-logs", () => deps.exportDebugLogs())
- ipcMain.handle("set-force-focus", (event: IpcMainInvokeEvent, enabled: boolean) =>
- setForceFocus(event.sender, enabled),
- )
- ipcMain.handle("record-fatal-renderer-error", (_event: IpcMainInvokeEvent, error: FatalRendererError) =>
- deps.recordFatalRendererError(error),
- )
- ipcMain.handle("store-get", (_event: IpcMainInvokeEvent, name: string, key: string) => {
- try {
- const store = getStore(name)
- const value = store.get(key)
- if (value === undefined || value === null) return null
- return typeof value === "string" ? value : JSON.stringify(value)
- } catch {
- return null
- }
- })
- ipcMain.handle("store-set", (_event: IpcMainInvokeEvent, name: string, key: string, value: string) => {
- getStore(name).set(key, value)
- })
- ipcMain.handle("store-delete", (_event: IpcMainInvokeEvent, name: string, key: string) => {
- getStore(name).delete(key)
- void removeStoreFileIfEmpty(name)
- })
- ipcMain.handle("store-clear", (_event: IpcMainInvokeEvent, name: string) => {
- getStore(name).clear()
- void removeStoreFileIfEmpty(name)
- })
- ipcMain.handle("store-keys", (_event: IpcMainInvokeEvent, name: string) => {
- const store = getStore(name)
- return Object.keys(store.store)
- })
- ipcMain.handle("store-length", (_event: IpcMainInvokeEvent, name: string) => {
- const store = getStore(name)
- return Object.keys(store.store).length
- })
- ipcMain.handle(
- "open-directory-picker",
- async (_event: IpcMainInvokeEvent, opts?: { multiple?: boolean; title?: string; defaultPath?: string }) => {
- const result = await dialog.showOpenDialog({
- properties: ["openDirectory", ...(opts?.multiple ? ["multiSelections" as const] : []), "createDirectory"],
- title: opts?.title ?? "Choose a folder",
- defaultPath: opts?.defaultPath,
- })
- if (result.canceled) return null
- return opts?.multiple ? result.filePaths : result.filePaths[0]
- },
- )
- ipcMain.handle(
- "open-file-picker",
- async (
- event: IpcMainInvokeEvent,
- opts?: { multiple?: boolean; title?: string; defaultPath?: string; extensions?: string[] },
- ) => {
- const result = await dialog.showOpenDialog({
- properties: ["openFile", ...(opts?.multiple ? ["multiSelections" as const] : [])],
- title: opts?.title ?? "Choose a file",
- defaultPath: opts?.defaultPath,
- filters: pickerFilters(opts?.extensions),
- })
- if (result.canceled) return null
- const files = await Promise.all(
- result.filePaths.map(async (filePath) => ({
- path: filePath,
- name: basename(filePath),
- size: (await stat(filePath)).size,
- })),
- )
- assertAttachmentBudget(files)
- const token = pickedFiles.add(event.sender.id, result.filePaths)
- return { token, files }
- },
- )
- ipcMain.handle("read-picked-file", async (event: IpcMainInvokeEvent, token: string, filePath: string) => {
- return pickedFiles.read(event.sender.id, token, filePath)
- })
- ipcMain.handle("release-picked-files", (event: IpcMainInvokeEvent, token: string) => {
- pickedFiles.release(event.sender.id, token)
- })
- ipcMain.handle(
- "save-file-picker",
- async (_event: IpcMainInvokeEvent, opts?: { title?: string; defaultPath?: string }) => {
- const result = await dialog.showSaveDialog({
- title: opts?.title ?? "Save file",
- defaultPath: opts?.defaultPath,
- })
- if (result.canceled) return null
- return result.filePath ?? null
- },
- )
- ipcMain.on("open-external", (_event: IpcMainEvent, url: string) => {
- openExternalURL(url)
- })
- ipcMain.on("open-local-file", (_event: IpcMainEvent, url: string) => {
- openLocalFileURL(url)
- })
- ipcMain.handle("open-path", async (_event: IpcMainInvokeEvent, path: string, app?: string) => {
- if (!app) return shell.openPath(path)
- await new Promise<void>((resolve, reject) => {
- const [cmd, args] =
- process.platform === "darwin" ? (["open", ["-a", app, path]] as const) : ([app, [path]] as const)
- execFile(cmd, args, (err) => (err ? reject(err) : resolve()))
- })
- })
- ipcMain.handle("reveal-path", async (_event: IpcMainInvokeEvent, path: string) => {
- const exists = await stat(path).then(
- () => true,
- () => false,
- )
- if (!exists) return false
- shell.showItemInFolder(path)
- return true
- })
- ipcMain.handle("read-clipboard-image", () => {
- const image = clipboard.readImage()
- if (image.isEmpty()) return null
- const buffer = image.toPNG().buffer
- const size = image.getSize()
- return { buffer, width: size.width, height: size.height }
- })
- ipcMain.handle("get-window-id", (event: IpcMainInvokeEvent) => {
- const win = BrowserWindow.fromWebContents(event.sender)
- if (!win) throw new Error("Window not found")
- const id = getWindowID(win)
- if (!id) throw new Error("Window ID not found")
- return id
- })
- ipcMain.handle("get-window-focused", (event: IpcMainInvokeEvent) => {
- const win = BrowserWindow.fromWebContents(event.sender)
- return win?.isFocused() ?? false
- })
- ipcMain.handle("get-window-fullscreen", (event: IpcMainInvokeEvent) => {
- const win = BrowserWindow.fromWebContents(event.sender)
- return win?.isFullScreen() ?? false
- })
- ipcMain.handle("set-window-focus", (event: IpcMainInvokeEvent) => {
- const win = BrowserWindow.fromWebContents(event.sender)
- win?.focus()
- })
- ipcMain.handle("show-window", (event: IpcMainInvokeEvent) => {
- const win = BrowserWindow.fromWebContents(event.sender)
- win?.show()
- })
- ipcMain.on("relaunch", () => {
- deps.relaunch()
- })
- ipcMain.handle("get-zoom-factor", (event: IpcMainInvokeEvent) => event.sender.getZoomFactor())
- ipcMain.handle("set-zoom-factor", (event: IpcMainInvokeEvent, factor: number) => {
- event.sender.setZoomFactor(factor)
- const win = BrowserWindow.fromWebContents(event.sender)
- if (!win) return
- updateTitlebar(win)
- })
- ipcMain.handle("get-pinch-zoom-enabled", () => getPinchZoomEnabled())
- ipcMain.handle("set-pinch-zoom-enabled", (_event: IpcMainInvokeEvent, enabled: boolean) => {
- setPinchZoomEnabled(enabled)
- })
- ipcMain.handle("set-titlebar", (event: IpcMainInvokeEvent, theme: TitlebarTheme) => {
- const win = BrowserWindow.fromWebContents(event.sender)
- if (!win) return
- setTitlebar(win, theme)
- })
- ipcMain.handle("run-desktop-menu-action", (event: IpcMainInvokeEvent, action: DesktopMenuAction) => {
- runDesktopMenuAction(BrowserWindow.fromWebContents(event.sender), action, {
- checkForUpdates: () => void deps.showUpdater(),
- relaunch: deps.relaunch,
- })
- })
- }
- export function sendMenuCommand(win: BrowserWindow, id: string) {
- win.webContents.send("menu-command", id)
- }
- export function sendDeepLinks(win: BrowserWindow, urls: string[]) {
- win.webContents.send("deep-link", urls)
- }
|