import { app, BrowserWindow, ipcMain, dialog, shell, Menu } from 'electron'; import fs from 'node:fs'; import path from 'node:path'; import os from 'node:os'; import { randomUUID } from 'node:crypto'; import { HostController, HOST_ENVIRONMENT } from '../core/desktop/host-controller.mjs'; import { DesktopBridge } from '../core/desktop/desktop-bridge.mjs'; import { ownedChild, assertLocalTree, samePath } from '../core/desktop/file-state.mjs'; import { observeWindowsProcess, protectUserDirectory } from '../core/desktop/process-identity.mjs'; import { DESKTOP_CHANNELS, desktopOrigin } from '../shared/contracts/desktop-bridge.mjs'; import { desktopLaunchOptions } from '../core/desktop/launch-options.mjs'; import { BrowsingView } from './browsing-view.mjs'; import { localPreviewAddress } from '../core/preview/local-file-preview.mjs'; const options = desktopLaunchOptions(process.argv, { defaultApp: process.defaultApp, mainFile: __filename }); const appRoot = path.resolve(options['--app-root'] || (app.isPackaged ? path.resolve(path.dirname(process.execPath), '..') : path.resolve(__dirname, '..'))); const dataRoot = path.resolve(options['--data-root'] || path.join(process.env.LOCALAPPDATA || os.homedir(), 'AgentWorkbench')); const port = Number(options['--port'] || 4318); assertLocalTree(dataRoot, { missing: true }); fs.mkdirSync(dataRoot, { recursive: true }); const profile = ownedChild(dataRoot, '.desktop-profile', { missing: true }); fs.mkdirSync(profile, { recursive: true }); protectUserDirectory(profile); app.setPath('userData', profile); app.setAppUserModelId('local.agent-workbench'); app.setName('Orven'); let window, controller, bridge, browsingView, windowId, windowOwner, quitting = false; const retained = app.requestSingleInstanceLock({ appRoot, dataRoot, port }); if (!retained) app.quit(); else { app.on('second-instance', (_event, _argv, _directory, incoming) => { if (!samePath(incoming?.appRoot ?? '', appRoot) || !samePath(incoming?.dataRoot ?? '', dataRoot) || incoming?.port !== port) return; if (window && !window.isDestroyed()) { if (window.isMinimized()) window.restore(); window.show(); window.focus(); } }); app.on('window-all-closed', () => app.quit()); // Node owns execution, independent of Electron. app.on('before-quit', event => { if (quitting || !controller || !windowOwner) return; event.preventDefault(); quitting = true; browsingView?.dispose(); void controller.api('/host/windows/unregister', { method: 'POST', input: windowOwner, timeoutMs: 5000 }).catch(() => {}).finally(() => app.quit()); }); app.whenReady().then(async () => { controller = new HostController({ appRoot, dataRoot, port, nodePath: options['--node'], environment: Object.fromEntries(HOST_ENVIRONMENT.filter(key => process.env[key]).map(key => [key, process.env[key]])) }); const host = await controller.start(), observed = observeWindowsProcess(process.pid); windowId = randomUUID(); windowOwner = { windowId, pid: process.pid, createdAt: observed.createdAt, instanceId: host.identity.instanceId, runtimeIdentity: host.identity.runtimeIdentity }; await controller.api('/host/windows/register', { method: 'POST', input: windowOwner }); const preload = path.join(appRoot, 'dist-desktop/preload.cjs'); window = new BrowserWindow({ title: 'Orven · AI 开发工作台', width: 1440, height: 1000, minWidth: 390, minHeight: 600, show: false, backgroundColor: '#ffffff', icon: path.join(appRoot, 'public/workbench-icon.png'), webPreferences: { preload, sandbox: true, contextIsolation: true, nodeIntegration: false, webSecurity: true, allowRunningInsecureContent: false } }); window.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); window.webContents.on('will-navigate', details => { if (!desktopOrigin(details.url, controller.url)) details.preventDefault(); }); window.webContents.on('will-frame-navigate', details => { if (!desktopOrigin(details.url, controller.url) && !(details.isMainFrame === false && localPreviewAddress(details.url))) details.preventDefault(); }); window.webContents.on('will-attach-webview', event => event.preventDefault()); const session = window.webContents.session; session.setPermissionRequestHandler((_contents, _permission, callback) => callback(false)); session.setPermissionCheckHandler(() => false); session.webRequest.onBeforeRequest((details, callback) => { const permitted = desktopOrigin(details.url, controller.url) || details.url.startsWith('data:image/') || details.url.startsWith('blob:' + controller.url + '/'); if (permitted) return callback({ cancel: false }); if (!localPreviewAddress(details.url) || details.resourceType === 'mainFrame') return callback({ cancel: true }); void controller.api('/local-file-preview-access?url=' + encodeURIComponent(details.url)).then(access => callback({ cancel: !access.allowed })).catch(() => callback({ cancel: true })); }); bridge = new DesktopBridge(controller, { dialog, shell, getWindow: () => window, onStopped: () => setTimeout(() => app.quit(), 150) }); for (const [action, channel] of Object.entries(DESKTOP_CHANNELS)) ipcMain.handle(channel, (event, input) => bridge.execute(event, action, input)); browsingView = new BrowsingView({ window, controller, windowOwner }); ipcMain.handle('awb:browsing-layout', (event, input) => browsingView.layout(event, input)); Menu.setApplicationMenu(Menu.buildFromTemplate([{ label: '工作台', submenu: [ { label: '刷新窗口', role: 'reload' }, { label: '关闭窗口(后台任务继续)', accelerator: 'Alt+F4', click: () => window.close() }, ] }, { label: '编辑', submenu: [{ role: 'undo' }, { role: 'redo' }, { type: 'separator' }, { role: 'cut' }, { role: 'copy' }, { role: 'paste' }, { role: 'selectAll' }] }])); window.on('close', () => browsingView?.dispose()); window.on('closed', () => { window = null; }); await window.loadURL(host.url + '/?desktop=1&release=' + host.identity.version); if (!options.hidden) window.show(); console.log(JSON.stringify({ app: 'agent-workbench-desktop', ready: true, pid: process.pid, hostPid: host.identity.pid, instanceId: host.identity.instanceId, appRoot, dataRoot, url: host.url })); }).catch(error => { console.error(JSON.stringify({ app: 'agent-workbench-desktop', ready: false, message: error.message })); if (!options.hidden) dialog.showErrorBox('Orven 无法打开', error.message); app.exit(1); }); }