import path from 'path'; import type { BrowserWindowConstructorOptions } from 'electron'; import { BrowserWindow, screen } from 'electron'; import { getBaseDir, isDev } from 'ee-core/ps'; import { logger } from 'ee-core/log'; import { getMainWindow } from 'ee-core/electron'; import { localSettingsService } from '../setting/localSettings'; export interface SubWindowOpenOptions { /** 完整路由(含 query),如 /workbench?newChat=1 */ fullPath?: string; /** 窗口已存在时是否整窗重载(换案后需要重新读案件上下文) */ reloadIfOpen?: boolean; /** 窗口已存在时是否导航到目标地址(显式导航意图) */ navigateIfOpen?: boolean; } export interface SubWindowDefinition { /** 允许的路径前缀,如 /workbench、/perm-window;其余地址一律改写到该前缀 */ pathPrefix: string; /** 本机设置里保存 bounds 的键名 */ boundsKey: string; /** 新建窗口与恢复 bounds 时的最小尺寸 */ minSize: { minWidth: number; minHeight: number }; /** 创建 BrowserWindow 的选项(标题 / 尺寸 / webPreferences 等) */ createWindowOptions: () => BrowserWindowConstructorOptions; /** 打开 / 关闭时通知主窗口的通道;不传则不通知 */ stateChannel?: string; /** * 已存在窗口时,仅当目标带 query 才导航。 * *

智能工作台沿用该旧规则:普通打开/聚焦不动它当前所在的视图, * 只有 ?newChat=1 / ?view=agent 这类明确意图才跳转。 */ navigateOnlyWhenQuery?: boolean; /** * 已保存 bounds 的使用方式。 * *

*/ restoreBoundsMode?: 'all' | 'position' | 'none'; } export interface SubWindowController { getWindow(): BrowserWindow | null; isOpen(): boolean; /** 判断某个窗口是不是本控制器创建的单例窗口(IPC 解析窗口角色用) */ matches(win: BrowserWindow | null | undefined): boolean; open(options?: SubWindowOpenOptions): BrowserWindow; close(): void; /** 把已打开的窗口拉到前台;没打开返回 false */ focus(): boolean; } interface SavedBounds { x: number; y: number; width: number; height: number; } function escapeRegExp(value: string): string { return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } /** 把任意窗口拉到前台(最小化时先还原) */ export function focusWindow(win: BrowserWindow): void { if (win.isMinimized()) win.restore(); win.show(); win.moveTop(); win.focus(); } /** * 创建一个单例子窗口控制器。 * *

把智能工作台窗口的既有行为原样抽出来(单例、聚焦、bounds 落盘、 * 渲染进程崩溃自愈、dev/prod 两套加载方式),供智能工作台与权限管理窗口共用。 */ export function createSubWindowController(definition: SubWindowDefinition): SubWindowController { const pathPattern = new RegExp(`^${escapeRegExp(definition.pathPrefix)}(?:/|\\?|$)`); const logPrefix = `[${definition.pathPrefix}]`; let win: BrowserWindow | null = null; const getWindow = (): BrowserWindow | null => (win && !win.isDestroyed() ? win : null); function normalizeFullPath(fullPath?: string): string { const raw = typeof fullPath === 'string' ? fullPath.trim() : ''; if (!raw) return definition.pathPrefix; // 只接受该窗口承载的地址,避免把业务页塞进来(如 /workbenchfoo 不算) return pathPattern.test(raw) ? raw : definition.pathPrefix; } function open(options: SubWindowOpenOptions = {}): BrowserWindow { const fullPath = normalizeFullPath(options.fullPath); const existing = getWindow(); if (existing) { focusWindow(existing); if (options.reloadIfOpen) { // 刚由本次导航创建、还在加载时不用再刷一次;已加载完成的才需要按新上下文重建 if (!existing.webContents.isLoading()) { existing.webContents.reload(); } } else if ( options.navigateIfOpen && (!definition.navigateOnlyWhenQuery || fullPath.includes('?')) ) { loadRenderer(existing, fullPath); } return existing; } const created = new BrowserWindow({ ...definition.createWindowOptions(), ...restoreBounds(), }); win = created; clampToVisibleArea(created); created.once('ready-to-show', () => { if (!created.isDestroyed()) { focusWindow(created); } }); created.on('close', () => saveBounds(created)); created.on('closed', () => { if (win === created) win = null; notifyState(false); }); // 渲染进程崩溃后留一个空壳没有意义:销毁它,下次点击重新创建 created.webContents.on('render-process-gone', (_event, details) => { logger.error(`${logPrefix} render-process-gone:`, details?.reason); if (!created.isDestroyed()) { saveBounds(created); created.destroy(); } }); loadRenderer(created, fullPath); notifyState(true); return created; } function close(): void { getWindow()?.close(); } function focus(): boolean { const current = getWindow(); if (!current) return false; focusWindow(current); return true; } function loadRenderer(target: BrowserWindow, fullPath: string): void { const devServerUrl = resolveDevServerUrl(); if (devServerUrl) { target.loadURL(`${devServerUrl}${fullPath}`).catch((err) => { logger.error(`${logPrefix} loadURL failed:`, err); }); return; } // 生产是 file:// + hash 路由:hash 带上完整路径与 query const indexPath = path.join(getBaseDir(), 'public', 'dist', 'index.html'); target.loadFile(indexPath, { hash: fullPath }).catch((err) => { logger.error(`${logPrefix} loadFile failed:`, err); }); } function saveBounds(target: BrowserWindow): void { try { const { x, y, width, height } = target.getBounds(); localSettingsService.set(definition.boundsKey, JSON.stringify({ x, y, width, height })); } catch (e) { logger.warn(`${logPrefix} 保存窗口位置失败:`, e instanceof Error ? e.message : String(e)); } } /** 恢复上次的位置与大小;越界或尺寸不合法时交给 Electron 默认放置 */ function restoreBounds(): Partial { try { const raw = localSettingsService.get(definition.boundsKey); if (!raw) return {}; const parsed = JSON.parse(raw) as Partial; const { x, y, width, height } = parsed || {}; if (![x, y, width, height].every((value) => typeof value === 'number' && Number.isFinite(value))) { return {}; } if ((width as number) < definition.minSize.minWidth || (height as number) < definition.minSize.minHeight) { return {}; } // 显示器拔掉/分辨率变化后,旧坐标可能落在屏幕外 const visible = screen.getAllDisplays().some((display) => { const area = display.workArea; return ( (x as number) < area.x + area.width && (x as number) + (width as number) > area.x && (y as number) < area.y + area.height && (y as number) + (height as number) > area.y ); }); return visible ? buildRestoredBounds({ x, y, width, height }) : {}; } catch (e) { logger.warn(`${logPrefix} 恢复窗口位置失败:`, e instanceof Error ? e.message : String(e)); return {}; } } /** 按配置决定恢复位置和/或尺寸 */ function buildRestoredBounds(saved: Partial): Partial { switch (definition.restoreBoundsMode) { case 'none': return {}; case 'position': // 尺寸交给 createWindowOptions(例如权限窗口跟随主窗口大小),这里只保留位置 return { x: saved.x, y: saved.y }; default: return saved; } } /** 位置可能配不上新的窗口尺寸(例如跟随最大化的主窗口):保证窗口完整落在最近显示器的工作区内 */ function clampToVisibleArea(target: BrowserWindow): void { try { const bounds = target.getBounds(); const display = screen.getDisplayMatching(bounds); const area = display.workArea; const width = Math.min(bounds.width, area.width); const height = Math.min(bounds.height, area.height); const x = Math.min(Math.max(bounds.x, area.x), Math.max(area.x, area.x + area.width - width)); const y = Math.min(Math.max(bounds.y, area.y), Math.max(area.y, area.y + area.height - height)); if (x !== bounds.x || y !== bounds.y || width !== bounds.width || height !== bounds.height) { target.setBounds({ x, y, width, height }); } } catch (e) { logger.warn(`${logPrefix} 校正窗口位置失败:`, e instanceof Error ? e.message : String(e)); } } function notifyState(open: boolean): void { const channel = definition.stateChannel; if (!channel) return; try { const main = getMainWindow(); if (!main.isDestroyed() && !main.webContents.isDestroyed()) { main.webContents.send(channel, { open }); } } catch { // 主窗口尚未创建或应用正在退出:忽略 } } return { getWindow, isOpen: () => !!getWindow(), matches: (target) => { const current = getWindow(); return !!target && !!current && target.id === current.id; }, open, close, focus, }; } /** * 开发环境的前端地址:与 ee-core 加载主窗口同口径,端口来自 cmd/bin.js 的 dev.frontend.port。 * 生产环境(或读不到配置)返回 null,走 loadFile。 */ function resolveDevServerUrl(): string | null { if (!isDev()) return null; try { // eslint-disable-next-line @typescript-eslint/no-var-requires const binConfig = require(path.join(getBaseDir(), 'cmd', 'bin.js')); const frontend = binConfig?.dev?.frontend || {}; const protocol = typeof frontend.protocol === 'string' ? frontend.protocol : 'http://'; if (protocol === 'file://') return null; const hostname = typeof frontend.hostname === 'string' ? frontend.hostname : 'localhost'; const port = Number(frontend.port) || 3100; return `${protocol}${hostname}:${port}`; } catch (e) { logger.warn('[subWindow] 读取 cmd/bin.js 失败,回退 http://localhost:3100'); return 'http://localhost:3100'; } }