Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(desktop): redesign the tray menu (#17048)

Innei350b8cc4af7a
diff --git a/apps/desktop/resources/locales/en/menu.json b/apps/desktop/resources/locales/en/menu.json
index 1000bd40a42..fcfbfcf2d92 100644
--- a/apps/desktop/resources/locales/en/menu.json
+++ b/apps/desktop/resources/locales/en/menu.json
@@ -70,10 +70,17 @@
"macOS.preferences": "Preferences...",
"macOS.services": "Services",
"macOS.unhide": "Show All",
+ "tray.more": "More",
+ "tray.moreAgents": "More Agents",
+ "tray.newChat": "New Chat",
"tray.open": "Open {{appName}}",
"tray.openMiniToolbar": "Quick Composer",
+ "tray.pinned": "Pinned",
"tray.quickChat": "Quick Chat",
"tray.quit": "Quit",
+ "tray.recent": "Recent",
+ "tray.recentAgents": "Recent Agents",
+ "tray.settings": "Settings",
"tray.show": "Show {{appName}}",
"view.forceReload": "Force Reload",
"view.reload": "Reload",
diff --git a/apps/desktop/resources/locales/zh-CN/menu.json b/apps/desktop/resources/locales/zh-CN/menu.json
index 9ac727b1004..95a9accb95a 100644
--- a/apps/desktop/resources/locales/zh-CN/menu.json
+++ b/apps/desktop/resources/locales/zh-CN/menu.json
@@ -73,10 +73,17 @@
"macOS.preferences": "偏好设置…",
"macOS.services": "服务",
"macOS.unhide": "全部显示",
+ "tray.more": "更多",
+ "tray.moreAgents": "更多智能体",
+ "tray.newChat": "新建对话",
"tray.open": "打开 {{appName}}",
"tray.openMiniToolbar": "Quick Composer",
+ "tray.pinned": "已置顶",
"tray.quickChat": "快捷聊天",
"tray.quit": "退出",
+ "tray.recent": "最近访问",
+ "tray.recentAgents": "最近使用的智能体",
+ "tray.settings": "设置",
"tray.show": "显示 {{appName}}",
"view.forceReload": "强制重新加载",
"view.reload": "重新加载",
diff --git a/apps/desktop/src/main/controllers/TrayMenuCtr.ts b/apps/desktop/src/main/controllers/TrayMenuCtr.ts
index 62a4ad62bbe..5ddc966479f 100644
--- a/apps/desktop/src/main/controllers/TrayMenuCtr.ts
+++ b/apps/desktop/src/main/controllers/TrayMenuCtr.ts
@@ -1,5 +1,6 @@
import type {
ShowTrayNotificationParams,
+ TrayNavigationSnapshot,
UpdateTrayIconParams,
UpdateTrayTooltipParams,
} from '@lobechat/electron-client-ipc';
@@ -39,6 +40,13 @@ export default class TrayMenuCtr extends ControllerModule {
return { success: true };
}
+ @IpcMethod()
+ updateNavigationSnapshot(snapshot: TrayNavigationSnapshot) {
+ this.app.trayManager.updateNavigationSnapshot(snapshot);
+
+ return { success: true as const };
+ }
+
/**
* Show tray balloon notification
* @param options Balloon options
diff --git a/apps/desktop/src/main/controllers/__tests__/TrayMenuCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/TrayMenuCtr.test.ts
index 8e45e3866b4..6bef66cf1a4 100644
--- a/apps/desktop/src/main/controllers/__tests__/TrayMenuCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/TrayMenuCtr.test.ts
@@ -1,5 +1,6 @@
import type {
ShowTrayNotificationParams,
+ TrayNavigationSnapshot,
UpdateTrayIconParams,
UpdateTrayTooltipParams,
} from '@lobechat/electron-client-ipc';
@@ -41,6 +42,7 @@ const mockUpdateIcon = vi.fn();
const mockUpdateTooltip = vi.fn();
const mockGetMainTray = vi.fn();
const mockSetAppTrayVisible = vi.fn();
+const mockUpdateNavigationSnapshot = vi.fn();
const mockStoreGet = vi.fn(() => true);
const mockStoreSet = vi.fn();
@@ -55,6 +57,7 @@ const mockApp = {
trayManager: {
getMainTray: mockGetMainTray,
setAppTrayVisible: mockSetAppTrayVisible,
+ updateNavigationSnapshot: mockUpdateNavigationSnapshot,
},
} as unknown as App;
@@ -91,6 +94,21 @@ describe('TrayMenuCtr', () => {
});
});
+ describe('updateNavigationSnapshot', () => {
+ it('should pass the latest navigation snapshot to the tray manager', () => {
+ const snapshot: TrayNavigationSnapshot = {
+ agents: [{ id: 'agent-1', title: 'Researcher', url: '/agent/agent-1' }],
+ pinned: [{ title: 'Pinned task', url: '/tasks/pinned' }],
+ recent: [{ title: 'Recent page', url: '/page/recent' }],
+ };
+
+ const result = trayMenuCtr.updateNavigationSnapshot(snapshot);
+
+ expect(mockUpdateNavigationSnapshot).toHaveBeenCalledWith(snapshot);
+ expect(result).toEqual({ success: true });
+ });
+ });
+
// Restore platform settings after all tests complete
afterAll(() => {
// Restore the original platform
diff --git a/apps/desktop/src/main/core/ui/MenuManager.ts b/apps/desktop/src/main/core/ui/MenuManager.ts
index 9513a8db55d..ab05bb1117c 100644
--- a/apps/desktop/src/main/core/ui/MenuManager.ts
+++ b/apps/desktop/src/main/core/ui/MenuManager.ts
@@ -1,6 +1,7 @@
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
import type { Menu } from 'electron';
-import type {IMenuPlatform, MenuOptions } from '@/menus';
+import type { IMenuPlatform, MenuOptions } from '@/menus';
import { createMenuImpl } from '@/menus';
import { createLogger } from '@/utils/logger';
@@ -40,9 +41,9 @@ export class MenuManager {
/**
* Build tray menu (usually called by tray manager)
*/
- buildTrayMenu(): Menu {
+ buildTrayMenu(snapshot?: TrayNavigationSnapshot): Menu {
logger.debug('Building tray menu');
- return this.platformImpl.buildTrayMenu();
+ return this.platformImpl.buildTrayMenu(snapshot);
}
/**
diff --git a/apps/desktop/src/main/core/ui/Tray.ts b/apps/desktop/src/main/core/ui/Tray.ts
index f827be25b87..f7f1af9cec4 100644
--- a/apps/desktop/src/main/core/ui/Tray.ts
+++ b/apps/desktop/src/main/core/ui/Tray.ts
@@ -9,18 +9,14 @@ import type {
import { app, Menu, nativeImage, Tray as ElectronTray } from 'electron';
import { resourcesDir } from '@/const/dir';
+import { isWindows } from '@/const/env';
import { createLogger } from '@/utils/logger';
import type { App } from '../App';
// Create logger
const logger = createLogger('core:Tray');
-
-// Debounce window for distinguishing a single-click from the leading edge of
-// a double-click. Electron delivers two `click` events before `double-click`,
-// so we defer the single-click action until this window passes — the
-// `double-click` handler clears it if it arrives in time.
-const CLICK_DEBOUNCE_MS = 250;
+const WINDOWS_CLICK_DEBOUNCE_MS = 250;
export interface TrayOptions {
/**
@@ -60,10 +56,7 @@ export class Tray {
*/
private _contextMenu?: ElectronMenu;
- /**
- * Pending single-click timer. Cleared by the double-click handler so a
- * double-click never accidentally fires startSession before showMainWindow.
- */
+ /** Pending Windows click while Electron determines whether it is a double-click. */
private _clickTimer?: NodeJS.Timeout;
/**
@@ -130,35 +123,38 @@ export class Tray {
// Set default context menu
this.setContextMenu();
- // Left-click: deferred so a follow-up `double-click` can pre-empt it.
+ // Both mouse buttons expose the same native menu.
this._tray.on('click', () => {
logger.debug(`[${this.identifier}] Tray clicked`);
+ if (!isWindows) {
+ this.popUpMenu();
+ return;
+ }
+
if (this._clickTimer) clearTimeout(this._clickTimer);
this._clickTimer = setTimeout(() => {
this._clickTimer = undefined;
- this.onClick();
- }, CLICK_DEBOUNCE_MS);
+ this.popUpMenu();
+ }, WINDOWS_CLICK_DEBOUNCE_MS);
});
- // Double-click (macOS / Windows): cancel the pending single-click and
- // surface the main window instead.
- this._tray.on('double-click', () => {
- logger.debug(`[${this.identifier}] Tray double-clicked`);
- if (this._clickTimer) {
- clearTimeout(this._clickTimer);
- this._clickTimer = undefined;
- }
- this.onDoubleClick();
- });
+ if (isWindows) {
+ this._tray.on('double-click', () => {
+ logger.debug(`[${this.identifier}] Tray double-clicked`);
+ if (this._clickTimer) {
+ clearTimeout(this._clickTimer);
+ this._clickTimer = undefined;
+ }
+ this.app.browserManager.showMainWindow();
+ });
+ }
// Right-click: pop the stored context menu manually so left-click stays
// free (macOS would auto-open the menu on either button if we called
// `_tray.setContextMenu`).
this._tray.on('right-click', () => {
logger.debug(`[${this.identifier}] Tray right-clicked`);
- if (this._contextMenu && this._tray) {
- this._tray.popUpContextMenu(this._contextMenu);
- }
+ this.popUpMenu();
});
logger.debug(`[${this.identifier}] Tray instance created successfully`);
@@ -203,31 +199,6 @@ export class Tray {
logger.debug(`[${this.identifier}] Tray context menu has been set`);
}
- /**
- * Handle tray click event — opens the Quick Composer overlay.
- * Right-click opens the context menu (handled by Electron automatically).
- */
- onClick() {
- logger.debug(`[${this.identifier}] Tray click → startSession`);
- try {
- void this.app.screenCaptureManager.startSession();
- } catch (error) {
- logger.error(`[${this.identifier}] Failed to start capture session:`, error);
- }
- }
-
- /**
- * Handle tray double-click event — surfaces the main window.
- */
- onDoubleClick() {
- logger.debug(`[${this.identifier}] Tray double-click → showMainWindow`);
- try {
- this.app.browserManager.showMainWindow();
- } catch (error) {
- logger.error(`[${this.identifier}] Failed to show main window:`, error);
- }
- }
-
/**
* Replace the tray context menu with a pre-built Electron Menu instance.
* Stored in-house and popped up manually on right-click to preserve
@@ -238,6 +209,12 @@ export class Tray {
this._contextMenu = menu;
}
+ private popUpMenu() {
+ if (this._contextMenu && this._tray) {
+ this._tray.popUpContextMenu(this._contextMenu);
+ }
+ }
+
/**
* Update tray icon
* @param iconPath New icon path (relative to resource directory)
diff --git a/apps/desktop/src/main/core/ui/TrayManager.ts b/apps/desktop/src/main/core/ui/TrayManager.ts
index 9ebd5b76759..93b5b119fc5 100644
--- a/apps/desktop/src/main/core/ui/TrayManager.ts
+++ b/apps/desktop/src/main/core/ui/TrayManager.ts
@@ -1,4 +1,8 @@
-import type { MainBroadcastEventKey, MainBroadcastParams } from '@lobechat/electron-client-ipc';
+import type {
+ MainBroadcastEventKey,
+ MainBroadcastParams,
+ TrayNavigationSnapshot,
+} from '@lobechat/electron-client-ipc';
import { name } from '@/../../package.json';
import { isMac } from '@/const/env';
@@ -18,6 +22,7 @@ export type TrayIdentifiers = 'main';
export class TrayManager {
app: App;
+ private navigationSnapshot: TrayNavigationSnapshot = { agents: [], pinned: [], recent: [] };
/**
* Store all tray instances
@@ -51,7 +56,7 @@ export class TrayManager {
// Attach the platform-specific context menu built by MenuManager so the
// tray right-click entries stay in sync with the app menu i18n.
try {
- mainTray.setMenu(this.app.menuManager.buildTrayMenu());
+ mainTray.setMenu(this.app.menuManager.buildTrayMenu(this.navigationSnapshot));
} catch (error) {
logger.error('Failed to attach tray context menu:', error);
}
@@ -77,6 +82,12 @@ export class TrayManager {
}
}
+ updateNavigationSnapshot(snapshot: TrayNavigationSnapshot) {
+ this.navigationSnapshot = snapshot;
+ const mainTray = this.getMainTray();
+ if (mainTray) mainTray.setMenu(this.app.menuManager.buildTrayMenu(snapshot));
+ }
+
/**
* Initialize main tray. On macOS we ship a template image (black + alpha)
* so the system recolors it automatically for light / dark menu bars.
diff --git a/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts b/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts
index c95ad61a4d0..f9e8d0022ba 100644
--- a/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts
+++ b/apps/desktop/src/main/core/ui/__tests__/Tray.test.ts
@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import type { App } from '../../App';
import { Tray } from '../Tray';
+const mockEnv = vi.hoisted(() => ({ isWindows: false }));
+
// Mock electron modules
vi.mock('electron', () => ({
Tray: vi.fn(),
@@ -33,6 +35,8 @@ vi.mock('@/const/dir', () => ({
resourcesDir: '/mock/resources',
}));
+vi.mock('@/const/env', () => mockEnv);
+
describe('Tray', () => {
let tray: Tray;
let mockApp: App;
@@ -42,6 +46,7 @@ describe('Tray', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mockEnv.isWindows = false;
// Mock Electron Tray instance
mockElectronTray = {
@@ -189,7 +194,7 @@ describe('Tray', () => {
expect(mockElectronTray.setContextMenu).not.toHaveBeenCalled();
});
- it('should register click, double-click and right-click listeners', () => {
+ it('should register click and right-click listeners only', () => {
tray = new Tray(
{
iconPath: 'tray.png',
@@ -200,8 +205,8 @@ describe('Tray', () => {
const events = mockElectronTray.on.mock.calls.map((c: any[]) => c[0]);
expect(events).toContain('click');
- expect(events).toContain('double-click');
expect(events).toContain('right-click');
+ expect(events).not.toContain('double-click');
});
it('should handle errors when creating tray', () => {
@@ -314,126 +319,60 @@ describe('Tray', () => {
});
});
- describe('onClick', () => {
- beforeEach(() => {
- tray = new Tray(
- {
- iconPath: 'tray.png',
- identifier: 'test-tray',
- },
- mockApp,
- );
- });
-
- it('should start the Quick Composer capture session', () => {
- tray.onClick();
-
- expect(mockApp.screenCaptureManager.startSession).toHaveBeenCalled();
- });
-
- it('should not touch main window visibility', () => {
- tray.onClick();
-
- expect(mockMainWindow.hide).not.toHaveBeenCalled();
- expect(mockMainWindow.show).not.toHaveBeenCalled();
- });
-
- it('should not throw when startSession rejects', () => {
- vi.mocked(mockApp.screenCaptureManager.startSession).mockImplementationOnce(() => {
- throw new Error('capture failed');
- });
-
- expect(() => tray.onClick()).not.toThrow();
- });
- });
-
- describe('onDoubleClick', () => {
- beforeEach(() => {
- tray = new Tray(
- {
- iconPath: 'tray.png',
- identifier: 'test-tray',
- },
- mockApp,
- );
- });
-
- it('should show the main window', () => {
- tray.onDoubleClick();
-
- expect(mockApp.browserManager.showMainWindow).toHaveBeenCalled();
- });
+ describe('mouse interaction', () => {
+ it.each(['click', 'right-click'])('should open the same menu on %s', (event) => {
+ const builtMenu = { _mockMenu: true } as any;
+ vi.mocked(Menu.buildFromTemplate).mockReturnValue(builtMenu);
+ tray = new Tray({ iconPath: 'tray.png', identifier: 'test-tray' }, mockApp);
+ const handler = mockElectronTray.on.mock.calls.find((call: any[]) => call[0] === event)?.[1];
- it('should not start the capture session', () => {
- tray.onDoubleClick();
+ handler?.();
+ expect(mockElectronTray.popUpContextMenu).toHaveBeenCalledWith(builtMenu);
expect(mockApp.screenCaptureManager.startSession).not.toHaveBeenCalled();
+ expect(mockApp.browserManager.showMainWindow).not.toHaveBeenCalled();
});
- it('should not throw when showMainWindow throws', () => {
- vi.mocked(mockApp.browserManager.showMainWindow).mockImplementationOnce(() => {
- throw new Error('window failed');
- });
-
- expect(() => tray.onDoubleClick()).not.toThrow();
- });
- });
-
- describe('click vs double-click handling', () => {
- let clickHandler: (() => void) | undefined;
- let doubleClickHandler: (() => void) | undefined;
-
- beforeEach(() => {
+ it('should preserve Windows double-click to show the main window', () => {
vi.useFakeTimers();
- tray = new Tray(
- {
- iconPath: 'tray.png',
- identifier: 'test-tray',
- },
- mockApp,
- );
-
- clickHandler = mockElectronTray.on.mock.calls.find((c: any[]) => c[0] === 'click')?.[1];
- doubleClickHandler = mockElectronTray.on.mock.calls.find(
- (c: any[]) => c[0] === 'double-click',
+ mockEnv.isWindows = true;
+ const builtMenu = { _mockMenu: true } as any;
+ vi.mocked(Menu.buildFromTemplate).mockReturnValue(builtMenu);
+ tray = new Tray({ iconPath: 'tray.png', identifier: 'windows-tray' }, mockApp);
+ const clickHandler = mockElectronTray.on.mock.calls.find(
+ (call: any[]) => call[0] === 'click',
+ )?.[1];
+ const doubleClickHandler = mockElectronTray.on.mock.calls.find(
+ (call: any[]) => call[0] === 'double-click',
)?.[1];
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it('should debounce single click before calling startSession', () => {
- expect(clickHandler).toBeDefined();
-
- clickHandler?.();
- expect(mockApp.screenCaptureManager.startSession).not.toHaveBeenCalled();
-
- vi.advanceTimersByTime(250);
- expect(mockApp.screenCaptureManager.startSession).toHaveBeenCalledTimes(1);
- });
-
- it('should cancel the pending single click when double-click fires', () => {
- expect(clickHandler).toBeDefined();
- expect(doubleClickHandler).toBeDefined();
- clickHandler?.();
clickHandler?.();
doubleClickHandler?.();
-
vi.advanceTimersByTime(1000);
- expect(mockApp.screenCaptureManager.startSession).not.toHaveBeenCalled();
+ expect(doubleClickHandler).toBeDefined();
+ expect(mockElectronTray.popUpContextMenu).not.toHaveBeenCalled();
expect(mockApp.browserManager.showMainWindow).toHaveBeenCalledTimes(1);
+ vi.useRealTimers();
});
- it('should only fire startSession once per single-click burst', () => {
- clickHandler?.();
- clickHandler?.();
+ it('should still open the tray menu on a Windows single click', () => {
+ vi.useFakeTimers();
+ mockEnv.isWindows = true;
+ const builtMenu = { _mockMenu: true } as any;
+ vi.mocked(Menu.buildFromTemplate).mockReturnValue(builtMenu);
+ tray = new Tray({ iconPath: 'tray.png', identifier: 'windows-tray' }, mockApp);
+ const clickHandler = mockElectronTray.on.mock.calls.find(
+ (call: any[]) => call[0] === 'click',
+ )?.[1];
+ clickHandler?.();
+ expect(mockElectronTray.popUpContextMenu).not.toHaveBeenCalled();
vi.advanceTimersByTime(250);
- expect(mockApp.screenCaptureManager.startSession).toHaveBeenCalledTimes(1);
+ expect(mockElectronTray.popUpContextMenu).toHaveBeenCalledWith(builtMenu);
+ expect(mockApp.browserManager.showMainWindow).not.toHaveBeenCalled();
+ vi.useRealTimers();
});
});
@@ -632,9 +571,13 @@ describe('Tray', () => {
tray.updateTooltip('New Tooltip');
expect(mockElectronTray.setToolTip).toHaveBeenCalledWith('New Tooltip');
- // Test click behavior — now opens the Quick Composer session
- tray.onClick();
- expect(mockApp.screenCaptureManager.startSession).toHaveBeenCalled();
+ // Test click behavior — opens the stored native menu
+ const clickHandler = mockElectronTray.on.mock.calls.find(
+ (call: any[]) => call[0] === 'click',
+ )?.[1];
+ clickHandler?.();
+ expect(mockElectronTray.popUpContextMenu).toHaveBeenCalled();
+ expect(mockApp.screenCaptureManager.startSession).not.toHaveBeenCalled();
// Destroy
tray.destroy();
diff --git a/apps/desktop/src/main/locales/default/menu.ts b/apps/desktop/src/main/locales/default/menu.ts
index d2988adaeca..7f6001dcebf 100644
--- a/apps/desktop/src/main/locales/default/menu.ts
+++ b/apps/desktop/src/main/locales/default/menu.ts
@@ -74,9 +74,15 @@ const menu = {
'macOS.services': 'Services',
'macOS.unhide': 'Show All',
'tray.openMiniToolbar': 'Quick Composer',
+ 'tray.more': 'More',
+ 'tray.moreAgents': 'More Agents',
+ 'tray.newChat': 'New Chat',
'tray.open': 'Open {{appName}}',
+ 'tray.pinned': 'Pinned',
'tray.quickChat': 'Quick Chat',
'tray.quit': 'Quit',
+ 'tray.recent': 'Recent',
+ 'tray.recentAgents': 'Recent Agents',
'tray.settings': 'Settings',
'tray.show': 'Show {{appName}}',
'view.forceReload': 'Force Reload',
diff --git a/apps/desktop/src/main/menus/impls/linux.ts b/apps/desktop/src/main/menus/impls/linux.ts
index 8b8a7f2a7b4..4fdd5691f81 100644
--- a/apps/desktop/src/main/menus/impls/linux.ts
+++ b/apps/desktop/src/main/menus/impls/linux.ts
@@ -1,11 +1,13 @@
import path from 'node:path';
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
import type { MenuItemConstructorOptions } from 'electron';
import { app, clipboard, dialog, Menu, shell } from 'electron';
import { isDev } from '@/const/env';
import { HETERO_AGENT_DIR } from '@/const/heteroAgent';
+import { buildTrayMenuTemplate } from '../trayMenu';
import type { ContextMenuData, IMenuPlatform, MenuOptions } from '../types';
import { BaseMenuPlatform } from './BaseMenuPlatform';
@@ -38,8 +40,8 @@ export class LinuxMenu extends BaseMenuPlatform implements IMenuPlatform {
return Menu.buildFromTemplate(template);
}
- buildTrayMenu(): Menu {
- const template = this.getTrayMenuTemplate();
+ buildTrayMenu(snapshot: TrayNavigationSnapshot = { agents: [], pinned: [], recent: [] }): Menu {
+ const template = buildTrayMenuTemplate(this.app, snapshot);
this.trayMenu = Menu.buildFromTemplate(template);
return this.trayMenu;
}
diff --git a/apps/desktop/src/main/menus/impls/macOS.test.ts b/apps/desktop/src/main/menus/impls/macOS.test.ts
index 85f7e8c741b..6b4bdc1025e 100644
--- a/apps/desktop/src/main/menus/impls/macOS.test.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.test.ts
@@ -186,12 +186,12 @@ describe('MacOSMenu', () => {
expect(menu).toBeDefined();
});
- it('should include show and quit items in tray menu', () => {
+ it('should include open and quit items in tray menu', () => {
macOSMenu.buildTrayMenu();
const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
expect(template.length).toBeGreaterThan(0);
- expect(template.some((item: any) => item.label?.includes('Show'))).toBe(true);
+ expect(template.some((item: any) => item.label?.includes('Open'))).toBe(true);
expect(template.some((item: any) => item.label === 'Settings')).toBe(true);
expect(template.some((item: any) => item.label === 'Quit')).toBe(true);
});
@@ -283,11 +283,11 @@ describe('MacOSMenu', () => {
expect(shell.openPath).toHaveBeenCalledWith('/path/to/logs');
});
- it('should handle tray show click', () => {
+ it('should handle tray open click', () => {
macOSMenu.buildTrayMenu();
const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
- const showItem = template.find((item: any) => item.label?.includes('Show'));
+ const showItem = template.find((item: any) => item.label?.includes('Open'));
expect(showItem).toBeDefined();
showItem.click();
diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.ts
index fc4a365d423..ea52c8a9257 100644
--- a/apps/desktop/src/main/menus/impls/macOS.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.ts
@@ -1,5 +1,6 @@
import path from 'node:path';
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
import type { MenuItemConstructorOptions } from 'electron';
import { app, clipboard, Menu, shell } from 'electron';
@@ -8,6 +9,7 @@ import { HETERO_AGENT_DIR } from '@/const/heteroAgent';
import NotificationCtr from '@/controllers/NotificationCtr';
import SystemController from '@/controllers/SystemCtr';
+import { buildTrayMenuTemplate } from '../trayMenu';
import type { ContextMenuData, IMenuPlatform, MenuOptions } from '../types';
import { BaseMenuPlatform } from './BaseMenuPlatform';
@@ -45,8 +47,8 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {
return Menu.buildFromTemplate(template);
}
- buildTrayMenu(): Menu {
- const template = this.getTrayMenuTemplate();
+ buildTrayMenu(snapshot: TrayNavigationSnapshot = { agents: [], pinned: [], recent: [] }): Menu {
+ const template = buildTrayMenuTemplate(this.app, snapshot);
this.trayMenu = Menu.buildFromTemplate(template);
return this.trayMenu;
}
diff --git a/apps/desktop/src/main/menus/impls/windows.ts b/apps/desktop/src/main/menus/impls/windows.ts
index 9a383192d5b..3062b1e79a4 100644
--- a/apps/desktop/src/main/menus/impls/windows.ts
+++ b/apps/desktop/src/main/menus/impls/windows.ts
@@ -1,11 +1,13 @@
import path from 'node:path';
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
import type { MenuItemConstructorOptions } from 'electron';
import { app, clipboard, Menu, shell } from 'electron';
import { isDev } from '@/const/env';
import { HETERO_AGENT_DIR } from '@/const/heteroAgent';
+import { buildTrayMenuTemplate } from '../trayMenu';
import type { ContextMenuData, IMenuPlatform, MenuOptions } from '../types';
import { BaseMenuPlatform } from './BaseMenuPlatform';
@@ -38,8 +40,8 @@ export class WindowsMenu extends BaseMenuPlatform implements IMenuPlatform {
return Menu.buildFromTemplate(template);
}
- buildTrayMenu(): Menu {
- const template = this.getTrayMenuTemplate();
+ buildTrayMenu(snapshot: TrayNavigationSnapshot = { agents: [], pinned: [], recent: [] }): Menu {
+ const template = buildTrayMenuTemplate(this.app, snapshot);
this.trayMenu = Menu.buildFromTemplate(template);
return this.trayMenu;
}
diff --git a/apps/desktop/src/main/menus/trayMenu.test.ts b/apps/desktop/src/main/menus/trayMenu.test.ts
new file mode 100644
index 00000000000..537010b044d
--- /dev/null
+++ b/apps/desktop/src/main/menus/trayMenu.test.ts
@@ -0,0 +1,130 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+
+import { buildTrayMenuTemplate } from './trayMenu';
+
+const createApp = () => {
+ const mainWindow = {
+ broadcast: vi.fn(),
+ show: vi.fn(),
+ };
+ const app = {
+ browserManager: {
+ getMainWindow: vi.fn(() => mainWindow),
+ openQuickChatPopup: vi.fn(),
+ showMainWindow: vi.fn(),
+ },
+ i18n: {
+ ns: vi.fn(() => (key: string) => key),
+ },
+ screenCaptureManager: {
+ startSession: vi.fn(),
+ },
+ } as unknown as App;
+
+ return { app, mainWindow };
+};
+
+describe('buildTrayMenuTemplate', () => {
+ it('keeps static actions when navigation data is empty', () => {
+ const { app } = createApp();
+
+ const template = buildTrayMenuTemplate(app, { agents: [], pinned: [], recent: [] });
+ const labels = template.map((item) => item.label);
+
+ expect(labels).toContain('tray.openMiniToolbar');
+ expect(labels).toContain('tray.quickChat');
+ expect(labels).toContain('tray.newChat');
+ expect(labels).toContain('tray.settings');
+ expect(labels).not.toContain('tray.pinned');
+ expect(labels).not.toContain('tray.recentAgents');
+ expect(labels).not.toContain('tray.recent');
+ });
+
+ it('limits dynamic sections and exposes More actions only on overflow', () => {
+ const { app } = createApp();
+ const template = buildTrayMenuTemplate(app, {
+ agents: Array.from({ length: 4 }, (_, index) => ({
+ id: `agent-${index}`,
+ title: `Agent ${index}`,
+ url: `/agent/agent-${index}`,
+ })),
+ pinned: Array.from({ length: 4 }, (_, index) => ({
+ title: `Pinned ${index}`,
+ url: `/page/pinned-${index}`,
+ })),
+ recent: Array.from({ length: 6 }, (_, index) => ({
+ title: `Recent ${index}`,
+ url: `/page/recent-${index}`,
+ })),
+ });
+ const labels = template.map((item) => item.label);
+
+ expect(labels.filter((label) => String(label).startsWith('Pinned '))).toHaveLength(3);
+ expect(labels.filter((label) => String(label).startsWith('Agent '))).toHaveLength(3);
+ expect(labels.filter((label) => String(label).startsWith('Recent '))).toHaveLength(5);
+ expect(labels).toContain('tray.moreAgents');
+ expect(labels).toContain('tray.more');
+ });
+
+ it('opens dynamic routes in the main window', () => {
+ const { app, mainWindow } = createApp();
+ const template = buildTrayMenuTemplate(app, {
+ agents: [],
+ pinned: [{ title: 'Pinned task', url: '/tasks/pinned' }],
+ recent: [],
+ });
+ const item = template.find(({ label }) => label === 'Pinned task');
+
+ item?.click?.(null as never, null as never, null as never);
+
+ expect(mainWindow.show).toHaveBeenCalled();
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('navigate', {
+ escape: true,
+ path: '/tasks/pinned',
+ });
+ });
+
+ it('renders recent topics and pages as two-line native items', () => {
+ const { app } = createApp();
+ const template = buildTrayMenuTemplate(app, {
+ agents: [],
+ pinned: [],
+ recent: [
+ { subtitle: 'Researcher', title: 'Topic title', url: '/agent/agent-1/topic-1' },
+ { subtitle: 'Page', title: 'Page title', url: '/page/page-1' },
+ ],
+ });
+
+ expect(template.find(({ label }) => label === 'Topic title')).toMatchObject({
+ sublabel: 'Researcher',
+ });
+ expect(template.find(({ label }) => label === 'Page title')).toMatchObject({
+ sublabel: 'Page',
+ });
+ });
+
+ it('keeps restoration and creation as separate actions', () => {
+ const { app, mainWindow } = createApp();
+ const template = buildTrayMenuTemplate(app, {
+ agents: [{ id: 'agent-1', title: 'Researcher', url: '/agent/agent-1' }],
+ pinned: [],
+ recent: [],
+ });
+
+ template
+ .find(({ label }) => label === 'Researcher')
+ ?.click?.(null as never, null as never, null as never);
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('navigate', {
+ escape: true,
+ path: '/agent/agent-1',
+ });
+ expect(mainWindow.broadcast).not.toHaveBeenCalledWith('createNewTopic');
+
+ template
+ .find(({ label }) => label === 'tray.newChat')
+ ?.click?.(null as never, null as never, null as never);
+ expect(mainWindow.broadcast).toHaveBeenCalledWith('createNewTopic');
+ });
+});
diff --git a/apps/desktop/src/main/menus/trayMenu.ts b/apps/desktop/src/main/menus/trayMenu.ts
new file mode 100644
index 00000000000..6605b956d32
--- /dev/null
+++ b/apps/desktop/src/main/menus/trayMenu.ts
@@ -0,0 +1,97 @@
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
+import type { MenuItemConstructorOptions } from 'electron';
+import { app as electronApp } from 'electron';
+
+import type { App } from '@/core/App';
+
+const PINNED_LIMIT = 3;
+const RECENT_AGENT_LIMIT = 3;
+const RECENT_LIMIT = 5;
+
+const openRoute = (app: App, path: string) => {
+ const mainWindow = app.browserManager.getMainWindow();
+ mainWindow.show();
+ mainWindow.broadcast('navigate', { escape: true, path });
+};
+
+const createSection = (
+ label: string,
+ items: MenuItemConstructorOptions[],
+): MenuItemConstructorOptions[] =>
+ items.length > 0 ? [{ enabled: false, label }, ...items, { type: 'separator' }] : [];
+
+export const buildTrayMenuTemplate = (
+ app: App,
+ snapshot: TrayNavigationSnapshot,
+): MenuItemConstructorOptions[] => {
+ const t = app.i18n.ns('menu');
+ const appName = electronApp.getName();
+ const pinnedItems = snapshot.pinned.slice(0, PINNED_LIMIT).map(({ title, url }) => ({
+ click: () => openRoute(app, url),
+ label: title,
+ }));
+ const agentItems: MenuItemConstructorOptions[] = snapshot.agents
+ .slice(0, RECENT_AGENT_LIMIT)
+ .map(({ title, url }) => ({ click: () => openRoute(app, url), label: title }));
+ const recentItems: MenuItemConstructorOptions[] = snapshot.recent
+ .slice(0, RECENT_LIMIT)
+ .map(({ subtitle, title, url }) => ({
+ click: () => openRoute(app, url),
+ label: title,
+ sublabel: subtitle,
+ }));
+
+ if (snapshot.agents.length > RECENT_AGENT_LIMIT) {
+ agentItems.push({
+ click: () => {
+ app.browserManager.showMainWindow();
+ app.browserManager.getMainWindow().broadcast('openAllAgents');
+ },
+ label: t('tray.moreAgents'),
+ });
+ }
+
+ if (snapshot.recent.length > RECENT_LIMIT) {
+ recentItems.push({
+ click: () => {
+ app.browserManager.showMainWindow();
+ app.browserManager.getMainWindow().broadcast('openRecentlyViewed');
+ },
+ label: t('tray.more'),
+ });
+ }
+
+ return [
+ ...createSection(t('tray.pinned'), pinnedItems),
+ ...createSection(t('tray.recentAgents'), agentItems),
+ ...createSection(t('tray.recent'), recentItems),
+ {
+ accelerator: 'Alt+Shift+Space',
+ click: () => app.screenCaptureManager.startSession(),
+ label: t('tray.openMiniToolbar'),
+ },
+ {
+ click: () => app.browserManager.openQuickChatPopup(),
+ label: t('tray.quickChat'),
+ },
+ {
+ click: () => {
+ const mainWindow = app.browserManager.getMainWindow();
+ mainWindow.show();
+ mainWindow.broadcast('createNewTopic');
+ },
+ label: t('tray.newChat'),
+ },
+ { type: 'separator' },
+ {
+ click: () => app.browserManager.showMainWindow(),
+ label: t('tray.open', { appName }),
+ },
+ {
+ click: () => openRoute(app, '/settings'),
+ label: t('tray.settings'),
+ },
+ { type: 'separator' },
+ { label: t('tray.quit'), role: 'quit' },
+ ];
+};
diff --git a/apps/desktop/src/main/menus/types.ts b/apps/desktop/src/main/menus/types.ts
index 9c0993e7bc8..9a44c504df3 100644
--- a/apps/desktop/src/main/menus/types.ts
+++ b/apps/desktop/src/main/menus/types.ts
@@ -1,3 +1,4 @@
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
import type { Menu } from 'electron';
export interface MenuOptions {
@@ -40,7 +41,7 @@ export interface IMenuPlatform {
/**
* Build tray menu
*/
- buildTrayMenu: () => Menu;
+ buildTrayMenu: (snapshot?: TrayNavigationSnapshot) => Menu;
/**
* Refresh menu
diff --git a/packages/electron-client-ipc/src/events/navigation.ts b/packages/electron-client-ipc/src/events/navigation.ts
index 191b59c044a..bb1fcfd71f0 100644
--- a/packages/electron-client-ipc/src/events/navigation.ts
+++ b/packages/electron-client-ipc/src/events/navigation.ts
@@ -51,4 +51,10 @@ export interface NavigationBroadcastEvents {
* Ask renderer to navigate within the SPA without reloading the whole page.
*/
navigate: (data: { escape?: boolean; path: string; replace?: boolean }) => void;
+
+ /** Ask the renderer to open the all-agents surface. */
+ openAllAgents: () => void;
+
+ /** Ask the renderer to open the Recently Viewed surface. */
+ openRecentlyViewed: () => void;
}
diff --git a/packages/electron-client-ipc/src/types/tray.ts b/packages/electron-client-ipc/src/types/tray.ts
index f625bc89045..7eac44e54a2 100644
--- a/packages/electron-client-ipc/src/types/tray.ts
+++ b/packages/electron-client-ipc/src/types/tray.ts
@@ -1,3 +1,21 @@
+export interface TrayAgentItem {
+ id: string;
+ title: string;
+ url: string;
+}
+
+export interface TrayNavigationItem {
+ subtitle?: string;
+ title: string;
+ url: string;
+}
+
+export interface TrayNavigationSnapshot {
+ agents: TrayAgentItem[];
+ pinned: TrayNavigationItem[];
+ recent: TrayNavigationItem[];
+}
+
/**
* Parameters for showing tray notification
*/
diff --git a/src/features/Electron/titlebar/NavigationBar.test.tsx b/src/features/Electron/titlebar/NavigationBar.test.tsx
new file mode 100644
index 00000000000..a28c90be173
--- /dev/null
+++ b/src/features/Electron/titlebar/NavigationBar.test.tsx
@@ -0,0 +1,91 @@
+import { act, render, screen } from '@testing-library/react';
+import type { ReactNode } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import NavigationBar from './NavigationBar';
+
+const mocks = vi.hoisted(() => ({
+ handlers: new Map<string, () => void>(),
+ navigate: vi.fn(),
+ openAllAgentsDrawer: vi.fn(),
+}));
+
+vi.mock('@lobechat/electron-client-ipc', () => ({
+ useWatchBroadcast: (event: string, handler: () => void) => mocks.handlers.set(event, handler),
+}));
+
+vi.mock('@lobehub/ui', () => ({
+ ActionIcon: ({ icon: _icon, ...props }: Record<string, unknown>) => <button {...props} />,
+ Flexbox: ({ children, ...props }: { children: ReactNode }) => <div {...props}>{children}</div>,
+ Popover: ({
+ children,
+ content,
+ open,
+ }: {
+ children: ReactNode;
+ content: ReactNode;
+ open: boolean;
+ }) => (
+ <div>
+ {children}
+ {open && content}
+ </div>
+ ),
+ Tooltip: ({ children }: { children: ReactNode }) => children,
+}));
+
+vi.mock('antd-style', () => ({
+ createStaticStyles: () => ({ clock: 'clock' }),
+}));
+
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
+vi.mock('@/features/NavPanel/ToggleLeftPanelButton', () => ({ default: () => null }));
+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({
+ useWorkspaceAwareNavigate: () => mocks.navigate,
+}));
+vi.mock('@/services/electron/system', () => ({ electronSystemService: {} }));
+vi.mock('@/store/global', () => ({ useGlobalStore: () => 0 }));
+vi.mock('@/store/global/selectors', () => ({ systemStatusSelectors: {} }));
+vi.mock('@/store/home', () => ({
+ getHomeStoreState: () => ({ openAllAgentsDrawer: mocks.openAllAgentsDrawer }),
+}));
+vi.mock('@/store/electron', () => ({
+ useElectronStore: (selector: (state: unknown) => unknown) =>
+ selector({ activeRecentScope: { slug: 'acme', type: 'workspace' } }),
+}));
+vi.mock('@/styles/electron', () => ({ electronStylish: { nodrag: 'nodrag' } }));
+vi.mock('@/utils/platform', () => ({ isMacOS: () => false }));
+vi.mock('../navigation/useNavigationHistory', () => ({
+ useNavigationHistory: () => ({
+ canGoBack: false,
+ canGoForward: false,
+ goBack: vi.fn(),
+ goForward: vi.fn(),
+ }),
+}));
+vi.mock('./RecentlyViewed', () => ({ default: () => <div>recently-viewed</div> }));
+vi.mock('./TrayMenu/useTrayMenuSync', () => ({ useTrayMenuSync: vi.fn() }));
+
+describe('NavigationBar tray broadcasts', () => {
+ beforeEach(() => {
+ mocks.handlers.clear();
+ vi.clearAllMocks();
+ });
+
+ it('opens the existing Recently Viewed popover', () => {
+ render(<NavigationBar />);
+
+ act(() => mocks.handlers.get('openRecentlyViewed')?.());
+
+ expect(screen.getByText('recently-viewed')).toBeInTheDocument();
+ });
+
+ it('opens the workspace agent browser without creating a topic', () => {
+ render(<NavigationBar />);
+
+ act(() => mocks.handlers.get('openAllAgents')?.());
+
+ expect(mocks.navigate).toHaveBeenCalledWith('/acme', { escape: true });
+ expect(mocks.openAllAgentsDrawer).toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Electron/titlebar/NavigationBar.tsx b/src/features/Electron/titlebar/NavigationBar.tsx
index c60bb8d856b..a09b563c3b5 100644
--- a/src/features/Electron/titlebar/NavigationBar.tsx
+++ b/src/features/Electron/titlebar/NavigationBar.tsx
@@ -8,16 +8,20 @@ import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import ToggleLeftPanelButton from '@/features/NavPanel/ToggleLeftPanelButton';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import { electronSystemService } from '@/services/electron/system';
+import { useElectronStore } from '@/store/electron';
import { useGlobalStore } from '@/store/global';
import type { GlobalState } from '@/store/global/initialState';
import { systemStatusSelectors } from '@/store/global/selectors';
+import { getHomeStoreState } from '@/store/home';
import { electronStylish } from '@/styles/electron';
import { isMacOS } from '@/utils/platform';
import { useNavigationHistory } from '../navigation/useNavigationHistory';
import { getMacTrafficLightPadding } from './layout';
import RecentlyViewed from './RecentlyViewed';
+import { useTrayMenuSync } from './TrayMenu/useTrayMenuSync';
const isMac = isMacOS();
@@ -45,10 +49,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const NavigationBar = memo(() => {
+ useTrayMenuSync();
const { t } = useTranslation('electron');
+ const navigate = useWorkspaceAwareNavigate();
const { canGoBack, canGoForward, goBack, goForward } = useNavigationHistory();
const [historyOpen, setHistoryOpen] = useState(false);
const [isWindowFullScreen, setIsWindowFullScreen] = useState(false);
+ const activeRecentScope = useElectronStore((state) => state.activeRecentScope);
const leftPanelWidth = useNavPanelWidth();
@@ -56,6 +63,14 @@ const NavigationBar = memo(() => {
if (isMac) setIsWindowFullScreen(isFullScreen);
});
+ useWatchBroadcast('openRecentlyViewed', () => setHistoryOpen(true));
+
+ useWatchBroadcast('openAllAgents', () => {
+ const homePath = activeRecentScope.type === 'workspace' ? `/${activeRecentScope.slug}` : '/';
+ navigate(homePath, { escape: true });
+ getHomeStoreState().openAllAgentsDrawer();
+ });
+
useEffect(() => {
if (!isMac) return;
diff --git a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts
new file mode 100644
index 00000000000..d77db245ea9
--- /dev/null
+++ b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest';
+
+import type { SidebarAgentItem } from '@/database/repositories/home';
+
+import type { ResolvedTab } from '../TabBar/hooks/useResolvedTabs';
+import { resolveTrayNavigationSnapshot } from './resolveSnapshot';
+
+const page = (title: string, url: string, lastVisited: number): ResolvedTab => ({
+ isActive: false,
+ meta: { title },
+ tab: { id: url, lastVisited, url },
+});
+
+const agent = (id: string, title: string, updatedAt: string): SidebarAgentItem =>
+ ({ id, pinned: false, title, type: 'agent', updatedAt }) as unknown as SidebarAgentItem;
+
+describe('resolveTrayNavigationSnapshot', () => {
+ it('sorts and deduplicates recent agents while preferring their latest visited route', () => {
+ const snapshot = resolveTrayNavigationSnapshot({
+ agents: [
+ agent('agent-1', 'Older duplicate', '2026-07-09T00:00:00.000Z'),
+ agent('agent-2', 'Writer', '2026-07-10T00:00:00.000Z'),
+ agent('agent-1', 'Researcher', '2026-07-11T00:00:00.000Z'),
+ agent('agent-3', 'Planner', '2026-07-08T00:00:00.000Z'),
+ agent('agent-4', 'Reviewer', '2026-07-07T00:00:00.000Z'),
+ ],
+ pinnedPages: [],
+ recentPages: [
+ page('Old Agent Route', '/acme/agent/agent-1/topic-old', 10),
+ page('Latest Agent Route', '/acme/agent/agent-1/topic-latest', 20),
+ ],
+ scope: { slug: 'acme', type: 'workspace' },
+ });
+
+ expect(snapshot.agents.slice(0, 3)).toEqual([
+ { id: 'agent-1', title: 'Researcher', url: '/acme/agent/agent-1/topic-latest' },
+ { id: 'agent-2', title: 'Writer', url: '/acme/agent/agent-2' },
+ { id: 'agent-3', title: 'Planner', url: '/acme/agent/agent-3' },
+ ]);
+ expect(snapshot.agents).toHaveLength(4);
+ });
+
+ it('keeps only concrete topics and pages with a descriptive second line', () => {
+ const snapshot = resolveTrayNavigationSnapshot({
+ agents: [agent('agent-1', 'Researcher', '2026-07-11T00:00:00.000Z')],
+ pinnedPages: [],
+ recentPages: [
+ page('Topic title · Researcher', '/agent/agent-1/topic-1', 5),
+ page('Page title', '/page/page-1', 4),
+ page('Agent root', '/agent/agent-1', 3),
+ page('Agent task', '/agent/agent-1/task/task-1', 3),
+ page('Page list', '/page', 2),
+ page('Settings', '/settings', 1),
+ ],
+ scope: { type: 'personal' },
+ });
+
+ expect(snapshot.recent).toEqual([
+ { subtitle: 'Researcher', title: 'Topic title', url: '/agent/agent-1/topic-1' },
+ { subtitle: 'Page', title: 'Page title', url: '/page/page-1' },
+ ]);
+ });
+
+ it('uses personal fallback routes and preserves overflow for More actions', () => {
+ const snapshot = resolveTrayNavigationSnapshot({
+ agents: [agent('agent 1', '', '2026-07-11T00:00:00.000Z')],
+ pinnedPages: Array.from({ length: 4 }, (_, index) =>
+ page(`Pinned ${index}`, `/page/pinned-${index}`, index),
+ ),
+ recentPages: Array.from({ length: 6 }, (_, index) =>
+ page(`Recent ${index}`, `/page/recent-${index}`, index),
+ ),
+ scope: { type: 'personal' },
+ });
+
+ expect(snapshot.agents[0]).toEqual({
+ id: 'agent 1',
+ title: 'Untitled',
+ url: '/agent/agent%201',
+ });
+ expect(snapshot.pinned).toHaveLength(4);
+ expect(snapshot.recent).toHaveLength(6);
+ });
+});
diff --git a/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts
new file mode 100644
index 00000000000..9a47fad6c0c
--- /dev/null
+++ b/src/features/Electron/titlebar/TrayMenu/resolveSnapshot.ts
@@ -0,0 +1,93 @@
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
+
+import type { SidebarAgentItem } from '@/database/repositories/home';
+
+import type { ResolvedTab } from '../TabBar/hooks/useResolvedTabs';
+import type { TabScope } from '../TabBar/scope';
+
+interface ResolveTrayNavigationSnapshotParams {
+ agents: SidebarAgentItem[];
+ pinnedPages: ResolvedTab[];
+ recentPages: ResolvedTab[];
+ scope: TabScope;
+}
+
+const timestamp = (value: Date | string | null | undefined) =>
+ value ? new Date(value).getTime() : 0;
+
+const getAgentIdFromUrl = (url: string): string | undefined => {
+ const pathname = new URL(url, 'https://lobehub.local').pathname;
+ const segments = pathname.split('/').filter(Boolean);
+ const agentIndex = segments.indexOf('agent');
+ const encodedId = agentIndex >= 0 ? segments[agentIndex + 1] : undefined;
+
+ return encodedId ? decodeURIComponent(encodedId) : undefined;
+};
+
+const fallbackAgentUrl = (scope: TabScope, agentId: string) => {
+ const prefix = scope.type === 'workspace' ? `/${encodeURIComponent(scope.slug)}` : '';
+ return `${prefix}/agent/${encodeURIComponent(agentId)}`;
+};
+
+const resolveRecentItem = (page: ResolvedTab, agentNames: ReadonlyMap<string, string>) => {
+ const pathname = new URL(page.tab.url, 'https://lobehub.local').pathname;
+ const segments = pathname.split('/').filter(Boolean);
+ const agentIndex = segments.indexOf('agent');
+ if (
+ agentIndex >= 0 &&
+ segments.length === agentIndex + 3 &&
+ segments[agentIndex + 1] &&
+ segments[agentIndex + 2]
+ ) {
+ const agentId = decodeURIComponent(segments[agentIndex + 1]);
+ const agentName = agentNames.get(agentId) || 'Untitled';
+ const agentSuffix = ` · ${agentName}`;
+ const title = page.meta.title.endsWith(agentSuffix)
+ ? page.meta.title.slice(0, -agentSuffix.length)
+ : page.meta.title;
+ return {
+ subtitle: agentName,
+ title,
+ url: page.tab.url,
+ };
+ }
+
+ const pageIndex = segments.indexOf('page');
+ if (pageIndex >= 0 && segments.length === pageIndex + 2 && segments[pageIndex + 1]) {
+ return { subtitle: 'Page', title: page.meta.title, url: page.tab.url };
+ }
+};
+
+export const resolveTrayNavigationSnapshot = ({
+ agents,
+ pinnedPages,
+ recentPages,
+ scope,
+}: ResolveTrayNavigationSnapshotParams): TrayNavigationSnapshot => {
+ const uniqueAgents = new Map<string, SidebarAgentItem>();
+ const sortedAgents = [...agents].sort((a, b) => timestamp(b.updatedAt) - timestamp(a.updatedAt));
+ for (const agent of sortedAgents) {
+ if (!uniqueAgents.has(agent.id)) uniqueAgents.set(agent.id, agent);
+ }
+ const agentNames = new Map(
+ [...uniqueAgents.values()].map((agent) => [agent.id, agent.title || 'Untitled']),
+ );
+
+ const visitedPages = [...pinnedPages, ...recentPages].sort(
+ (a, b) => b.tab.lastVisited - a.tab.lastVisited,
+ );
+
+ return {
+ agents: [...uniqueAgents.values()].map((agent) => ({
+ id: agent.id,
+ title: agent.title || 'Untitled',
+ url:
+ visitedPages.find((page) => getAgentIdFromUrl(page.tab.url) === agent.id)?.tab.url ??
+ fallbackAgentUrl(scope, agent.id),
+ })),
+ pinned: pinnedPages.map(({ meta, tab }) => ({ title: meta.title, url: tab.url })),
+ recent: recentPages
+ .map((page) => resolveRecentItem(page, agentNames))
+ .filter((item) => item !== undefined),
+ };
+};
diff --git a/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsx b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsx
new file mode 100644
index 00000000000..e140b1be49c
--- /dev/null
+++ b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.test.tsx
@@ -0,0 +1,80 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useTrayMenuSync } from './useTrayMenuSync';
+
+const mocks = vi.hoisted(() => ({
+ agents: [{ id: 'agent-1', title: 'Researcher', updatedAt: '2026-07-11T00:00:00.000Z' }],
+ useFetchAgentList: vi.fn(),
+ updateNavigationSnapshot: vi.fn(),
+}));
+
+vi.mock('@/hooks/useFetchAgentList', () => ({ useFetchAgentList: mocks.useFetchAgentList }));
+
+vi.mock('@/services/electron/tray', () => ({
+ desktopTrayService: { updateNavigationSnapshot: mocks.updateNavigationSnapshot },
+}));
+
+vi.mock('@/store/home', () => ({
+ useHomeStore: vi.fn(() => mocks.agents),
+}));
+
+vi.mock('@/store/home/slices/agentList/selectors', () => ({
+ homeAgentListSelectors: { allAgents: vi.fn() },
+}));
+
+vi.mock('@/store/electron', () => ({
+ useElectronStore: vi.fn((selector) => selector({ activeRecentScope: { type: 'personal' } })),
+}));
+
+vi.mock('../RecentlyViewed/hooks/useResolvedPages', () => ({
+ useResolvedPages: () => ({
+ pinnedPages: [],
+ recentPages: [
+ {
+ isActive: false,
+ meta: { title: 'Research' },
+ tab: {
+ id: '/agent/agent-1/topic-1',
+ lastVisited: 1,
+ url: '/agent/agent-1/topic-1',
+ },
+ },
+ ],
+ }),
+}));
+
+describe('useTrayMenuSync', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.updateNavigationSnapshot.mockResolvedValue({ success: true });
+ });
+
+ it('pushes resolved navigation data and does not resend an identical render', async () => {
+ const { rerender } = renderHook(() => useTrayMenuSync());
+
+ await waitFor(() => expect(mocks.updateNavigationSnapshot).toHaveBeenCalledTimes(1));
+ expect(mocks.useFetchAgentList).toHaveBeenCalled();
+ expect(mocks.updateNavigationSnapshot).toHaveBeenCalledWith({
+ agents: [{ id: 'agent-1', title: 'Researcher', url: '/agent/agent-1/topic-1' }],
+ pinned: [],
+ recent: [{ subtitle: 'Researcher', title: 'Research', url: '/agent/agent-1/topic-1' }],
+ });
+
+ rerender();
+ expect(mocks.updateNavigationSnapshot).toHaveBeenCalledTimes(1);
+ });
+
+ it('logs synchronization failures without throwing into the titlebar', async () => {
+ const error = new Error('IPC unavailable');
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mocks.updateNavigationSnapshot.mockRejectedValue(error);
+
+ expect(() => renderHook(() => useTrayMenuSync())).not.toThrow();
+ await waitFor(() =>
+ expect(consoleError).toHaveBeenCalledWith('Failed to synchronize tray menu:', error),
+ );
+
+ consoleError.mockRestore();
+ });
+});
diff --git a/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.ts b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.ts
new file mode 100644
index 00000000000..19d4f7428b7
--- /dev/null
+++ b/src/features/Electron/titlebar/TrayMenu/useTrayMenuSync.ts
@@ -0,0 +1,35 @@
+'use client';
+
+import { useEffect, useMemo, useRef } from 'react';
+
+import { useFetchAgentList } from '@/hooks/useFetchAgentList';
+import { desktopTrayService } from '@/services/electron/tray';
+import { useElectronStore } from '@/store/electron';
+import { useHomeStore } from '@/store/home';
+import { homeAgentListSelectors } from '@/store/home/slices/agentList/selectors';
+
+import { useResolvedPages } from '../RecentlyViewed/hooks/useResolvedPages';
+import { resolveTrayNavigationSnapshot } from './resolveSnapshot';
+
+export const useTrayMenuSync = () => {
+ useFetchAgentList();
+ const agents = useHomeStore(homeAgentListSelectors.allAgents);
+ const scope = useElectronStore((state) => state.activeRecentScope);
+ const { pinnedPages, recentPages } = useResolvedPages();
+ const lastSnapshotRef = useRef<string | undefined>(undefined);
+
+ const snapshot = useMemo(
+ () => resolveTrayNavigationSnapshot({ agents, pinnedPages, recentPages, scope }),
+ [agents, pinnedPages, recentPages, scope],
+ );
+
+ useEffect(() => {
+ const signature = JSON.stringify(snapshot);
+ if (signature === lastSnapshotRef.current) return;
+ lastSnapshotRef.current = signature;
+
+ void desktopTrayService
+ .updateNavigationSnapshot(snapshot)
+ .catch((error) => console.error('Failed to synchronize tray menu:', error));
+ }, [snapshot]);
+};
diff --git a/src/services/electron/tray.ts b/src/services/electron/tray.ts
new file mode 100644
index 00000000000..250fa87bcdc
--- /dev/null
+++ b/src/services/electron/tray.ts
@@ -0,0 +1,11 @@
+import type { TrayNavigationSnapshot } from '@lobechat/electron-client-ipc';
+
+import { ensureElectronIpc } from '@/utils/electron/ipc';
+
+class DesktopTrayService {
+ updateNavigationSnapshot = async (snapshot: TrayNavigationSnapshot) => {
+ return ensureElectronIpc().tray.updateNavigationSnapshot(snapshot);
+ };
+}
+
+export const desktopTrayService = new DesktopTrayService();