ipc.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import { execFile } from "node:child_process"
  2. import { stat, readFile, writeFile, rename, rm } from "node:fs/promises"
  3. import { createWriteStream } from "node:fs"
  4. import { Readable } from "node:stream"
  5. import { pipeline } from "node:stream/promises"
  6. import { basename } from "node:path"
  7. import { app, BrowserWindow, clipboard, dialog, ipcMain, shell, safeStorage } from "electron"
  8. import type { IpcMainEvent, IpcMainInvokeEvent } from "electron"
  9. import type { DesktopMenuAction } from "@opencode-ai/app/desktop-menu"
  10. import type { FatalRendererError, ServerReadyData, TitlebarTheme } from "../preload/types"
  11. import { runDesktopMenuAction } from "./desktop-menu-actions"
  12. import { setForceFocus } from "./debug"
  13. import { assertAttachmentBudget, createPickedFileAuthorizations } from "./attachment-picker"
  14. import { getStore, removeStoreFileIfEmpty } from "./store"
  15. import {
  16. getPinchZoomEnabled,
  17. getWindowID,
  18. openExternalURL,
  19. openLocalFileURL,
  20. setPinchZoomEnabled,
  21. setTitlebar,
  22. updateTitlebar,
  23. } from "./windows"
  24. import type { UpdaterController } from "./updater-controller"
  25. import { createUpdaterSubscriptions } from "./updater-subscriptions"
  26. import { createPaasConnections } from "./paas"
  27. import { createPaasConnectionStorage } from "./paas-connection-storage"
  28. const pickerFilters = (ext?: string[]) => {
  29. if (!ext || ext.length === 0) return undefined
  30. return [{ name: "Files", extensions: ext }]
  31. }
  32. const pickedFiles = createPickedFileAuthorizations()
  33. type Deps = {
  34. killSidecar: () => Promise<void> | void
  35. relaunch: () => void
  36. awaitInitialization: () => Promise<ServerReadyData>
  37. consumeInitialDeepLinks: () => Promise<string[]> | string[]
  38. getDefaultServerUrl: () => Promise<string | null> | string | null
  39. setDefaultServerUrl: (url: string | null) => Promise<void> | void
  40. isFirstLaunchOnboardingPending: () => Promise<boolean> | boolean
  41. finishFirstLaunchOnboarding: (createDefaultProject: boolean) => Promise<string | null> | string | null
  42. isOldLayoutEligible: () => Promise<boolean> | boolean
  43. getDisplayBackend: () => Promise<string | null>
  44. setDisplayBackend: (backend: string | null) => Promise<void> | void
  45. checkAppExists: (appName: string) => Promise<boolean> | boolean
  46. resolveAppPath: (appName: string) => Promise<string | null>
  47. updater: UpdaterController
  48. showUpdater: () => Promise<void> | void
  49. setBackgroundColor: (color: string) => void
  50. exportDebugLogs: () => Promise<string>
  51. recordFatalRendererError: (error: FatalRendererError) => Promise<void> | void
  52. }
  53. export function registerIpcHandlers(deps: Deps) {
  54. const paas = createPaasConnections()
  55. const selections = new Map<number, Map<string, { path: string; connection: unknown }>>()
  56. const connectionStorage = createPaasConnectionStorage({
  57. secure: () =>
  58. safeStorage.isEncryptionAvailable() &&
  59. (process.platform !== "linux" || safeStorage.getSelectedStorageBackend() !== "basic_text"),
  60. read: () => getStore("lambda-scientist.connection").get("connection"),
  61. write: (value) => getStore("lambda-scientist.connection").set("connection", value),
  62. remove: () => getStore("lambda-scientist.connection").delete("connection"),
  63. encrypt: (value) => safeStorage.encryptString(value).toString("base64"),
  64. decrypt: (value) => safeStorage.decryptString(Buffer.from(value, "base64")),
  65. })
  66. const owners = new Set<number>()
  67. ipcMain.handle("paas-connect", async (event, input) => {
  68. const owner = event.sender.id
  69. if (!owners.has(owner)) {
  70. owners.add(owner)
  71. event.sender.once("destroyed", () => {
  72. paas.disconnect(owner)
  73. selections.delete(owner)
  74. owners.delete(owner)
  75. })
  76. }
  77. input ??= connectionStorage.load()
  78. const result = await paas.connect(owner, input)
  79. const remembered = input ? connectionStorage.save({ ...input, url: result.url }) : false
  80. return { ...result, remembered }
  81. })
  82. ipcMain.handle("paas-disconnect", (event, forget) => {
  83. paas.disconnect(event.sender.id)
  84. selections.delete(event.sender.id)
  85. if (forget === true) connectionStorage.clear()
  86. })
  87. ipcMain.handle("paas-select-files", async (event) => {
  88. const owner = event.sender.id
  89. const connection = paas.identity(owner)
  90. if (!connection) throw new Error("请先连接平台。")
  91. const selected = await dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], title: "选择研究材料" })
  92. if (selected.canceled) return []
  93. if (paas.identity(owner) !== connection) throw new Error("连接已改变,请重新选择材料。")
  94. const owned = selections.get(owner) || new Map<string, { path: string; connection: unknown }>()
  95. selections.set(owner, owned)
  96. return Promise.all(
  97. selected.filePaths.map(async (path) => {
  98. const size = (await stat(path)).size
  99. const selectionID = crypto.randomUUID()
  100. owned.set(selectionID, { path, connection })
  101. return { selectionID, name: basename(path), size }
  102. }),
  103. )
  104. })
  105. ipcMain.handle("paas-upload-files", async (event, input) => {
  106. const connection = paas.identity(event.sender.id)
  107. const selected = await dialog.showOpenDialog({ properties: ["openFile", "multiSelections"], title: "选择研究材料" })
  108. if (selected.canceled) return []
  109. const capabilities = await paas.request(event.sender.id, { action: "file-capabilities" }).catch(() => undefined)
  110. const advertised =
  111. capabilities && typeof capabilities === "object" && "direct_upload_max_bytes" in capabilities
  112. ? capabilities.direct_upload_max_bytes
  113. : undefined
  114. const limit = typeof advertised === "number" && advertised > 0 ? advertised : 256 * 1024 * 1024
  115. for (const path of selected.filePaths) {
  116. if ((await stat(path)).size > limit)
  117. throw new Error(`${basename(path)} 超过当前平台直接上传额度(${Math.floor(limit / 1024 / 1024)} MB)。`)
  118. }
  119. const files = []
  120. for (const path of selected.filePaths) {
  121. if (!connection || paas.identity(event.sender.id) !== connection)
  122. throw new Error("平台连接已改变,请重新选择材料。")
  123. const data = new Uint8Array(await readFile(path))
  124. if (paas.identity(event.sender.id) !== connection) throw new Error("平台连接已改变,请重新选择材料。")
  125. const file = await paas.request(event.sender.id, {
  126. action: "upload-file",
  127. agentID: input.agentID,
  128. threadID: input.threadID,
  129. name: basename(path),
  130. data,
  131. })
  132. files.push(file)
  133. }
  134. return files
  135. })
  136. ipcMain.handle("paas-request", async (event, input) => {
  137. if (input?.action === "export-report") {
  138. if (typeof input.text !== "string" || typeof input.name !== "string") throw new Error("报告内容无效。")
  139. const format: string = input.format ?? "md"
  140. if (!["md", "docx", "pdf"].includes(format)) throw new Error("不支持的报告格式。")
  141. const selected = await dialog.showSaveDialog({
  142. title: "导出研究报告",
  143. defaultPath: `${basename(input.name).replace(/\.(md|docx|pdf)$/i, "") || "研究报告"}.${format}`,
  144. filters: [
  145. { name: format === "docx" ? "Word 文档" : format === "pdf" ? "PDF 文档" : "Markdown", extensions: [format] },
  146. ],
  147. })
  148. if (selected.canceled || !selected.filePath) return { saved: false }
  149. const temporary = `${selected.filePath}.${crypto.randomUUID()}.export`
  150. try {
  151. const contents = await (async () => {
  152. if (format === "md") return input.text
  153. const { reportDOCX, reportHTML } = await import("./report-document")
  154. if (format === "docx") return reportDOCX(input.name, input.text)
  155. const preview = new BrowserWindow({
  156. show: false,
  157. webPreferences: {
  158. sandbox: true,
  159. contextIsolation: true,
  160. nodeIntegration: false,
  161. javascript: false,
  162. partition: `report-${crypto.randomUUID()}`,
  163. },
  164. })
  165. preview.webContents.setWindowOpenHandler(() => ({ action: "deny" }))
  166. preview.webContents.on("will-navigate", (event) => event.preventDefault())
  167. try {
  168. await preview.loadURL(
  169. `data:text/html;charset=utf-8,${encodeURIComponent(reportHTML(input.name, input.text))}`,
  170. )
  171. return await preview.webContents.printToPDF({
  172. pageSize: "A4",
  173. printBackground: true,
  174. margins: { top: 0.55, bottom: 0.55, left: 0.6, right: 0.6 },
  175. })
  176. } finally {
  177. preview.destroy()
  178. }
  179. })()
  180. await writeFile(temporary, contents, { flag: "wx" })
  181. await rename(temporary, selected.filePath)
  182. } finally {
  183. await rm(temporary, { force: true })
  184. }
  185. return { saved: true, name: basename(selected.filePath), path: selected.filePath }
  186. }
  187. if (input?.action === "upload-selected") {
  188. const selected = selections.get(event.sender.id)?.get(input.selectionID)
  189. if (!selected || paas.identity(event.sender.id) !== selected.connection)
  190. throw new Error("该材料的本地选择已失效,请重新选择文件。")
  191. const capabilities = await paas.request(event.sender.id, { action: "file-capabilities" }).catch(() => undefined)
  192. const advertised =
  193. capabilities && typeof capabilities === "object" && "direct_upload_max_bytes" in capabilities
  194. ? Number(capabilities.direct_upload_max_bytes)
  195. : 256 * 1024 * 1024
  196. const maximum = Number.isFinite(advertised) && advertised > 0 ? advertised : 256 * 1024 * 1024
  197. if ((await stat(selected.path)).size > maximum) throw new Error("该文件超过当前平台直接上传额度。")
  198. const data = new Uint8Array(await readFile(selected.path))
  199. if (paas.identity(event.sender.id) !== selected.connection) throw new Error("平台连接已改变,请重新选择材料。")
  200. input = { ...input, action: "upload-file", name: basename(selected.path), data }
  201. }
  202. if (input?.action === "download") {
  203. const connection = paas.identity(event.sender.id)
  204. const selected = await dialog.showSaveDialog({
  205. title: "保存研究成果",
  206. defaultPath: basename(input.name || "研究成果"),
  207. })
  208. if (selected.canceled || !selected.filePath) return { saved: false }
  209. if (!connection || paas.identity(event.sender.id) !== connection) throw new Error("平台连接已改变,请重新下载。")
  210. const response = await paas.request(event.sender.id, input)
  211. if (!(response instanceof Response) || !response.body) throw new Error("平台未返回文件。")
  212. const temporary = `${selected.filePath}.${crypto.randomUUID()}.download`
  213. try {
  214. await pipeline(
  215. Readable.fromWeb(response.body as import("node:stream/web").ReadableStream),
  216. createWriteStream(temporary, { flags: "wx" }),
  217. )
  218. await rename(temporary, selected.filePath)
  219. } finally {
  220. await rm(temporary, { force: true })
  221. }
  222. return { saved: true, name: basename(selected.filePath), path: selected.filePath }
  223. }
  224. return paas.request(
  225. event.sender.id,
  226. input,
  227. (progress) => {
  228. if (!event.sender.isDestroyed()) event.sender.send("paas-progress", progress)
  229. },
  230. (progress) => {
  231. if (!event.sender.isDestroyed()) event.sender.send("paas-upload-progress", progress)
  232. },
  233. )
  234. })
  235. const updaterSubscriptions = createUpdaterSubscriptions()
  236. app.once("will-quit", updaterSubscriptions.clear)
  237. ipcMain.handle("kill-sidecar", () => deps.killSidecar())
  238. ipcMain.handle("await-initialization", () => deps.awaitInitialization())
  239. ipcMain.handle("consume-initial-deep-links", () => deps.consumeInitialDeepLinks())
  240. ipcMain.handle("get-default-server-url", () => deps.getDefaultServerUrl())
  241. ipcMain.handle("set-default-server-url", (_event: IpcMainInvokeEvent, url: string | null) =>
  242. deps.setDefaultServerUrl(url),
  243. )
  244. ipcMain.handle("is-first-launch-onboarding-pending", () => deps.isFirstLaunchOnboardingPending())
  245. ipcMain.handle("finish-first-launch-onboarding", (_event: IpcMainInvokeEvent, createDefaultProject: boolean) =>
  246. deps.finishFirstLaunchOnboarding(createDefaultProject),
  247. )
  248. ipcMain.handle("is-old-layout-eligible", () => deps.isOldLayoutEligible())
  249. ipcMain.handle("get-display-backend", () => deps.getDisplayBackend())
  250. ipcMain.handle("set-display-backend", (_event: IpcMainInvokeEvent, backend: string | null) =>
  251. deps.setDisplayBackend(backend),
  252. )
  253. ipcMain.handle("check-app-exists", (_event: IpcMainInvokeEvent, appName: string) => deps.checkAppExists(appName))
  254. ipcMain.handle("resolve-app-path", (_event: IpcMainInvokeEvent, appName: string) => deps.resolveAppPath(appName))
  255. ipcMain.handle("updater-subscribe", (event) => {
  256. const id = event.sender.id
  257. updaterSubscriptions.set(
  258. id,
  259. deps.updater.subscribe((state) => {
  260. if (event.sender.isDestroyed()) return updaterSubscriptions.delete(id)
  261. event.sender.send("updater-state", state)
  262. }),
  263. )
  264. event.sender.once("destroyed", () => updaterSubscriptions.delete(id))
  265. })
  266. ipcMain.handle("updater-unsubscribe", (event) => updaterSubscriptions.delete(event.sender.id))
  267. ipcMain.handle("updater-check", () => deps.updater.check())
  268. ipcMain.handle("updater-install", () => deps.updater.install())
  269. ipcMain.handle("set-background-color", (_event: IpcMainInvokeEvent, color: string) => deps.setBackgroundColor(color))
  270. ipcMain.handle("export-debug-logs", () => deps.exportDebugLogs())
  271. ipcMain.handle("set-force-focus", (event: IpcMainInvokeEvent, enabled: boolean) =>
  272. setForceFocus(event.sender, enabled),
  273. )
  274. ipcMain.handle("record-fatal-renderer-error", (_event: IpcMainInvokeEvent, error: FatalRendererError) =>
  275. deps.recordFatalRendererError(error),
  276. )
  277. ipcMain.handle("store-get", (_event: IpcMainInvokeEvent, name: string, key: string) => {
  278. try {
  279. const store = getStore(name)
  280. const value = store.get(key)
  281. if (value === undefined || value === null) return null
  282. return typeof value === "string" ? value : JSON.stringify(value)
  283. } catch {
  284. return null
  285. }
  286. })
  287. ipcMain.handle("store-set", (_event: IpcMainInvokeEvent, name: string, key: string, value: string) => {
  288. getStore(name).set(key, value)
  289. })
  290. ipcMain.handle("store-delete", (_event: IpcMainInvokeEvent, name: string, key: string) => {
  291. getStore(name).delete(key)
  292. void removeStoreFileIfEmpty(name)
  293. })
  294. ipcMain.handle("store-clear", (_event: IpcMainInvokeEvent, name: string) => {
  295. getStore(name).clear()
  296. void removeStoreFileIfEmpty(name)
  297. })
  298. ipcMain.handle("store-keys", (_event: IpcMainInvokeEvent, name: string) => {
  299. const store = getStore(name)
  300. return Object.keys(store.store)
  301. })
  302. ipcMain.handle("store-length", (_event: IpcMainInvokeEvent, name: string) => {
  303. const store = getStore(name)
  304. return Object.keys(store.store).length
  305. })
  306. ipcMain.handle(
  307. "open-directory-picker",
  308. async (_event: IpcMainInvokeEvent, opts?: { multiple?: boolean; title?: string; defaultPath?: string }) => {
  309. const result = await dialog.showOpenDialog({
  310. properties: ["openDirectory", ...(opts?.multiple ? ["multiSelections" as const] : []), "createDirectory"],
  311. title: opts?.title ?? "Choose a folder",
  312. defaultPath: opts?.defaultPath,
  313. })
  314. if (result.canceled) return null
  315. return opts?.multiple ? result.filePaths : result.filePaths[0]
  316. },
  317. )
  318. ipcMain.handle(
  319. "open-file-picker",
  320. async (
  321. event: IpcMainInvokeEvent,
  322. opts?: { multiple?: boolean; title?: string; defaultPath?: string; extensions?: string[] },
  323. ) => {
  324. const result = await dialog.showOpenDialog({
  325. properties: ["openFile", ...(opts?.multiple ? ["multiSelections" as const] : [])],
  326. title: opts?.title ?? "Choose a file",
  327. defaultPath: opts?.defaultPath,
  328. filters: pickerFilters(opts?.extensions),
  329. })
  330. if (result.canceled) return null
  331. const files = await Promise.all(
  332. result.filePaths.map(async (filePath) => ({
  333. path: filePath,
  334. name: basename(filePath),
  335. size: (await stat(filePath)).size,
  336. })),
  337. )
  338. assertAttachmentBudget(files)
  339. const token = pickedFiles.add(event.sender.id, result.filePaths)
  340. return { token, files }
  341. },
  342. )
  343. ipcMain.handle("read-picked-file", async (event: IpcMainInvokeEvent, token: string, filePath: string) => {
  344. return pickedFiles.read(event.sender.id, token, filePath)
  345. })
  346. ipcMain.handle("release-picked-files", (event: IpcMainInvokeEvent, token: string) => {
  347. pickedFiles.release(event.sender.id, token)
  348. })
  349. ipcMain.handle(
  350. "save-file-picker",
  351. async (_event: IpcMainInvokeEvent, opts?: { title?: string; defaultPath?: string }) => {
  352. const result = await dialog.showSaveDialog({
  353. title: opts?.title ?? "Save file",
  354. defaultPath: opts?.defaultPath,
  355. })
  356. if (result.canceled) return null
  357. return result.filePath ?? null
  358. },
  359. )
  360. ipcMain.on("open-external", (_event: IpcMainEvent, url: string) => {
  361. openExternalURL(url)
  362. })
  363. ipcMain.on("open-local-file", (_event: IpcMainEvent, url: string) => {
  364. openLocalFileURL(url)
  365. })
  366. ipcMain.handle("open-path", async (_event: IpcMainInvokeEvent, path: string, app?: string) => {
  367. if (!app) return shell.openPath(path)
  368. await new Promise<void>((resolve, reject) => {
  369. const [cmd, args] =
  370. process.platform === "darwin" ? (["open", ["-a", app, path]] as const) : ([app, [path]] as const)
  371. execFile(cmd, args, (err) => (err ? reject(err) : resolve()))
  372. })
  373. })
  374. ipcMain.handle("reveal-path", async (_event: IpcMainInvokeEvent, path: string) => {
  375. const exists = await stat(path).then(
  376. () => true,
  377. () => false,
  378. )
  379. if (!exists) return false
  380. shell.showItemInFolder(path)
  381. return true
  382. })
  383. ipcMain.handle("read-clipboard-image", () => {
  384. const image = clipboard.readImage()
  385. if (image.isEmpty()) return null
  386. const buffer = image.toPNG().buffer
  387. const size = image.getSize()
  388. return { buffer, width: size.width, height: size.height }
  389. })
  390. ipcMain.handle("get-window-id", (event: IpcMainInvokeEvent) => {
  391. const win = BrowserWindow.fromWebContents(event.sender)
  392. if (!win) throw new Error("Window not found")
  393. const id = getWindowID(win)
  394. if (!id) throw new Error("Window ID not found")
  395. return id
  396. })
  397. ipcMain.handle("get-window-focused", (event: IpcMainInvokeEvent) => {
  398. const win = BrowserWindow.fromWebContents(event.sender)
  399. return win?.isFocused() ?? false
  400. })
  401. ipcMain.handle("get-window-fullscreen", (event: IpcMainInvokeEvent) => {
  402. const win = BrowserWindow.fromWebContents(event.sender)
  403. return win?.isFullScreen() ?? false
  404. })
  405. ipcMain.handle("set-window-focus", (event: IpcMainInvokeEvent) => {
  406. const win = BrowserWindow.fromWebContents(event.sender)
  407. win?.focus()
  408. })
  409. ipcMain.handle("show-window", (event: IpcMainInvokeEvent) => {
  410. const win = BrowserWindow.fromWebContents(event.sender)
  411. win?.show()
  412. })
  413. ipcMain.on("relaunch", () => {
  414. deps.relaunch()
  415. })
  416. ipcMain.handle("get-zoom-factor", (event: IpcMainInvokeEvent) => event.sender.getZoomFactor())
  417. ipcMain.handle("set-zoom-factor", (event: IpcMainInvokeEvent, factor: number) => {
  418. event.sender.setZoomFactor(factor)
  419. const win = BrowserWindow.fromWebContents(event.sender)
  420. if (!win) return
  421. updateTitlebar(win)
  422. })
  423. ipcMain.handle("get-pinch-zoom-enabled", () => getPinchZoomEnabled())
  424. ipcMain.handle("set-pinch-zoom-enabled", (_event: IpcMainInvokeEvent, enabled: boolean) => {
  425. setPinchZoomEnabled(enabled)
  426. })
  427. ipcMain.handle("set-titlebar", (event: IpcMainInvokeEvent, theme: TitlebarTheme) => {
  428. const win = BrowserWindow.fromWebContents(event.sender)
  429. if (!win) return
  430. setTitlebar(win, theme)
  431. })
  432. ipcMain.handle("run-desktop-menu-action", (event: IpcMainInvokeEvent, action: DesktopMenuAction) => {
  433. runDesktopMenuAction(BrowserWindow.fromWebContents(event.sender), action, {
  434. checkForUpdates: () => void deps.showUpdater(),
  435. relaunch: deps.relaunch,
  436. })
  437. })
  438. }
  439. export function sendMenuCommand(win: BrowserWindow, id: string) {
  440. win.webContents.send("menu-command", id)
  441. }
  442. export function sendDeepLinks(win: BrowserWindow, urls: string[]) {
  443. win.webContents.send("deep-link", urls)
  444. }