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。

feat(desktop): 为 Linux 添加系统托盘入口 (#6093)

Dashf2f5ba54edb1
diff --git a/apps/desktop/src/main/__tests__/linuxTrayLifecycle.test.ts b/apps/desktop/src/main/__tests__/linuxTrayLifecycle.test.ts
new file mode 100644
index 0000000000..046a6851bf
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/linuxTrayLifecycle.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createLinuxTrayController } from '../linuxTrayLifecycle';
+
+function harness() {
+ let destroyed = false;
+ const tray = {
+ isDestroyed: () => destroyed,
+ destroy: vi.fn(() => {
+ destroyed = true;
+ }),
+ setContextMenu: vi.fn(),
+ on: vi.fn<(event: 'click', listener: () => void) => void>(),
+ };
+ const deps = {
+ createTray: vi.fn(() => tray),
+ buildMenu: vi.fn(() => ({ label: 'Show Cindy' })),
+ showWindow: vi.fn(),
+ onError: vi.fn(),
+ };
+ return { tray, deps, controller: createLinuxTrayController(deps) };
+}
+
+describe('Linux tray lifetime', () => {
+ it('publishes a native menu and restores the window on activation', () => {
+ const { tray, deps, controller } = harness();
+ expect(controller.ensure()).toBe(true);
+ expect(controller.ensure()).toBe(true);
+ expect(deps.createTray).toHaveBeenCalledOnce();
+ expect(tray.setContextMenu).toHaveBeenCalledWith({ label: 'Show Cindy' });
+ const [event, activate] = tray.on.mock.calls[0];
+ expect(event).toBe('click');
+ activate();
+ expect(deps.showWindow).toHaveBeenCalledOnce();
+ });
+
+ it('republishes localized menus without recreating the icon', () => {
+ const { tray, deps, controller } = harness();
+ controller.ensure();
+ deps.buildMenu.mockReturnValue({ label: '显示 Cindy' });
+ controller.refreshMenu();
+ expect(tray.setContextMenu).toHaveBeenLastCalledWith({ label: '显示 Cindy' });
+ expect(deps.createTray).toHaveBeenCalledOnce();
+ });
+
+ it('does not create a tray on language changes before startup or after disposal', () => {
+ const { tray, deps, controller } = harness();
+ controller.refreshMenu();
+ expect(deps.createTray).not.toHaveBeenCalled();
+ controller.ensure();
+ controller.dispose();
+ controller.dispose();
+ controller.refreshMenu();
+ expect(tray.destroy).toHaveBeenCalledOnce();
+ expect(tray.setContextMenu).toHaveBeenCalledOnce();
+ });
+
+ it('cleans up a partially initialized icon and reports setup failure', () => {
+ const { tray, deps, controller } = harness();
+ const error = new Error('menu unavailable');
+ tray.setContextMenu.mockImplementation(() => {
+ throw error;
+ });
+ expect(controller.ensure()).toBe(false);
+ expect(tray.destroy).toHaveBeenCalledOnce();
+ expect(deps.onError).toHaveBeenCalledWith(error);
+ });
+
+ it('does not throw if the desktop cannot create a tray', () => {
+ const { deps, controller } = harness();
+ deps.createTray.mockImplementation(() => {
+ throw new Error('no tray');
+ });
+ expect(controller.ensure()).toBe(false);
+ expect(deps.onError).toHaveBeenCalledOnce();
+ });
+
+ it('reports refresh failure while preserving the existing icon', () => {
+ const { tray, deps, controller } = harness();
+ controller.ensure();
+ deps.buildMenu.mockImplementation(() => {
+ throw new Error('menu failure');
+ });
+ controller.refreshMenu();
+ expect(deps.onError).toHaveBeenCalledOnce();
+ expect(tray.destroy).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 17dbe9b41d..68c74ea4ec 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1012,6 +1012,7 @@ import {
popUpWindowsTrayMenu,
requestWindowsTrayQuit,
} from './windowsTrayLifecycle.js';
+import { createLinuxTrayController } from './linuxTrayLifecycle.js';
import {
applyLinuxMainWindowCloseBehavior,
createCloseBehaviorPromptFallbackController,
@@ -3025,7 +3026,7 @@ ipcMain.handle('app-menu:set-locale', (_event, locale: unknown): { ok: true } =>
if (mainWindow) {
installApplicationMenu(mainWindow, currentApplicationMenuLocale);
}
- invalidateWindowsTrayMenu();
+ refreshDesktopTrayMenus();
getAgentIslandService()?.refreshLocalization();
refreshMenubarLocalization();
return { ok: true };
@@ -3187,7 +3188,7 @@ const activeWindowsTrayMenus = new Set<Menu>();
const windowsTrayLog = createLogger('windows-tray');
const CLOSE_BEHAVIOR_PROMPT_FALLBACK_DELAY_MS = 2_000;
-function buildWindowsTrayMenu(): Menu {
+function buildDesktopTrayMenu(): Menu {
return Menu.buildFromTemplate([
{
label: t('settings.windowBehavior.trayMenu.show'),
@@ -3197,14 +3198,15 @@ function buildWindowsTrayMenu(): Menu {
{ type: 'separator' },
{
label: t('settings.windowBehavior.trayMenu.quit'),
- click: () => quitFromWindowsTray(),
+ click: () => quitFromDesktopTray(),
},
]);
}
-/** 语言切换后丢弃缓存的菜单,下一次右键按新语言重建。 */
-function invalidateWindowsTrayMenu(): void {
+/** Windows rebuilds lazily on right-click; Linux must republish its native menu. */
+function refreshDesktopTrayMenus(): void {
windowsTrayMenu = null;
+ linuxTray.refreshMenu();
}
function openWindowsTrayMenu(): void {
@@ -3218,7 +3220,7 @@ function openWindowsTrayMenu(): void {
popUpWindowsTrayMenu<Menu>({
tray: windowsTray,
menu: windowsTrayMenu,
- buildMenu: buildWindowsTrayMenu,
+ buildMenu: buildDesktopTrayMenu,
retainMenu: (menu) => {
windowsTrayMenu = menu;
},
@@ -3239,7 +3241,7 @@ function openWindowsTrayMenu(): void {
});
}
-function quitFromWindowsTray(): void {
+function quitFromDesktopTray(): void {
requestWindowsTrayQuit({
hasActiveTurn: () => {
try {
@@ -3270,6 +3272,26 @@ function destroyWindowsTray(): void {
windowsTrayMenu = null;
}
+const linuxTrayLog = createLogger('linux-tray');
+const linuxTray = createLinuxTrayController<Menu>({
+ createTray: () => {
+ 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}`);
+ // Keep the source resolution: Linux panels choose their own icon size/scale.
+ return new Tray(icon);
+ },
+ buildMenu: buildDesktopTrayMenu,
+ showWindow: () => focusMainWindow(),
+ onError: (error) => {
+ linuxTrayLog.error('Linux tray operation failed', {
+ error: error instanceof Error ? error.message : String(error),
+ });
+ },
+});
+
function ensureWindowsTray(): boolean {
if (windowsTray && !windowsTray.isDestroyed()) return true;
@@ -3433,6 +3455,7 @@ app.on('before-quit', () => {
windowsClosePromptFallback.dispose();
linuxClosePromptFallback.dispose();
destroyWindowsTray();
+ linuxTray.dispose();
disposeUpdatePresentationRecovery();
authCredentialRecovery.dispose();
});
@@ -3957,6 +3980,9 @@ const createWindow = () => {
void ensureMainAppPresence('main-window-created', mainWindow);
// Keep diagnostics reachable from the tray even before login or if the renderer fails.
if (process.platform === 'win32') ensureWindowsTray();
+ // Tray construction is not proof that a Linux panel hosts the icon. Keep the
+ // existing minimize/quit close choices so an absent tray never strands a hidden window.
+ if (process.platform === 'linux') linuxTray.ensure();
installApplicationMenu(
mainWindow,
diff --git a/apps/desktop/src/main/linuxTrayLifecycle.ts b/apps/desktop/src/main/linuxTrayLifecycle.ts
new file mode 100644
index 0000000000..491616d45e
--- /dev/null
+++ b/apps/desktop/src/main/linuxTrayLifecycle.ts
@@ -0,0 +1,54 @@
+/** Linux exposes its menu through StatusNotifierItem/DBus, not Windows right-click events. */
+export interface LinuxTray<TMenu> {
+ isDestroyed(): boolean;
+ destroy(): void;
+ setContextMenu(menu: TMenu): void;
+ on(event: 'click', listener: () => void): unknown;
+}
+
+export interface LinuxTrayDependencies<TMenu> {
+ createTray(): LinuxTray<TMenu>;
+ buildMenu(): TMenu;
+ showWindow(): void;
+ onError(error: unknown): void;
+}
+
+/** Own one icon for the app lifetime; menu updates must be republished on Linux. */
+export function createLinuxTrayController<TMenu>(deps: LinuxTrayDependencies<TMenu>) {
+ let tray: LinuxTray<TMenu> | null = null;
+
+ const dispose = (): void => {
+ const previous = tray;
+ tray = null;
+ try {
+ if (previous && !previous.isDestroyed()) previous.destroy();
+ } catch (error) {
+ deps.onError(error);
+ }
+ };
+
+ return {
+ ensure(): boolean {
+ if (tray && !tray.isDestroyed()) return true;
+ try {
+ tray = deps.createTray();
+ tray.setContextMenu(deps.buildMenu());
+ tray.on('click', deps.showWindow);
+ return true;
+ } catch (error) {
+ dispose();
+ deps.onError(error);
+ return false;
+ }
+ },
+ refreshMenu(): void {
+ if (!tray || tray.isDestroyed()) return;
+ try {
+ tray.setContextMenu(deps.buildMenu());
+ } catch (error) {
+ deps.onError(error);
+ }
+ },
+ dispose,
+ };
+}
diff --git a/docs/dev-rules/desktop-development.md b/docs/dev-rules/desktop-development.md
index ea239fa1ea..51938813c5 100644
--- a/docs/dev-rules/desktop-development.md
+++ b/docs/dev-rules/desktop-development.md
@@ -203,6 +203,19 @@ pnpm test:unit
对应规则,不以本页命令替代专项验证。
- 记录实际执行和结果;未执行的高相关检查必须说明原因。
+## Linux 系统托盘
+
+Linux 主窗口创建时注册 Electron Tray,提供显示主窗口、打开日志目录、退出 Cindy。
+与 Windows 共用菜单动作和活动任务退出确认,但 Linux 使用 `setContextMenu` 发布原生
+菜单,切换语言后重新发布;不依赖仅 Windows/macOS 提供的 `right-click` 事件。
+实现见 `main/linuxTrayLifecycle.ts` 与 `bootstrap-electron.ts`,回归见
+`main/__tests__/linuxTrayLifecycle.test.ts`。
+
+图标创建成功不代表桌面面板一定显示它,因此关闭主窗口仍保留 Linux 原有的
+「最小化/退出」选择,不自动隐藏到托盘,也不迁移用户已有偏好。无托盘宿主或初始化失败
+不阻止主窗口使用。托盘实际显示、激活、菜单与退出须在 Linux 桌面验证;macOS 上的
+单测不能替代 Omarchy/Hyprland、GNOME 或 KDE 的实机验收。
+
## Windows 窗口恢复实验
Windows 偶发黑屏/灰屏的后台节流对照实验见