diff --git a/web/electron/main.cjs b/web/electron/main.cjs index 64a1021..a934bc9 100644 --- a/web/electron/main.cjs +++ b/web/electron/main.cjs @@ -2,9 +2,10 @@ * AgentMail Electron 主进程。 * * 职责: - * - 创建 BrowserWindow 加载前端(dev=http://localhost:5173,prod=../dist/index.html) - * - 系统托盘(Phase 4 完整实现,这里先预留) - * - SSE 长连接由主进程维持(Phase 2),这里先只做窗口生命周期 + * - 创建 BrowserWindow 加载前端(dev=<ELECTRON_START_URL>,prod=../dist/index.html) + * - 系统托盘(Phase 4 完整实现) + * - 离线缓存(Phase 4) + * - 把 Gateway 地址与用户密钥注入渲染进程(Phase 2:让 web/src 以独立客户端身份连任意 Gateway) * * 设计约束: * - 渲染进程复用 web/src 的 React 代码,零改动 @@ -18,11 +19,21 @@ const path = require('node:path'); const DEV_URL = process.env.ELECTRON_START_URL || 'http://localhost:5173'; const isDev = !!process.env.ELECTRON_START_URL || !app.isPackaged; +// Gateway 地址与用户密钥:环境变量注入(桌面客户端用 user_key 认证) +const GATEWAY_URL = (process.env.AGENTMAIL_GATEWAY_URL || 'http://127.0.0.1:8180').replace(/\/+$/, ''); +const API_BASE = `${GATEWAY_URL}/api/v1`; +const TOKEN = process.env.AGENTMAIL_TOKEN || process.env.AGENTMAIL_USER_KEY || ''; + let mainWindow = null; let tray = null; /** 创建主窗口 */ function createMainWindow() { + // 通过 additionalArguments 把 API 基地址与 token 传给 preload(preload 从 renderer 的 process.argv 末尾读) + // 传入的是透传 arg,用户页面不能直接改,preload 能读到 + const injectArgs = [`--agentmail-api-base=${API_BASE}`]; + if (TOKEN) injectArgs.push(`--agentmail-token=${TOKEN}`); + mainWindow = new BrowserWindow({ width: 1280, height: 800, @@ -31,10 +42,11 @@ function createMainWindow() { title: 'AgentMail', icon: path.join(__dirname, '..', 'src', 'icons', 'tray-icon.png'), webPreferences: { - preload: path.join(__dirname, 'preload.js'), + preload: path.join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true, + additionalArguments: injectArgs, }, }); diff --git a/web/electron/preload.cjs b/web/electron/preload.cjs index d245a20..d9967b3 100644 --- a/web/electron/preload.cjs +++ b/web/electron/preload.cjs @@ -9,6 +9,18 @@ const { contextBridge, ipcRenderer } = require('electron'); +// 注入 API 基地址与 token:渲染进程的 config.ts 在读 window.__AGENTMAIL_API_BASE__ +// 与 __AGENTMAIL_TOKEN__ 时拿到它们,于是现有 client.ts/sse.ts **零改动**复用。 +// 这两个值由主进程在创建窗口时通过附加参数传进来(见 main.cjs 的 additionalArguments)。 +function getInjected(name) { + const prefix = `--agentmail-${name}=`; + const arg = process.argv.find(a => a.startsWith(prefix)); + return arg ? arg.slice(prefix.length) : undefined; +} + +contextBridge.exposeInMainWorld('__AGENTMAIL_API_BASE__', getInjected('api-base') || 'http://127.0.0.1:8180/api/v1'); +contextBridge.exposeInMainWorld('__AGENTMAIL_TOKEN__', getInjected('token') || undefined); + contextBridge.exposeInMainWorld('agentmail', { /** Gateway 基础地址(主进程 env 或默认 127.0.0.1:8180) */ gatewayUrl: () => ipcRenderer.invoke('get-gateway-url'),