P1 修复面收口: v0.6.3 截断自愈推全量(Anthropic/Ollama/非流式/引擎兜底); SSE 上游错误帧检测进重试通道; clearMessages 摘要游标根治; truncateResult 内联图片白名单统一; 前端四 bug(确认弹窗锁死/MemoryViewer/ Virtuoso Footer/abort 尾部过滤) + reasoning 缓冲跨迭代污染; 托盘通知过滤与新建会话死链接线 P2 安全纵深: MCP 审批闭环(ConfirmationHook×PolicyEngine 联动+重名拒注册); SSRF 收敛 ssrf-guard 共享模块 (web_fetch 双通道校验+重定向终态复检); Electron 加固(preload CJS 化→sandbox:true/CSP/权限白名单/will-navigate); run_command cmd.exe 白名单通道元字符守门; diff_viewer 10MB 预检; Anthropic thinking 预算下限; Agnes 思考显式关闭 P3 架构还债: OpenAICompatibleAdapter 中间基类收敛四家样板; 错误分类单轨化(删 mapError/getFetchSignal, 超时显式 ETIMEDOUT); PRAGMA user_version 迁移版本化; 死代码清理专项(cn.ts/SHORTCUTS/ContextMenu 分支/ getWindowState/modifiedArgs/sandbox 空壳); i18next 引入; a11y 第一轮; SearXNG 页批量草稿模型统一 P4 能力演进: Ollama pull 可取消/capabilities 探测/num_ctx 实测缓存; UpdateService feed 比对式自动更新 (app:updateCheck IPC + StatusBar 入口); MiMo providerOptions(web_search 服务端工具/strict JSON); web_fetch extract_mode=markdown(turndown); network.proxyUrl 全局代理(Chromium sessions+undici dispatcher) 测试: 264 → 507 用例(Electron ABI 全绿零跳过), 覆盖引擎压缩管线/重试竞速/MEMORY.md 闸门/file_editor 五操作/ filesystem 七工具实体夹具/git 真实仓库/SSE 错误帧/全线截断自愈/Provider 请求形态矩阵/SSRF 表测/钩子分级矩阵/ OutputValidator 全量/SLO 指标/MCP 安全纯函数/task_manager 链路/渲染层纯域/i18n 桥契约
263 lines
7.6 KiB
TypeScript
263 lines
7.6 KiB
TypeScript
/**
|
||
* Window Manager — 多窗口管理
|
||
*
|
||
* 职责:
|
||
* 1. 创建和管理多个窗口(每个工作空间可独立开窗口)
|
||
* 2. 窗口状态持久化(位置、大小)
|
||
* 3. 全局快捷键注册(Cmd+Shift+M 切换到 Metona)
|
||
* 4. 关闭到托盘行为
|
||
*
|
||
* @see docs/MetonaAI-Desktop UI UX 设计集成方案.html — 窗口管理
|
||
*/
|
||
|
||
import { BrowserWindow, globalShortcut, shell } from 'electron';
|
||
import { join } from 'path';
|
||
import { existsSync } from 'fs';
|
||
import { is } from '@electron-toolkit/utils';
|
||
import log from 'electron-log';
|
||
|
||
export interface WindowState {
|
||
x?: number;
|
||
y?: number;
|
||
width: number;
|
||
height: number;
|
||
isMaximized?: boolean;
|
||
}
|
||
|
||
export class WindowManager {
|
||
private windows = new Map<string, BrowserWindow>();
|
||
private activeWindowId: string | null = null;
|
||
|
||
/**
|
||
* 创建新窗口
|
||
*/
|
||
createWindow(options: {
|
||
id?: string;
|
||
workspacePath?: string;
|
||
title?: string;
|
||
state?: WindowState;
|
||
beforeLoad?: (win: BrowserWindow) => void;
|
||
}): BrowserWindow {
|
||
const id = options.id ?? `window_${Date.now()}`;
|
||
const state = options.state ?? { width: 1440, height: 900 };
|
||
|
||
const win = new BrowserWindow({
|
||
width: state.width,
|
||
height: state.height,
|
||
x: state.x,
|
||
y: state.y,
|
||
minWidth: 960,
|
||
minHeight: 600,
|
||
icon: this.getIconPath(),
|
||
show: false,
|
||
titleBarStyle: 'hiddenInset',
|
||
title: options.title ?? 'MetonaAI Desktop',
|
||
webPreferences: {
|
||
// v0.6.4 安全加固: preload 已迁移为 CJS 产物(preload.cjs,见 electron.vite.config.ts
|
||
// 的 rollupOptions.output.format:'cjs'),原 ESM .mjs 与 sandbox 不兼容的限制解除。
|
||
// sandbox:true 后渲染进程即使被 XSS 也无法触碰 Node/加载任意模块 —— 这是
|
||
// Electron 官方推荐的最高优先级防线(Electron 安全清单第 1 条)。
|
||
preload: join(__dirname, '../preload/preload.cjs'),
|
||
sandbox: true,
|
||
contextIsolation: true,
|
||
nodeIntegration: false,
|
||
},
|
||
});
|
||
|
||
// P2-11 修复: 在 loadURL 之前执行回调,确保 IPC handler 在渲染进程加载前注册
|
||
if (options.beforeLoad) options.beforeLoad(win);
|
||
|
||
// 加载页面
|
||
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
|
||
win.loadURL(process.env['ELECTRON_RENDERER_URL']);
|
||
} else {
|
||
win.loadFile(join(__dirname, '../../dist/index.html'));
|
||
}
|
||
|
||
// 窗口事件
|
||
win.on('ready-to-show', () => {
|
||
if (state.isMaximized) {
|
||
win.maximize();
|
||
}
|
||
win.show();
|
||
});
|
||
|
||
win.on('closed', () => {
|
||
this.windows.delete(id);
|
||
if (this.activeWindowId === id) {
|
||
this.activeWindowId =
|
||
this.windows.size > 0 ? (this.windows.keys().next().value ?? null) : null;
|
||
}
|
||
});
|
||
|
||
// 崩溃可观测性 + 自愈: 渲染进程崩溃(OOM/原生崩溃)时记录归因日志并自动重载,
|
||
// 替代静默白屏(用户此前感知为"应用崩溃"且无从恢复)
|
||
win.webContents.on('render-process-gone', (_event, details) => {
|
||
log.error(
|
||
`[WindowManager] render-process-gone (id=${win.id}): reason=${details.reason} exitCode=${details.exitCode}`,
|
||
);
|
||
if (!win.isDestroyed() && details.reason !== 'clean-exit') {
|
||
try {
|
||
win.webContents.reload();
|
||
log.info(`[WindowManager] Window ${id} reloaded after renderer crash`);
|
||
} catch (err) {
|
||
log.error(`[WindowManager] Reload after crash failed:`, err);
|
||
}
|
||
}
|
||
});
|
||
|
||
win.webContents.setWindowOpenHandler(({ url }) => {
|
||
// C-8 修复: 校验 URL 协议,只允许 http/https,防止 javascript:/file: 等协议执行代码
|
||
try {
|
||
const parsed = new URL(url);
|
||
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
||
shell.openExternal(url);
|
||
} else {
|
||
log.warn(`[WindowManager] Blocked window.open with unsafe protocol: ${parsed.protocol}`);
|
||
}
|
||
} catch {
|
||
log.warn(`[WindowManager] Blocked window.open with invalid URL: ${url.slice(0, 100)}`);
|
||
}
|
||
return { action: 'deny' };
|
||
});
|
||
|
||
// v0.6.4 安全加固: will-navigate 拦截 —— SPA 应用主框架不应发生顶层导航;
|
||
// 除开发服务器热更新入口外的一切导航一律取消,http(s) 外链转系统浏览器。
|
||
// (此前渲染进程若被注入 webContents.location=... 可静默替换页面。)
|
||
win.webContents.on('will-navigate', (event, url) => {
|
||
const isDevServer =
|
||
process.env['ELECTRON_RENDERER_URL'] !== undefined &&
|
||
(() => {
|
||
try {
|
||
return new URL(url).origin === new URL(process.env['ELECTRON_RENDERER_URL']!).origin;
|
||
} catch {
|
||
return false;
|
||
}
|
||
})();
|
||
const isAppFile = url.startsWith('file://');
|
||
if (!isDevServer && !isAppFile) {
|
||
event.preventDefault();
|
||
log.warn(`[WindowManager] Blocked top-level navigation to ${url.slice(0, 120)}`);
|
||
try {
|
||
const parsed = new URL(url);
|
||
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
||
void import('electron').then(({ shell }) => shell.openExternal(url));
|
||
}
|
||
} catch {
|
||
/* 非 URL 一律丢弃 */
|
||
}
|
||
}
|
||
});
|
||
|
||
this.windows.set(id, win);
|
||
this.activeWindowId = id;
|
||
|
||
log.info(`Window created: ${id} (${options.title ?? 'MetonaAI Desktop'})`);
|
||
|
||
return win;
|
||
}
|
||
|
||
/**
|
||
* 获取窗口
|
||
*/
|
||
getWindow(id: string): BrowserWindow | undefined {
|
||
return this.windows.get(id);
|
||
}
|
||
|
||
/**
|
||
* 获取活动窗口
|
||
*/
|
||
getActiveWindow(): BrowserWindow | null {
|
||
if (this.activeWindowId) {
|
||
return this.windows.get(this.activeWindowId) ?? null;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/**
|
||
* 获取所有窗口
|
||
*/
|
||
getAllWindows(): BrowserWindow[] {
|
||
return Array.from(this.windows.values());
|
||
}
|
||
|
||
/**
|
||
* 聚焦到窗口(从任意应用切换)
|
||
*/
|
||
focusWindow(): void {
|
||
const win = this.getActiveWindow();
|
||
if (win) {
|
||
if (win.isMinimized()) {
|
||
win.restore();
|
||
}
|
||
win.show();
|
||
win.focus();
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 注册全局快捷键
|
||
*/
|
||
registerGlobalShortcuts(): void {
|
||
// Cmd/Ctrl+Shift+M — 从任意应用切换到 Metona
|
||
const registered = globalShortcut.register('CommandOrControl+Shift+M', () => {
|
||
this.focusWindow();
|
||
log.info('Global shortcut: Switch to Metona');
|
||
});
|
||
|
||
if (!registered) {
|
||
log.warn('Failed to register global shortcut: Cmd+Shift+M');
|
||
} else {
|
||
log.info('Global shortcut registered: Cmd+Shift+M');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 注销全局快捷键
|
||
*/
|
||
unregisterGlobalShortcuts(): void {
|
||
globalShortcut.unregisterAll();
|
||
log.info('Global shortcuts unregistered');
|
||
}
|
||
|
||
/**
|
||
* 关闭所有窗口
|
||
*/
|
||
closeAll(): void {
|
||
for (const [id, win] of this.windows) {
|
||
try {
|
||
win.destroy();
|
||
} catch {
|
||
log.warn(`Failed to close window: ${id}`);
|
||
}
|
||
}
|
||
this.windows.clear();
|
||
this.activeWindowId = null;
|
||
}
|
||
|
||
/**
|
||
* 获取窗口数量
|
||
*/
|
||
get count(): number {
|
||
return this.windows.size;
|
||
}
|
||
|
||
/**
|
||
* 获取应用图标路径
|
||
*/
|
||
private getIconPath(): string | undefined {
|
||
const candidates = [
|
||
join(__dirname, '../../assets/logo.ico'),
|
||
join(__dirname, '../../assets/logo.png'),
|
||
join(process.resourcesPath || '', 'app.asar.unpacked', 'assets/logo.ico'),
|
||
join(process.resourcesPath || '', 'app.asar.unpacked', 'assets/logo.png'),
|
||
join(process.resourcesPath || '', 'assets/logo.ico'),
|
||
join(process.resourcesPath || '', 'assets/logo.png'),
|
||
];
|
||
for (const p of candidates) {
|
||
if (existsSync(p)) return p;
|
||
}
|
||
return undefined;
|
||
}
|
||
}
|