Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): Windows 托盘右键菜单改为自己 popUp,不再依赖 setContextMenu (#1100)

Dashd6f7e51b91c5
diff --git a/apps/desktop/src/main/__tests__/windowsTrayLifecycle.test.ts b/apps/desktop/src/main/__tests__/windowsTrayLifecycle.test.ts
index 475f64a2a4..3f4924b332 100644
--- a/apps/desktop/src/main/__tests__/windowsTrayLifecycle.test.ts
+++ b/apps/desktop/src/main/__tests__/windowsTrayLifecycle.test.ts
@@ -2,9 +2,11 @@ import { describe, expect, it, vi } from 'vitest';
import {
hideWindowToWindowsTray,
+ popUpWindowsTrayMenu,
requestWindowsCloseBehavior,
requestWindowsTrayQuit,
type WindowsClosePromptWindow,
+ type WindowsTrayMenuHost,
type WindowsTrayWindow,
} from '../windowsTrayLifecycle';
@@ -149,3 +151,168 @@ describe('Windows tray lifecycle', () => {
expect(quit).toHaveBeenCalledTimes(1);
});
});
+
+/** Tray fake for the JS-driven menu popup (`setContextMenu` is deliberately unused). */
+function makeTrayMenuHost(): WindowsTrayMenuHost<object> & { destroyed: boolean } {
+ return {
+ destroyed: false,
+ isDestroyed() {
+ return this.destroyed;
+ },
+ popUpContextMenu: vi.fn(),
+ };
+}
+
+describe('Windows tray menu popup', () => {
+ it('builds the menu on first popup and keeps it referenced for the next one', () => {
+ const tray = makeTrayMenuHost();
+ const built = { id: 'built' };
+ const buildMenu = vi.fn(() => built);
+ let retained: object | null = null;
+ const retainMenu = vi.fn((menu: object) => {
+ retained = menu;
+ });
+
+ expect(
+ popUpWindowsTrayMenu({
+ tray,
+ menu: retained,
+ buildMenu,
+ retainMenu,
+ onUnavailable: vi.fn(),
+ onError: vi.fn(),
+ }),
+ ).toBe(true);
+ expect(buildMenu).toHaveBeenCalledTimes(1);
+ expect(retained).toBe(built);
+
+ // 第二次右键复用同一个菜单对象: 弹出期间必须一直有 JS 引用,不能每次交出新对象。
+ expect(
+ popUpWindowsTrayMenu({
+ tray,
+ menu: retained,
+ buildMenu,
+ retainMenu,
+ onUnavailable: vi.fn(),
+ onError: vi.fn(),
+ }),
+ ).toBe(true);
+ expect(buildMenu).toHaveBeenCalledTimes(1);
+ expect(tray.popUpContextMenu).toHaveBeenNthCalledWith(1, built);
+ expect(tray.popUpContextMenu).toHaveBeenNthCalledWith(2, built);
+ });
+
+ it('rebuilds the menu after the caller drops it on a language change', () => {
+ const tray = makeTrayMenuHost();
+ const menus = [{ id: 'zh-CN' }, { id: 'en' }];
+ const buildMenu = vi.fn(() => menus.shift() ?? { id: 'exhausted' });
+ const retainMenu = vi.fn();
+
+ popUpWindowsTrayMenu({
+ tray,
+ menu: null,
+ buildMenu,
+ retainMenu,
+ onUnavailable: vi.fn(),
+ onError: vi.fn(),
+ });
+ // invalidateWindowsTrayMenu() 把缓存置空后的下一次右键。
+ popUpWindowsTrayMenu({
+ tray,
+ menu: null,
+ buildMenu,
+ retainMenu,
+ onUnavailable: vi.fn(),
+ onError: vi.fn(),
+ });
+
+ expect(buildMenu).toHaveBeenCalledTimes(2);
+ expect(retainMenu.mock.calls).toEqual([[{ id: 'zh-CN' }], [{ id: 'en' }]]);
+ expect(tray.popUpContextMenu).toHaveBeenNthCalledWith(2, { id: 'en' });
+ });
+
+ it('reports a missing tray icon without building a menu', () => {
+ const buildMenu = vi.fn(() => ({}));
+ const onUnavailable = vi.fn();
+
+ expect(
+ popUpWindowsTrayMenu({
+ tray: null,
+ menu: null,
+ buildMenu,
+ retainMenu: vi.fn(),
+ onUnavailable,
+ onError: vi.fn(),
+ }),
+ ).toBe(false);
+
+ expect(onUnavailable).toHaveBeenCalledWith('no-tray');
+ expect(buildMenu).not.toHaveBeenCalled();
+ });
+
+ it('reports a destroyed tray icon without building a menu', () => {
+ const tray = makeTrayMenuHost();
+ tray.destroyed = true;
+ const buildMenu = vi.fn(() => ({}));
+ const onUnavailable = vi.fn();
+
+ expect(
+ popUpWindowsTrayMenu({
+ tray,
+ menu: null,
+ buildMenu,
+ retainMenu: vi.fn(),
+ onUnavailable,
+ onError: vi.fn(),
+ }),
+ ).toBe(false);
+
+ expect(onUnavailable).toHaveBeenCalledWith('destroyed');
+ expect(buildMenu).not.toHaveBeenCalled();
+ expect(tray.popUpContextMenu).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a failing popup instead of throwing into the tray event handler', () => {
+ const tray = makeTrayMenuHost();
+ const failure = new Error('popup rejected by the shell');
+ tray.popUpContextMenu = vi.fn(() => {
+ throw failure;
+ });
+ const onError = vi.fn();
+
+ expect(
+ popUpWindowsTrayMenu({
+ tray,
+ menu: null,
+ buildMenu: () => ({}),
+ retainMenu: vi.fn(),
+ onUnavailable: vi.fn(),
+ onError,
+ }),
+ ).toBe(false);
+
+ expect(onError).toHaveBeenCalledWith(failure);
+ });
+
+ it('surfaces a failing menu build', () => {
+ const tray = makeTrayMenuHost();
+ const failure = new Error('menu template rejected');
+ const onError = vi.fn();
+
+ expect(
+ popUpWindowsTrayMenu({
+ tray,
+ menu: null,
+ buildMenu: () => {
+ throw failure;
+ },
+ retainMenu: vi.fn(),
+ onUnavailable: vi.fn(),
+ onError,
+ }),
+ ).toBe(false);
+
+ expect(onError).toHaveBeenCalledWith(failure);
+ expect(tray.popUpContextMenu).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index af6f8ff6e5..1b71ccfcea 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -513,6 +513,7 @@ import {
} from './window-behavior-settings-store.js';
import {
hideWindowToWindowsTray,
+ popUpWindowsTrayMenu,
requestWindowsCloseBehavior,
requestWindowsTrayQuit,
} from './windowsTrayLifecycle.js';
@@ -1511,7 +1512,7 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>
if (mainWindow) {
installApplicationMenu(mainWindow, currentApplicationMenuLocale);
}
- updateWindowsTrayMenu();
+ invalidateWindowsTrayMenu();
getAgentIslandService()?.refreshLocalization();
return { ok: true };
});
@@ -1610,23 +1611,55 @@ const updatePresentationRecovery = isUpdateRelaunchCandidate
// 让窗口 close handler 放行真正的销毁。
let isQuitting = false;
let windowsTray: Tray | null = null;
+// 当前的托盘菜单。我们自己 popUp(见 popUpWindowsTrayMenu 的注释),菜单对象必须由
+// JS 侧持有,不能只作为实参交出去。语言切换时置 null,下一次右键按新语言重建。
+let windowsTrayMenu: Menu | null = null;
+const windowsTrayLog = createLogger('windows-tray');
const WINDOWS_CLOSE_PROMPT_FALLBACK_DELAY_MS = 2_000;
-function updateWindowsTrayMenu(): void {
- if (!windowsTray || windowsTray.isDestroyed()) return;
- windowsTray.setContextMenu(
- Menu.buildFromTemplate([
- {
- label: t('settings.windowBehavior.trayMenu.show'),
- click: () => focusMainWindow(),
- },
- { type: 'separator' },
- {
- label: t('settings.windowBehavior.trayMenu.quit'),
- click: () => quitFromWindowsTray(),
- },
- ]),
- );
+function buildWindowsTrayMenu(): Menu {
+ return Menu.buildFromTemplate([
+ {
+ label: t('settings.windowBehavior.trayMenu.show'),
+ click: () => focusMainWindow(),
+ },
+ { type: 'separator' },
+ {
+ label: t('settings.windowBehavior.trayMenu.quit'),
+ click: () => quitFromWindowsTray(),
+ },
+ ]);
+}
+
+/** 语言切换后丢弃缓存的菜单,下一次右键按新语言重建。 */
+function invalidateWindowsTrayMenu(): void {
+ windowsTrayMenu = null;
+}
+
+function openWindowsTrayMenu(): void {
+ // 这条日志是长期诊断留的,不是临时排查: 上游那条弹不出的 bug 是静默失败(不抛错),
+ // 所以日志里有没有这一行,是区分 "右键事件没到" 与 "事件到了但菜单没弹" 的唯一依据。
+ // 再有用户报 "右键没反应" 时,先让他看这行。
+ // 用 info 而不是 debug: packaged 的默认级别就是 info (logger.ts 的 level 解析),
+ // debug 会被 shouldLog 过滤掉 —— 那样它恰好在唯一需要它的场景(用户手上的正式包)
+ // 里不会出现。频率上也不担心刷屏: 只有用户真的右键托盘图标才会走到这里。
+ windowsTrayLog.info('tray right-click received, opening tray menu');
+ popUpWindowsTrayMenu<Menu>({
+ tray: windowsTray,
+ menu: windowsTrayMenu,
+ buildMenu: buildWindowsTrayMenu,
+ retainMenu: (menu) => {
+ windowsTrayMenu = menu;
+ },
+ onUnavailable: (reason) => {
+ windowsTrayLog.warn('tray menu requested without a live tray icon', { reason });
+ },
+ onError: (error) => {
+ windowsTrayLog.error('failed to open Windows tray menu', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ },
+ });
}
function quitFromWindowsTray(): void {
@@ -1657,30 +1690,39 @@ function quitFromWindowsTray(): void {
function destroyWindowsTray(): void {
windowsTray?.destroy();
windowsTray = null;
+ windowsTrayMenu = null;
}
function ensureWindowsTray(): boolean {
- if (windowsTray && !windowsTray.isDestroyed()) {
- updateWindowsTrayMenu();
- return true;
- }
+ if (windowsTray && !windowsTray.isDestroyed()) return true;
+ let tray: Tray | null = null;
try {
const iconPath = app.isPackaged
? path.join(process.resourcesPath, 'icon.png')
: path.join(__dirname, '../../resources/icon.png');
const icon = nativeImage.createFromPath(iconPath);
if (icon.isEmpty()) throw new Error(`tray icon is empty: ${iconPath}`);
- windowsTray = new Tray(icon.resize({ width: 16, height: 16 }));
- windowsTray.setToolTip(BRAND_NAME);
- windowsTray.on('click', () => focusMainWindow());
- updateWindowsTrayMenu();
+ tray = new Tray(icon.resize({ width: 16, height: 16 }));
+ tray.setToolTip(BRAND_NAME);
+ tray.on('click', () => focusMainWindow());
+ tray.on('right-click', () => openWindowsTrayMenu());
+ windowsTray = tray;
+ windowsTrayMenu = null;
return true;
} catch (err) {
- createLogger('windows-tray').error('failed to create Windows tray icon', {
+ // 图标可能已经进了通知区域: 只置 null 会留下一个仍响应左键、却再也引用不到的
+ // 僵尸图标(destroyWindowsTray 摸不到它,右键也没有菜单可弹)。
+ try {
+ tray?.destroy();
+ } catch {
+ /* 已经没了,忽略 */
+ }
+ windowsTrayLog.error('failed to create Windows tray icon', {
error: err instanceof Error ? err.message : String(err),
});
windowsTray = null;
+ windowsTrayMenu = null;
return false;
}
}
diff --git a/apps/desktop/src/main/windowsTrayLifecycle.ts b/apps/desktop/src/main/windowsTrayLifecycle.ts
index 1dc346801b..a0b3b8001b 100644
--- a/apps/desktop/src/main/windowsTrayLifecycle.ts
+++ b/apps/desktop/src/main/windowsTrayLifecycle.ts
@@ -28,6 +28,60 @@ export interface WindowsTrayQuitDependencies {
quit(): void;
}
+/** Tray surface needed to open the tray menu from JS instead of via `setContextMenu`. */
+export interface WindowsTrayMenuHost<TMenu> {
+ isDestroyed(): boolean;
+ popUpContextMenu(menu: TMenu): void;
+}
+
+/** Dependencies for the JS-driven tray menu popup. */
+export interface WindowsTrayMenuPopupDependencies<TMenu> {
+ tray: WindowsTrayMenuHost<TMenu> | null;
+ /** Cached menu, or null when it must be (re)built — callers drop it on language change. */
+ menu: TMenu | null;
+ buildMenu(): TMenu;
+ /** Hands the menu back to the caller, which keeps it referenced for the next popup. */
+ retainMenu(menu: TMenu): void;
+ onUnavailable(reason: 'no-tray' | 'destroyed'): void;
+ onError(error: unknown): void;
+}
+
+/**
+ * Open the Windows tray menu ourselves on right-click.
+ *
+ * ⚠️ 不要改回 `tray.setContextMenu()`。那条路径把弹菜单整个交给 native 侧,
+ * 一旦系统那次弹出失败(上游 electron#47421: 前台有全屏应用时右键固定在任务栏的
+ * 托盘图标毫无反应),JS 侧既收不到事件也记不下日志,用户就只剩任务管理器可用 ——
+ * 这正是 Windows 用户报的 "左键能恢复窗口、右键什么都不弹" 的现象。
+ * 而且 `setContextMenu` 一旦设置,`right-click` 事件按设计不再 emit
+ * (electron#5058,维护者明确说是预期行为),所以两种方式不能并存做双保险:
+ * 设了它,这里的兜底就永远不会被触发。
+ */
+export function popUpWindowsTrayMenu<TMenu>(
+ deps: WindowsTrayMenuPopupDependencies<TMenu>,
+): boolean {
+ const { tray } = deps;
+ if (!tray) {
+ deps.onUnavailable('no-tray');
+ return false;
+ }
+ if (tray.isDestroyed()) {
+ deps.onUnavailable('destroyed');
+ return false;
+ }
+
+ try {
+ // 缓存不只是省一次构建: 菜单对象必须一直有 JS 引用,否则弹出期间被 GC 掉。
+ const menu = deps.menu ?? deps.buildMenu();
+ deps.retainMenu(menu);
+ tray.popUpContextMenu(menu);
+ return true;
+ } catch (error) {
+ deps.onError(error);
+ return false;
+ }
+}
+
/** Hide immediately, or wait for the native fullscreen transition to finish first. */
export function hideWindowToWindowsTray(window: WindowsTrayWindow): void {
if (!window.isFullScreen()) {
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index fe41e5885b..a48b62614f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -481,7 +481,7 @@
"closePrompt": {
"title": "Close Cindy",
"message": "What should happen when you close the main window?",
- "detail": "Tasks keep running when Cindy is minimized to the system tray. You can change this later in Settings."
+ "detail": "Tasks keep running when Cindy is minimized to the system tray; right-click the tray icon to quit. You can change this later in Settings."
},
"trayMenu": {
"show": "Open Cindy",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index b571aebb9a..d91f1b720a 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -481,7 +481,7 @@
"closePrompt": {
"title": "Cindy を閉じる",
"message": "メインウィンドウを閉じるときの動作を選択してください。",
- "detail": "システムトレイに最小化すると、タスクは実行を続けます。後から設定で変更できます。"
+ "detail": "システムトレイに最小化すると、タスクは実行を続けます。終了するにはトレイアイコンを右クリックします。後から設定で変更できます。"
},
"trayMenu": {
"show": "Cindy を開く",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index b577fa1a70..f22523ae0f 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -481,7 +481,7 @@
"closePrompt": {
"title": "Cindy 닫기",
"message": "기본 창을 닫을 때 어떻게 할까요?",
- "detail": "시스템 트레이로 최소화하면 작업이 계속 실행됩니다. 나중에 설정에서 변경할 수 있습니다."
+ "detail": "시스템 트레이로 최소화하면 작업이 계속 실행됩니다. 종료하려면 트레이 아이콘을 오른쪽 클릭하세요. 나중에 설정에서 변경할 수 있습니다."
},
"trayMenu": {
"show": "Cindy 열기",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 74f3b83665..c22a115e3c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -481,7 +481,7 @@
"closePrompt": {
"title": "关闭 Cindy",
"message": "关闭主窗口时要执行什么操作?",
- "detail": "收起到系统托盘后,任务会继续运行。你可以稍后在设置中修改。"
+ "detail": "收起到系统托盘后,任务会继续运行;右键托盘图标可以退出。你可以稍后在设置中修改。"
},
"trayMenu": {
"show": "打开 Cindy",