Skip to content

A full-featured download manager.

feat(menu): add cross-platform application menu (#1847)

Dr_rOotccbbed26d885
diff --git a/README.md b/README.md
index 851a20cf..da72f00f 100644
--- a/README.md
+++ b/README.md
@@ -148,6 +148,25 @@ pnpm run lint # Run Biome checks
pnpm build # Fetch signed built-in plugins, then build the native host and four Vite targets
```
+### Preview the in-window application menu on macOS
+
+Windows and Linux render the application menu inside the Motrix window. To
+preview that chrome while developing on macOS, start the app with the preview
+flag enabled:
+
+```bash
+MOTRIX_PREVIEW_MAC_MENU=1 pnpm start
+```
+
+The flag hides the main window's macOS traffic-light buttons and enables the
+renderer dropdown menu. Restart the development process after changing the
+flag because both Electron and Vite read it at startup.
+
+This mode is intended for layout and command-item debugging. Electron routes
+macOS role items through AppKit's native menu, so role-backed actions such as
+**Window → Minimize** do not behave identically when invoked from the preview
+dropdown. Validate those native role actions on Windows or Linux.
+
See the scripts in `package.json` for the available packaging commands. Platform-specific settings for macOS, Windows, and Linux live in `electron-builder.json`.
## 🔧 Tech stack
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 89f5e1de..c1f83a55 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -145,6 +145,22 @@ pnpm run lint # biome check .
pnpm build # 下载已签名的内置插件,并构建 native host 和 4 个 Vite target
```
+### 在 macOS 预览窗口内应用菜单
+
+Windows 和 Linux 会在 Motrix 窗口内渲染应用菜单。在 macOS 开发环境中,可以通过
+以下预览开关检查相同的窗口布局:
+
+```bash
+MOTRIX_PREVIEW_MAC_MENU=1 pnpm start
+```
+
+该开关会隐藏主窗口的 macOS 红绿灯按钮,并启用 renderer dropdown menu。Electron
+和 Vite 都会在启动时读取此开关,因此修改后需要重启开发进程。
+
+此模式用于调试布局和 command 菜单项。Electron 会通过 AppKit 原生菜单处理 macOS
+role 菜单项,因此 **Window → Minimize** 等 role action 从预览 dropdown 调用时,行为
+不会与原生菜单完全一致;这些原生 role action 需要在 Windows 或 Linux 上验收。
+
macOS、Windows 和 Linux 的打包命令(`pack:*` / `dist:*`)可以在 `package.json` 的 scripts 字段和 `electron-builder.json` 中查看。
## 🔧 技术栈
diff --git a/e2e/application-menu.spec.ts b/e2e/application-menu.spec.ts
new file mode 100644
index 00000000..11ffce09
--- /dev/null
+++ b/e2e/application-menu.spec.ts
@@ -0,0 +1,94 @@
+import { expect, test } from './fixtures/electron-app'
+
+test.describe('application menu', () => {
+ test('uses the native macOS menu without rendering the custom trigger', async ({
+ electronApp,
+ mainWindow,
+ }) => {
+ test.skip(process.platform !== 'darwin')
+
+ await expect(
+ mainWindow.locator('[data-slot="motrix-menu-trigger"]')
+ ).toHaveCount(0)
+ await expect
+ .poll(() =>
+ electronApp.evaluate(({ Menu }) => Boolean(Menu.getApplicationMenu()))
+ )
+ .toBe(true)
+ })
+
+ test('keeps the Windows/Linux native menu hidden while preserving behavior', async ({
+ electronApp,
+ mainWindow,
+ }) => {
+ test.skip(process.platform === 'darwin')
+
+ await expect(
+ mainWindow.locator('[data-slot="motrix-menu-trigger"]')
+ ).toBeVisible()
+
+ const isMainMenuBarVisible = () =>
+ electronApp.evaluate(({ BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ return main?.isMenuBarVisible() ?? null
+ })
+
+ await expect.poll(isMainMenuBarVisible).toBe(false)
+ await mainWindow.keyboard.press('Alt')
+ await expect.poll(isMainMenuBarVisible).toBe(false)
+
+ await mainWindow.keyboard.press('Control+N')
+ await expect
+ .poll(() =>
+ electronApp.evaluate(({ BrowserWindow }) =>
+ BrowserWindow.getAllWindows().some(
+ (window) =>
+ window.webContents.getURL().includes('w=add-task') &&
+ window.isVisible()
+ )
+ )
+ )
+ .toBe(true)
+
+ const request = await mainWindow.evaluate(async () => {
+ const api = (
+ window as unknown as {
+ motrix: {
+ invoke: (channel: string, ...args: unknown[]) => Promise<unknown>
+ }
+ }
+ ).motrix
+ const snapshot = (await api.invoke('query:getApplicationMenu')) as {
+ revision: number
+ }
+ return api.invoke('command:executeApplicationMenuItem', {
+ itemId: 'menubar.window.minimize',
+ revision: snapshot.revision,
+ trigger: 'menu',
+ selectedTaskId: null,
+ })
+ })
+ expect(request).toEqual({ ok: true })
+
+ await expect
+ .poll(() =>
+ electronApp.evaluate(({ BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ return main?.isMinimized() ?? null
+ })
+ )
+ .toBe(true)
+
+ await electronApp.evaluate(({ BrowserWindow }) => {
+ const main = BrowserWindow.getAllWindows().find((window) =>
+ window.webContents.getURL().includes('w=main')
+ )
+ main?.restore()
+ main?.show()
+ })
+ })
+})
diff --git a/public/mo-logo.svg b/public/mo-logo.svg
new file mode 100644
index 00000000..bf318f42
--- /dev/null
+++ b/public/mo-logo.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="62" height="14" viewBox="0 0 62 14" class="h-auto w-full" aria-hidden="true"><g fill="currentColor" fill-rule="evenodd"><path d="M40,2 C40,1 41,1.53477231e-14 42,1.53477231e-14 C42,1.53477231e-14 60,1.27897692e-14 60,1.53477231e-14 C61,1.27897692e-14 62,1 62,2 C62,2 62,12 62,12 C62,13 61,14 60,14 C60,14 42,14 42,14 C41,14 40,13 40,12 C40,12 40,2 40,2 Z M44,3.5 C44,3.5 44,10.5 44,10.5 C44,11 44.5,11.5 45,11.5 C45,11.5 57,11.5 57,11.5 C57.5,11.5 58,11 58,10.5 C58,10.5 58,3.5 58,3.5 C58,3 57.5,2.5 57,2.5 C57,2.5 45,2.5 45,2.5 C44.5,2.5 44,3 44,3.5 Z"></path><rect width="4" height="2" x="32" y="6" rx=".5"></rect><path d="M2,0 L26,0 C27,-2.04003481e-15 28,1 28,2 L28,14 L24,14 L24,3.5 C24,3 23.5,2.5 23,2.5 L16,2.5 L16,14 L12,14 L12,2.5 L5,2.5 C4.5,2.5 4,3 4,3.5 L4,14 L0,14 L0,2 C0,1 1,-2.04003481e-15 2,0 Z"></path></g></svg>
\ No newline at end of file
diff --git a/src/main/index.ts b/src/main/index.ts
index 64ea0b49..283ae43d 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -122,6 +122,7 @@ import { KeybindingRegistry } from './commands/keybindings/keybinding-registry'
import type { CommandDeps } from './commands/types'
import { UpdateManager } from './core/update-manager'
import { setupExceptionHandler } from './exception-handler'
+import { registerApplicationMenuIpc } from './ipc/application-menu'
import { registerCommandHandlers } from './ipc/commands'
import { registerDisclaimerIpc } from './ipc/disclaimer'
import { setupEventForwarding } from './ipc/events'
@@ -1839,7 +1840,7 @@ async function initializeMainProcess(): Promise<void> {
}
registerAllCommands(commandRegistry, commandDeps)
- installAllMenubarContributions(menuRegistry, process.platform)
+ installAllMenubarContributions(menuRegistry)
menuManager = new MenuManager({
commandRegistry,
@@ -1852,6 +1853,13 @@ async function initializeMainProcess(): Promise<void> {
if (!mainProcessWork.isAccepting()) return
log.warn({ err }, 'menu command tracking failed')
},
+ onApplicationMenuSet: () => {
+ if (process.platform !== 'win32' && process.platform !== 'linux') return
+ for (const win of windowManager.getAllWindows()) {
+ win.setAutoHideMenuBar(false)
+ win.setMenuBarVisibility(false)
+ }
+ },
})
menuManager.install()
@@ -2085,6 +2093,15 @@ async function initializeMainProcess(): Promise<void> {
trackAsyncWork: (operation) => mainProcessWork.run(operation),
})
+ // The main window can mount before the full IPC ingress is ready. The
+ // application-menu bridge subscribes and immediately publishes the current
+ // snapshot so an early renderer query is reconciled without losing state.
+ const disposeApplicationMenuIpc = registerApplicationMenuIpc({
+ menuManager: menuManager as MenuManager,
+ windowManager,
+ trackAsyncWork: (operation) => mainProcessWork.run(operation),
+ })
+
const disposeCommandHandlers = registerCommandHandlers({
cliToolService,
supervisor,
@@ -2178,6 +2195,7 @@ async function initializeMainProcess(): Promise<void> {
disposeCommandHandlers()
disposeQueryHandlers()
disposeNotificationIpc()
+ disposeApplicationMenuIpc()
}
// Plugin log stream: forward every ring-buffer entry to renderers as
diff --git a/src/main/ipc/application-menu.test.ts b/src/main/ipc/application-menu.test.ts
new file mode 100644
index 00000000..639c3c9a
--- /dev/null
+++ b/src/main/ipc/application-menu.test.ts
@@ -0,0 +1,288 @@
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import type { ApplicationMenuSnapshot } from '@shared/schemas/application-menu'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const { handle, removeHandler } = vi.hoisted(() => ({
+ handle: vi.fn(),
+ removeHandler: vi.fn(),
+}))
+
+vi.mock('electron', () => ({
+ ipcMain: { handle, removeHandler },
+}))
+
+vi.mock('./trusted-ipc', () => ({
+ registerTrustedIpcHandler: (
+ channel: string,
+ listener: (...args: never[]) => unknown
+ ) => handle(channel, listener),
+}))
+
+import {
+ type ApplicationMenuIpcDeps,
+ registerApplicationMenuIpc,
+} from './application-menu'
+
+const initialSnapshot: ApplicationMenuSnapshot = {
+ revision: 1,
+ items: [
+ {
+ id: 'menubar.task',
+ type: 'submenu',
+ label: 'Task',
+ enabled: true,
+ visible: true,
+ children: [
+ {
+ id: 'task.pause',
+ type: 'normal',
+ label: 'Pause',
+ enabled: true,
+ visible: true,
+ },
+ ],
+ },
+ ],
+}
+
+function createDeps() {
+ let changedListener: ((snapshot: ApplicationMenuSnapshot) => void) | undefined
+ const offMenuChanged = vi.fn()
+ const mainWindow = {
+ isDestroyed: vi.fn(() => false),
+ webContents: { send: vi.fn(), isDestroyed: vi.fn(() => false) },
+ }
+ const menuManager = {
+ getApplicationMenuSnapshot: vi.fn(() => initialSnapshot),
+ executeApplicationMenuItem: vi.fn().mockResolvedValue(undefined),
+ onApplicationMenuChanged: vi.fn(
+ (listener: (snapshot: ApplicationMenuSnapshot) => void) => {
+ changedListener = listener
+ return offMenuChanged
+ }
+ ),
+ }
+ const windowManager = {
+ get: vi.fn((id: 'main') => (id === 'main' ? mainWindow : null)),
+ getWindowIdBySender: vi.fn((sender: unknown) =>
+ sender === mainWindow.webContents ? 'main' : 'add-task'
+ ),
+ }
+
+ return {
+ deps: { menuManager, windowManager } as unknown as ApplicationMenuIpcDeps,
+ mainWindow,
+ menuManager,
+ offMenuChanged,
+ emitChanged: (snapshot: ApplicationMenuSnapshot) =>
+ changedListener?.(snapshot),
+ }
+}
+
+function registeredHandler(channel: string) {
+ return handle.mock.calls.find(([registered]) => registered === channel)?.[1]
+}
+
+describe('application-menu IPC', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('registers the query and execute channels and pushes the initial snapshot only to main', () => {
+ const { deps, mainWindow, menuManager } = createDeps()
+
+ registerApplicationMenuIpc(deps)
+
+ expect(handle).toHaveBeenCalledTimes(2)
+ expect(handle).toHaveBeenCalledWith(
+ Queries.GetApplicationMenu,
+ expect.any(Function)
+ )
+ expect(handle).toHaveBeenCalledWith(
+ Commands.ExecuteApplicationMenuItem,
+ expect.any(Function)
+ )
+ expect(menuManager.onApplicationMenuChanged).toHaveBeenCalledOnce()
+ expect(mainWindow.webContents.send).toHaveBeenCalledOnce()
+ expect(mainWindow.webContents.send).toHaveBeenCalledWith(
+ Events.ApplicationMenuChanged,
+ initialSnapshot
+ )
+ })
+
+ it('returns the current validated snapshot to the main renderer', async () => {
+ const { deps, mainWindow } = createDeps()
+ registerApplicationMenuIpc(deps)
+ const query = registeredHandler(Queries.GetApplicationMenu)
+
+ await expect(query({ sender: mainWindow.webContents })).resolves.toEqual(
+ initialSnapshot
+ )
+ })
+
+ it('rejects query and execute calls from any renderer except current main', async () => {
+ const { deps } = createDeps()
+ registerApplicationMenuIpc(deps)
+ const event = { sender: {} }
+ const request = {
+ itemId: 'task.pause',
+ revision: 1,
+ trigger: 'menu',
+ selectedTaskId: null,
+ }
+
+ await expect(
+ registeredHandler(Queries.GetApplicationMenu)(event)
+ ).rejects.toThrow('non-main window')
+ await expect(
+ registeredHandler(Commands.ExecuteApplicationMenuItem)(event, request)
+ ).rejects.toThrow('non-main window')
+ })
+
+ it('requires the sender to match the current main even when its id is spoofed', async () => {
+ const { deps } = createDeps()
+ deps.windowManager.getWindowIdBySender = vi.fn(() => 'main')
+ registerApplicationMenuIpc(deps)
+
+ await expect(
+ registeredHandler(Queries.GetApplicationMenu)({ sender: {} })
+ ).rejects.toThrow('non-main window')
+ })
+
+ it('strictly parses execute input and passes the current main BrowserWindow', async () => {
+ const { deps, mainWindow, menuManager } = createDeps()
+ registerApplicationMenuIpc(deps)
+ const execute = registeredHandler(Commands.ExecuteApplicationMenuItem)
+ const request = {
+ itemId: 'task.pause',
+ revision: 1,
+ trigger: 'menu',
+ selectedTaskId: null,
+ modifiers: {
+ alt: false,
+ control: true,
+ meta: false,
+ shift: false,
+ },
+ }
+
+ await expect(
+ execute({ sender: mainWindow.webContents }, request)
+ ).resolves.toEqual({ ok: true })
+ expect(menuManager.executeApplicationMenuItem).toHaveBeenCalledWith(
+ request,
+ mainWindow
+ )
+
+ await expect(
+ execute(
+ { sender: mainWindow.webContents },
+ { ...request, unexpected: true }
+ )
+ ).rejects.toThrow()
+ expect(menuManager.executeApplicationMenuItem).toHaveBeenCalledOnce()
+ })
+
+ it('pushes changes only to the current main window and skips a destroyed main', () => {
+ const { deps, emitChanged, mainWindow } = createDeps()
+ registerApplicationMenuIpc(deps)
+ mainWindow.webContents.send.mockClear()
+ const changedSnapshot = { ...initialSnapshot, revision: 2 }
+
+ emitChanged(changedSnapshot)
+ expect(mainWindow.webContents.send).toHaveBeenCalledWith(
+ Events.ApplicationMenuChanged,
+ changedSnapshot
+ )
+
+ mainWindow.isDestroyed.mockReturnValue(true)
+ emitChanged({ ...initialSnapshot, revision: 3 })
+ expect(mainWindow.webContents.send).toHaveBeenCalledOnce()
+ })
+
+ it('skips destroyed webContents and tolerates a send destruction race', () => {
+ const { deps, emitChanged, mainWindow } = createDeps()
+ registerApplicationMenuIpc(deps)
+ mainWindow.webContents.send.mockClear()
+
+ mainWindow.webContents.isDestroyed.mockReturnValue(true)
+ emitChanged({ ...initialSnapshot, revision: 2 })
+ expect(mainWindow.webContents.send).not.toHaveBeenCalled()
+
+ mainWindow.webContents.isDestroyed.mockReturnValue(false)
+ mainWindow.webContents.send.mockImplementationOnce(() => {
+ throw new Error('destroyed')
+ })
+ expect(() => emitChanged({ ...initialSnapshot, revision: 3 })).not.toThrow()
+ })
+
+ it('tracks both snapshot queries and menu-item execution', async () => {
+ const { deps, mainWindow } = createDeps()
+ const trackedOperations: Array<() => Promise<unknown>> = []
+ const trackAsyncWork = <T>(operation: () => Promise<T>): Promise<T> => {
+ trackedOperations.push(operation)
+ return operation()
+ }
+ deps.trackAsyncWork = trackAsyncWork
+ registerApplicationMenuIpc(deps)
+
+ await registeredHandler(Queries.GetApplicationMenu)({
+ sender: mainWindow.webContents,
+ })
+ await registeredHandler(Commands.ExecuteApplicationMenuItem)(
+ { sender: mainWindow.webContents },
+ {
+ itemId: 'task.pause',
+ revision: 1,
+ trigger: 'menu',
+ selectedTaskId: null,
+ }
+ )
+
+ expect(trackedOperations).toHaveLength(2)
+ })
+
+ it('revalidates the current main window after tracked work is admitted', async () => {
+ const { deps, mainWindow, menuManager } = createDeps()
+ let release: (() => void) | undefined
+ const gate = new Promise<void>((resolve) => {
+ release = resolve
+ })
+ deps.trackAsyncWork = async (operation) => {
+ await gate
+ return operation()
+ }
+ registerApplicationMenuIpc(deps)
+ const execution = registeredHandler(Commands.ExecuteApplicationMenuItem)(
+ { sender: mainWindow.webContents },
+ {
+ itemId: 'task.pause',
+ revision: 1,
+ trigger: 'menu',
+ selectedTaskId: null,
+ }
+ )
+
+ mainWindow.isDestroyed.mockReturnValue(true)
+ release?.()
+
+ await expect(execution).rejects.toThrow('non-main window')
+ expect(menuManager.executeApplicationMenuItem).not.toHaveBeenCalled()
+ })
+
+ it('removes both handlers and the menu listener on dispose', () => {
+ const { deps, offMenuChanged } = createDeps()
+ const dispose = registerApplicationMenuIpc(deps)
+
+ dispose()
+
+ expect(offMenuChanged).toHaveBeenCalledOnce()
+ expect(removeHandler).toHaveBeenCalledTimes(2)
+ expect(removeHandler).toHaveBeenCalledWith(Queries.GetApplicationMenu)
+ expect(removeHandler).toHaveBeenCalledWith(
+ Commands.ExecuteApplicationMenuItem
+ )
+ })
+})
diff --git a/src/main/ipc/application-menu.ts b/src/main/ipc/application-menu.ts
new file mode 100644
index 00000000..c1effdac
--- /dev/null
+++ b/src/main/ipc/application-menu.ts
@@ -0,0 +1,109 @@
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import {
+ type ApplicationMenuSnapshot,
+ applicationMenuSnapshotSchema,
+ type ExecuteApplicationMenuItemRequest,
+ executeApplicationMenuItemRequestSchema,
+} from '@shared/schemas/application-menu'
+import { type BrowserWindow, ipcMain } from 'electron'
+import { registerTrustedIpcHandler } from './trusted-ipc'
+
+export interface ApplicationMenuIpcDeps {
+ menuManager: {
+ getApplicationMenuSnapshot(): ApplicationMenuSnapshot
+ executeApplicationMenuItem(
+ request: ExecuteApplicationMenuItemRequest,
+ targetWindow: BrowserWindow
+ ): void | Promise<void>
+ onApplicationMenuChanged(
+ listener: (snapshot: ApplicationMenuSnapshot) => void
+ ): () => void
+ }
+ windowManager: {
+ get(id: 'main'): BrowserWindow | null
+ getWindowIdBySender(sender: Electron.WebContents): string | null
+ }
+ trackAsyncWork?: <T>(operation: () => Promise<T>) => Promise<T>
+}
+
+function requireMainWindow(
+ event: Electron.IpcMainInvokeEvent,
+ deps: ApplicationMenuIpcDeps
+): BrowserWindow {
+ const mainWindow = deps.windowManager.get('main')
+ if (
+ deps.windowManager.getWindowIdBySender(event.sender) !== 'main' ||
+ !mainWindow ||
+ mainWindow.isDestroyed() ||
+ mainWindow.webContents !== event.sender
+ ) {
+ throw new Error('Blocked application-menu IPC call from a non-main window')
+ }
+ return mainWindow
+}
+
+function sendSnapshotToMain(
+ snapshot: ApplicationMenuSnapshot,
+ deps: ApplicationMenuIpcDeps
+): void {
+ const mainWindow = deps.windowManager.get('main')
+ if (
+ !mainWindow ||
+ mainWindow.isDestroyed() ||
+ mainWindow.webContents.isDestroyed?.()
+ ) {
+ return
+ }
+ const parsed = applicationMenuSnapshotSchema.parse(snapshot)
+ try {
+ mainWindow.webContents.send(Events.ApplicationMenuChanged, parsed)
+ } catch {
+ // A main window can be destroyed between the guards above and send().
+ }
+}
+
+function runTracked<T>(
+ deps: ApplicationMenuIpcDeps,
+ operation: () => T | Promise<T>
+): Promise<T> {
+ const run = async () => operation()
+ return deps.trackAsyncWork ? deps.trackAsyncWork(run) : run()
+}
+
+export function registerApplicationMenuIpc(
+ deps: ApplicationMenuIpcDeps
+): () => void {
+ registerTrustedIpcHandler(Queries.GetApplicationMenu, async (event) => {
+ return runTracked(deps, () => {
+ requireMainWindow(event, deps)
+ return applicationMenuSnapshotSchema.parse(
+ deps.menuManager.getApplicationMenuSnapshot()
+ )
+ })
+ })
+
+ registerTrustedIpcHandler(
+ Commands.ExecuteApplicationMenuItem,
+ async (event, input: unknown) => {
+ return runTracked(deps, async () => {
+ const mainWindow = requireMainWindow(event, deps)
+ const request = executeApplicationMenuItemRequestSchema.parse(input)
+ await deps.menuManager.executeApplicationMenuItem(request, mainWindow)
+ return { ok: true }
+ })
+ }
+ )
+
+ const offMenuChanged = deps.menuManager.onApplicationMenuChanged((snapshot) =>
+ sendSnapshotToMain(snapshot, deps)
+ )
+ sendSnapshotToMain(deps.menuManager.getApplicationMenuSnapshot(), deps)
+
+ return () => {
+ offMenuChanged()
+ ipcMain.removeHandler(Queries.GetApplicationMenu)
+ ipcMain.removeHandler(Commands.ExecuteApplicationMenuItem)
+ }
+}
diff --git a/src/main/ipc/commands.test.ts b/src/main/ipc/commands.test.ts
index f4d55c38..0e05e537 100644
--- a/src/main/ipc/commands.test.ts
+++ b/src/main/ipc/commands.test.ts
@@ -15,7 +15,7 @@ import type { CommandContext } from './commands'
import { buildCommandHandlers, registerCommandHandlers } from './commands'
// Mock electron so BrowserWindow.fromWebContents can be stubbed in the
-// ResizeWindow test. ipcMain/dialog are not invoked by buildCommandHandlers,
+// Window-bound command tests. ipcMain/dialog are not invoked by buildCommandHandlers,
// but we stub them for safety.
const fromWebContentsMock = vi.fn()
const ipcHandleMock = vi.fn()
@@ -652,6 +652,25 @@ describe('buildCommandHandlers', () => {
expect(result).toEqual({ ok: true })
})
+ it('MinimizeCurrentWindow minimizes only its sender window', async () => {
+ const minimize = vi.fn()
+ fromWebContentsMock.mockReturnValueOnce({
+ isDestroyed: vi.fn(() => false),
+ isMinimizable: vi.fn(() => true),
+ minimize,
+ })
+ const ctx = fakeCtx()
+ // @ts-expect-error partial ctx
+ const handlers = buildCommandHandlers(ctx)
+ const fakeSender = {} as never
+
+ await expect(
+ handlers[Commands.MinimizeCurrentWindow]?.(fakeSender)
+ ).resolves.toEqual({ ok: true })
+ expect(fromWebContentsMock).toHaveBeenCalledWith(fakeSender)
+ expect(minimize).toHaveBeenCalledOnce()
+ })
+
it('routes direct shell commands to their owning collaborators', async () => {
const ctx = fakeCtx()
// @ts-expect-error partial ctx
@@ -669,7 +688,9 @@ describe('buildCommandHandlers', () => {
await handlers[Commands.CheckForUpdates]?.()
await handlers[Commands.DownloadUpdate]?.()
await handlers[Commands.InstallUpdate]?.()
- await handlers[Commands.UpdateMenuContext]?.({
+ const mainSender = {} as never
+ ctx.windowManager.getWindowIdBySender.mockReturnValue('main')
+ await handlers[Commands.UpdateMenuContext]?.(mainSender, {
currentRoute: '/downloads',
})
@@ -689,6 +710,20 @@ describe('buildCommandHandlers', () => {
})
})
+ it('rejects menu-context updates from auxiliary windows', async () => {
+ const ctx = fakeCtx()
+ ctx.windowManager.getWindowIdBySender.mockReturnValue('add-task')
+ // @ts-expect-error partial ctx
+ const handlers = buildCommandHandlers(ctx)
+
+ await expect(
+ handlers[Commands.UpdateMenuContext]?.({} as never, {
+ selectedTaskId: 'victim-task',
+ })
+ ).rejects.toThrow('non-main window')
+ expect(ctx.contextStore.merge).not.toHaveBeenCalled()
+ })
+
it('returns a picked save directory and handles cancellation', async () => {
showOpenDialogMock.mockReset()
showOpenDialogMock
@@ -785,23 +820,45 @@ describe('buildCommandHandlers', () => {
const closeRegistration = ipcHandleMock.mock.calls.find(
([channel]) => channel === Commands.CloseCurrentWindow
)
+ const minimizeRegistration = ipcHandleMock.mock.calls.find(
+ ([channel]) => channel === Commands.MinimizeCurrentWindow
+ )
+ const menuContextRegistration = ipcHandleMock.mock.calls.find(
+ ([channel]) => channel === Commands.UpdateMenuContext
+ )
const restartRegistration = ipcHandleMock.mock.calls.find(
([channel]) => channel === Commands.RestartEngine
)
expect(closeRegistration).toBeDefined()
+ expect(minimizeRegistration).toBeDefined()
+ expect(menuContextRegistration).toBeDefined()
expect(restartRegistration).toBeDefined()
await closeRegistration?.[1]({ sender }, { showMain: true })
+ fromWebContentsMock.mockReturnValueOnce({
+ isDestroyed: () => false,
+ isMinimizable: () => true,
+ minimize: vi.fn(),
+ })
+ await minimizeRegistration?.[1]({ sender })
+ await menuContextRegistration?.[1]({ sender }, { currentRoute: '/tasks' })
await restartRegistration?.[1]({})
expect(ctx.windowManager.getWindowIdBySender).toHaveBeenCalledWith(sender)
expect(ctx.windowManager.closeAndRecycle).toHaveBeenCalledWith('main')
+ expect(fromWebContentsMock).toHaveBeenCalledWith(sender)
+ expect(ctx.contextStore.merge).toHaveBeenCalledWith({
+ currentRoute: '/tasks',
+ })
expect(ctx.supervisor.restart).toHaveBeenCalledOnce()
dispose()
expect(ipcRemoveHandlerMock).toHaveBeenCalledWith(
Commands.CloseCurrentWindow
)
+ expect(ipcRemoveHandlerMock).toHaveBeenCalledWith(
+ Commands.MinimizeCurrentWindow
+ )
expect(ipcRemoveHandlerMock).toHaveBeenCalledWith(Commands.RestartEngine)
})
diff --git a/src/main/ipc/commands.ts b/src/main/ipc/commands.ts
index 5400b13b..de320c50 100644
--- a/src/main/ipc/commands.ts
+++ b/src/main/ipc/commands.ts
@@ -965,6 +965,16 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
return { ok: true }
},
+ // Minimize only the trusted window that originated the request. This is
+ // the Linux frameless-window replacement for a native caption button.
+ [Commands.MinimizeCurrentWindow]: async (sender: WebContents) => {
+ const win = BrowserWindow.fromWebContents(sender)
+ if (win && !win.isDestroyed() && win.isMinimizable()) {
+ win.minimize()
+ }
+ return { ok: true }
+ },
+
[Commands.PickSaveDir]: async (params: { defaultPath?: string }) => {
const result = await dialog.showOpenDialog({
properties: ['openDirectory'],
@@ -1113,7 +1123,10 @@ export function buildCommandHandlers(ctx: CommandContext): CommandHandlerMap {
await trackerManager.syncBtTracker(task.id, params.engineGid, isPrivate)
},
- [Commands.UpdateMenuContext]: async (raw: unknown) => {
+ [Commands.UpdateMenuContext]: async (sender: WebContents, raw: unknown) => {
+ if (windowManager.getWindowIdBySender(sender) !== 'main') {
+ throw new Error('Blocked menu-context update from a non-main window')
+ }
const patch = MenuContextPatchSchema.parse(raw)
contextStore.merge(patch)
return { ok: true }
@@ -1406,10 +1419,12 @@ export function registerCommandHandlers(ctx: CommandContext): () => void {
: Promise.resolve().then(operation)
for (const [channel, handler] of Object.entries(handlers)) {
- // CloseCurrentWindow and ResizeWindow need event.sender — pass it as first arg
+ // Window-bound commands need event.sender — pass it as the first arg.
if (
channel === Commands.CloseCurrentWindow ||
- channel === Commands.ResizeWindow
+ channel === Commands.MinimizeCurrentWindow ||
+ channel === Commands.ResizeWindow ||
+ channel === Commands.UpdateMenuContext
) {
registerTrustedIpcHandler(channel, (event, ...args) =>
invoke(() =>
diff --git a/src/main/menu/application-menu-snapshot.test.ts b/src/main/menu/application-menu-snapshot.test.ts
new file mode 100644
index 00000000..a651fbad
--- /dev/null
+++ b/src/main/menu/application-menu-snapshot.test.ts
@@ -0,0 +1,554 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { CommandRegistry } from '../commands/command-registry'
+import { ContextStore } from '../commands/context-store'
+import { KeybindingRegistry } from '../commands/keybindings/keybinding-registry'
+import type { CommandDeps, CommandExecContext } from '../commands/types'
+import { i18n } from '../lib/i18n'
+import { MenuIds, MenuItemIds } from './menu-ids'
+import { MenuManager } from './menu-manager'
+import { MenuRegistry } from './menu-registry'
+
+interface FakeMenuItem {
+ id: string
+ type: string
+ label: string
+ accelerator: unknown
+ enabled: unknown
+ visible: unknown
+ checked: unknown
+ submenu: FakeMenu | null
+ click: unknown
+}
+
+interface FakeMenu {
+ items: FakeMenuItem[]
+}
+
+const electronMenu = vi.hoisted(() => {
+ const roleClicks = new Map<string, ReturnType<typeof vi.fn>>()
+ const applicationMenus: unknown[] = []
+ const checkedAssignments = new Map<string, unknown[]>()
+ const radioChecked = new Map<string, boolean>()
+
+ const build = (template: Array<Record<string, unknown>>): FakeMenu => {
+ const menu: FakeMenu = {
+ items: template.map((entry): FakeMenuItem => {
+ const id = String(entry.id ?? '')
+ const roleClick = entry.role ? vi.fn() : undefined
+ if (roleClick) roleClicks.set(id, roleClick)
+ const submenu = Array.isArray(entry.submenu)
+ ? build(entry.submenu as Array<Record<string, unknown>>)
+ : null
+ const item: FakeMenuItem = {
+ id,
+ type: String(entry.type ?? (submenu ? 'submenu' : 'normal')),
+ label: String(entry.label ?? ''),
+ accelerator: entry.accelerator ?? null,
+ enabled: entry.enabled ?? true,
+ visible: entry.visible ?? true,
+ checked: entry.checked ?? false,
+ submenu,
+ click: entry.click ?? roleClick,
+ }
+ if (item.type === 'radio') {
+ radioChecked.set(id, Boolean(entry.checked))
+ Object.defineProperty(item, 'checked', {
+ configurable: true,
+ get: () => radioChecked.get(id) ?? false,
+ set: (value: unknown) => {
+ const assignments = checkedAssignments.get(id) ?? []
+ assignments.push(value)
+ checkedAssignments.set(id, assignments)
+ const ownIndex = menu.items.indexOf(item)
+ let first = ownIndex
+ let last = ownIndex
+ while (menu.items[first - 1]?.type === 'radio') first -= 1
+ while (menu.items[last + 1]?.type === 'radio') last += 1
+ for (let index = first; index <= last; index += 1) {
+ const sibling = menu.items[index]
+ if (sibling) radioChecked.set(sibling.id, sibling === item)
+ }
+ },
+ })
+ }
+ if (item.type === 'checkbox' || item.type === 'radio') {
+ const commandClick = item.click as (() => void) | undefined
+ item.click = () => {
+ item.checked = !item.checked
+ commandClick?.()
+ }
+ }
+ return item
+ }),
+ }
+ return menu
+ }
+
+ return {
+ roleClicks,
+ checkedAssignments,
+ radioChecked,
+ applicationMenus,
+ buildFromTemplate: vi.fn(build),
+ setApplicationMenu: vi.fn((menu: unknown) => {
+ applicationMenus.push(menu)
+ }),
+ }
+})
+
+vi.mock('electron', () => ({
+ Menu: {
+ buildFromTemplate: electronMenu.buildFromTemplate,
+ setApplicationMenu: electronMenu.setApplicationMenu,
+ },
+}))
+
+function createManager(
+ options: {
+ trackAsyncWork?: (operation: () => Promise<void>) => Promise<void>
+ } = {}
+) {
+ const commandRegistry = new CommandRegistry()
+ const menuRegistry = new MenuRegistry()
+ const contextStore = new ContextStore()
+ contextStore.merge({ platform: 'win32' })
+
+ let onAboutRun = (): void => {}
+ const aboutRun = vi.fn(async () => onAboutRun())
+ const protectedRun = vi.fn(async (_context: CommandExecContext) => {})
+ const hiddenRun = vi.fn(async () => {})
+ const nestedRun = vi.fn(async () => {})
+ let compactMode = true
+ const onApplicationMenuSet = vi.fn()
+ commandRegistry.register({
+ id: 'test.about',
+ title: 'menu.app.about',
+ run: aboutRun,
+ })
+ commandRegistry.register({
+ id: 'test.nested',
+ title: 'menu.task.pauseTask',
+ run: nestedRun,
+ })
+ commandRegistry.register({
+ id: 'test.protected',
+ title: 'menu.task.pauseTask',
+ precondition: (context) => context.taskSelected,
+ run: protectedRun,
+ })
+ commandRegistry.register({
+ id: 'test.hidden',
+ title: 'menu.help.website',
+ run: hiddenRun,
+ })
+
+ menuRegistry.appendItem({
+ id: MenuItemIds.AppAbout,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
+ group: '1_about',
+ commandId: 'test.about',
+ })
+ menuRegistry.appendItem({
+ id: 'menubar.window.mode.compact',
+ type: 'radio',
+ menuId: MenuIds.MenubarWindow,
+ group: '2_mode',
+ commandId: 'test.about',
+ toggled: () => compactMode,
+ radioGroupId: 'menubar.window.mode',
+ })
+ menuRegistry.appendItem({
+ id: 'menubar.window.mode.comfortable',
+ type: 'radio',
+ menuId: MenuIds.MenubarWindow,
+ group: '2_mode',
+ commandId: 'test.about',
+ toggled: () => !compactMode,
+ radioGroupId: 'menubar.window.mode',
+ })
+ menuRegistry.appendItem({
+ id: 'menubar.task.hiddenParent',
+ type: 'submenu',
+ menuId: MenuIds.MenubarTask,
+ group: '2_hidden',
+ submenu: MenuIds.MenubarFile,
+ when: () => false,
+ })
+ menuRegistry.appendItem({
+ id: 'menubar.file.nested',
+ type: 'normal',
+ menuId: MenuIds.MenubarFile,
+ group: '1_nested',
+ commandId: 'test.nested',
+ })
+ menuRegistry.appendItem({
+ id: MenuItemIds.AppQuit,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
+ group: '9_quit',
+ role: 'quit',
+ titleOverride: 'menu.app.quit',
+ })
+ menuRegistry.appendItem({
+ id: MenuItemIds.TaskPause,
+ type: 'normal',
+ menuId: MenuIds.MenubarTask,
+ group: '1_task',
+ commandId: 'test.protected',
+ contextBinding: 'selectedTask',
+ })
+ menuRegistry.appendItem({
+ id: MenuItemIds.EditCopy,
+ type: 'normal',
+ menuId: MenuIds.MenubarEdit,
+ group: '1_edit',
+ role: 'copy',
+ titleOverride: 'menu.edit.copy',
+ })
+ menuRegistry.appendItem({
+ id: MenuItemIds.WindowMinimize,
+ type: 'normal',
+ menuId: MenuIds.MenubarWindow,
+ group: '1_window',
+ role: 'minimize',
+ titleOverride: 'menu.window.minimize',
+ })
+ menuRegistry.appendItem({
+ id: MenuItemIds.HelpWebsite,
+ type: 'normal',
+ menuId: MenuIds.MenubarHelp,
+ group: '1_help',
+ commandId: 'test.hidden',
+ when: () => false,
+ })
+ menuRegistry.appendItem({
+ id: MenuItemIds.HelpToggleDevTools,
+ type: 'normal',
+ menuId: MenuIds.MenubarHelp,
+ group: '2_help',
+ role: 'toggleDevTools',
+ titleOverride: 'menu.help.toggleDevTools',
+ })
+
+ const manager = new MenuManager({
+ commandRegistry,
+ menuRegistry,
+ keybindingRegistry: new KeybindingRegistry(),
+ contextStore,
+ commandDeps: {
+ log: { error: vi.fn() },
+ } as unknown as CommandDeps,
+ trackAsyncWork: options.trackAsyncWork,
+ onApplicationMenuSet,
+ })
+ return {
+ manager,
+ contextStore,
+ aboutRun,
+ protectedRun,
+ hiddenRun,
+ nestedRun,
+ onApplicationMenuSet,
+ setCompactMode: (value: boolean) => {
+ compactMode = value
+ contextStore.merge({ currentRoute: value ? '/compact' : '/comfortable' })
+ },
+ setOnAboutRun: (run: () => void) => {
+ onAboutRun = run
+ },
+ }
+}
+
+describe('MenuManager application-menu snapshot', () => {
+ beforeEach(() => {
+ electronMenu.roleClicks.clear()
+ electronMenu.checkedAssignments.clear()
+ electronMenu.radioChecked.clear()
+ electronMenu.applicationMenus.length = 0
+ electronMenu.buildFromTemplate.mockClear()
+ electronMenu.setApplicationMenu.mockClear()
+ })
+
+ it('publishes an initially evaluated, stable dropdown projection', () => {
+ const { manager } = createManager()
+ const changed = vi.fn()
+ manager.onApplicationMenuChanged(changed)
+
+ manager.install()
+
+ const snapshot = manager.getApplicationMenuSnapshot()
+ expect(snapshot.revision).toBe(1)
+ expect(snapshot.items.map((item) => item.id)).toEqual([
+ MenuItemIds.AppAbout,
+ MenuItemIds.ApplicationSubmenusSeparator,
+ MenuIds.MenubarTask,
+ MenuIds.MenubarEdit,
+ MenuIds.MenubarWindow,
+ MenuIds.MenubarHelp,
+ MenuItemIds.ApplicationQuitSeparator,
+ MenuItemIds.AppQuit,
+ ])
+ expect(snapshot.items[2]?.children?.[0]).toMatchObject({
+ id: MenuItemIds.TaskPause,
+ enabled: false,
+ visible: true,
+ })
+ expect(
+ snapshot.items[5]?.children?.find(
+ (item) => item.id === MenuItemIds.HelpWebsite
+ )
+ ).toMatchObject({ visible: false })
+ expect(changed).toHaveBeenCalledOnce()
+
+ snapshot.items[0]!.label = 'mutated outside the manager'
+ expect(manager.getApplicationMenuSnapshot().items[0]?.label).not.toBe(
+ 'mutated outside the manager'
+ )
+ })
+
+ it('increments revision only for menu or command-context changes', () => {
+ const { manager, contextStore } = createManager()
+ const changed = vi.fn()
+ manager.install()
+ manager.onApplicationMenuChanged(changed)
+
+ contextStore.merge({ currentRoute: '/settings' })
+ expect(manager.getApplicationMenuSnapshot().revision).toBe(1)
+ expect(changed).not.toHaveBeenCalled()
+
+ contextStore.merge({ selectedTaskId: 'task-1' })
+ expect(manager.getApplicationMenuSnapshot().revision).toBe(2)
+ expect(changed).toHaveBeenCalledOnce()
+ expect(
+ manager.getApplicationMenuSnapshot().items[2]?.children?.[0]?.enabled
+ ).toBe(true)
+
+ contextStore.merge({ selectedTaskId: 'task-1' })
+ expect(changed).toHaveBeenCalledOnce()
+
+ contextStore.merge({ selectedTaskId: 'task-2' })
+ expect(manager.getApplicationMenuSnapshot().revision).toBe(2)
+ expect(changed).toHaveBeenCalledOnce()
+ })
+
+ it('rebuilds an evaluated menu and reapplies native visibility after a locale change', async () => {
+ const originalLanguage = i18n.language
+ const alternateLanguage = originalLanguage.startsWith('zh') ? 'en' : 'zh-CN'
+ const { manager, contextStore, onApplicationMenuSet } = createManager()
+ contextStore.merge({ selectedTaskId: 'task-1' })
+ manager.install()
+
+ await i18n.changeLanguage(alternateLanguage)
+
+ expect(onApplicationMenuSet).toHaveBeenCalledTimes(2)
+ expect(
+ manager.getApplicationMenuSnapshot().items[2]?.children?.[0]
+ ).toMatchObject({ enabled: true, visible: true })
+
+ manager.dispose()
+ await i18n.changeLanguage(originalLanguage)
+ })
+
+ it('revalidates revision and native state before executing current items', async () => {
+ const { manager, contextStore, protectedRun, hiddenRun, nestedRun } =
+ createManager()
+ manager.install()
+ const initialRevision = manager.getApplicationMenuSnapshot().revision
+ const targetWindow = { webContents: {} } as Electron.BrowserWindow
+
+ expect(() =>
+ manager.executeApplicationMenuItem(
+ {
+ itemId: MenuItemIds.TaskPause,
+ revision: initialRevision,
+ trigger: 'menu',
+ selectedTaskId: null,
+ },
+ targetWindow
+ )
+ ).toThrow('cannot be executed')
+
+ contextStore.merge({ selectedTaskId: 'task-1' })
+ const enabledRevision = manager.getApplicationMenuSnapshot().revision
+ manager.executeApplicationMenuItem(
+ {
+ itemId: MenuItemIds.TaskPause,
+ revision: enabledRevision,
+ trigger: 'menu',
+ selectedTaskId: 'task-1',
+ },
+ targetWindow
+ )
+ await Promise.resolve()
+ expect(protectedRun).toHaveBeenCalledOnce()
+
+ contextStore.merge({ selectedTaskId: 'task-2' })
+ expect(() =>
+ manager.executeApplicationMenuItem(
+ {
+ itemId: MenuItemIds.TaskPause,
+ revision: manager.getApplicationMenuSnapshot().revision,
+ trigger: 'menu',
+ selectedTaskId: 'task-1',
+ },
+ targetWindow
+ )
+ ).toThrow('command context is stale')
+
+ contextStore.merge({ selectedTaskId: null })
+ expect(() =>
+ manager.executeApplicationMenuItem(
+ {
+ itemId: MenuItemIds.TaskPause,
+ revision: enabledRevision,
+ trigger: 'menu',
+ selectedTaskId: 'task-1',
+ },
+ targetWindow
+ )
+ ).toThrow('stale')
+
+ const currentRevision = manager.getApplicationMenuSnapshot().revision
+ for (const itemId of [
+ 'missing',
+ MenuIds.MenubarTask,
+ 'menubar.file.nested',
+ MenuItemIds.ApplicationSubmenusSeparator,
+ MenuItemIds.ApplicationQuitSeparator,
+ MenuItemIds.HelpWebsite,
+ ]) {
+ expect(() =>
+ manager.executeApplicationMenuItem(
+ {
+ itemId,
+ revision: currentRevision,
+ trigger: 'menu',
+ selectedTaskId: null,
+ },
+ targetWindow
+ )
+ ).toThrow('cannot be executed')
+ }
+ expect(hiddenRun).not.toHaveBeenCalled()
+ expect(nestedRun).not.toHaveBeenCalled()
+ })
+
+ it('invokes the current Electron role item with the target window', () => {
+ const { manager } = createManager()
+ manager.install()
+ const targetWindow = { webContents: { id: 7 } } as Electron.BrowserWindow
+ const revision = manager.getApplicationMenuSnapshot().revision
+
+ manager.executeApplicationMenuItem(
+ {
+ itemId: MenuItemIds.WindowMinimize,
+ revision,
+ trigger: 'menu',
+ selectedTaskId: null,
+ modifiers: { alt: true, control: false, meta: false, shift: true },
+ },
+ targetWindow
+ )
+
+ expect(
+ electronMenu.roleClicks.get(MenuItemIds.WindowMinimize)
+ ).toHaveBeenCalledWith(
+ {
+ altKey: true,
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: true,
+ triggeredByAccelerator: false,
+ },
+ targetWindow,
+ targetWindow.webContents
+ )
+ })
+
+ it('captures the authorized task context before tracked work can be retargeted', async () => {
+ const queuedOperations: Array<() => Promise<void>> = []
+ const { manager, contextStore, protectedRun } = createManager({
+ trackAsyncWork: (operation) => {
+ queuedOperations.push(operation)
+ return Promise.resolve()
+ },
+ })
+ contextStore.merge({ selectedTaskId: 'task-a' })
+ manager.install()
+ const targetWindow = { webContents: {} } as Electron.BrowserWindow
+
+ manager.executeApplicationMenuItem(
+ {
+ itemId: MenuItemIds.TaskPause,
+ revision: manager.getApplicationMenuSnapshot().revision,
+ trigger: 'menu',
+ selectedTaskId: 'task-a',
+ },
+ targetWindow
+ )
+ expect(queuedOperations).toHaveLength(1)
+
+ // Simulate another IPC operation already queued ahead of the accepted
+ // command's microtask. The command must still operate on task-a.
+ contextStore.merge({ selectedTaskId: 'task-b' })
+ await queuedOperations[0]?.()
+
+ expect(protectedRun).toHaveBeenCalledOnce()
+ expect(protectedRun.mock.calls[0]?.[0].menuContext.selectedTaskId).toBe(
+ 'task-a'
+ )
+ })
+
+ it('reevaluates and publishes after a native command item click settles', async () => {
+ const { manager, setCompactMode, setOnAboutRun } = createManager()
+ manager.install()
+ const changed = vi.fn()
+ manager.onApplicationMenuChanged(changed)
+ const appMenu = electronMenu.applicationMenus.at(-1) as FakeMenu
+ const windowRoot = appMenu.items.find(
+ (item) => item.id === MenuIds.MenubarWindow
+ )
+ const compactItem = windowRoot?.submenu?.items.find(
+ (item) => item.id === 'menubar.window.mode.compact'
+ )
+
+ setOnAboutRun(() => setCompactMode(false))
+ changed.mockClear()
+ ;(compactItem?.click as (() => void) | undefined)?.()
+ await Promise.resolve()
+ await Promise.resolve()
+ await Promise.resolve()
+
+ expect(changed).toHaveBeenCalled()
+ const windowNode = manager
+ .getApplicationMenuSnapshot()
+ .items.find((item) => item.id === MenuIds.MenubarWindow)
+ expect(
+ windowNode?.children?.find(
+ (item) => item.id === 'menubar.window.mode.comfortable'
+ )
+ ).toMatchObject({ checked: true })
+ })
+
+ it('selects only the radio whose predicate is true during reevaluation', () => {
+ const { manager, setCompactMode } = createManager()
+ manager.install()
+ electronMenu.checkedAssignments.clear()
+
+ setCompactMode(false)
+
+ expect(
+ electronMenu.checkedAssignments.get('menubar.window.mode.compact')
+ ).toBeUndefined()
+ expect(
+ electronMenu.checkedAssignments.get('menubar.window.mode.comfortable')
+ ).toEqual([true])
+ expect(electronMenu.radioChecked.get('menubar.window.mode.compact')).toBe(
+ false
+ )
+ expect(
+ electronMenu.radioChecked.get('menubar.window.mode.comfortable')
+ ).toBe(true)
+ })
+})
diff --git a/src/main/menu/contributions/index.test.ts b/src/main/menu/contributions/index.test.ts
index 648c36d9..119c82e5 100644
--- a/src/main/menu/contributions/index.test.ts
+++ b/src/main/menu/contributions/index.test.ts
@@ -4,25 +4,33 @@ import { MenuRegistry } from '../menu-registry'
import { installAllMenubarContributions } from './index'
describe('installAllMenubarContributions', () => {
- it('darwin populates MenubarApp but not MenubarFile', () => {
+ it('registers one cross-platform app menu and projects Darwin extras', () => {
const reg = new MenuRegistry()
- installAllMenubarContributions(reg, 'darwin')
+ installAllMenubarContributions(reg)
const ids = new Set(reg.listMenuIds())
expect(ids.has(MenuIds.MenubarApp)).toBe(true)
expect(ids.has(MenuIds.MenubarFile)).toBe(false)
+ expect(
+ reg
+ .getItems(MenuIds.MenubarWindow, 'darwin')
+ .some((item) => item.platforms?.includes('darwin'))
+ ).toBe(true)
})
- it('win32 populates MenubarFile but not MenubarApp', () => {
+ it('filters Darwin-only items from the Windows projection', () => {
const reg = new MenuRegistry()
- installAllMenubarContributions(reg, 'win32')
- const ids = new Set(reg.listMenuIds())
- expect(ids.has(MenuIds.MenubarFile)).toBe(true)
- expect(ids.has(MenuIds.MenubarApp)).toBe(false)
+ installAllMenubarContributions(reg)
+ expect(
+ reg
+ .getItems(MenuIds.MenubarWindow, 'win32')
+ .some((item) => item.platforms?.includes('darwin'))
+ ).toBe(false)
+ expect(reg.getItems(MenuIds.MenubarApp, 'win32')).not.toHaveLength(0)
})
it('task menu starts with New/NewBt/OpenFile', () => {
const reg = new MenuRegistry()
- installAllMenubarContributions(reg, 'darwin')
+ installAllMenubarContributions(reg)
const items = reg.getItems(MenuIds.MenubarTask)
expect(items[0].commandId).toBe('motrix.task.new')
expect(items[1].commandId).toBe('motrix.task.newBt')
diff --git a/src/main/menu/contributions/index.ts b/src/main/menu/contributions/index.ts
index 286884a4..f1bea15e 100644
--- a/src/main/menu/contributions/index.ts
+++ b/src/main/menu/contributions/index.ts
@@ -1,18 +1,14 @@
import type { MenuRegistry } from '../menu-registry'
+import { contributeApplicationMenubar } from './menubar.app'
import { contributeDarwinMenubar } from './menubar.darwin'
import { contributeWin32Menubar } from './menubar.win32'
import { contributeSharedMenubar } from './shared'
import { contributeTrayMenu } from './tray'
-export function installAllMenubarContributions(
- menuReg: MenuRegistry,
- platform: NodeJS.Platform
-): void {
- if (platform === 'darwin') {
- contributeDarwinMenubar(menuReg)
- } else {
- contributeWin32Menubar(menuReg)
- }
+export function installAllMenubarContributions(menuReg: MenuRegistry): void {
+ contributeApplicationMenubar(menuReg)
+ contributeDarwinMenubar(menuReg)
+ contributeWin32Menubar(menuReg)
contributeSharedMenubar(menuReg)
contributeTrayMenu(menuReg)
}
diff --git a/src/main/menu/contributions/menubar.app.ts b/src/main/menu/contributions/menubar.app.ts
new file mode 100644
index 00000000..dadc30cd
--- /dev/null
+++ b/src/main/menu/contributions/menubar.app.ts
@@ -0,0 +1,39 @@
+import { CommandIds } from '@shared/commands-catalog'
+import { MenuIds, MenuItemIds } from '../menu-ids'
+import type { MenuRegistry } from '../menu-registry'
+
+export function contributeApplicationMenubar(menuReg: MenuRegistry): void {
+ menuReg.appendItem({
+ id: MenuItemIds.AppAbout,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
+ group: '1_about',
+ order: 10,
+ commandId: CommandIds.AppShowAbout,
+ })
+ menuReg.appendItem({
+ id: MenuItemIds.AppPreferences,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
+ group: '2_prefs',
+ order: 10,
+ commandId: CommandIds.AppOpenPreferences,
+ })
+ menuReg.appendItem({
+ id: MenuItemIds.AppCheckForUpdates,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
+ group: '2_prefs',
+ order: 20,
+ commandId: CommandIds.AppCheckForUpdates,
+ })
+ menuReg.appendItem({
+ id: MenuItemIds.AppQuit,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
+ group: '9_quit',
+ order: 10,
+ role: 'quit',
+ titleOverride: 'menu.app.quit',
+ })
+}
diff --git a/src/main/menu/contributions/menubar.darwin.ts b/src/main/menu/contributions/menubar.darwin.ts
index fc22f320..6940ddef 100644
--- a/src/main/menu/contributions/menubar.darwin.ts
+++ b/src/main/menu/contributions/menubar.darwin.ts
@@ -1,68 +1,60 @@
-import { CommandIds } from '@shared/commands-catalog'
-import { MenuIds } from '../menu-ids'
+import { MenuIds, MenuItemIds } from '../menu-ids'
import type { MenuRegistry } from '../menu-registry'
export function contributeDarwinMenubar(menuReg: MenuRegistry): void {
menuReg.appendItem({
- menuId: MenuIds.MenubarApp,
- group: '1_about',
- order: 10,
- commandId: CommandIds.AppShowAbout,
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarApp,
- group: '2_prefs',
- order: 10,
- commandId: CommandIds.AppOpenPreferences,
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarApp,
- group: '2_prefs',
- order: 20,
- commandId: CommandIds.AppCheckForUpdates,
- })
- menuReg.appendItem({
+ id: MenuItemIds.AppHide,
+ type: 'normal',
menuId: MenuIds.MenubarApp,
group: '3_hide',
order: 10,
role: 'hide',
titleOverride: 'menu.app.hide',
+ platforms: ['darwin'],
+ includeInApplicationMenu: false,
})
menuReg.appendItem({
+ id: MenuItemIds.AppHideOthers,
+ type: 'normal',
menuId: MenuIds.MenubarApp,
group: '3_hide',
order: 20,
role: 'hideOthers',
titleOverride: 'menu.app.hideOthers',
+ platforms: ['darwin'],
+ includeInApplicationMenu: false,
})
menuReg.appendItem({
+ id: MenuItemIds.AppUnhide,
+ type: 'normal',
menuId: MenuIds.MenubarApp,
group: '3_hide',
order: 30,
role: 'unhide',
titleOverride: 'menu.app.unhide',
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarApp,
- group: '9_quit',
- order: 10,
- role: 'quit',
- titleOverride: 'menu.app.quit',
+ platforms: ['darwin'],
+ includeInApplicationMenu: false,
})
// macOS-only Window menu extras
menuReg.appendItem({
+ id: MenuItemIds.WindowZoom,
+ type: 'normal',
menuId: MenuIds.MenubarWindow,
group: '1_basic',
order: 40,
role: 'zoom',
titleOverride: 'menu.window.zoom',
+ platforms: ['darwin'],
})
menuReg.appendItem({
+ id: MenuItemIds.WindowFront,
+ type: 'normal',
menuId: MenuIds.MenubarWindow,
group: '2_front',
order: 10,
role: 'front',
titleOverride: 'menu.window.front',
+ platforms: ['darwin'],
})
}
diff --git a/src/main/menu/contributions/menubar.win32.ts b/src/main/menu/contributions/menubar.win32.ts
index 9cb04421..7158fea5 100644
--- a/src/main/menu/contributions/menubar.win32.ts
+++ b/src/main/menu/contributions/menubar.win32.ts
@@ -1,38 +1,18 @@
import { CommandIds } from '@shared/commands-catalog'
-import { MenuIds } from '../menu-ids'
+import { MenuIds, MenuItemIds } from '../menu-ids'
import type { MenuRegistry } from '../menu-registry'
// Used by both Windows and Linux.
export function contributeWin32Menubar(menuReg: MenuRegistry): void {
menuReg.appendItem({
- menuId: MenuIds.MenubarFile,
- group: '1_about',
- order: 10,
- commandId: CommandIds.AppShowAbout,
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarFile,
- group: '2_prefs',
- order: 10,
- commandId: CommandIds.AppOpenPreferences,
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarFile,
- group: '2_prefs',
- order: 20,
- commandId: CommandIds.AppCheckForUpdates,
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarFile,
- group: '3_show',
- order: 10,
- commandId: CommandIds.AppShowMain,
- })
- menuReg.appendItem({
- menuId: MenuIds.MenubarFile,
+ id: MenuItemIds.AppShow,
+ type: 'normal',
+ menuId: MenuIds.MenubarApp,
group: '9_quit',
- order: 10,
- role: 'quit',
- titleOverride: 'menu.app.quit',
+ order: 5,
+ commandId: CommandIds.AppShowMain,
+ visible: false,
+ platforms: ['win32', 'linux'],
+ includeInApplicationMenu: false,
})
}
diff --git a/src/main/menu/contributions/shared.ts b/src/main/menu/contributions/shared.ts
index 0874cc0e..21a3730c 100644
--- a/src/main/menu/contributions/shared.ts
+++ b/src/main/menu/contributions/shared.ts
@@ -1,76 +1,105 @@
import { CommandIds } from '@shared/commands-catalog'
-import { MenuIds } from '../menu-ids'
+import { MenuIds, MenuItemIds } from '../menu-ids'
import type { MenuRegistry } from '../menu-registry'
export function contributeSharedMenubar(menuReg: MenuRegistry): void {
// Task menu
menuReg.appendItem({
+ id: MenuItemIds.TaskNew,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '1_new',
order: 10,
commandId: CommandIds.TaskNew,
})
menuReg.appendItem({
+ id: MenuItemIds.TaskNewBt,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '1_new',
order: 20,
commandId: CommandIds.TaskNewBt,
})
menuReg.appendItem({
+ id: MenuItemIds.TaskOpenFile,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '1_new',
order: 30,
commandId: CommandIds.TaskOpenFile,
})
menuReg.appendItem({
+ id: MenuItemIds.TaskList,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 10,
commandId: CommandIds.NavigateTaskList,
})
menuReg.appendItem({
+ id: MenuItemIds.TaskPause,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 20,
commandId: CommandIds.TaskPause,
+ contextBinding: 'selectedTask',
})
menuReg.appendItem({
+ id: MenuItemIds.TaskResume,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 30,
commandId: CommandIds.TaskResume,
+ contextBinding: 'selectedTask',
})
menuReg.appendItem({
+ id: MenuItemIds.TaskDelete,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 40,
commandId: CommandIds.TaskDelete,
+ contextBinding: 'selectedTask',
})
menuReg.appendItem({
+ id: MenuItemIds.TaskMoveUp,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 50,
commandId: CommandIds.TaskMoveUp,
+ contextBinding: 'selectedTask',
})
menuReg.appendItem({
+ id: MenuItemIds.TaskMoveDown,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 60,
commandId: CommandIds.TaskMoveDown,
+ contextBinding: 'selectedTask',
})
menuReg.appendItem({
+ id: MenuItemIds.TaskPauseAll,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '3_bulk',
order: 10,
commandId: CommandIds.TaskPauseAll,
})
menuReg.appendItem({
+ id: MenuItemIds.TaskResumeAll,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '3_bulk',
order: 20,
commandId: CommandIds.TaskResumeAll,
})
menuReg.appendItem({
+ id: MenuItemIds.TaskSelectAll,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '3_bulk',
order: 30,
@@ -78,6 +107,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.task.selectAllTask',
})
menuReg.appendItem({
+ id: MenuItemIds.TaskClearStopped,
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '4_clear',
order: 10,
@@ -86,6 +117,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
// Edit menu (all roles)
menuReg.appendItem({
+ id: MenuItemIds.EditUndo,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '1_undo',
order: 10,
@@ -93,6 +126,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.edit.undo',
})
menuReg.appendItem({
+ id: MenuItemIds.EditRedo,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '1_undo',
order: 20,
@@ -100,6 +135,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.edit.redo',
})
menuReg.appendItem({
+ id: MenuItemIds.EditCut,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '2_clipboard',
order: 10,
@@ -107,6 +144,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.edit.cut',
})
menuReg.appendItem({
+ id: MenuItemIds.EditCopy,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '2_clipboard',
order: 20,
@@ -114,6 +153,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.edit.copy',
})
menuReg.appendItem({
+ id: MenuItemIds.EditPaste,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '2_clipboard',
order: 30,
@@ -121,6 +162,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.edit.paste',
})
menuReg.appendItem({
+ id: MenuItemIds.EditDelete,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '2_clipboard',
order: 40,
@@ -128,6 +171,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.edit.delete',
})
menuReg.appendItem({
+ id: MenuItemIds.EditSelectAll,
+ type: 'normal',
menuId: MenuIds.MenubarEdit,
group: '3_select',
order: 10,
@@ -137,6 +182,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
// Window menu (baseline — darwin adds zoom/front separately)
menuReg.appendItem({
+ id: MenuItemIds.WindowReload,
+ type: 'normal',
menuId: MenuIds.MenubarWindow,
group: '1_basic',
order: 10,
@@ -144,6 +191,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.window.reload',
})
menuReg.appendItem({
+ id: MenuItemIds.WindowClose,
+ type: 'normal',
menuId: MenuIds.MenubarWindow,
group: '1_basic',
order: 20,
@@ -151,6 +200,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.window.close',
})
menuReg.appendItem({
+ id: MenuItemIds.WindowMinimize,
+ type: 'normal',
menuId: MenuIds.MenubarWindow,
group: '1_basic',
order: 30,
@@ -158,6 +209,8 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
titleOverride: 'menu.window.minimize',
})
menuReg.appendItem({
+ id: MenuItemIds.WindowToggleFullscreen,
+ type: 'normal',
menuId: MenuIds.MenubarWindow,
group: '1_basic',
order: 50,
@@ -167,30 +220,40 @@ export function contributeSharedMenubar(menuReg: MenuRegistry): void {
// Help menu
menuReg.appendItem({
+ id: MenuItemIds.HelpWebsite,
+ type: 'normal',
menuId: MenuIds.MenubarHelp,
group: '1_links',
order: 10,
commandId: CommandIds.HelpOpenWebsite,
})
menuReg.appendItem({
+ id: MenuItemIds.HelpManual,
+ type: 'normal',
menuId: MenuIds.MenubarHelp,
group: '1_links',
order: 20,
commandId: CommandIds.HelpOpenManual,
})
menuReg.appendItem({
+ id: MenuItemIds.HelpChangelog,
+ type: 'normal',
menuId: MenuIds.MenubarHelp,
group: '1_links',
order: 30,
commandId: CommandIds.HelpOpenChangelog,
})
menuReg.appendItem({
+ id: MenuItemIds.HelpReportProblem,
+ type: 'normal',
menuId: MenuIds.MenubarHelp,
group: '2_report',
order: 10,
commandId: CommandIds.HelpReportProblem,
})
menuReg.appendItem({
+ id: MenuItemIds.HelpToggleDevTools,
+ type: 'normal',
menuId: MenuIds.MenubarHelp,
group: '3_dev',
order: 10,
diff --git a/src/main/menu/contributions/tray.ts b/src/main/menu/contributions/tray.ts
index 1bb3ccd5..cfc7ce14 100644
--- a/src/main/menu/contributions/tray.ts
+++ b/src/main/menu/contributions/tray.ts
@@ -1,51 +1,67 @@
import { CommandIds } from '@shared/commands-catalog'
-import { MenuIds } from '../menu-ids'
+import { MenuIds, MenuItemIds } from '../menu-ids'
import type { MenuRegistry } from '../menu-registry'
export function contributeTrayMenu(menuReg: MenuRegistry): void {
menuReg.appendItem({
+ id: MenuItemIds.TrayNew,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '1_new',
order: 10,
commandId: CommandIds.TaskNew,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayNewBt,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '1_new',
order: 20,
commandId: CommandIds.TaskNewBt,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayOpenFile,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '1_new',
order: 30,
commandId: CommandIds.TaskOpenFile,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayShow,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '2_window',
order: 10,
commandId: CommandIds.AppShowMain,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayManual,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '2_window',
order: 20,
commandId: CommandIds.HelpOpenManual,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayCheckForUpdates,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '2_window',
order: 30,
commandId: CommandIds.AppCheckForUpdates,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayPreferences,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '3_app',
order: 10,
commandId: CommandIds.AppOpenPreferences,
})
menuReg.appendItem({
+ id: MenuItemIds.TrayQuit,
+ type: 'normal',
menuId: MenuIds.Tray,
group: '9_quit',
order: 10,
diff --git a/src/main/menu/menu-ids.ts b/src/main/menu/menu-ids.ts
index decb6649..1fd6791a 100644
--- a/src/main/menu/menu-ids.ts
+++ b/src/main/menu/menu-ids.ts
@@ -9,3 +9,55 @@ export const MenuIds = {
} as const
export type MenuId = (typeof MenuIds)[keyof typeof MenuIds]
+
+export const MenuItemIds = {
+ AppAbout: 'menubar.app.about',
+ AppPreferences: 'menubar.app.preferences',
+ AppCheckForUpdates: 'menubar.app.checkForUpdates',
+ AppShow: 'menubar.app.show',
+ AppHide: 'menubar.app.hide',
+ AppHideOthers: 'menubar.app.hideOthers',
+ AppUnhide: 'menubar.app.unhide',
+ AppQuit: 'menubar.app.quit',
+ TaskNew: 'menubar.task.new',
+ TaskNewBt: 'menubar.task.newBt',
+ TaskOpenFile: 'menubar.task.openFile',
+ TaskList: 'menubar.task.list',
+ TaskPause: 'menubar.task.pause',
+ TaskResume: 'menubar.task.resume',
+ TaskDelete: 'menubar.task.delete',
+ TaskMoveUp: 'menubar.task.moveUp',
+ TaskMoveDown: 'menubar.task.moveDown',
+ TaskPauseAll: 'menubar.task.pauseAll',
+ TaskResumeAll: 'menubar.task.resumeAll',
+ TaskSelectAll: 'menubar.task.selectAll',
+ TaskClearStopped: 'menubar.task.clearStopped',
+ EditUndo: 'menubar.edit.undo',
+ EditRedo: 'menubar.edit.redo',
+ EditCut: 'menubar.edit.cut',
+ EditCopy: 'menubar.edit.copy',
+ EditPaste: 'menubar.edit.paste',
+ EditDelete: 'menubar.edit.delete',
+ EditSelectAll: 'menubar.edit.selectAll',
+ WindowReload: 'menubar.window.reload',
+ WindowClose: 'menubar.window.close',
+ WindowMinimize: 'menubar.window.minimize',
+ WindowZoom: 'menubar.window.zoom',
+ WindowToggleFullscreen: 'menubar.window.toggleFullscreen',
+ WindowFront: 'menubar.window.front',
+ HelpWebsite: 'menubar.help.website',
+ HelpManual: 'menubar.help.manual',
+ HelpChangelog: 'menubar.help.changelog',
+ HelpReportProblem: 'menubar.help.reportProblem',
+ HelpToggleDevTools: 'menubar.help.toggleDevTools',
+ TrayNew: 'tray.new',
+ TrayNewBt: 'tray.newBt',
+ TrayOpenFile: 'tray.openFile',
+ TrayShow: 'tray.show',
+ TrayManual: 'tray.manual',
+ TrayCheckForUpdates: 'tray.checkForUpdates',
+ TrayPreferences: 'tray.preferences',
+ TrayQuit: 'tray.quit',
+ ApplicationSubmenusSeparator: 'application-menu.separator.submenus',
+ ApplicationQuitSeparator: 'application-menu.separator.quit',
+} as const
diff --git a/src/main/menu/menu-manager.test.ts b/src/main/menu/menu-manager.test.ts
index c55d8f1c..acd85616 100644
--- a/src/main/menu/menu-manager.test.ts
+++ b/src/main/menu/menu-manager.test.ts
@@ -59,6 +59,7 @@ describe('MenuManager command lifecycle', () => {
const coordinator = new MainProcessWorkCoordinator()
const commandGate = deferred()
const commandStarted = deferred()
+ const onApplicationMenuSet = vi.fn()
const run = vi.fn(async () => {
commandStarted.resolve()
await commandGate.promise
@@ -69,6 +70,8 @@ describe('MenuManager command lifecycle', () => {
run,
})
menuRegistry.appendItem({
+ id: 'menubar.task.test',
+ type: 'normal',
menuId: MenuIds.MenubarTask,
commandId: 'test.command',
group: '1_test',
@@ -84,8 +87,10 @@ describe('MenuManager command lifecycle', () => {
},
} as unknown as CommandDeps,
trackAsyncWork: (operation) => coordinator.run(operation),
+ onApplicationMenuSet,
})
manager.install()
+ expect(onApplicationMenuSet).toHaveBeenCalledOnce()
const click = electronMenu.clicks[0]
expect(click).toBeTypeOf('function')
diff --git a/src/main/menu/menu-manager.ts b/src/main/menu/menu-manager.ts
index ebb54cd8..671df389 100644
--- a/src/main/menu/menu-manager.ts
+++ b/src/main/menu/menu-manager.ts
@@ -1,14 +1,24 @@
import type { CommandId } from '@shared/commands-catalog'
+import type {
+ ApplicationMenuNode,
+ ApplicationMenuSnapshot,
+ ExecuteApplicationMenuItemRequest,
+} from '@shared/schemas/application-menu'
+import { applicationMenuSnapshotSchema } from '@shared/schemas/application-menu'
import type { MenuContext } from '@shared/types/menu-context'
-import { Menu, type MenuItemConstructorOptions } from 'electron'
+import {
+ type BrowserWindow,
+ Menu,
+ type MenuItemConstructorOptions,
+} from 'electron'
import type { CommandRegistry } from '../commands/command-registry'
import type { ContextStore } from '../commands/context-store'
import type { KeybindingRegistry } from '../commands/keybindings/keybinding-registry'
import type { CommandDeps } from '../commands/types'
import { i18n } from '../lib/i18n'
-import { type MenuId, MenuIds } from './menu-ids'
+import { type MenuId, MenuIds, MenuItemIds } from './menu-ids'
import type { MenuRegistry } from './menu-registry'
-import type { MenuItem } from './types'
+import type { MenuItem, MenuPlatform } from './types'
export interface MenuManagerDeps {
commandRegistry: CommandRegistry
@@ -18,18 +28,23 @@ export interface MenuManagerDeps {
commandDeps: CommandDeps
trackAsyncWork?: (operation: () => Promise<void>) => Promise<void>
onCommandError?: (error: unknown) => void
+ onApplicationMenuSet?: () => void
}
-function rootMenubarIds(platform: NodeJS.Platform): MenuId[] {
- const first = platform === 'darwin' ? MenuIds.MenubarApp : MenuIds.MenubarFile
- return [
- first,
- MenuIds.MenubarTask,
- MenuIds.MenubarEdit,
- MenuIds.MenubarWindow,
- MenuIds.MenubarHelp,
- ]
-}
+const ROOT_MENUBAR_IDS: readonly MenuId[] = [
+ MenuIds.MenubarApp,
+ MenuIds.MenubarTask,
+ MenuIds.MenubarEdit,
+ MenuIds.MenubarWindow,
+ MenuIds.MenubarHelp,
+]
+
+const DROPDOWN_SUBMENU_IDS: readonly MenuId[] = [
+ MenuIds.MenubarTask,
+ MenuIds.MenubarEdit,
+ MenuIds.MenubarWindow,
+ MenuIds.MenubarHelp,
+]
function rootMenubarLabelKey(menuId: MenuId): string {
switch (menuId) {
@@ -50,179 +65,495 @@ function rootMenubarLabelKey(menuId: MenuId): string {
}
}
+function separatorId(menuId: MenuId, followingGroup: string): string {
+ return `separator:${menuId}:${followingGroup}`
+}
+
+function toMenuPlatform(platform: MenuContext['platform']): MenuPlatform {
+ return platform
+}
+
export class MenuManager {
private appMenu: Menu | null = null
private trayMenu: Menu | null = null
private itemsById = new Map<string, MenuItem>()
- private trayRebuiltListeners = new Set<(m: Menu) => void>()
+ private applicationItemParentIds = new Map<string, string | null>()
+ private applicationItemsById = new Map<string, Electron.MenuItem>()
+ private trayRebuiltListeners = new Set<(menu: Menu) => void>()
+ private applicationMenuChangedListeners = new Set<
+ (snapshot: ApplicationMenuSnapshot) => void
+ >()
private disposables: Array<() => void> = []
+ private applicationMenuSnapshot: ApplicationMenuSnapshot = {
+ revision: 0,
+ items: [],
+ }
+ private applicationMenuSemantic = JSON.stringify([])
+ private enabled = false
constructor(private deps: MenuManagerDeps) {}
install(): void {
+ this.enabled = true
this.rebuild()
- const offCtx = this.deps.contextStore.onChange(() => this.reevaluate())
- this.disposables.push(offCtx)
- const onLang = (): void => this.rebuild()
- i18n.on('languageChanged', onLang)
- this.disposables.push(() => i18n.off('languageChanged', onLang))
+ const offContext = this.deps.contextStore.onChange(() => this.reevaluate())
+ this.disposables.push(offContext)
+ const onLanguageChanged = (): void => this.rebuild()
+ i18n.on('languageChanged', onLanguageChanged)
+ this.disposables.push(() => i18n.off('languageChanged', onLanguageChanged))
}
dispose(): void {
this.disable()
- for (const off of this.disposables) off()
+ for (const dispose of this.disposables) dispose()
this.disposables = []
this.appMenu = null
this.trayMenu = null
this.itemsById.clear()
+ this.applicationItemParentIds.clear()
+ this.applicationItemsById.clear()
this.trayRebuiltListeners.clear()
+ this.applicationMenuChangedListeners.clear()
}
disable(): void {
+ this.enabled = false
Menu.setApplicationMenu(null)
- this.appMenu = null
+ if (this.appMenu) this.disableItems(this.appMenu)
if (this.trayMenu) this.disableItems(this.trayMenu)
+ this.appMenu = null
+ this.applicationItemsById.clear()
+ this.applicationItemParentIds.clear()
}
getTrayMenu(): Menu | null {
return this.trayMenu
}
- onTrayRebuilt(fn: (m: Menu) => void): () => void {
- this.trayRebuiltListeners.add(fn)
+ onTrayRebuilt(listener: (menu: Menu) => void): () => void {
+ this.trayRebuiltListeners.add(listener)
return () => {
- this.trayRebuiltListeners.delete(fn)
+ this.trayRebuiltListeners.delete(listener)
+ }
+ }
+
+ getApplicationMenuSnapshot(): ApplicationMenuSnapshot {
+ return applicationMenuSnapshotSchema.parse(this.applicationMenuSnapshot)
+ }
+
+ onApplicationMenuChanged(
+ listener: (snapshot: ApplicationMenuSnapshot) => void
+ ): () => void {
+ this.applicationMenuChangedListeners.add(listener)
+ return () => {
+ this.applicationMenuChangedListeners.delete(listener)
+ }
+ }
+
+ executeApplicationMenuItem(
+ request: ExecuteApplicationMenuItemRequest,
+ targetWindow: BrowserWindow
+ ): void {
+ if (!this.enabled || !this.appMenu) {
+ throw new Error('Application menu is not available')
+ }
+
+ // Revalidate against the current context immediately before dispatch. The
+ // renderer snapshot is an authorization hint, never the source of truth.
+ this.reevaluate()
+ if (request.revision !== this.applicationMenuSnapshot.revision) {
+ throw new Error('Application menu snapshot is stale')
+ }
+
+ const item = this.applicationItemsById.get(request.itemId)
+ const definition = this.itemsById.get(request.itemId)
+ if (
+ !item ||
+ !definition ||
+ definition.includeInApplicationMenu === false ||
+ item.type === 'separator' ||
+ item.submenu ||
+ !item.enabled ||
+ !item.visible ||
+ typeof item.click !== 'function'
+ ) {
+ throw new Error('Application menu item cannot be executed')
}
+ let parentId = this.applicationItemParentIds.get(request.itemId)
+ while (parentId) {
+ const parent = this.applicationItemsById.get(parentId)
+ const parentDefinition = this.itemsById.get(parentId)
+ if (
+ !parent?.visible ||
+ parentDefinition?.includeInApplicationMenu === false
+ ) {
+ throw new Error('Application menu item cannot be executed')
+ }
+ parentId = this.applicationItemParentIds.get(parentId)
+ }
+ if (
+ definition.contextBinding === 'selectedTask' &&
+ request.selectedTaskId !== this.deps.contextStore.get().selectedTaskId
+ ) {
+ throw new Error('Application menu command context is stale')
+ }
+
+ const modifiers = request.modifiers
+ item.click.call(
+ item,
+ {
+ altKey: modifiers?.alt ?? false,
+ ctrlKey: modifiers?.control ?? false,
+ metaKey: modifiers?.meta ?? false,
+ shiftKey: modifiers?.shift ?? false,
+ triggeredByAccelerator: false,
+ } satisfies Electron.KeyboardEvent,
+ targetWindow,
+ targetWindow.webContents
+ )
+ this.reevaluate()
}
private rebuild(): void {
+ if (!this.enabled) return
this.itemsById.clear()
- this.buildAppMenu()
- this.buildTrayMenu()
- this.notifyTrayRebuilt()
- }
+ this.applicationItemsById.clear()
+ this.applicationItemParentIds.clear()
- private buildAppMenu(): void {
- const platform = this.deps.contextStore.get().platform
- const template: MenuItemConstructorOptions[] = rootMenubarIds(platform).map(
- (rootId) => ({
+ const platform = toMenuPlatform(this.deps.contextStore.get().platform)
+ const applicationTemplate: MenuItemConstructorOptions[] =
+ ROOT_MENUBAR_IDS.map((rootId) => ({
+ id: rootId,
+ type: 'submenu',
label: i18n.t(rootMenubarLabelKey(rootId)),
- submenu: this.buildSubmenu(rootId),
- })
+ submenu: this.buildSubmenu(rootId, platform),
+ }))
+
+ this.appMenu = Menu.buildFromTemplate(applicationTemplate)
+ this.trayMenu = Menu.buildFromTemplate(
+ this.buildSubmenu(MenuIds.Tray, platform)
)
- this.appMenu = Menu.buildFromTemplate(template)
+ this.indexApplicationItems(this.appMenu)
+ this.reevaluateMenus()
Menu.setApplicationMenu(this.appMenu)
+ this.deps.onApplicationMenuSet?.()
+ this.publishApplicationMenuSnapshot()
+ this.notifyTrayRebuilt()
}
- private buildTrayMenu(): void {
- const template = this.buildSubmenu(MenuIds.Tray)
- this.trayMenu = Menu.buildFromTemplate(template)
- }
-
- private buildSubmenu(menuId: MenuId): MenuItemConstructorOptions[] {
- const items = this.deps.menuRegistry.getItems(menuId)
+ private buildSubmenu(
+ menuId: MenuId,
+ platform: MenuPlatform
+ ): MenuItemConstructorOptions[] {
+ const items = this.deps.menuRegistry.getItems(menuId, platform)
const template: MenuItemConstructorOptions[] = []
- let lastGroup: string | null = null
+ let previousGroup: string | null = null
for (const item of items) {
- if (lastGroup !== null && item.group !== lastGroup) {
- template.push({ type: 'separator' })
+ if (previousGroup !== null && item.group !== previousGroup) {
+ template.push({
+ id: separatorId(menuId, item.group),
+ type: 'separator',
+ })
}
- lastGroup = item.group
- const entry = this.toTemplateEntry(item)
- if (entry) template.push(entry)
+ previousGroup = item.group
+ this.itemsById.set(item.id, item)
+ template.push(this.toTemplateEntry(item, platform))
}
return template
}
private toTemplateEntry(
- item: MenuItem
- ): MenuItemConstructorOptions | undefined {
- const id = item.commandId ?? item.titleOverride ?? item.role
- if (id) this.itemsById.set(id, item)
- const label = this.resolveLabel(item)
+ item: MenuItem,
+ platform: MenuPlatform
+ ): MenuItemConstructorOptions {
+ const state = this.evaluateItem(item, this.deps.contextStore.get())
+ const base: MenuItemConstructorOptions = {
+ id: item.id,
+ type: item.type,
+ label: this.resolveLabel(item),
+ enabled: state.enabled,
+ visible: state.visible,
+ checked: state.checked,
+ }
if (item.submenu) {
- return { id, label, submenu: this.buildSubmenu(item.submenu) }
- }
- if (item.role) {
- return { id, label, role: item.role }
+ return {
+ ...base,
+ type: 'submenu',
+ submenu: this.buildSubmenu(item.submenu, platform),
+ }
}
+ if (item.role) return { ...base, role: item.role }
if (item.commandId) {
- const accelerator = this.deps.keybindingRegistry.forCommand(
- item.commandId as CommandId
- )
return {
- id: item.commandId,
- label,
- accelerator,
+ ...base,
+ accelerator: this.deps.keybindingRegistry.forCommand(
+ item.commandId as CommandId
+ ),
click: () => {
- const execute = () =>
- this.deps.commandRegistry.execute(
- item.commandId as string,
- undefined,
- {
- menuContext: this.deps.contextStore.get(),
- deps: this.deps.commandDeps,
- }
- )
- const execution = this.deps.trackAsyncWork
- ? this.deps.trackAsyncWork(execute)
- : execute()
- void execution.catch((error) => this.deps.onCommandError?.(error))
+ void this.executeCommand(item.commandId as string).finally(() => {
+ if (!this.enabled) return
+ this.reevaluate()
+ })
},
}
}
- return undefined
+ return base
+ }
+
+ private executeCommand(commandId: string): Promise<void> {
+ if (!this.enabled) return Promise.resolve()
+ // AsyncWorkTracker intentionally defers accepted work to a microtask.
+ // Capture the exact context authorized by this click before yielding so a
+ // queued renderer context update cannot retarget a destructive command.
+ const menuContext = { ...this.deps.contextStore.get() }
+ const execute = () =>
+ this.deps.commandRegistry.execute(commandId, undefined, {
+ menuContext,
+ deps: this.deps.commandDeps,
+ })
+ const execution = this.deps.trackAsyncWork
+ ? this.deps.trackAsyncWork(execute)
+ : execute()
+ return execution.catch((error) => {
+ this.deps.onCommandError?.(error)
+ })
+ }
+
+ private evaluateItem(
+ item: MenuItem,
+ context: Readonly<MenuContext>
+ ): { enabled: boolean; visible: boolean; checked: boolean } {
+ return {
+ enabled: item.commandId
+ ? this.deps.commandRegistry.canExecute(item.commandId, context)
+ : true,
+ visible:
+ item.visible !== false && (!item.when || item.when(context) === true),
+ checked: item.toggled?.(context) ?? false,
+ }
}
private resolveLabel(item: MenuItem): string {
if (item.titleOverride) return i18n.t(item.titleOverride)
if (item.commandId) {
- const cmd = this.deps.commandRegistry.get(item.commandId)
- return cmd ? i18n.t(cmd.title) : item.commandId
+ const command = this.deps.commandRegistry.get(item.commandId)
+ return command ? i18n.t(command.title) : item.commandId
}
return ''
}
private reevaluate(): void {
- const ctx = this.deps.contextStore.get()
- if (this.appMenu) this.walkAndUpdate(this.appMenu, ctx)
- if (this.trayMenu) this.walkAndUpdate(this.trayMenu, ctx)
+ if (!this.enabled) return
+ this.reevaluateMenus()
+ this.publishApplicationMenuSnapshot()
}
- private walkAndUpdate(menu: Menu, ctx: Readonly<MenuContext>): void {
+ private reevaluateMenus(): void {
+ const context = this.deps.contextStore.get()
+ if (this.appMenu) {
+ this.walkAndUpdate(this.appMenu, context)
+ this.normalizeElectronSeparators(this.appMenu)
+ }
+ if (this.trayMenu) {
+ this.walkAndUpdate(this.trayMenu, context)
+ this.normalizeElectronSeparators(this.trayMenu)
+ }
+ }
+
+ private walkAndUpdate(menu: Menu, context: Readonly<MenuContext>): void {
for (const item of menu.items) {
- this.updateElectronItem(item, ctx)
- if (item.submenu) this.walkAndUpdate(item.submenu, ctx)
+ const definition = this.itemsById.get(item.id)
+ if (definition) {
+ const state = this.evaluateItem(definition, context)
+ item.enabled = state.enabled
+ item.visible = state.visible
+ if (definition.toggled && item.type === 'radio') {
+ if (state.checked) item.checked = true
+ } else if (definition.toggled) {
+ item.checked = state.checked
+ }
+ }
+ if (item.submenu) {
+ this.walkAndUpdate(item.submenu, context)
+ if (
+ definition?.type === 'submenu' &&
+ !item.submenu.items.some((child) => child.visible)
+ ) {
+ item.visible = false
+ }
+ }
}
}
- private disableItems(menu: Menu): void {
+ private normalizeElectronSeparators(menu: Menu): void {
for (const item of menu.items) {
- item.enabled = false
- if (item.submenu) this.disableItems(item.submenu)
+ if (item.submenu) this.normalizeElectronSeparators(item.submenu)
+ }
+
+ let hasVisibleItemSinceSeparator = false
+ for (let index = 0; index < menu.items.length; index += 1) {
+ const item = menu.items[index]
+ if (!item) continue
+ if (item.type !== 'separator') {
+ if (item.visible) hasVisibleItemSinceSeparator = true
+ continue
+ }
+ const hasVisibleItemAfter = menu.items
+ .slice(index + 1)
+ .some((candidate) =>
+ candidate.type === 'separator' ? false : candidate.visible
+ )
+ item.visible = hasVisibleItemSinceSeparator && hasVisibleItemAfter
+ if (item.visible) hasVisibleItemSinceSeparator = false
}
}
- private updateElectronItem(
- electronItem: Electron.MenuItem,
- ctx: Readonly<MenuContext>
+ private indexApplicationItems(
+ menu: Menu,
+ parentId: string | null = null
): void {
- if (!electronItem.id) return
- const meta = this.itemsById.get(electronItem.id)
- if (!meta) return
- if (meta.when) electronItem.visible = meta.when(ctx)
- if (meta.commandId) {
- electronItem.enabled = this.deps.commandRegistry.canExecute(
- meta.commandId,
- ctx
+ for (const item of menu.items) {
+ if (item.id) {
+ this.applicationItemsById.set(item.id, item)
+ this.applicationItemParentIds.set(item.id, parentId)
+ }
+ if (item.submenu) this.indexApplicationItems(item.submenu, item.id)
+ }
+ }
+
+ private buildApplicationMenuItems(): ApplicationMenuNode[] {
+ if (!this.appMenu) return []
+ const appRoot = this.appMenu.items.find(
+ (item) => item.id === MenuIds.MenubarApp
+ )
+ const appChildren = appRoot?.submenu?.items ?? []
+ const primary = appChildren
+ .filter(
+ (item) =>
+ item.type !== 'separator' &&
+ item.id !== MenuItemIds.AppQuit &&
+ this.itemsById.get(item.id)?.includeInApplicationMenu !== false
)
+ .map((item) => this.toSnapshotNode(item))
+
+ const submenus = DROPDOWN_SUBMENU_IDS.map((menuId) =>
+ this.appMenu?.items.find((item) => item.id === menuId)
+ )
+ .filter((item): item is Electron.MenuItem => Boolean(item))
+ .map((item) => this.toSnapshotNode(item))
+
+ const quitItem = appChildren.find((item) => item.id === MenuItemIds.AppQuit)
+ const items: ApplicationMenuNode[] = [...primary]
+ if (submenus.length > 0) {
+ items.push({
+ id: MenuItemIds.ApplicationSubmenusSeparator,
+ type: 'separator',
+ label: '',
+ enabled: false,
+ visible: true,
+ })
+ items.push(...submenus)
+ }
+ if (quitItem) {
+ items.push({
+ id: MenuItemIds.ApplicationQuitSeparator,
+ type: 'separator',
+ label: '',
+ enabled: false,
+ visible:
+ quitItem.visible && items.some((candidate) => candidate.visible),
+ })
+ items.push(this.toSnapshotNode(quitItem))
+ }
+ return this.normalizeSnapshotTree(items)
+ }
+
+ private toSnapshotNode(item: Electron.MenuItem): ApplicationMenuNode {
+ const definition = this.itemsById.get(item.id)
+ const children = item.submenu?.items
+ .filter(
+ (child) =>
+ this.itemsById.get(child.id)?.includeInApplicationMenu !== false
+ )
+ .map((child) => this.toSnapshotNode(child))
+ const type =
+ item.type === 'separator' ||
+ item.type === 'submenu' ||
+ item.type === 'checkbox' ||
+ item.type === 'radio'
+ ? item.type
+ : 'normal'
+ const node: ApplicationMenuNode = {
+ id: item.id,
+ type,
+ label: item.label,
+ enabled: item.enabled,
+ visible: item.visible,
+ }
+ if (item.accelerator) node.accelerator = item.accelerator
+ if (type === 'checkbox' || type === 'radio') node.checked = item.checked
+ if (definition?.radioGroupId) node.radioGroupId = definition.radioGroupId
+ if (children) node.children = this.normalizeSnapshotTree(children)
+ return node
+ }
+
+ private normalizeSnapshotTree(
+ input: ApplicationMenuNode[]
+ ): ApplicationMenuNode[] {
+ const items = input.map((item) => {
+ if (!item.children) return item
+ const children = this.normalizeSnapshotTree(item.children)
+ return {
+ ...item,
+ children,
+ visible: item.visible && children.some((child) => child.visible),
+ }
+ })
+ let hasVisibleItemSinceSeparator = false
+ return items.map((item, index) => {
+ if (item.type !== 'separator') {
+ if (item.visible) hasVisibleItemSinceSeparator = true
+ return item
+ }
+ const hasVisibleItemAfter = items
+ .slice(index + 1)
+ .some(
+ (candidate) => candidate.type !== 'separator' && candidate.visible
+ )
+ const visible =
+ item.visible && hasVisibleItemSinceSeparator && hasVisibleItemAfter
+ if (visible) hasVisibleItemSinceSeparator = false
+ return { ...item, visible }
+ })
+ }
+
+ private publishApplicationMenuSnapshot(): void {
+ const items = this.buildApplicationMenuItems()
+ const semantic = JSON.stringify(items)
+ if (semantic === this.applicationMenuSemantic) return
+ this.applicationMenuSemantic = semantic
+ this.applicationMenuSnapshot = {
+ revision: this.applicationMenuSnapshot.revision + 1,
+ items,
+ }
+ const snapshot = this.getApplicationMenuSnapshot()
+ for (const listener of this.applicationMenuChangedListeners) {
+ listener(snapshot)
+ }
+ }
+
+ private disableItems(menu: Menu): void {
+ for (const item of menu.items) {
+ item.enabled = false
+ if (item.submenu) this.disableItems(item.submenu)
}
- if (meta.toggled) electronItem.checked = meta.toggled(ctx)
}
private notifyTrayRebuilt(): void {
if (!this.trayMenu) return
- for (const fn of this.trayRebuiltListeners) fn(this.trayMenu)
+ for (const listener of this.trayRebuiltListeners) {
+ listener(this.trayMenu)
+ }
}
}
diff --git a/src/main/menu/menu-registry.test.ts b/src/main/menu/menu-registry.test.ts
index 92fd983b..b2b35e40 100644
--- a/src/main/menu/menu-registry.test.ts
+++ b/src/main/menu/menu-registry.test.ts
@@ -6,24 +6,32 @@ describe('MenuRegistry', () => {
it('returns items sorted by group then order', () => {
const r = new MenuRegistry()
r.appendItem({
+ id: 'b',
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 20,
commandId: 'b',
})
r.appendItem({
+ id: 'a1',
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '1_new',
order: 10,
commandId: 'a1',
})
r.appendItem({
+ id: 'a2',
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '1_new',
order: 20,
commandId: 'a2',
})
r.appendItem({
+ id: 'b0',
+ type: 'normal',
menuId: MenuIds.MenubarTask,
group: '2_primary',
order: 10,
@@ -40,10 +48,141 @@ describe('MenuRegistry', () => {
it('listMenuIds returns every registered id', () => {
const r = new MenuRegistry()
- r.appendItem({ menuId: MenuIds.MenubarTask, group: '1', commandId: 'x' })
- r.appendItem({ menuId: MenuIds.Tray, group: '1', commandId: 'y' })
+ r.appendItem({
+ id: 'menubar.x',
+ type: 'normal',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ commandId: 'x',
+ })
+ r.appendItem({
+ id: 'tray.y',
+ type: 'normal',
+ menuId: MenuIds.Tray,
+ group: '1',
+ commandId: 'y',
+ })
expect(new Set(r.listMenuIds())).toEqual(
new Set([MenuIds.MenubarTask, MenuIds.Tray])
)
})
+
+ it('rejects duplicate stable ids across menu surfaces', () => {
+ const r = new MenuRegistry()
+ r.appendItem({
+ id: 'duplicate',
+ type: 'normal',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ commandId: 'x',
+ })
+ expect(() =>
+ r.appendItem({
+ id: 'duplicate',
+ type: 'normal',
+ menuId: MenuIds.Tray,
+ group: '1',
+ commandId: 'y',
+ })
+ ).toThrow('already registered')
+ })
+
+ it('rejects ambiguous or actionless menu definitions', () => {
+ const r = new MenuRegistry()
+ expect(() =>
+ r.appendItem({
+ id: 'ambiguous',
+ type: 'normal',
+ menuId: MenuIds.Tray,
+ group: '1',
+ commandId: 'x',
+ role: 'quit',
+ })
+ ).toThrow('exactly one action')
+ expect(() =>
+ r.appendItem({
+ id: 'actionless',
+ type: 'normal',
+ menuId: MenuIds.Tray,
+ group: '1',
+ })
+ ).toThrow('exactly one action')
+ })
+
+ it('requires an explicit group only for radio items', () => {
+ const r = new MenuRegistry()
+ expect(() =>
+ r.appendItem({
+ id: 'radio.missing-group',
+ type: 'radio',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ commandId: 'radio',
+ })
+ ).toThrow('invalid radio group')
+ expect(() =>
+ r.appendItem({
+ id: 'normal.with-group',
+ type: 'normal',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ commandId: 'normal',
+ radioGroupId: 'mode',
+ })
+ ).toThrow('invalid radio group')
+ expect(() =>
+ r.appendItem({
+ id: 'checkbox.role',
+ type: 'checkbox',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ role: 'toggleSpellChecker',
+ })
+ ).toThrow('must use a command')
+ })
+
+ it('requires adjacent radio items to share Electron native grouping', () => {
+ const r = new MenuRegistry()
+ r.appendItem({
+ id: 'radio.compact',
+ type: 'radio',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ order: 1,
+ commandId: 'compact',
+ radioGroupId: 'density',
+ })
+ r.appendItem({
+ id: 'radio.light',
+ type: 'radio',
+ menuId: MenuIds.MenubarTask,
+ group: '1',
+ order: 2,
+ commandId: 'light',
+ radioGroupId: 'theme',
+ })
+
+ expect(() => r.getItems(MenuIds.MenubarTask, 'win32')).toThrow(
+ 'must share a group'
+ )
+
+ const separated = new MenuRegistry()
+ separated.appendItem({
+ id: 'radio.compact',
+ type: 'radio',
+ menuId: MenuIds.MenubarTask,
+ group: '1_density',
+ commandId: 'compact',
+ radioGroupId: 'density',
+ })
+ separated.appendItem({
+ id: 'radio.light',
+ type: 'radio',
+ menuId: MenuIds.MenubarTask,
+ group: '2_theme',
+ commandId: 'light',
+ radioGroupId: 'theme',
+ })
+ expect(() => separated.getItems(MenuIds.MenubarTask, 'win32')).not.toThrow()
+ })
})
diff --git a/src/main/menu/menu-registry.ts b/src/main/menu/menu-registry.ts
index de9acafb..b657e42e 100644
--- a/src/main/menu/menu-registry.ts
+++ b/src/main/menu/menu-registry.ts
@@ -1,21 +1,66 @@
import type { MenuId } from './menu-ids'
-import type { MenuItem } from './types'
+import type { MenuItem, MenuPlatform } from './types'
export class MenuRegistry {
private items = new Map<MenuId, MenuItem[]>()
+ private itemIds = new Set<string>()
appendItem(item: MenuItem): void {
+ if (this.itemIds.has(item.id)) {
+ throw new Error(`Menu item already registered: ${item.id}`)
+ }
+ if ((item.type === 'submenu') !== Boolean(item.submenu)) {
+ throw new Error(`Menu item ${item.id} has an invalid submenu type`)
+ }
+ if ((item.type === 'radio') !== Boolean(item.radioGroupId)) {
+ throw new Error(`Menu item ${item.id} has an invalid radio group`)
+ }
+ if (
+ (item.type === 'checkbox' || item.type === 'radio') &&
+ !item.commandId
+ ) {
+ throw new Error(`Menu item ${item.id} must use a command when checkable`)
+ }
+ const actionCount = [item.commandId, item.role, item.submenu].filter(
+ Boolean
+ ).length
+ if (actionCount !== 1) {
+ throw new Error(`Menu item ${item.id} must declare exactly one action`)
+ }
+ this.itemIds.add(item.id)
const list = this.items.get(item.menuId) ?? []
list.push(item)
this.items.set(item.menuId, list)
}
- getItems(menuId: MenuId): readonly MenuItem[] {
+ getItems(menuId: MenuId, platform?: MenuPlatform): readonly MenuItem[] {
const list = this.items.get(menuId) ?? []
- return [...list].sort((a, b) => {
- if (a.group !== b.group) return a.group < b.group ? -1 : 1
- return (a.order ?? 0) - (b.order ?? 0)
- })
+ const sortedItems = [...list]
+ .filter(
+ (item) =>
+ !platform || !item.platforms || item.platforms.includes(platform)
+ )
+ .sort((a, b) => {
+ if (a.group !== b.group) return a.group < b.group ? -1 : 1
+ return (a.order ?? 0) - (b.order ?? 0)
+ })
+
+ for (let index = 1; index < sortedItems.length; index += 1) {
+ const previous = sortedItems[index - 1]
+ const current = sortedItems[index]
+ if (
+ previous?.type === 'radio' &&
+ current?.type === 'radio' &&
+ previous.group === current.group &&
+ previous.radioGroupId !== current.radioGroupId
+ ) {
+ throw new Error(
+ `Adjacent radio items ${previous.id} and ${current.id} must share a group`
+ )
+ }
+ }
+
+ return sortedItems
}
listMenuIds(): readonly MenuId[] {
diff --git a/src/main/menu/types.ts b/src/main/menu/types.ts
index 2116d08f..fb4ac567 100644
--- a/src/main/menu/types.ts
+++ b/src/main/menu/types.ts
@@ -2,7 +2,12 @@ import type { MenuItemConstructorOptions } from 'electron'
import type { WhenExpr } from '../commands/when'
import type { MenuId } from './menu-ids'
+export type MenuPlatform = 'darwin' | 'win32' | 'linux'
+export type MenuItemType = 'normal' | 'submenu' | 'checkbox' | 'radio'
+
export interface MenuItem {
+ id: string
+ type: MenuItemType
menuId: MenuId
commandId?: string
submenu?: MenuId
@@ -12,4 +17,9 @@ export interface MenuItem {
when?: WhenExpr
toggled?: WhenExpr
titleOverride?: string
+ visible?: boolean
+ platforms?: readonly MenuPlatform[]
+ includeInApplicationMenu?: boolean
+ radioGroupId?: string
+ contextBinding?: 'selectedTask'
}
diff --git a/src/main/window/window-manager.test.ts b/src/main/window/window-manager.test.ts
index 55730284..d3bd0376 100644
--- a/src/main/window/window-manager.test.ts
+++ b/src/main/window/window-manager.test.ts
@@ -58,6 +58,9 @@ vi.mock('electron', () => {
}
)
setMinimumSize = vi.fn()
+ setAutoHideMenuBar = vi.fn()
+ setMenuBarVisibility = vi.fn()
+ setWindowButtonVisibility = vi.fn()
center = vi.fn()
on = vi.fn().mockReturnThis()
onceListeners: Record<string, ((...args: unknown[]) => void)[]> = {}
@@ -154,6 +157,59 @@ describe('WindowManager', () => {
})
})
+ it.each(['win32', 'linux'])(
+ 'keeps the native menu bar hidden for every new %s window',
+ (platform) => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ platform,
+ })
+
+ wm.open('main')
+ wm.precreate('add-task')
+ wm.recreate('main')
+
+ const instances = (
+ BrowserWindow as unknown as {
+ instances: Array<{
+ setAutoHideMenuBar: ReturnType<typeof vi.fn>
+ setMenuBarVisibility: ReturnType<typeof vi.fn>
+ }>
+ }
+ ).instances
+ expect(instances).toHaveLength(3)
+ for (const win of instances) {
+ expect(win.setAutoHideMenuBar).toHaveBeenCalledExactlyOnceWith(false)
+ expect(win.setMenuBarVisibility).toHaveBeenCalledExactlyOnceWith(false)
+ expect(win.setAutoHideMenuBar.mock.invocationCallOrder[0]).toBeLessThan(
+ win.setMenuBarVisibility.mock.invocationCallOrder[0]
+ )
+ }
+ }
+ )
+
+ it.each(['darwin', 'web'])(
+ 'does not configure native menu bar visibility on %s',
+ (platform) => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ platform,
+ })
+
+ const win = wm.open('main') as unknown as {
+ setAutoHideMenuBar: ReturnType<typeof vi.fn>
+ setMenuBarVisibility: ReturnType<typeof vi.fn>
+ }
+
+ expect(win.setAutoHideMenuBar).not.toHaveBeenCalled()
+ expect(win.setMenuBarVisibility).not.toHaveBeenCalled()
+ }
+ )
+
it('blocks navigation and redirects outside the trusted renderer URL', () => {
const wm = new WindowManager({
settingsManager: createMockSettingsManager(),
@@ -205,6 +261,29 @@ describe('WindowManager', () => {
expect(liquidGlass.attach).toHaveBeenCalledWith('main', win)
})
+ it('hides macOS traffic lights after attaching the main-window preview', () => {
+ const sm = createMockSettingsManager()
+ const liquidGlass = {
+ shouldUseLiquidGlass: vi.fn(() => true),
+ attach: vi.fn(),
+ } as unknown as LiquidGlassController
+ const wm = new WindowManager({
+ settingsManager: sm,
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ liquidGlass,
+ platform: 'darwin',
+ previewMacMenu: true,
+ })
+
+ const win = wm.open('main')
+ const setWindowButtonVisibility = vi.mocked(win.setWindowButtonVisibility)
+
+ expect(liquidGlass.attach).toHaveBeenCalledWith('main', win)
+ expect(setWindowButtonVisibility).toHaveBeenCalledWith(false)
+ expect(liquidGlass.attach).toHaveBeenCalledBefore(setWindowButtonVisibility)
+ })
+
it('creates the onboarding window with Liquid Glass chrome when enabled', () => {
const sm = createMockSettingsManager()
const liquidGlass = {
diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.ts
index 6a338a03..d213f8f3 100644
--- a/src/main/window/window-manager.ts
+++ b/src/main/window/window-manager.ts
@@ -25,6 +25,8 @@ export interface WindowManagerDeps {
* Injected by tests so platform-specific chrome is verifiable on any host.
*/
platform?: string
+ /** Enables the development-only macOS in-window application-menu preview. */
+ previewMacMenu?: boolean
/** Central legal/startup gate for every window-opening entry point. */
resolveOpenTarget?: (requested: WindowId) => WindowId
/** Invoked when the OS signals session end (Windows window 'session-end'). */
@@ -272,11 +274,22 @@ export class WindowManager {
private registerWindow(id: WindowId, show: boolean): BrowserWindow {
const config = WINDOW_CONFIGS[id]
const win = this.createBrowserWindow(config, show)
+ const previewMacMenu =
+ id === 'main' &&
+ (this.deps.platform ?? process.platform) === 'darwin' &&
+ (this.deps.previewMacMenu ??
+ (process.env.VITE_DEV_SERVER_URL !== undefined &&
+ process.env.MOTRIX_PREVIEW_MAC_MENU === '1'))
this.windows.set(id, win)
if (config.liquidGlass) {
this.deps.liquidGlass?.attach(id, win)
}
+ if (previewMacMenu) {
+ // Local-only product preview: liquid glass may have made the native
+ // buttons visible during attach(), so apply the preview override last.
+ win.setWindowButtonVisibility(false)
+ }
this.deps.loadUrl(win, config.route)
this.setupCloseHandler(id, win)
@@ -295,10 +308,11 @@ export class WindowManager {
config: (typeof WINDOW_CONFIGS)[WindowId],
show: boolean
): BrowserWindow {
+ const platform = this.deps.platform ?? process.platform
const liquidGlass =
config.liquidGlass &&
this.deps.liquidGlass?.shouldUseLiquidGlass() === true
- const platformOpts = buildPlatformOptions(this.deps.platform, {
+ const platformOpts = buildPlatformOptions(platform, {
vibrancy: config.vibrancy && !liquidGlass,
liquidGlass,
windowControlsSymbolColor: config.windowControlsSymbolColor,
@@ -322,6 +336,11 @@ export class WindowManager {
},
})
+ if (platform === 'win32' || platform === 'linux') {
+ win.setAutoHideMenuBar(false)
+ win.setMenuBarVisibility(false)
+ }
+
if (config.minWidth && config.minHeight) {
win.setMinimumSize(config.minWidth, config.minHeight)
}
diff --git a/src/preload/preload.test.ts b/src/preload/preload.test.ts
index faa6833e..6dee7192 100644
--- a/src/preload/preload.test.ts
+++ b/src/preload/preload.test.ts
@@ -161,6 +161,14 @@ describe('preload IPC channel allowlist', () => {
Commands.InstallCliTool,
'argument'
)
+ expect(mocks.invoke).toHaveBeenCalledWith(
+ Commands.ExecuteApplicationMenuItem,
+ 'argument'
+ )
+ expect(mocks.invoke).toHaveBeenCalledWith(
+ Queries.GetApplicationMenu,
+ 'argument'
+ )
})
it('blocks undeclared invoke channels before Electron sees them', () => {
@@ -181,6 +189,9 @@ describe('preload IPC channel allowlist', () => {
for (const channel of channels) {
expect(mocks.listeners.get(channel)?.size).toBeGreaterThan(0)
}
+ expect(
+ mocks.listeners.get(Events.ApplicationMenuChanged)?.size
+ ).toBeGreaterThan(0)
})
it('allows valid plugin log channels and rejects malformed events', () => {
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
index 447cdf52..23df641a 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.test.tsx
@@ -47,6 +47,18 @@ describe('PanelShell', () => {
expect(input).toHaveClass('compact-header:w-40')
})
+ it('uses the shared window-chrome safe areas in compact mode', () => {
+ const { container } = render(
+ <PanelShell title="X">
+ <div />
+ </PanelShell>
+ )
+ expect(container.querySelector('header')).toHaveClass(
+ 'compact-header:pl-[var(--window-chrome-safe-area-leading)]',
+ 'compact-header:pr-[var(--window-chrome-safe-area-trailing)]'
+ )
+ })
+
it('renders footer content when provided', () => {
render(
<PanelShell title="X" footer={<button type="button">go</button>}>
diff --git a/src/renderer/components/desktop-kit/panel/panel-shell.tsx b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
index 8b344f00..45f37fe4 100644
--- a/src/renderer/components/desktop-kit/panel/panel-shell.tsx
+++ b/src/renderer/components/desktop-kit/panel/panel-shell.tsx
@@ -1,5 +1,4 @@
import { Input } from '@renderer/components/ui/input'
-import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
import type React from 'react'
@@ -33,10 +32,6 @@ export function PanelShell({
headerClassName,
contentClassName,
}: PanelShellProps) {
- const platform = transport.platform
-
- const isMac = platform === 'darwin'
- const showTrafficLight = __MOTRIX_TARGET__ === 'electron' && isMac
return (
<div className="relative flex h-full flex-col">
{/* PanelShell header */}
@@ -49,10 +44,8 @@ export function PanelShell({
// down (m-2), so 5px top padding centers a 28px row at
// 8 + 5 + 14 = 27 — same line as the traffic lights ({x:20,y:20}).
'compact-header:py-[5px]',
- headerClassName,
- showTrafficLight
- ? 'compact-header:pl-[160px]'
- : 'compact-header:pl-[77px]'
+ 'compact-header:pl-[var(--window-chrome-safe-area-leading)] compact-header:pr-[var(--window-chrome-safe-area-trailing)]',
+ headerClassName
)}
>
{typeof title === 'string' ? (
diff --git a/src/renderer/components/window-chrome/motrix-menu-button.test.tsx b/src/renderer/components/window-chrome/motrix-menu-button.test.tsx
new file mode 100644
index 00000000..8b79e00e
--- /dev/null
+++ b/src/renderer/components/window-chrome/motrix-menu-button.test.tsx
@@ -0,0 +1,283 @@
+import '@renderer/lib/i18n'
+import '@testing-library/jest-dom/vitest'
+import type { ApplicationMenuSnapshot } from '@shared/schemas/application-menu'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ executeItem: vi.fn(),
+ platform: 'win32' as NodeJS.Platform | 'web',
+ refresh: vi.fn(),
+ selectedTaskId: null as string | null,
+ useApplicationMenu: vi.fn(),
+}))
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ get platform() {
+ return mocks.platform
+ },
+ },
+}))
+
+vi.mock('@renderer/hooks/use-application-menu', () => ({
+ useApplicationMenu: mocks.useApplicationMenu,
+}))
+
+vi.mock('@renderer/hooks/use-selected-task', () => ({
+ useSelectedTask: () => ({
+ task: mocks.selectedTaskId ? { id: mocks.selectedTaskId } : null,
+ }),
+}))
+
+import {
+ formatMenuAccelerator,
+ MotrixMenuButton,
+ shouldRestoreMenuFocus,
+} from './motrix-menu-button'
+
+const menuSnapshot: ApplicationMenuSnapshot = {
+ revision: 7,
+ items: [
+ {
+ id: 'app.about',
+ type: 'normal',
+ label: 'About Motrix',
+ accelerator: 'CommandOrControl+,',
+ enabled: true,
+ visible: true,
+ },
+ {
+ id: 'view.hidden',
+ type: 'normal',
+ label: 'Hidden command',
+ enabled: true,
+ visible: false,
+ },
+ {
+ id: 'view.separator',
+ type: 'separator',
+ label: '',
+ enabled: false,
+ visible: true,
+ },
+ {
+ id: 'view.sidebar',
+ type: 'checkbox',
+ label: 'Show Sidebar',
+ enabled: true,
+ visible: true,
+ checked: true,
+ },
+ {
+ id: 'view.mode.compact',
+ type: 'radio',
+ label: 'Compact',
+ enabled: true,
+ visible: true,
+ checked: false,
+ radioGroupId: 'view.mode',
+ },
+ {
+ id: 'view.mode.comfortable',
+ type: 'radio',
+ label: 'Comfortable',
+ enabled: true,
+ visible: true,
+ checked: true,
+ radioGroupId: 'view.mode',
+ },
+ {
+ id: 'task',
+ type: 'submenu',
+ label: 'Task',
+ enabled: true,
+ visible: true,
+ children: [
+ {
+ id: 'task.pause',
+ type: 'normal',
+ label: 'Pause Task',
+ enabled: true,
+ visible: true,
+ },
+ ],
+ },
+ ],
+}
+
+beforeAll(() => {
+ HTMLElement.prototype.scrollIntoView = vi.fn()
+ if (!HTMLElement.prototype.hasPointerCapture) {
+ HTMLElement.prototype.hasPointerCapture = () => false
+ }
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+ )
+})
+
+describe('MotrixMenuButton', () => {
+ beforeEach(() => {
+ mocks.platform = 'win32'
+ mocks.selectedTaskId = null
+ mocks.executeItem.mockReset().mockResolvedValue(undefined)
+ mocks.refresh.mockReset().mockResolvedValue(undefined)
+ mocks.useApplicationMenu.mockReset().mockReturnValue({
+ snapshot: menuSnapshot,
+ refresh: mocks.refresh,
+ executeItem: mocks.executeItem,
+ })
+ })
+
+ it('gates before mounting its hook outside Windows and Linux', () => {
+ mocks.platform = 'darwin'
+ const { container } = render(<MotrixMenuButton />)
+ expect(container).toBeEmptyDOMElement()
+ expect(mocks.useApplicationMenu).not.toHaveBeenCalled()
+ })
+
+ it('renders a fixed-width no-drag trigger and refreshes when opened', async () => {
+ const user = userEvent.setup()
+ render(<MotrixMenuButton />)
+
+ const trigger = screen.getByRole('button', { name: 'Motrix' })
+ expect(trigger).toHaveAttribute('data-slot', 'motrix-menu-trigger')
+ expect(trigger).toHaveClass(
+ 'app-no-drag',
+ 'h-7',
+ 'w-[72px]',
+ 'pl-2',
+ 'pr-1'
+ )
+ const logo = trigger.querySelector('[data-slot="motrix-menu-logo"]')
+ expect(logo).toHaveClass('h-2.5', 'w-11', 'bg-foreground')
+ expect(logo).toHaveStyle({ maskImage: 'url("./mo-logo.svg")' })
+
+ await user.click(trigger)
+ await waitFor(() => expect(mocks.refresh).toHaveBeenCalledTimes(1))
+ expect(
+ await screen.findByRole('menuitem', { name: /About Motrix/ })
+ ).toBeInTheDocument()
+ expect(screen.getByText('Ctrl+,')).toBeInTheDocument()
+ })
+
+ it('renders visibility, checkbox, radio, separator, and submenu state', async () => {
+ const user = userEvent.setup()
+ const { container } = render(<MotrixMenuButton />)
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+
+ const checkbox = await screen.findByRole('menuitemcheckbox', {
+ name: 'Show Sidebar',
+ })
+ expect(screen.queryByText('Hidden command')).toBeNull()
+ expect(checkbox).toHaveAttribute('aria-checked', 'true')
+ expect(
+ screen.getByRole('menuitemradio', { name: 'Comfortable' })
+ ).toHaveAttribute('aria-checked', 'true')
+ expect(
+ container.ownerDocument.querySelectorAll(
+ '[data-slot="dropdown-menu-separator"]'
+ )
+ ).toHaveLength(1)
+
+ await user.hover(screen.getByRole('menuitem', { name: 'Task' }))
+ expect(
+ await screen.findByRole('menuitem', { name: 'Pause Task' })
+ ).toBeInTheDocument()
+ })
+
+ it('executes checkbox and radio items with the rendered revision', async () => {
+ const user = userEvent.setup()
+ render(<MotrixMenuButton />)
+
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await user.click(
+ await screen.findByRole('menuitemcheckbox', { name: 'Show Sidebar' })
+ )
+ await waitFor(() => expect(mocks.executeItem).toHaveBeenCalledTimes(1))
+
+ await user.click(screen.getByRole('button', { name: 'Motrix' }))
+ await user.click(
+ await screen.findByRole('menuitemradio', { name: 'Compact' })
+ )
+ await waitFor(() => expect(mocks.executeItem).toHaveBeenCalledTimes(2))
+
+ expect(mocks.executeItem.mock.calls.map(([request]) => request)).toEqual([
+ expect.objectContaining({ itemId: 'view.sidebar', revision: 7 }),
+ expect.objectContaining({ itemId: 'view.mode.compact', revision: 7 }),
+ ])
+ })
+
+ it('restores the pre-open focus before executing with click modifiers', async () => {
+ let focusWhenExecuted: Element | null = null
+ mocks.executeItem.mockImplementation(async () => {
+ focusWhenExecuted = document.activeElement
+ })
+ const { container } = render(
+ <>
+ <input aria-label="Source input" />
+ <MotrixMenuButton />
+ </>
+ )
+ const sourceInput = screen.getByRole('textbox', { name: 'Source input' })
+ sourceInput.focus()
+
+ const trigger = screen.getByRole('button', { name: 'Motrix' })
+ fireEvent.pointerDown(trigger)
+ fireEvent.click(trigger)
+ const item = await screen.findByRole('menuitem', { name: /About Motrix/ })
+ fireEvent.click(item, { altKey: true, ctrlKey: true, shiftKey: true })
+
+ await waitFor(() => expect(mocks.executeItem).toHaveBeenCalledTimes(1))
+ expect(focusWhenExecuted).toBe(sourceInput)
+ await waitFor(() => expect(sourceInput).toHaveFocus())
+ expect(mocks.executeItem).toHaveBeenCalledWith({
+ itemId: 'app.about',
+ revision: 7,
+ trigger: 'menu',
+ selectedTaskId: null,
+ modifiers: { alt: true, control: true, meta: false, shift: true },
+ })
+ expect(container.querySelector('[role="menu"]')).toBeNull()
+ })
+
+ it('returns keyboard focus to the trigger after Escape closes the menu', async () => {
+ const user = userEvent.setup()
+ render(<MotrixMenuButton />)
+
+ const trigger = screen.getByRole('button', { name: 'Motrix' })
+ trigger.focus()
+ await user.keyboard('{ArrowDown}')
+ expect(await screen.findByRole('menu')).toBeInTheDocument()
+ await user.keyboard('{Escape}')
+
+ await waitFor(() => expect(screen.queryByRole('menu')).toBeNull(), {
+ timeout: 3_000,
+ })
+ expect(trigger).toHaveFocus()
+ expect(mocks.executeItem).not.toHaveBeenCalled()
+ })
+
+ it('restores focus only for selection and Escape close reasons', () => {
+ expect(shouldRestoreMenuFocus('item-press')).toBe(true)
+ expect(shouldRestoreMenuFocus('escape-key')).toBe(true)
+ expect(shouldRestoreMenuFocus('outside-press')).toBe(false)
+ })
+})
+
+describe('formatMenuAccelerator', () => {
+ it('formats Electron CommandOrControl accelerators for Windows/Linux', () => {
+ expect(formatMenuAccelerator('CommandOrControl+Shift+N')).toBe(
+ 'Ctrl+Shift+N'
+ )
+ expect(formatMenuAccelerator('CmdOrCtrl+Option+Return')).toBe(
+ 'Ctrl+Alt+Enter'
+ )
+ })
+})
diff --git a/src/renderer/components/window-chrome/motrix-menu-button.tsx b/src/renderer/components/window-chrome/motrix-menu-button.tsx
new file mode 100644
index 00000000..f9cd44b1
--- /dev/null
+++ b/src/renderer/components/window-chrome/motrix-menu-button.tsx
@@ -0,0 +1,347 @@
+import { Button } from '@renderer/components/ui/button'
+import {
+ DropdownMenu,
+ DropdownMenuCheckboxItem,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuTrigger,
+} from '@renderer/components/ui/dropdown-menu'
+import { useApplicationMenu } from '@renderer/hooks/use-application-menu'
+import { useSelectedTask } from '@renderer/hooks/use-selected-task'
+import { transport } from '@renderer/lib/transport'
+import type {
+ ApplicationMenuNode,
+ ExecuteApplicationMenuItemRequest,
+} from '@shared/schemas/application-menu'
+import { ChevronDown } from 'lucide-react'
+import {
+ type MouseEvent as ReactMouseEvent,
+ type ReactNode,
+ useRef,
+} from 'react'
+import { useTranslation } from 'react-i18next'
+
+type RendererMenuPlatform = 'darwin' | 'win32' | 'linux'
+
+function rendererMenuPlatform(): RendererMenuPlatform | null {
+ if (__MOTRIX_TARGET__ !== 'electron') return null
+ return transport.platform === 'win32' ||
+ transport.platform === 'linux' ||
+ (transport.platform === 'darwin' && __MOTRIX_PREVIEW_MAC_MENU__)
+ ? transport.platform
+ : null
+}
+
+const ACCELERATOR_LABELS: Readonly<Record<string, string>> = {
+ alt: 'Alt',
+ cmd: 'Ctrl',
+ cmdorctrl: 'Ctrl',
+ command: 'Ctrl',
+ commandorcontrol: 'Ctrl',
+ control: 'Ctrl',
+ ctrl: 'Ctrl',
+ option: 'Alt',
+ return: 'Enter',
+ shift: 'Shift',
+}
+
+const MOTRIX_LOGO_MASK = 'url("./mo-logo.svg")'
+
+export function formatMenuAccelerator(accelerator: string): string {
+ return accelerator
+ .split('+')
+ .map((part) => ACCELERATOR_LABELS[part.trim().toLowerCase()] ?? part.trim())
+ .join('+')
+}
+
+export function shouldRestoreMenuFocus(reason: string): boolean {
+ return reason === 'item-press' || reason === 'escape-key'
+}
+
+function modifiersFromEvent(
+ event: ReactMouseEvent<HTMLElement>
+): ExecuteApplicationMenuItemRequest['modifiers'] {
+ return {
+ alt: event.altKey,
+ control: event.ctrlKey,
+ meta: event.metaKey,
+ shift: event.shiftKey,
+ }
+}
+
+interface MenuTreeProps {
+ items: ApplicationMenuNode[]
+ queueExecution: (
+ item: ApplicationMenuNode,
+ event: ReactMouseEvent<HTMLElement>
+ ) => void
+}
+
+function ItemLabel({ item }: { item: ApplicationMenuNode }) {
+ return (
+ <>
+ <span>{item.label}</span>
+ {item.accelerator && (
+ <DropdownMenuShortcut className="opacity-60">
+ {formatMenuAccelerator(item.accelerator)}
+ </DropdownMenuShortcut>
+ )}
+ </>
+ )
+}
+
+function RadioItems({
+ items,
+ queueExecution,
+}: {
+ items: ApplicationMenuNode[]
+ queueExecution: MenuTreeProps['queueExecution']
+}) {
+ const checkedItem = items.find((item) => item.checked)
+ return (
+ <DropdownMenuRadioGroup value={checkedItem?.id ?? ''}>
+ {items.map((item) => (
+ <DropdownMenuRadioItem
+ key={item.id}
+ value={item.id}
+ disabled={!item.enabled}
+ closeOnClick
+ onClick={(event) => queueExecution(item, event)}
+ >
+ <ItemLabel item={item} />
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ )
+}
+
+function MenuTree({ items, queueExecution }: MenuTreeProps) {
+ const visibleItems = items.filter((item) => item.visible)
+ const rendered: ReactNode[] = []
+
+ for (let index = 0; index < visibleItems.length; index += 1) {
+ const item = visibleItems[index]
+ if (!item) continue
+
+ if (item.type === 'radio') {
+ const groupId = item.radioGroupId ?? item.id
+ const group = [item]
+ while (
+ visibleItems[index + 1]?.type === 'radio' &&
+ (visibleItems[index + 1]?.radioGroupId ??
+ visibleItems[index + 1]?.id) === groupId
+ ) {
+ const next = visibleItems[index + 1]
+ if (next) group.push(next)
+ index += 1
+ }
+ rendered.push(
+ <RadioItems
+ key={`radio:${groupId}:${item.id}`}
+ items={group}
+ queueExecution={queueExecution}
+ />
+ )
+ continue
+ }
+
+ if (item.type === 'separator') {
+ rendered.push(<DropdownMenuSeparator key={item.id} />)
+ continue
+ }
+
+ if (item.type === 'submenu') {
+ const hasVisibleChildren = item.children?.some((child) => child.visible)
+ rendered.push(
+ <DropdownMenuSub key={item.id}>
+ <DropdownMenuSubTrigger
+ disabled={!item.enabled || !hasVisibleChildren}
+ >
+ <ItemLabel item={item} />
+ </DropdownMenuSubTrigger>
+ <DropdownMenuSubContent className="app-no-drag">
+ <MenuTree
+ items={item.children ?? []}
+ queueExecution={queueExecution}
+ />
+ </DropdownMenuSubContent>
+ </DropdownMenuSub>
+ )
+ continue
+ }
+
+ if (item.type === 'checkbox') {
+ rendered.push(
+ <DropdownMenuCheckboxItem
+ key={item.id}
+ checked={item.checked ?? false}
+ disabled={!item.enabled}
+ closeOnClick
+ onClick={(event) => queueExecution(item, event)}
+ >
+ <ItemLabel item={item} />
+ </DropdownMenuCheckboxItem>
+ )
+ continue
+ }
+
+ rendered.push(
+ <DropdownMenuItem
+ key={item.id}
+ disabled={!item.enabled}
+ onClick={(event) => queueExecution(item, event)}
+ >
+ <ItemLabel item={item} />
+ </DropdownMenuItem>
+ )
+ }
+
+ return <>{rendered}</>
+}
+
+function ElectronMotrixMenuButton() {
+ const { t } = useTranslation()
+ const { snapshot, refresh, executeItem } = useApplicationMenu()
+ const selectedTaskId = useSelectedTask().task?.id ?? null
+ const triggerRef = useRef<HTMLButtonElement | null>(null)
+ const previousFocusRef = useRef<HTMLElement | null>(null)
+ const focusCapturedForOpenRef = useRef(false)
+ const restoreFocusRef = useRef(false)
+ const pendingExecution = useRef<ExecuteApplicationMenuItemRequest | null>(
+ null
+ )
+
+ const queueExecution: MenuTreeProps['queueExecution'] = (item, event) => {
+ if (!snapshot) return
+ pendingExecution.current = {
+ itemId: item.id,
+ revision: snapshot.revision,
+ trigger: 'menu',
+ selectedTaskId,
+ modifiers: modifiersFromEvent(event),
+ }
+ }
+
+ const executeAfterFocusRestore = (open: boolean) => {
+ if (open) return
+ const request = pendingExecution.current
+ pendingExecution.current = null
+ // Keep the Escape decision available until FloatingFocusManager unmounts;
+ // its return-focus cleanup runs after this completion callback.
+ if (!request) return
+ const previousFocus = previousFocusRef.current
+ const focusTarget = previousFocus?.isConnected
+ ? previousFocus
+ : triggerRef.current
+ focusTarget?.focus({ preventScroll: true })
+ restoreFocusRef.current = false
+ void executeItem(request)
+ }
+
+ return (
+ <DropdownMenu
+ onOpenChange={(open, eventDetails) => {
+ if (!open) {
+ restoreFocusRef.current = shouldRestoreMenuFocus(eventDetails.reason)
+ return
+ }
+ // Reopening during the close animation cancels the prior selection.
+ pendingExecution.current = null
+ restoreFocusRef.current = false
+ if (!focusCapturedForOpenRef.current) {
+ previousFocusRef.current =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
+ }
+ focusCapturedForOpenRef.current = false
+ void refresh()
+ }}
+ onOpenChangeComplete={executeAfterFocusRestore}
+ >
+ <DropdownMenuTrigger
+ data-slot="motrix-menu-trigger"
+ ref={triggerRef}
+ render={
+ <Button
+ type="button"
+ variant="ghost"
+ size="xs"
+ aria-label={t('menu.app.title')}
+ className="app-no-drag h-7 w-[72px] gap-1 bg-transparent pl-2 pr-1 hover:bg-accent"
+ onPointerDownCapture={() => {
+ previousFocusRef.current =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
+ focusCapturedForOpenRef.current = true
+ }}
+ onKeyDownCapture={(event) => {
+ if (
+ event.key === 'Enter' ||
+ event.key === ' ' ||
+ event.key === 'ArrowDown' ||
+ event.key === 'ArrowUp'
+ ) {
+ previousFocusRef.current =
+ document.activeElement instanceof HTMLElement
+ ? document.activeElement
+ : null
+ focusCapturedForOpenRef.current = true
+ }
+ }}
+ />
+ }
+ >
+ <span
+ aria-hidden="true"
+ data-slot="motrix-menu-logo"
+ className="h-2.5 w-11 shrink-0 bg-foreground"
+ style={{
+ maskImage: MOTRIX_LOGO_MASK,
+ maskPosition: 'center',
+ maskRepeat: 'no-repeat',
+ maskSize: 'contain',
+ WebkitMaskImage: MOTRIX_LOGO_MASK,
+ WebkitMaskPosition: 'center',
+ WebkitMaskRepeat: 'no-repeat',
+ WebkitMaskSize: 'contain',
+ }}
+ />
+ <ChevronDown aria-hidden="true" className="size-3 shrink-0" />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="app-no-drag min-w-56"
+ finalFocus={() => {
+ if (!restoreFocusRef.current) return false
+ return previousFocusRef.current?.isConnected
+ ? previousFocusRef.current
+ : true
+ }}
+ >
+ <MenuTree
+ items={snapshot?.items ?? []}
+ queueExecution={queueExecution}
+ />
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+/**
+ * Platform gate deliberately lives outside the hook-owning component: web and
+ * macOS use their native menus and never subscribe to the renderer menu IPC.
+ */
+export function MotrixMenuButton() {
+ const platform = rendererMenuPlatform()
+ if (!platform) return null
+ return <ElectronMotrixMenuButton />
+}
diff --git a/src/renderer/components/window-chrome/window-chrome.test.tsx b/src/renderer/components/window-chrome/window-chrome.test.tsx
index 0b8f9396..109e0974 100644
--- a/src/renderer/components/window-chrome/window-chrome.test.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.test.tsx
@@ -1,7 +1,8 @@
import '@renderer/lib/i18n'
import '@testing-library/jest-dom/vitest'
+import { Commands } from '@shared/protocol/commands'
import { fireEvent, render, screen } from '@testing-library/react'
-import { beforeAll, describe, expect, it, vi } from 'vitest'
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { WindowChrome } from './window-chrome'
beforeAll(() => {
@@ -14,6 +15,23 @@ beforeAll(() => {
)
})
+function setPlatform(platform: NodeJS.Platform) {
+ Object.defineProperty(
+ window.motrix as NonNullable<Window['motrix']>,
+ 'platform',
+ {
+ value: platform,
+ writable: true,
+ configurable: true,
+ }
+ )
+}
+
+beforeEach(() => {
+ setPlatform('darwin')
+ vi.mocked(window.motrix?.invoke).mockClear()
+})
+
describe('WindowChrome', () => {
it('renders no title text in overlay variant', () => {
render(<WindowChrome variant="overlay" title="ignored" />)
@@ -72,4 +90,69 @@ describe('WindowChrome', () => {
container.querySelector('[data-slot="window-chrome-actions"]')
).toHaveClass('ml-auto')
})
+
+ it('renders a vertically aligned no-drag leading slot before actions', () => {
+ const { container } = render(
+ <WindowChrome
+ variant="overlay"
+ leading={<button type="button">Menu</button>}
+ >
+ <button type="button">Action</button>
+ </WindowChrome>
+ )
+
+ const leading = container.querySelector(
+ '[data-slot="window-chrome-leading"]'
+ )
+ const actions = container.querySelector(
+ '[data-slot="window-chrome-actions"]'
+ )
+ expect(leading).toHaveClass('app-no-drag', 'pt-3.5', 'mr-1.5')
+ expect(leading?.compareDocumentPosition(actions as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
+ })
+
+ it('keeps Linux controls trailing for start-positioned actions', () => {
+ setPlatform('linux')
+ const { container } = render(
+ <WindowChrome variant="overlay">
+ <button type="button">Action</button>
+ </WindowChrome>
+ )
+
+ const actions = container.querySelector(
+ '[data-slot="window-chrome-actions"]'
+ )
+ const controls = container.querySelector('.window-controls')
+ expect(controls).toHaveClass('ml-auto')
+ expect(actions?.compareDocumentPosition(controls as Node)).toBe(
+ Node.DOCUMENT_POSITION_FOLLOWING
+ )
+ })
+
+ it('routes Linux caption controls to sender-bound window commands', () => {
+ setPlatform('linux')
+ render(<WindowChrome variant="overlay" />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'Minimize' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Close' }))
+
+ expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
+ 1,
+ Commands.MinimizeCurrentWindow
+ )
+ expect(window.motrix?.invoke).toHaveBeenNthCalledWith(
+ 2,
+ Commands.CloseCurrentWindow
+ )
+ })
+
+ it('always reserves the Windows caption-button area', () => {
+ setPlatform('win32')
+ const { container } = render(<WindowChrome variant="overlay" />)
+ expect((container.firstChild as HTMLElement).style.paddingRight).toBe(
+ '148px'
+ )
+ })
})
diff --git a/src/renderer/components/window-chrome/window-chrome.tsx b/src/renderer/components/window-chrome/window-chrome.tsx
index 14714c1c..5921a87b 100644
--- a/src/renderer/components/window-chrome/window-chrome.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.tsx
@@ -4,18 +4,18 @@ import { Commands } from '@shared/protocol/commands'
import type React from 'react'
import { useTranslation } from 'react-i18next'
-function LinuxWindowControls() {
+function LinuxWindowControls({ pushToEnd }: { pushToEnd: boolean }) {
const { t } = useTranslation()
const minimize = () => {
- transport.invoke(Commands.ShowMainWindow)
+ void transport.invoke(Commands.MinimizeCurrentWindow)
}
const close = () => {
- transport.invoke(Commands.CloseCurrentWindow)
+ void transport.invoke(Commands.CloseCurrentWindow)
}
return (
<div
- className="window-controls app-no-drag"
+ className={cn('window-controls app-no-drag', pushToEnd && 'ml-auto')}
style={{ display: 'flex', gap: 8 }}
>
<button
@@ -54,6 +54,7 @@ interface WindowChromeProps {
compact?: boolean
title?: string
variant?: 'overlay' | 'titled'
+ leading?: React.ReactNode
children?: React.ReactNode
}
@@ -62,6 +63,7 @@ export function WindowChrome({
compact: _compact,
title,
variant = 'titled',
+ leading,
children,
}: WindowChromeProps) {
const platform = transport.platform
@@ -69,14 +71,15 @@ export function WindowChrome({
const showLinuxControls = platform === 'linux'
const isOverlay = variant === 'overlay'
const isMac = platform === 'darwin'
- const showTrafficLight = __MOTRIX_TARGET__ === 'electron' && isMac
+ const showTrafficLight =
+ __MOTRIX_TARGET__ === 'electron' && isMac && !__MOTRIX_PREVIEW_MAC_MENU__
const containerStyle: React.CSSProperties = {
height,
display: 'flex',
alignItems: 'center',
paddingLeft: showTrafficLight ? 93 : 12,
- paddingRight: actionsPosition === 'end' && platform === 'win32' ? 148 : 20,
+ paddingRight: platform === 'win32' ? 148 : 20,
flexShrink: 0,
userSelect: 'none',
...(isOverlay && {
@@ -94,8 +97,13 @@ export function WindowChrome({
{!isOverlay && title && (
<div className="text-[13px] font-[600] pt-[14px]">{title}</div>
)}
- {actionsPosition === 'start' && showLinuxControls && (
- <LinuxWindowControls />
+ {leading && (
+ <div
+ data-slot="window-chrome-leading"
+ className="app-no-drag relative z-[60] mr-1.5 flex shrink-0 items-center pt-3.5 empty:hidden"
+ >
+ {leading}
+ </div>
)}
<div
data-slot="window-chrome-actions"
@@ -106,8 +114,8 @@ export function WindowChrome({
>
{children}
</div>
- {actionsPosition === 'end' && showLinuxControls && (
- <LinuxWindowControls />
+ {showLinuxControls && (
+ <LinuxWindowControls pushToEnd={actionsPosition === 'start'} />
)}
</div>
)
diff --git a/src/renderer/env.d.ts b/src/renderer/env.d.ts
index bc0025ba..81fe58ee 100644
--- a/src/renderer/env.d.ts
+++ b/src/renderer/env.d.ts
@@ -1,6 +1,7 @@
/// <reference types="vite/client" />
declare const __MOTRIX_TARGET__: 'electron' | 'web'
+declare const __MOTRIX_PREVIEW_MAC_MENU__: boolean
declare const __MOTRIX_APP_METADATA__: {
readonly name: string
diff --git a/src/renderer/hooks/use-application-menu.test.tsx b/src/renderer/hooks/use-application-menu.test.tsx
new file mode 100644
index 00000000..df76b15f
--- /dev/null
+++ b/src/renderer/hooks/use-application-menu.test.tsx
@@ -0,0 +1,184 @@
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import type { ApplicationMenuSnapshot } from '@shared/schemas/application-menu'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ invoke: vi.fn(),
+ on: vi.fn(),
+ off: vi.fn(),
+ platform: 'win32' as NodeJS.Platform | 'web',
+}))
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ get platform() {
+ return mocks.platform
+ },
+ invoke: mocks.invoke,
+ on: mocks.on,
+ off: mocks.off,
+ },
+}))
+
+import { useApplicationMenu } from './use-application-menu'
+
+function snapshot(
+ revision: number,
+ label = `Item ${revision}`
+): ApplicationMenuSnapshot {
+ return {
+ revision,
+ items: [
+ {
+ id: `item-${revision}`,
+ type: 'normal',
+ label,
+ enabled: true,
+ visible: true,
+ },
+ ],
+ }
+}
+
+describe('useApplicationMenu', () => {
+ beforeEach(() => {
+ mocks.platform = 'win32'
+ mocks.invoke.mockReset().mockResolvedValue(snapshot(1))
+ mocks.on.mockReset()
+ mocks.off.mockReset()
+ })
+
+ it('subscribes before loading the initial snapshot', async () => {
+ renderHook(() => useApplicationMenu())
+
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledTimes(1))
+ expect(mocks.on).toHaveBeenCalledWith(
+ Events.ApplicationMenuChanged,
+ expect.any(Function)
+ )
+ expect(mocks.on.mock.invocationCallOrder[0]).toBeLessThan(
+ mocks.invoke.mock.invocationCallOrder[0] ?? 0
+ )
+ expect(mocks.invoke).toHaveBeenCalledWith(Queries.GetApplicationMenu)
+ })
+
+ it('does not let a slow query roll an event snapshot backward', async () => {
+ let resolveQuery: ((value: ApplicationMenuSnapshot) => void) | undefined
+ mocks.invoke.mockReturnValue(
+ new Promise<ApplicationMenuSnapshot>((resolve) => {
+ resolveQuery = resolve
+ })
+ )
+
+ const { result } = renderHook(() => useApplicationMenu())
+ const onChanged = mocks.on.mock.calls[0]?.[1] as (
+ value: ApplicationMenuSnapshot
+ ) => void
+
+ act(() => onChanged(snapshot(4, 'Newer event')))
+ expect(result.current.snapshot?.revision).toBe(4)
+
+ await act(async () => {
+ resolveQuery?.(snapshot(3, 'Older query'))
+ await Promise.resolve()
+ })
+ expect(result.current.snapshot?.revision).toBe(4)
+ expect(result.current.snapshot?.items[0]?.label).toBe('Newer event')
+ })
+
+ it('ignores malformed and lower-revision change events', async () => {
+ const { result } = renderHook(() => useApplicationMenu())
+ await waitFor(() => expect(result.current.snapshot?.revision).toBe(1))
+ const onChanged = mocks.on.mock.calls[0]?.[1] as (value: unknown) => void
+
+ act(() => {
+ onChanged(snapshot(2))
+ onChanged({ revision: 99, items: [{ id: 'incomplete' }] })
+ onChanged(snapshot(1))
+ })
+
+ expect(result.current.snapshot?.revision).toBe(2)
+ })
+
+ it('refreshes on demand and executes the typed request', async () => {
+ const { result } = renderHook(() => useApplicationMenu())
+ await waitFor(() => expect(result.current.snapshot?.revision).toBe(1))
+
+ mocks.invoke.mockResolvedValueOnce(snapshot(2))
+ await act(() => result.current.refresh())
+ expect(result.current.snapshot?.revision).toBe(2)
+
+ const request = {
+ itemId: 'file.quit',
+ revision: 2,
+ trigger: 'menu' as const,
+ selectedTaskId: null,
+ modifiers: { alt: false, control: true, meta: false, shift: false },
+ }
+ mocks.invoke.mockResolvedValueOnce({ ok: true })
+ await act(() => result.current.executeItem(request))
+ expect(mocks.invoke).toHaveBeenLastCalledWith(
+ Commands.ExecuteApplicationMenuItem,
+ request
+ )
+ })
+
+ it('refreshes but never auto-retries an execution rejected as stale', async () => {
+ const { result } = renderHook(() => useApplicationMenu())
+ await waitFor(() => expect(result.current.snapshot?.revision).toBe(1))
+ mocks.invoke.mockClear()
+
+ const request = {
+ itemId: 'task.delete',
+ revision: 1,
+ trigger: 'menu' as const,
+ selectedTaskId: 'task-1',
+ }
+ mocks.invoke
+ .mockRejectedValueOnce(new Error('Application menu snapshot is stale'))
+ .mockResolvedValueOnce(snapshot(2))
+
+ await act(() => result.current.executeItem(request))
+
+ expect(mocks.invoke).toHaveBeenNthCalledWith(
+ 1,
+ Commands.ExecuteApplicationMenuItem,
+ request
+ )
+ expect(mocks.invoke).toHaveBeenNthCalledWith(2, Queries.GetApplicationMenu)
+ expect(mocks.invoke).toHaveBeenCalledTimes(2)
+ expect(result.current.snapshot?.revision).toBe(2)
+ })
+
+ it('unsubscribes the same listener on cleanup', () => {
+ const { unmount } = renderHook(() => useApplicationMenu())
+ const listener = mocks.on.mock.calls[0]?.[1]
+ unmount()
+ expect(mocks.off).toHaveBeenCalledWith(
+ Events.ApplicationMenuChanged,
+ listener
+ )
+ })
+
+ it('refreshes when the window regains focus', async () => {
+ renderHook(() => useApplicationMenu())
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledTimes(1))
+
+ window.dispatchEvent(new Event('focus'))
+
+ await waitFor(() => expect(mocks.invoke).toHaveBeenCalledTimes(2))
+ expect(mocks.invoke).toHaveBeenLastCalledWith(Queries.GetApplicationMenu)
+ })
+
+ it('does not subscribe or query on macOS', () => {
+ mocks.platform = 'darwin'
+ renderHook(() => useApplicationMenu())
+ expect(transport.platform).toBe('darwin')
+ expect(mocks.on).not.toHaveBeenCalled()
+ expect(mocks.invoke).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/hooks/use-application-menu.ts b/src/renderer/hooks/use-application-menu.ts
new file mode 100644
index 00000000..67116845
--- /dev/null
+++ b/src/renderer/hooks/use-application-menu.ts
@@ -0,0 +1,97 @@
+import { transport } from '@renderer/lib/transport'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import {
+ type ApplicationMenuSnapshot,
+ applicationMenuSnapshotSchema,
+ type ExecuteApplicationMenuItemRequest,
+} from '@shared/schemas/application-menu'
+import { useCallback, useEffect, useRef, useState } from 'react'
+
+export interface ApplicationMenuState {
+ snapshot: ApplicationMenuSnapshot | null
+ refresh: () => Promise<void>
+ executeItem: (request: ExecuteApplicationMenuItemRequest) => Promise<void>
+}
+
+function supportsRendererApplicationMenu(): boolean {
+ return (
+ __MOTRIX_TARGET__ === 'electron' &&
+ (transport.platform === 'win32' ||
+ transport.platform === 'linux' ||
+ (transport.platform === 'darwin' && __MOTRIX_PREVIEW_MAC_MENU__))
+ )
+}
+
+/**
+ * Mirrors the main-process application menu for the Windows/Linux renderer.
+ * The event listener is installed before the initial query and revisions can
+ * only move forward, so a slow query cannot overwrite a newer pushed snapshot.
+ */
+export function useApplicationMenu(): ApplicationMenuState {
+ const [snapshot, setSnapshot] = useState<ApplicationMenuSnapshot | null>(null)
+ const snapshotRef = useRef<ApplicationMenuSnapshot | null>(null)
+ const activeRef = useRef(false)
+
+ const applySnapshot = useCallback((value: unknown) => {
+ const parsed = applicationMenuSnapshotSchema.safeParse(value)
+ if (!parsed.success || !activeRef.current) return
+
+ const currentRevision = snapshotRef.current?.revision ?? -1
+ if (parsed.data.revision < currentRevision) return
+
+ snapshotRef.current = parsed.data
+ setSnapshot(parsed.data)
+ }, [])
+
+ const refresh = useCallback(async () => {
+ if (!supportsRendererApplicationMenu()) return
+ try {
+ applySnapshot(await transport.invoke(Queries.GetApplicationMenu))
+ } catch {
+ // A menu-open refresh or the next change event will retry.
+ }
+ }, [applySnapshot])
+
+ const executeItem = useCallback(
+ async (request: ExecuteApplicationMenuItemRequest) => {
+ if (!supportsRendererApplicationMenu()) return
+ try {
+ await transport.invoke(Commands.ExecuteApplicationMenuItem, request)
+ } catch {
+ // Never auto-retry an action: it may be destructive. Refresh instead
+ // so the next deliberate interaction uses the current revision.
+ await refresh()
+ }
+ },
+ [refresh]
+ )
+
+ useEffect(() => {
+ if (!supportsRendererApplicationMenu()) return
+
+ activeRef.current = true
+ const onChanged = (...args: unknown[]) => {
+ applySnapshot(args[0])
+ }
+
+ // Subscribe first, then snapshot: a mutation during the query cannot be
+ // lost, and the revision guard rejects an older query response afterward.
+ transport.on(Events.ApplicationMenuChanged, onChanged)
+ void refresh()
+
+ const onFocus = (): void => {
+ void refresh()
+ }
+ window.addEventListener('focus', onFocus)
+
+ return () => {
+ activeRef.current = false
+ transport.off(Events.ApplicationMenuChanged, onChanged)
+ window.removeEventListener('focus', onFocus)
+ }
+ }, [applySnapshot, refresh])
+
+ return { snapshot, refresh, executeItem }
+}
diff --git a/src/renderer/hooks/use-menu-context-sync.test.ts b/src/renderer/hooks/use-menu-context-sync.test.ts
new file mode 100644
index 00000000..639f67fa
--- /dev/null
+++ b/src/renderer/hooks/use-menu-context-sync.test.ts
@@ -0,0 +1,266 @@
+import { Commands } from '@shared/protocol/commands'
+import { act, renderHook } from '@testing-library/react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const hookState = vi.hoisted(() => ({
+ task: null as { id: string; status: string } | null,
+ atTop: false,
+ atBottom: false,
+ hasAnyActive: false,
+ hasAnyPaused: false,
+ hasStopped: false,
+ route: '/downloads',
+}))
+
+const transportMock = vi.hoisted(() => ({
+ invoke: vi.fn(),
+}))
+
+vi.mock('@renderer/lib/transport', () => ({
+ transport: transportMock,
+}))
+
+vi.mock('./use-selected-task', () => ({
+ useSelectedTask: () => ({
+ task: hookState.task,
+ atTop: hookState.atTop,
+ atBottom: hookState.atBottom,
+ }),
+}))
+
+vi.mock('./use-task-list', () => ({
+ useTaskList: () => ({
+ hasAnyActive: hookState.hasAnyActive,
+ hasAnyPaused: hookState.hasAnyPaused,
+ hasStopped: hookState.hasStopped,
+ }),
+}))
+
+vi.mock('./use-current-route', () => ({
+ useCurrentRoute: () => hookState.route,
+}))
+
+import { useMenuContextSync } from './use-menu-context-sync'
+
+interface Deferred<T = void> {
+ promise: Promise<T>
+ resolve(value: T): void
+ reject(reason?: unknown): void
+}
+
+function deferred<T = void>(): Deferred<T> {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise
+ reject = rejectPromise
+ })
+ return { promise, resolve, reject }
+}
+
+function fullContext(overrides: Record<string, unknown> = {}) {
+ return {
+ selectedTaskId: null,
+ selectedTaskStatus: null,
+ selectedTaskAtTop: false,
+ selectedTaskAtBottom: false,
+ hasAnyActiveTask: false,
+ hasAnyPausedTask: false,
+ hasStoppedTasks: false,
+ currentRoute: '/downloads',
+ ...overrides,
+ }
+}
+
+beforeEach(() => {
+ hookState.task = null
+ hookState.atTop = false
+ hookState.atBottom = false
+ hookState.hasAnyActive = false
+ hookState.hasAnyPaused = false
+ hookState.hasStopped = false
+ hookState.route = '/downloads'
+ transportMock.invoke.mockReset()
+})
+
+afterEach(() => {
+ vi.useRealTimers()
+ vi.clearAllMocks()
+})
+
+describe('useMenuContextSync', () => {
+ it('serializes writes and sends only the latest desired state after each acknowledgement', async () => {
+ const first = deferred()
+ const second = deferred()
+ transportMock.invoke
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise)
+ .mockResolvedValue(undefined)
+
+ const { rerender } = renderHook(() => useMenuContextSync())
+
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+ expect(transportMock.invoke).toHaveBeenNthCalledWith(
+ 1,
+ Commands.UpdateMenuContext,
+ fullContext()
+ )
+
+ hookState.hasAnyActive = true
+ hookState.route = '/settings'
+ rerender()
+ hookState.hasAnyPaused = true
+ hookState.route = '/activity'
+ rerender()
+
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ first.resolve()
+ await first.promise
+ })
+
+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)
+ expect(transportMock.invoke).toHaveBeenNthCalledWith(
+ 2,
+ Commands.UpdateMenuContext,
+ {
+ hasAnyActiveTask: true,
+ hasAnyPausedTask: true,
+ currentRoute: '/activity',
+ }
+ )
+
+ hookState.hasStopped = true
+ rerender()
+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)
+
+ await act(async () => {
+ second.resolve()
+ await second.promise
+ })
+
+ expect(transportMock.invoke).toHaveBeenCalledTimes(3)
+ expect(transportMock.invoke).toHaveBeenNthCalledWith(
+ 3,
+ Commands.UpdateMenuContext,
+ { hasStoppedTasks: true }
+ )
+
+ await act(async () => {
+ await Promise.resolve()
+ })
+ rerender()
+ expect(transportMock.invoke).toHaveBeenCalledTimes(3)
+ })
+
+ it('retries failures every 500ms from the acknowledged state to the latest desired state', async () => {
+ vi.useFakeTimers()
+ const first = deferred()
+ const second = deferred()
+ const third = deferred()
+ transportMock.invoke
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise)
+ .mockReturnValueOnce(third.promise)
+
+ const { rerender } = renderHook(() => useMenuContextSync())
+
+ await act(async () => {
+ first.reject(new Error('preload is not ready'))
+ await Promise.resolve()
+ })
+
+ hookState.task = { id: 'task-1', status: 'downloading' }
+ hookState.atTop = true
+ hookState.hasAnyActive = true
+ hookState.route = '/activity'
+ rerender()
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(499)
+ })
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1)
+ })
+ expect(transportMock.invoke).toHaveBeenCalledTimes(2)
+ expect(transportMock.invoke).toHaveBeenNthCalledWith(
+ 2,
+ Commands.UpdateMenuContext,
+ fullContext({
+ selectedTaskId: 'task-1',
+ selectedTaskStatus: 'downloading',
+ selectedTaskAtTop: true,
+ hasAnyActiveTask: true,
+ currentRoute: '/activity',
+ })
+ )
+
+ await act(async () => {
+ second.reject(new Error('main process is still unavailable'))
+ await Promise.resolve()
+ await vi.advanceTimersByTimeAsync(500)
+ })
+
+ expect(transportMock.invoke).toHaveBeenCalledTimes(3)
+ expect(transportMock.invoke).toHaveBeenNthCalledWith(
+ 3,
+ Commands.UpdateMenuContext,
+ fullContext({
+ selectedTaskId: 'task-1',
+ selectedTaskStatus: 'downloading',
+ selectedTaskAtTop: true,
+ hasAnyActiveTask: true,
+ currentRoute: '/activity',
+ })
+ )
+
+ await act(async () => {
+ third.resolve()
+ await third.promise
+ await vi.advanceTimersByTimeAsync(2_000)
+ })
+ expect(transportMock.invoke).toHaveBeenCalledTimes(3)
+ })
+
+ it('clears a scheduled retry when unmounted', async () => {
+ vi.useFakeTimers()
+ transportMock.invoke.mockRejectedValue(new Error('not ready'))
+
+ const { unmount } = renderHook(() => useMenuContextSync())
+ await act(async () => {
+ await Promise.resolve()
+ })
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+ expect(vi.getTimerCount()).toBe(1)
+
+ unmount()
+ expect(vi.getTimerCount()).toBe(0)
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(2_000)
+ })
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not retry or acknowledge a request that settles after unmount', async () => {
+ vi.useFakeTimers()
+ const request = deferred()
+ transportMock.invoke.mockReturnValue(request.promise)
+
+ const { unmount } = renderHook(() => useMenuContextSync())
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+
+ unmount()
+ await act(async () => {
+ request.reject(new Error('late failure'))
+ await Promise.resolve()
+ await vi.advanceTimersByTimeAsync(2_000)
+ })
+
+ expect(transportMock.invoke).toHaveBeenCalledTimes(1)
+ expect(vi.getTimerCount()).toBe(0)
+ })
+})
diff --git a/src/renderer/hooks/use-menu-context-sync.ts b/src/renderer/hooks/use-menu-context-sync.ts
index dc71bd2a..dd038244 100644
--- a/src/renderer/hooks/use-menu-context-sync.ts
+++ b/src/renderer/hooks/use-menu-context-sync.ts
@@ -8,6 +8,8 @@ import { useTaskList } from './use-task-list'
type Patch = Partial<MenuContext>
+const RETRY_DELAY_MS = 500
+
function diff(prev: Patch, next: Patch): Patch {
const out: Patch = {}
let changed = false
@@ -29,12 +31,69 @@ export function useMenuContextSync(): void {
const selected = useSelectedTask()
const list = useTaskList()
const route = useCurrentRoute()
- const lastSent = useRef<Patch>({})
+ const acknowledged = useRef<Patch>({})
+ const desired = useRef<Patch>({})
+ const drainOutbox = useRef<() => void>(() => {})
useEffect(() => {
if (__MOTRIX_TARGET__ !== 'electron') return
- const next: Patch = {
+ let disposed = false
+ let inFlight = false
+ let retryTimer: ReturnType<typeof setTimeout> | null = null
+
+ const clearRetry = (): void => {
+ if (retryTimer === null) return
+ clearTimeout(retryTimer)
+ retryTimer = null
+ }
+
+ const scheduleRetry = (): void => {
+ if (disposed || retryTimer !== null) return
+ retryTimer = setTimeout(() => {
+ retryTimer = null
+ drain()
+ }, RETRY_DELAY_MS)
+ }
+
+ const drain = (): void => {
+ if (disposed || inFlight || retryTimer !== null) return
+
+ const patch = diff(acknowledged.current, desired.current)
+ if (Object.keys(patch).length === 0) return
+
+ inFlight = true
+ void (async () => {
+ try {
+ await transport.invoke(Commands.UpdateMenuContext, patch)
+ } catch {
+ if (disposed) return
+ inFlight = false
+ scheduleRetry()
+ return
+ }
+
+ if (disposed) return
+ acknowledged.current = { ...acknowledged.current, ...patch }
+ inFlight = false
+ drain()
+ })()
+ }
+
+ drainOutbox.current = drain
+ drain()
+
+ return () => {
+ disposed = true
+ clearRetry()
+ drainOutbox.current = () => {}
+ }
+ }, [])
+
+ useEffect(() => {
+ if (__MOTRIX_TARGET__ !== 'electron') return
+
+ desired.current = {
selectedTaskId: selected.task?.id ?? null,
selectedTaskStatus: selected.task?.status ?? null,
selectedTaskAtTop: selected.atTop,
@@ -44,13 +103,6 @@ export function useMenuContextSync(): void {
hasStoppedTasks: list.hasStopped,
currentRoute: route,
}
-
- const patch = diff(lastSent.current, next)
- if (Object.keys(patch).length === 0) return
-
- lastSent.current = next
- transport.invoke(Commands.UpdateMenuContext, patch).catch(() => {
- // Ignore — preload may not be ready yet; next render retries.
- })
+ drainOutbox.current()
}, [selected, list, route])
}
diff --git a/src/renderer/layouts/app-layout.test.tsx b/src/renderer/layouts/app-layout.test.tsx
index addd16d5..817d4fba 100644
--- a/src/renderer/layouts/app-layout.test.tsx
+++ b/src/renderer/layouts/app-layout.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
-import { render, screen } from '@testing-library/react'
+import { act, render, screen } from '@testing-library/react'
import { createMemoryRouter, RouterProvider } from 'react-router'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { AppLayout } from './app-layout'
@@ -80,6 +80,37 @@ beforeEach(() => {
})
describe('AppLayout', () => {
+ it('renders the renderer application menu in the Windows leading slot', async () => {
+ Object.defineProperty(window.motrix, 'platform', {
+ value: 'win32',
+ configurable: true,
+ })
+ await act(async () => {
+ renderAppLayout()
+ await Promise.resolve()
+ })
+
+ const trigger = screen.getByRole('button', { name: 'Motrix' })
+ expect(trigger).toHaveAttribute('data-slot', 'motrix-menu-trigger')
+ expect(
+ trigger.closest('[data-slot="window-chrome-leading"]')
+ ).not.toBeNull()
+ expect(document.querySelector('[data-slot="sidebar-wrapper"]')).toHaveClass(
+ 'electron-window-chrome'
+ )
+ })
+
+ it('keeps Electron chrome safe-area overrides out of the web target', () => {
+ vi.stubGlobal('__MOTRIX_TARGET__', 'web')
+
+ renderAppLayout()
+
+ expect(
+ document.querySelector('[data-slot="sidebar-wrapper"]')
+ ).not.toHaveClass('electron-window-chrome')
+ vi.stubGlobal('__MOTRIX_TARGET__', 'electron')
+ })
+
it('keeps the sidebar-wrapper background in mobile mode', () => {
// Below the 768px breakpoint the Sidebar renders as a portaled Sheet
// without data-variant="inset", so the wrapper's conditional
diff --git a/src/renderer/layouts/app-layout.tsx b/src/renderer/layouts/app-layout.tsx
index a7b4be13..1dee4176 100644
--- a/src/renderer/layouts/app-layout.tsx
+++ b/src/renderer/layouts/app-layout.tsx
@@ -4,6 +4,7 @@ import { SidebarInset, SidebarProvider } from '@renderer/components/ui/sidebar'
import { Toaster } from '@renderer/components/ui/toast'
import { TooltipProvider } from '@renderer/components/ui/tooltip'
import { AddTaskTriggerButton } from '@renderer/components/window-chrome/add-task-trigger-button'
+import { MotrixMenuButton } from '@renderer/components/window-chrome/motrix-menu-button'
import { SidebarTriggerButton } from '@renderer/components/window-chrome/sidebar-trigger-button'
import { WindowChrome } from '@renderer/components/window-chrome/window-chrome'
import { EngineDiagnosticsDialogHost } from '@renderer/features/engine-diagnostics/engine-diagnostics-dialog'
@@ -50,8 +51,13 @@ export function AppLayout() {
wrapper's built-in has-data-[variant=inset]:bg-sidebar stops
matching and transparent-inset pages would fall through to the
white body background. */}
- <SidebarProvider className="h-svh overflow-hidden bg-sidebar">
- <WindowChrome variant="overlay">
+ <SidebarProvider
+ className={cn(
+ 'h-svh overflow-hidden bg-sidebar',
+ __MOTRIX_TARGET__ === 'electron' && 'electron-window-chrome'
+ )}
+ >
+ <WindowChrome variant="overlay" leading={<MotrixMenuButton />}>
<div className="pt-3.5 flex items-center gap-1.5">
<SidebarTriggerButton />
<AddTaskTriggerButton />
diff --git a/src/renderer/styles/globals.css b/src/renderer/styles/globals.css
index 362195d0..d6d9ef55 100644
--- a/src/renderer/styles/globals.css
+++ b/src/renderer/styles/globals.css
@@ -97,6 +97,8 @@
:root {
--radius: 0.625rem;
--dashboard-tile-radius: 18px;
+ --window-chrome-safe-area-leading: 77px;
+ --window-chrome-safe-area-trailing: 24px;
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
@@ -139,6 +141,20 @@
--tab-background: oklch(0.95 0 0);
}
+.platform-darwin.window-main .electron-window-chrome,
+.platform-linux.window-main .electron-window-chrome,
+.platform-win32.window-main .electron-window-chrome {
+ --window-chrome-safe-area-leading: 160px;
+}
+
+.platform-win32.window-main .electron-window-chrome {
+ --window-chrome-safe-area-trailing: 148px;
+}
+
+.platform-linux.window-main .electron-window-chrome {
+ --window-chrome-safe-area-trailing: 88px;
+}
+
.dark {
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
diff --git a/src/shared/protocol/commands.ts b/src/shared/protocol/commands.ts
index 17770567..2b14d49e 100644
--- a/src/shared/protocol/commands.ts
+++ b/src/shared/protocol/commands.ts
@@ -49,6 +49,7 @@ export const Commands = {
NextTorrent: 'command:nextTorrent',
DownloadAllTorrents: 'command:downloadAllTorrents',
CloseCurrentWindow: 'command:closeCurrentWindow',
+ MinimizeCurrentWindow: 'command:minimizeCurrentWindow',
ShowMainWindow: 'command:showMainWindow',
ShowAddTaskWindow: 'command:showAddTaskWindow',
// Torrent
@@ -81,6 +82,7 @@ export const Commands = {
RevealInFolder: 'command:revealInFolder',
// Menu
UpdateMenuContext: 'command:updateMenuContext',
+ ExecuteApplicationMenuItem: 'command:executeApplicationMenuItem',
// Task creation (engine-neutral)
CreateTask: 'command:createTask',
// GeoIP
diff --git a/src/shared/protocol/events.ts b/src/shared/protocol/events.ts
index e09972a9..7af7aa8d 100644
--- a/src/shared/protocol/events.ts
+++ b/src/shared/protocol/events.ts
@@ -96,6 +96,7 @@ export const Events = {
// Payload: EngineFailurePayload (Task 13). NOT included in
// ForwardableEvents — internal main-process producer signal only.
EngineFailureOccurred: 'event:engineFailureOccurred',
+ ApplicationMenuChanged: 'event:applicationMenuChanged',
} as const
export type EventChannel = (typeof Events)[keyof typeof Events]
diff --git a/src/shared/protocol/forwardable-events.test.ts b/src/shared/protocol/forwardable-events.test.ts
index a477745d..69d7ded6 100644
--- a/src/shared/protocol/forwardable-events.test.ts
+++ b/src/shared/protocol/forwardable-events.test.ts
@@ -104,4 +104,8 @@ describe('ForwardableEvents', () => {
it('excludes EngineFailureOccurred (internal main-process producer signal)', () => {
expect(ForwardableEvents).not.toContain(Events.EngineFailureOccurred)
})
+
+ it('excludes the Electron-only application-menu mirror event', () => {
+ expect(ForwardableEvents).not.toContain(Events.ApplicationMenuChanged)
+ })
})
diff --git a/src/shared/protocol/queries.ts b/src/shared/protocol/queries.ts
index 2875b394..0d73ab17 100644
--- a/src/shared/protocol/queries.ts
+++ b/src/shared/protocol/queries.ts
@@ -71,6 +71,7 @@ export const Queries = {
// GetUnreadNotificationCount returns the unread badge count as a number.
GetUnreadNotificationCount: 'query:getUnreadNotificationCount',
GetCliToolStatus: 'query:getCliToolStatus',
+ GetApplicationMenu: 'query:getApplicationMenu',
} as const
export type QueryChannel = (typeof Queries)[keyof typeof Queries]
diff --git a/src/shared/schemas/application-menu.test.ts b/src/shared/schemas/application-menu.test.ts
new file mode 100644
index 00000000..17cf6b4a
--- /dev/null
+++ b/src/shared/schemas/application-menu.test.ts
@@ -0,0 +1,235 @@
+import { describe, expect, it } from 'vitest'
+import {
+ applicationMenuNodeSchema,
+ applicationMenuSnapshotSchema,
+ executeApplicationMenuItemRequestSchema,
+} from './application-menu'
+
+const snapshot = {
+ revision: 7,
+ items: [
+ {
+ id: 'menubar.task',
+ type: 'submenu',
+ label: 'Task',
+ enabled: true,
+ visible: true,
+ children: [
+ {
+ id: 'task.pause',
+ type: 'normal',
+ label: 'Pause',
+ accelerator: 'CommandOrControl+P',
+ enabled: false,
+ visible: true,
+ },
+ {
+ id: 'task.mode.fast',
+ type: 'radio',
+ label: 'Fast',
+ enabled: true,
+ visible: true,
+ checked: true,
+ radioGroupId: 'task.mode',
+ },
+ ],
+ },
+ ],
+} as const
+
+describe('applicationMenuSnapshotSchema', () => {
+ it('parses a recursive application-menu snapshot', () => {
+ expect(applicationMenuSnapshotSchema.parse(snapshot)).toEqual(snapshot)
+ })
+
+ it('supports every menu node type', () => {
+ for (const type of [
+ 'normal',
+ 'submenu',
+ 'separator',
+ 'checkbox',
+ 'radio',
+ ]) {
+ expect(
+ applicationMenuNodeSchema.safeParse({
+ id: `item.${type}`,
+ type,
+ label: type === 'separator' ? '' : type,
+ enabled: true,
+ visible: true,
+ ...(type === 'checkbox' || type === 'radio'
+ ? { checked: false }
+ : {}),
+ ...(type === 'radio' ? { radioGroupId: 'item.mode' } : {}),
+ ...(type === 'submenu' ? { children: [] } : {}),
+ }).success
+ ).toBe(true)
+ }
+ })
+
+ it('rejects unknown keys at the snapshot and every recursive node', () => {
+ expect(
+ applicationMenuSnapshotSchema.safeParse({ ...snapshot, extra: true })
+ .success
+ ).toBe(false)
+ expect(
+ applicationMenuSnapshotSchema.safeParse({
+ ...snapshot,
+ items: [
+ {
+ ...snapshot.items[0],
+ children: [
+ {
+ ...snapshot.items[0].children[0],
+ injected: 'value',
+ },
+ ],
+ },
+ ],
+ }).success
+ ).toBe(false)
+ })
+
+ it('rejects invalid revisions and node types', () => {
+ expect(
+ applicationMenuSnapshotSchema.safeParse({ ...snapshot, revision: -1 })
+ .success
+ ).toBe(false)
+ expect(
+ applicationMenuSnapshotSchema.safeParse({ ...snapshot, revision: 1.5 })
+ .success
+ ).toBe(false)
+ expect(
+ applicationMenuSnapshotSchema.safeParse({
+ ...snapshot,
+ items: [{ ...snapshot.items[0], type: 'heading' }],
+ }).success
+ ).toBe(false)
+ })
+
+ it('enforces checkable, radio-group, and submenu structure', () => {
+ expect(
+ applicationMenuNodeSchema.safeParse({
+ id: 'radio.missing-group',
+ type: 'radio',
+ label: 'Radio',
+ enabled: true,
+ visible: true,
+ checked: true,
+ }).success
+ ).toBe(false)
+ expect(
+ applicationMenuNodeSchema.safeParse({
+ id: 'normal.with-children',
+ type: 'normal',
+ label: 'Normal',
+ enabled: true,
+ visible: true,
+ children: [],
+ }).success
+ ).toBe(false)
+ })
+
+ it('rejects empty and oversized node identifiers', () => {
+ for (const id of ['', 'x'.repeat(257)]) {
+ expect(
+ applicationMenuSnapshotSchema.safeParse({
+ ...snapshot,
+ items: [{ ...snapshot.items[0], id }],
+ }).success
+ ).toBe(false)
+ }
+
+ expect(
+ applicationMenuNodeSchema.safeParse({
+ ...snapshot.items[0].children[1],
+ radioGroupId: 'x'.repeat(257),
+ }).success
+ ).toBe(false)
+ })
+})
+
+describe('executeApplicationMenuItemRequestSchema', () => {
+ const request = {
+ itemId: 'task.pause',
+ revision: 7,
+ trigger: 'menu',
+ selectedTaskId: 'task-1',
+ modifiers: {
+ alt: false,
+ control: true,
+ meta: false,
+ shift: false,
+ },
+ } as const
+
+ it('parses the strict execution request', () => {
+ expect(executeApplicationMenuItemRequestSchema.parse(request)).toEqual(
+ request
+ )
+ expect(
+ executeApplicationMenuItemRequestSchema.parse({
+ itemId: 'task.pause',
+ revision: 7,
+ trigger: 'menu',
+ selectedTaskId: null,
+ })
+ ).toEqual({
+ itemId: 'task.pause',
+ revision: 7,
+ trigger: 'menu',
+ selectedTaskId: null,
+ })
+ })
+
+ it('rejects unknown request and modifier keys', () => {
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse({
+ ...request,
+ extra: true,
+ }).success
+ ).toBe(false)
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse({
+ ...request,
+ modifiers: { ...request.modifiers, super: true },
+ }).success
+ ).toBe(false)
+ })
+
+ it('requires a complete modifier snapshot and the menu trigger', () => {
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse({
+ ...request,
+ modifiers: { alt: false },
+ }).success
+ ).toBe(false)
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse({
+ ...request,
+ trigger: 'keyboard',
+ }).success
+ ).toBe(false)
+ const { selectedTaskId: _selectedTaskId, ...withoutContext } = request
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse(withoutContext).success
+ ).toBe(false)
+ })
+
+ it('rejects empty or oversized item IDs and fractional revisions', () => {
+ for (const itemId of ['', 'x'.repeat(257)]) {
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse({
+ ...request,
+ itemId,
+ }).success
+ ).toBe(false)
+ }
+ expect(
+ executeApplicationMenuItemRequestSchema.safeParse({
+ ...request,
+ revision: 1.5,
+ }).success
+ ).toBe(false)
+ })
+})
diff --git a/src/shared/schemas/application-menu.ts b/src/shared/schemas/application-menu.ts
new file mode 100644
index 00000000..afc7a5af
--- /dev/null
+++ b/src/shared/schemas/application-menu.ts
@@ -0,0 +1,93 @@
+import { z } from 'zod'
+
+export const applicationMenuNodeTypeSchema = z.enum([
+ 'normal',
+ 'submenu',
+ 'separator',
+ 'checkbox',
+ 'radio',
+])
+
+const menuItemIdSchema = z.string().min(1).max(256)
+
+const applicationMenuNodeFieldsSchema = z
+ .object({
+ id: menuItemIdSchema,
+ type: applicationMenuNodeTypeSchema,
+ label: z.string(),
+ accelerator: z.string().min(1).optional(),
+ enabled: z.boolean(),
+ visible: z.boolean(),
+ checked: z.boolean().optional(),
+ radioGroupId: menuItemIdSchema.optional(),
+ })
+ .strict()
+
+type ApplicationMenuNodeFields = z.infer<typeof applicationMenuNodeFieldsSchema>
+
+export interface ApplicationMenuNode extends ApplicationMenuNodeFields {
+ children?: ApplicationMenuNode[]
+}
+
+export const applicationMenuNodeSchema: z.ZodType<ApplicationMenuNode> = z.lazy(
+ () =>
+ applicationMenuNodeFieldsSchema
+ .extend({
+ children: z.array(applicationMenuNodeSchema).optional(),
+ })
+ .superRefine((node, context) => {
+ const checkable = node.type === 'checkbox' || node.type === 'radio'
+ if (checkable && node.checked === undefined) {
+ context.addIssue({
+ code: 'custom',
+ message: `${node.type} nodes require checked state`,
+ })
+ }
+ if ((node.type === 'radio') !== Boolean(node.radioGroupId)) {
+ context.addIssue({
+ code: 'custom',
+ message: 'radio nodes require an exclusive radioGroupId',
+ })
+ }
+ if ((node.type === 'submenu') !== Boolean(node.children)) {
+ context.addIssue({
+ code: 'custom',
+ message: 'only submenu nodes may contain children',
+ })
+ }
+ })
+)
+
+export const applicationMenuSnapshotSchema = z
+ .object({
+ revision: z.number().int().nonnegative(),
+ items: z.array(applicationMenuNodeSchema),
+ })
+ .strict()
+
+export type ApplicationMenuSnapshot = z.infer<
+ typeof applicationMenuSnapshotSchema
+>
+
+export const applicationMenuModifiersSchema = z
+ .object({
+ alt: z.boolean(),
+ control: z.boolean(),
+ meta: z.boolean(),
+ shift: z.boolean(),
+ })
+ .strict()
+
+export const executeApplicationMenuItemRequestSchema = z
+ .object({
+ itemId: menuItemIdSchema,
+ revision: z.number().int().nonnegative(),
+ trigger: z.literal('menu'),
+ selectedTaskId: z.string().min(1).nullable(),
+ modifiers: applicationMenuModifiersSchema.optional(),
+ })
+ .strict()
+
+export type ExecuteApplicationMenuItemRequest = z.infer<
+ typeof executeApplicationMenuItemRequestSchema
+>
diff --git a/vite.renderer.config.ts b/vite.renderer.config.ts
index 9ed45e6f..a1630d8f 100644
--- a/vite.renderer.config.ts
+++ b/vite.renderer.config.ts
@@ -3,13 +3,16 @@ import tailwindcss from '@tailwindcss/vite'
import { defineConfig } from 'vite'
import packageJson from './package.json' with { type: 'json' }
-export default defineConfig({
+export default defineConfig(({ command }) => ({
// Electron file:// + asar needs relative asset paths; the default
// '/' resolves to the filesystem root, not inside the asar.
base: './',
plugins: [tailwindcss()],
define: {
__MOTRIX_TARGET__: JSON.stringify('electron'),
+ __MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(
+ command === 'serve' && process.env.MOTRIX_PREVIEW_MAC_MENU === '1'
+ ),
__MOTRIX_APP_METADATA__: JSON.stringify({
name: packageJson.productName,
version: packageJson.version,
@@ -27,4 +30,4 @@ export default defineConfig({
'@renderer': path.resolve(import.meta.dirname, 'src/renderer'),
},
},
-})
+}))
diff --git a/vite.renderer.web.config.ts b/vite.renderer.web.config.ts
index bf69ff7e..181edcf6 100644
--- a/vite.renderer.web.config.ts
+++ b/vite.renderer.web.config.ts
@@ -8,6 +8,7 @@ export default defineConfig({
plugins: [tailwindcss()],
define: {
__MOTRIX_TARGET__: JSON.stringify('web'),
+ __MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(false),
__MOTRIX_APP_METADATA__: JSON.stringify({
name: packageJson.productName,
version: packageJson.version,
diff --git a/vitest.config.ts b/vitest.config.ts
index dcdc6460..89d8d881 100644
--- a/vitest.config.ts
+++ b/vitest.config.ts
@@ -5,6 +5,7 @@ import packageJson from './package.json' with { type: 'json' }
export default defineConfig({
define: {
__MOTRIX_TARGET__: JSON.stringify('electron'),
+ __MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(false),
__MOTRIX_APP_METADATA__: JSON.stringify({
name: packageJson.productName,
version: packageJson.version,