Skip to content

A full-featured download manager.

feat(linux): use native window controls overlay (#2447)

Dr_rOot6d4febecd7b8
diff --git a/README.md b/README.md
index c3a6a161..59d65bd1 100644
--- a/README.md
+++ b/README.md
@@ -247,8 +247,10 @@ MOTRIX_PREVIEW_MAC_MENU=1 pnpm start
```
The flag hides the main window's macOS traffic-light buttons, enables the
-renderer dropdown menu, and shows the custom window controls used on Windows
-and Linux. Collapse the sidebar in this mode to check the application menu,
+renderer dropdown menu, and shows the custom window controls used on Windows.
+Linux uses Electron's Window Controls Overlay to follow supported desktop
+button layouts and themes; validate those native controls in a Linux desktop
+session. Collapse the sidebar in preview mode to check the application menu,
attached actions, drag region, and caption-control safe areas together.
Restart the development process after changing the flag because both Electron
and Vite read it at startup.
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 63b1e152..e0ecd986 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -232,7 +232,9 @@ MOTRIX_PREVIEW_MAC_MENU=1 pnpm start
```
该开关会隐藏主窗口的 macOS 红绿灯按钮,启用 renderer dropdown menu,并显示
-Windows/Linux 使用的自绘窗体按钮。可在这个模式下收起 Sidebar,联合检查应用菜单、
+Windows 使用的自绘窗体按钮。Linux 使用 Electron Window Controls Overlay,跟随其
+支持的桌面按钮布局和主题;这些原生按钮需要在 Linux 桌面会话中验收。
+可在预览模式下收起 Sidebar,联合检查应用菜单、
附加 actions、拖拽区域和窗体按钮的安全间距。Electron 和 Vite 都会在启动时读取此
开关,因此修改后需要重启开发进程。
diff --git a/e2e/window-chrome/harness.css b/e2e/window-chrome/harness.css
new file mode 100644
index 00000000..7a8f1364
--- /dev/null
+++ b/e2e/window-chrome/harness.css
@@ -0,0 +1,4 @@
+@import "../../src/renderer/styles/globals.css";
+
+/* Include real component utilities when Vite runs from this fixture directory. */
+@source "../../src/renderer";
diff --git a/e2e/window-chrome/harness.tsx b/e2e/window-chrome/harness.tsx
new file mode 100644
index 00000000..e71f716d
--- /dev/null
+++ b/e2e/window-chrome/harness.tsx
@@ -0,0 +1,222 @@
+import { PanelShell } from '@renderer/components/desktop-kit/panel/panel-shell'
+import { OnboardingLanguageSelect } from '@renderer/components/onboarding/onboarding-language-select'
+import { PluginConfigField } from '@renderer/components/settings-kit/plugin-config-field'
+import { DirectionProvider } from '@renderer/components/ui/direction'
+import {
+ Sidebar,
+ SidebarContent,
+ SidebarHeader,
+ SidebarInset,
+ SidebarProvider,
+} from '@renderer/components/ui/sidebar'
+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 { WindowControlsOverlayProvider } from '@renderer/components/window-chrome/window-controls-overlay-provider'
+import { applyRendererLocale } from '@renderer/lib/i18n'
+import { DownloadsToolbar } from '@renderer/routes/downloads/downloads-toolbar'
+import {
+ countTasksByTab,
+ countTasksByType,
+ type DownloadsTab,
+} from '@renderer/routes/downloads/filter'
+import { StatusTitleMenu } from '@renderer/routes/downloads/status-title-menu'
+import { useDownloadsSelection } from '@renderer/routes/downloads/store'
+import './harness.css'
+import { WINDOW_CONTROLS_OVERLAY_HEIGHT } from '@shared/constants/window-chrome'
+import { Commands } from '@shared/protocol/commands'
+import { Events } from '@shared/protocol/events'
+import { Queries } from '@shared/protocol/queries'
+import type { TaskType } from '@shared/types/task'
+import { useState } from 'react'
+import { createRoot } from 'react-dom/client'
+import { FormProvider, useForm } from 'react-hook-form'
+import { MemoryRouter } from 'react-router'
+
+declare global {
+ interface Window {
+ windowChromeFixture: { commands: string[] }
+ }
+}
+
+const params = new URLSearchParams(location.search)
+const platform = params.get('platform') ?? 'linux'
+const mode = params.get('mode') ?? 'main'
+const expanded = params.has('expanded')
+const dir = params.get('dir') === 'rtl' ? 'rtl' : 'ltr'
+const listeners = new Map<string, Set<(...args: unknown[]) => void>>()
+class FixtureOverlay extends EventTarget {
+ visible = !params.has('fullscreen')
+ getTitlebarAreaRect() {
+ return new DOMRect(
+ 0,
+ 0,
+ innerWidth,
+ this.visible ? WINDOW_CONTROLS_OVERLAY_HEIGHT : 0
+ )
+ }
+}
+const overlay = new FixtureOverlay()
+Object.defineProperty(navigator, 'windowControlsOverlay', {
+ value: overlay,
+ configurable: true,
+})
+Object.assign(window, {
+ windowChromeFixture: { commands: [] },
+ motrix: {
+ platform,
+ invoke: async (channel: string) => {
+ window.windowChromeFixture.commands.push(channel)
+ if (channel === Queries.GetSettings)
+ return { app: { liquidGlassEffect: false } }
+ if (channel === Commands.GetPluginOperations) return { descriptors: [] }
+ if (channel === Queries.GetDisclaimerState) return { language: 'system' }
+ if (channel === Queries.GetApplicationMenu) {
+ return {
+ revision: 1,
+ items: [
+ {
+ id: 'app.about',
+ type: 'normal',
+ label: 'About Motrix',
+ enabled: true,
+ visible: true,
+ },
+ ],
+ }
+ }
+ return undefined
+ },
+ on(channel: string, listener: (...args: unknown[]) => void) {
+ if (!listeners.has(channel)) listeners.set(channel, new Set())
+ listeners.get(channel)?.add(listener)
+ return () => listeners.get(channel)?.delete(listener)
+ },
+ },
+})
+window.addEventListener('fixture-fullscreen', (event) => {
+ overlay.visible = !(event as CustomEvent).detail
+ overlay.dispatchEvent(new Event('geometrychange'))
+ for (const listener of listeners.get(Events.WindowMaximizedChanged) ?? []) {
+ listener({ maximized: false, fullscreen: (event as CustomEvent).detail })
+ }
+})
+document.documentElement.className = `platform-${platform} window-${mode}`
+await applyRendererLocale('en-US')
+document.documentElement.dir = dir
+
+function MainWindow() {
+ const [query, setQuery] = useState('')
+ const [types, setTypes] = useState<TaskType[]>([])
+ const [tab, setTab] = useState<DownloadsTab>('all')
+ return (
+ <SidebarProvider
+ defaultOpen={expanded}
+ className="electron-window-chrome h-svh overflow-hidden bg-sidebar"
+ >
+ <WindowChrome variant="overlay" leading={<MotrixMenuButton />}>
+ <div className="flex items-center gap-1.5">
+ <SidebarTriggerButton />
+ <AddTaskTriggerButton />
+ </div>
+ </WindowChrome>
+ <Sidebar variant="inset" side={dir === 'rtl' ? 'right' : 'left'}>
+ <SidebarHeader style={{ height: 45 }} />
+ <SidebarContent />
+ </Sidebar>
+ <SidebarInset className="m-2 min-h-0 overflow-hidden rounded-xl bg-sidebar-inset">
+ <PanelShell
+ title={
+ <StatusTitleMenu
+ tab={tab}
+ onTabChange={setTab}
+ counts={countTasksByTab([])}
+ />
+ }
+ actions={
+ <DownloadsToolbar
+ tasks={[]}
+ selection={useDownloadsSelection}
+ onHideInspector={() => {}}
+ query={query}
+ onQueryChange={setQuery}
+ types={types}
+ onTypesChange={setTypes}
+ typeCounts={countTasksByType([])}
+ />
+ }
+ actionsDraggable
+ headerClassName="compact-header:py-1"
+ actionsClassName="min-w-0 flex-1"
+ >
+ <div data-testid="panel-content">Download list</div>
+ </PanelShell>
+ </SidebarInset>
+ </SidebarProvider>
+ )
+}
+
+function PluginSettings() {
+ const form = useForm({ defaultValues: { choice: 'Option 15' } })
+ return (
+ <FormProvider {...form}>
+ <div className="px-4 pt-20">
+ <PluginConfigField
+ name="choice"
+ node={{
+ type: 'string',
+ enum: Array.from({ length: 30 }, (_, index) => `Option ${index}`),
+ }}
+ />
+ </div>
+ </FormProvider>
+ )
+}
+
+const root = document.getElementById('root')
+if (!root) throw new Error('Missing fixture root')
+createRoot(root).render(
+ <MemoryRouter>
+ <DirectionProvider direction={dir}>
+ <TooltipProvider>
+ <WindowControlsOverlayProvider>
+ {mode === 'main' ? (
+ <MainWindow />
+ ) : mode === 'plugin-settings' ? (
+ <PluginSettings />
+ ) : (
+ <div className="flex h-svh flex-col bg-background">
+ <WindowChrome
+ title={mode === 'add-task' ? 'New task' : 'Motrix'}
+ maximizable={false}
+ actionsPosition="end"
+ >
+ {mode === 'onboarding' && <OnboardingLanguageSelect />}
+ </WindowChrome>
+ <div data-testid="panel-content">Window content</div>
+ </div>
+ )}
+ </WindowControlsOverlayProvider>
+ </TooltipProvider>
+ </DirectionProvider>
+ </MemoryRouter>
+)
+
+// Inject only WCO geometry/hit regions: toolbar, popup and menu behavior is real.
+for (const side of ['left', 'right'] as const) {
+ const overlay = document.createElement('div')
+ overlay.dataset.nativeOverlay = side
+ Object.assign(overlay.style, {
+ position: 'fixed',
+ top: '0',
+ [side]: '0',
+ width: `var(--window-controls-overlay-${side})`,
+ height: `${WINDOW_CONTROLS_OVERLAY_HEIGHT}px`,
+ zIndex: '9999',
+ background: '#808080',
+ pointerEvents: platform === 'linux' ? 'auto' : 'none',
+ })
+ document.body.append(overlay)
+}
diff --git a/e2e/window-chrome/index.html b/e2e/window-chrome/index.html
new file mode 100644
index 00000000..7e04cd5d
--- /dev/null
+++ b/e2e/window-chrome/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Motrix window chrome verification</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/harness.tsx"></script>
+ </body>
+</html>
diff --git a/e2e/window-chrome/native.playwright.config.ts b/e2e/window-chrome/native.playwright.config.ts
new file mode 100644
index 00000000..3fab65ec
--- /dev/null
+++ b/e2e/window-chrome/native.playwright.config.ts
@@ -0,0 +1,30 @@
+import path from 'node:path'
+import { defineConfig } from '@playwright/test'
+
+// Opt-in: runs against a real GNOME desktop and temporarily changes its button
+// layout / GTK theme. The fixture restores both settings after every test.
+export default defineConfig({
+ testDir: '.',
+ testMatch: '*.native.ts',
+ workers: 1,
+ fullyParallel: false,
+ retries: 0,
+ timeout: 90_000,
+ expect: { timeout: 15_000 },
+ globalSetup: '../global-setup.ts',
+ reporter: [
+ ['list'],
+ [
+ 'html',
+ {
+ open: 'never',
+ outputFolder: path.resolve(
+ import.meta.dirname,
+ '../../output/playwright/reports/window-chrome-native'
+ ),
+ },
+ ],
+ ],
+ outputDir: '../../output/playwright/test-results/window-chrome-native',
+ use: { screenshot: 'only-on-failure', trace: 'retain-on-failure' },
+})
diff --git a/e2e/window-chrome/playwright.config.ts b/e2e/window-chrome/playwright.config.ts
new file mode 100644
index 00000000..4ea1a302
--- /dev/null
+++ b/e2e/window-chrome/playwright.config.ts
@@ -0,0 +1,27 @@
+import { fileURLToPath } from 'node:url'
+import { defineConfig } from '@playwright/test'
+
+export default defineConfig({
+ testDir: '.',
+ testMatch: '**/*.browser.ts',
+ workers: 1,
+ retries: 0,
+ timeout: 30_000,
+ reporter: [['list']],
+ outputDir: '../../output/playwright/test-results/window-chrome',
+ use: {
+ baseURL: 'http://127.0.0.1:4186',
+ browserName: 'chromium',
+ headless: true,
+ screenshot: 'only-on-failure',
+ launchOptions: process.env.MOTRIX_BROWSER_EXECUTABLE
+ ? { executablePath: process.env.MOTRIX_BROWSER_EXECUTABLE }
+ : undefined,
+ },
+ webServer: {
+ command: 'pnpm exec vite --config e2e/window-chrome/vite.config.ts',
+ cwd: fileURLToPath(new URL('../..', import.meta.url)),
+ url: 'http://127.0.0.1:4186',
+ reuseExistingServer: !process.env.CI,
+ },
+})
diff --git a/e2e/window-chrome/vite.config.ts b/e2e/window-chrome/vite.config.ts
new file mode 100644
index 00000000..1f300a16
--- /dev/null
+++ b/e2e/window-chrome/vite.config.ts
@@ -0,0 +1,29 @@
+import path from 'node:path'
+import tailwindcss from '@tailwindcss/vite'
+import { defineConfig } from 'vite'
+import packageJson from '../../package.json' with { type: 'json' }
+
+const repositoryRoot = path.resolve(import.meta.dirname, '../..')
+
+export default defineConfig({
+ root: import.meta.dirname,
+ plugins: [tailwindcss()],
+ define: {
+ __MOTRIX_TARGET__: JSON.stringify('electron'),
+ __MOTRIX_PREVIEW_MAC_MENU__: JSON.stringify(false),
+ __MOTRIX_APP_METADATA__: JSON.stringify({
+ name: packageJson.productName,
+ version: packageJson.version,
+ author: packageJson.author,
+ license: packageJson.license,
+ }),
+ },
+ resolve: {
+ alias: {
+ '@renderer': path.join(repositoryRoot, 'src/renderer'),
+ '@shared': path.join(repositoryRoot, 'src/shared'),
+ path: path.join(repositoryRoot, 'src/renderer/lib/path-browser-shim.ts'),
+ },
+ },
+ server: { host: '127.0.0.1', port: 4186, strictPort: true },
+})
diff --git a/e2e/window-chrome/window-chrome.browser.ts b/e2e/window-chrome/window-chrome.browser.ts
new file mode 100644
index 00000000..583e5883
--- /dev/null
+++ b/e2e/window-chrome/window-chrome.browser.ts
@@ -0,0 +1,331 @@
+import { expect, type Locator, type Page, test } from '@playwright/test'
+import { Commands } from '../../src/shared/protocol/commands'
+
+async function expectSafePopup(popup: Locator, page: Page, top = 54) {
+ await expect(popup).toBeVisible()
+ await expect
+ .poll(async () => {
+ const rect = await popup.boundingBox()
+ return (
+ !!rect &&
+ rect.y >= top - 0.5 &&
+ rect.x >= -0.5 &&
+ rect.y + rect.height <= (page.viewportSize()?.height ?? 0) + 0.5 &&
+ rect.x + rect.width <= (page.viewportSize()?.width ?? 0) + 0.5
+ )
+ })
+ .toBe(true)
+}
+
+async function openListView(page: Page) {
+ const button = page.getByRole('button', { name: 'List View', exact: true })
+ if (await button.isVisible()) await button.click()
+ else {
+ await page.getByRole('button', { name: 'More', exact: true }).click()
+ await page.getByRole('menuitem', { name: 'List View', exact: true }).hover()
+ }
+ await expect(
+ page.getByRole('menuitem', { name: 'Sort By', exact: true })
+ ).toBeVisible()
+}
+
+async function openSortMenu(page: Page) {
+ await openListView(page)
+ await page.getByRole('menuitem', { name: 'Sort By', exact: true }).hover()
+ return page.getByRole('menu', { name: 'Sort By', exact: true })
+}
+
+async function setGeometry(page: Page, left: number, right: number) {
+ await page.evaluate(
+ ({ left, right }) => {
+ const root = document.documentElement
+ root.style.setProperty('--window-controls-overlay-x', `${left}px`)
+ root.style.setProperty(
+ '--window-controls-overlay-width',
+ `calc(100vw - ${left + right}px)`
+ )
+ },
+ { left, right }
+ )
+}
+
+test('long plugin settings selects keep options outside native controls', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 640, height: 360 })
+ await page.goto('/?mode=plugin-settings')
+ await setGeometry(page, 108, 0)
+ const trigger = page.getByRole('combobox')
+ await trigger.click()
+ const list = page.locator('[data-slot="select-content"]')
+ await expectSafePopup(list, page)
+ await page.getByRole('option', { name: 'Option 0', exact: true }).click()
+ await expect(trigger).toHaveText('Option 0')
+ await trigger.click()
+ await page.getByRole('option', { name: 'Option 29', exact: true }).click()
+ await expect(trigger).toHaveText('Option 29')
+})
+
+test('an open settings select follows native controls returning from fullscreen', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 640, height: 360 })
+ await page.goto('/?mode=plugin-settings&fullscreen')
+ await setGeometry(page, 0, 0)
+ await page.getByRole('combobox').click()
+ const list = page.locator('[data-slot="select-content"]')
+ await expectSafePopup(list, page, 0)
+ await setGeometry(page, 108, 0)
+ await page.evaluate(() => {
+ window.dispatchEvent(
+ new CustomEvent('fixture-fullscreen', { detail: false })
+ )
+ })
+ await expectSafePopup(list, page)
+ await page.getByRole('option', { name: 'Option 0', exact: true }).click()
+ await expect(page.getByRole('combobox')).toHaveText('Option 0')
+})
+
+for (const platform of ['win32', 'web']) {
+ test(`${platform} settings selects retain item alignment`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 640, height: 360 })
+ await page.goto(`/?mode=plugin-settings&platform=${platform}`)
+ await page.getByRole('combobox').click()
+ await expect(page.locator('[data-slot="select-content"]')).toHaveAttribute(
+ 'data-side',
+ 'none'
+ )
+ await page.getByRole('option', { name: 'Option 0', exact: true }).click()
+ await expect(page.getByRole('combobox')).toHaveText('Option 0')
+ })
+}
+
+async function expectClickableActions(page: Page, safeTop = 54) {
+ await page.getByRole('button', { name: 'Motrix', exact: true }).click()
+ await expect(
+ page.getByRole('menuitem', { name: 'About Motrix' })
+ ).toBeVisible()
+ await expect
+ .poll(
+ async () =>
+ (
+ await page
+ .getByRole('menu', { name: 'Motrix', exact: true })
+ .boundingBox()
+ )?.y
+ )
+ .toBeGreaterThanOrEqual(safeTop)
+ await page.keyboard.press('Escape')
+ await page
+ .getByRole('button', { name: 'Toggle sidebar', exact: true })
+ .click({ trial: true })
+ await page.getByRole('button', { name: 'New task', exact: true }).click()
+ expect(
+ await page.evaluate(() => window.windowChromeFixture.commands)
+ ).toContain(Commands.ShowAddTaskWindow)
+ await page.getByRole('button', { name: 'More', exact: true }).click()
+ await expectSafePopup(
+ page.getByRole('menu', { name: 'More', exact: true }),
+ page,
+ safeTop
+ )
+ await page.keyboard.press('Escape')
+ await expect(
+ page.getByRole('menu', { name: 'More', exact: true })
+ ).toBeHidden()
+ expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBe(
+ page.viewportSize()?.width
+ )
+}
+
+for (const dir of ['ltr', 'rtl']) {
+ for (const [layout, left, right] of [
+ ['left', 108, 0],
+ ['right', 0, 108],
+ ['split', 36, 72],
+ ] as const) {
+ test(`${dir} ${layout}: real toolbar sorting menus stay clickable in short windows`, async ({
+ page,
+ }) => {
+ for (const width of [320, 640]) {
+ await page.setViewportSize({ width, height: 240 })
+ await page.goto(`/?dir=${dir}`)
+ await setGeometry(page, left, right)
+ let sort = await openSortMenu(page)
+ await expectSafePopup(sort, page)
+ await sort
+ .getByRole('menuitemradio', { name: 'Name', exact: true })
+ .click()
+ if (!(await sort.isVisible())) sort = await openSortMenu(page)
+ await expectSafePopup(sort, page)
+ // Auto-scroll must reach the final choice inside the submenu itself.
+ await sort
+ .getByRole('menuitemradio', { name: 'Descending', exact: true })
+ .click()
+ await page.keyboard.press('Escape')
+ await page.keyboard.press('Escape')
+ expect(
+ await page.evaluate(() => document.documentElement.scrollHeight)
+ ).toBe(240)
+ expect(
+ await page.evaluate(() => document.documentElement.scrollWidth)
+ ).toBe(width)
+ }
+ })
+ }
+}
+
+test('real search/filter popover respects the native boundary after the toolbar collapses', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 640, height: 240 })
+ await page.goto('/')
+ await setGeometry(page, 108, 0)
+ await page
+ .getByRole('button', { name: 'Search downloads', exact: true })
+ .click()
+ await page
+ .getByRole('textbox', { name: 'Search downloads', exact: true })
+ .fill('linux')
+ await page.getByRole('button', { name: /^Filters/ }).click()
+ await expectSafePopup(page.locator('[data-slot="popover-content"]'), page)
+ await page.keyboard.press('Escape')
+ await page.getByRole('button', { name: 'Clear search', exact: true }).click()
+ const sort = await openSortMenu(page)
+ await expectSafePopup(sort, page)
+ await sort.getByRole('menuitemradio', { name: 'Name', exact: true }).click()
+})
+
+test('an already-open sorting submenu follows fullscreen geometry changes', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 320, height: 240 })
+ await page.goto('/')
+ await setGeometry(page, 108, 0)
+ const sort = await openSortMenu(page)
+ await expectSafePopup(sort, page)
+ for (const fullscreen of [true, false]) {
+ await page.evaluate((fullscreen) => {
+ document
+ .querySelectorAll<HTMLElement>('[data-native-overlay]')
+ .forEach((element) => {
+ element.hidden = fullscreen
+ })
+ window.dispatchEvent(
+ new CustomEvent('fixture-fullscreen', { detail: fullscreen })
+ )
+ }, fullscreen)
+ await expectSafePopup(sort, page, fullscreen ? 0 : 54)
+ }
+ await sort.getByRole('menuitemradio', { name: 'Name', exact: true }).click()
+})
+
+for (const dir of ['ltr', 'rtl']) {
+ for (const [layout, left, right] of [
+ ['right', 0, 108],
+ ['left', 108, 0],
+ ['split', 36, 72],
+ ] as const) {
+ test(`${dir} ${layout} controls leave main actions usable in compact and expanded layouts`, async ({
+ page,
+ }) => {
+ for (const width of [320, 700, 1000]) {
+ await page.setViewportSize({ width, height: 672 })
+ await page.goto(`/?dir=${dir}${width === 1000 ? '&expanded' : ''}`)
+ await setGeometry(page, left, right)
+ await expect(
+ page.locator('[data-slot="desktop-window-controls"]')
+ ).toHaveCount(0)
+ await expectClickableActions(page)
+ const content = await page.getByTestId('panel-content').boundingBox()
+ expect(content?.y).toBeGreaterThanOrEqual(54)
+ await page.evaluate(() =>
+ document.documentElement.classList.add('dark')
+ )
+ await expectClickableActions(page)
+ }
+ })
+ }
+}
+
+test('safe areas react to layout changes and fullscreen without remounting', async ({
+ page,
+}) => {
+ await page.setViewportSize({ width: 800, height: 672 })
+ await page.goto('/')
+ for (const [left, right] of [
+ [0, 108],
+ [108, 0],
+ [36, 72],
+ ]) {
+ await setGeometry(page, left, right)
+ await expectClickableActions(page)
+ }
+ await page.evaluate(() => {
+ document
+ .querySelectorAll<HTMLElement>('[data-native-overlay]')
+ .forEach((el) => {
+ el.hidden = true
+ })
+ window.dispatchEvent(
+ new CustomEvent('fixture-fullscreen', { detail: true })
+ )
+ })
+ await expect(page.locator('.window-chrome')).toHaveAttribute(
+ 'data-fullscreen',
+ 'true'
+ )
+ await expect(page.locator('.window-chrome')).toHaveCSS('padding-left', '12px')
+ await expect(page.locator('[data-slot="panel-shell-header"]')).toHaveCSS(
+ 'padding-right',
+ '24px'
+ )
+ await expectClickableActions(page, 0)
+ await page.evaluate(() => {
+ document
+ .querySelectorAll<HTMLElement>('[data-native-overlay]')
+ .forEach((el) => {
+ el.hidden = false
+ })
+ window.dispatchEvent(
+ new CustomEvent('fixture-fullscreen', { detail: false })
+ )
+ })
+ await expect(page.locator('.window-chrome')).toHaveCSS('padding-left', '48px')
+ await expectClickableActions(page)
+})
+
+for (const mode of ['add-task', 'onboarding']) {
+ test(`${mode} leaves space for native controls on both sides`, async ({
+ page,
+ }) => {
+ await page.setViewportSize({
+ width: mode === 'add-task' ? 640 : 400,
+ height: 670,
+ })
+ await page.goto(`/?mode=${mode}`)
+ for (const [left, right] of [
+ [0, 108],
+ [108, 0],
+ [36, 72],
+ ]) {
+ await setGeometry(page, left, right)
+ await expect(
+ page.locator('[data-slot="desktop-window-controls"]')
+ ).toHaveCount(0)
+ const content = await page.getByTestId('panel-content').boundingBox()
+ expect(content?.y).toBe(54)
+ if (mode === 'onboarding') {
+ await page.getByRole('combobox', { name: 'Language' }).click()
+ const options = page.getByRole('listbox')
+ await expect(options).toBeVisible()
+ await expect
+ .poll(async () => (await options.boundingBox())?.y)
+ .toBeGreaterThanOrEqual(54)
+ await page.keyboard.press('Escape')
+ }
+ }
+ })
+}
diff --git a/e2e/window-chrome/window-chrome.native.ts b/e2e/window-chrome/window-chrome.native.ts
new file mode 100644
index 00000000..d2162f41
--- /dev/null
+++ b/e2e/window-chrome/window-chrome.native.ts
@@ -0,0 +1,404 @@
+import { execFileSync } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import {
+ access,
+ chmod,
+ mkdir,
+ readFile,
+ rename,
+ writeFile,
+} from 'node:fs/promises'
+import path from 'node:path'
+import type { Page, TestInfo } from '@playwright/test'
+import { CURRENT_SETTINGS_VERSION } from '../../src/core/settings/migrations'
+import { Commands } from '../../src/shared/protocol/commands'
+import {
+ test as base,
+ expect,
+ launchMotrix,
+ waitForEngineReady,
+ waitForQueryHandlers,
+} from '../fixtures/electron-app'
+
+const WM_SCHEMA = 'org.gnome.desktop.wm.preferences'
+const INTERFACE_SCHEMA = 'org.gnome.desktop.interface'
+
+function setting(schema: string, key: string): string {
+ return execFileSync('gsettings', ['get', schema, key], {
+ encoding: 'utf8',
+ }).trim()
+}
+
+function setSetting(schema: string, key: string, value: string): void {
+ execFileSync('gsettings', ['set', schema, key, value])
+}
+
+const test = base.extend<{
+ desktopLayout: string
+ desktopGtkTheme: string
+ gtkVersion: string
+ desktop: undefined
+}>({
+ desktopLayout: [':minimize,maximize,close', { option: true }],
+ desktopGtkTheme: ['Adwaita', { option: true }],
+ gtkVersion: ['', { option: true }],
+ desktop: async ({ desktopLayout, desktopGtkTheme }, use) => {
+ const layout = setting(WM_SCHEMA, 'button-layout')
+ const theme = setting(INTERFACE_SCHEMA, 'gtk-theme')
+ try {
+ setSetting(WM_SCHEMA, 'button-layout', desktopLayout)
+ setSetting(INTERFACE_SCHEMA, 'gtk-theme', desktopGtkTheme)
+ await use(undefined)
+ } finally {
+ setSetting(WM_SCHEMA, 'button-layout', layout)
+ setSetting(INTERFACE_SCHEMA, 'gtk-theme', theme)
+ }
+ },
+ electronApp: async (
+ { desktop, gtkVersion, userDataDir, rpcPort },
+ use,
+ info
+ ) => {
+ void desktop
+ await writeFile(
+ path.join(userDataDir, 'settings.json'),
+ JSON.stringify({
+ version: CURRENT_SETTINGS_VERSION,
+ app: {
+ theme: 'light',
+ language: 'en-US',
+ autofillClipboardLinks: false,
+ mainWindowMinWidth: 320,
+ mainWindowMinHeight: 240,
+ lightweightMode: false,
+ },
+ tracker: { autoSync: false },
+ nat: { enabled: false },
+ onboarding: { disclaimerAccepted: true },
+ })
+ )
+ const app = await launchMotrix({
+ userDataDir,
+ rpcPort,
+ commandLineArgs: [
+ `--ozone-platform=${process.env.MOTRIX_E2E_OZONE_PLATFORM ?? 'wayland'}`,
+ ...(gtkVersion ? [`--gtk-version=${gtkVersion}`] : []),
+ ],
+ })
+ try {
+ const environment = await app.evaluate(async ({ app, screen }) => {
+ await app.whenReady()
+ return {
+ platform: process.platform,
+ arch: process.arch,
+ electron: process.versions.electron,
+ ozone: app.commandLine.getSwitchValue('ozone-platform'),
+ gtk: app.commandLine.getSwitchValue('gtk-version') || 'default',
+ displays: screen.getAllDisplays().map((display) => ({
+ bounds: display.bounds,
+ workArea: display.workArea,
+ scale: display.scaleFactor,
+ })),
+ }
+ })
+ await info.attach('native-environment', {
+ body: JSON.stringify(environment, null, 2),
+ contentType: 'application/json',
+ })
+ await use(app)
+ } finally {
+ await app.close().catch(() => {})
+ }
+ },
+})
+
+test.skip(
+ process.platform !== 'linux',
+ 'Native WCO requires a Linux desktop session'
+)
+
+async function geometry(page: Page) {
+ return page.evaluate(() => {
+ const overlay = (
+ navigator as Navigator & {
+ windowControlsOverlay?: {
+ visible: boolean
+ getTitlebarAreaRect(): DOMRect
+ }
+ }
+ ).windowControlsOverlay
+ if (!overlay)
+ throw new Error('Native Window Controls Overlay API is absent')
+ const rect = overlay.getTitlebarAreaRect()
+ return {
+ visible: overlay.visible,
+ x: rect.x,
+ y: rect.y,
+ width: rect.width,
+ height: rect.height,
+ viewportWidth: innerWidth,
+ viewportHeight: innerHeight,
+ right: innerWidth - rect.x - rect.width,
+ scale: devicePixelRatio,
+ }
+ })
+}
+
+async function expectNativeControls(
+ page: Page,
+ layout: 'left' | 'right' | 'split'
+) {
+ await expect(page.locator('.window-chrome')).toBeVisible()
+ await expect.poll(async () => (await geometry(page)).visible).toBe(true)
+ await expect
+ .poll(async () => {
+ const rect = await geometry(page)
+ return layout === 'left'
+ ? rect.x > 40 && rect.right < 32
+ : layout === 'right'
+ ? rect.x < 32 && rect.right > 40
+ : rect.x > 20 && rect.right > 20
+ })
+ .toBe(true)
+ expect((await geometry(page)).height).toBe(54)
+ await expect(
+ page.locator('[data-slot="desktop-window-controls"]')
+ ).toHaveCount(0)
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const overlay = (
+ navigator as Navigator & {
+ windowControlsOverlay: { getTitlebarAreaRect(): DOMRect }
+ }
+ ).windowControlsOverlay.getTitlebarAreaRect()
+ return [
+ ...document.querySelectorAll<HTMLElement>(
+ '[data-slot="window-chrome-leading"] button, [data-slot="window-chrome-actions"] button, [data-slot="panel-shell-actions"] button'
+ ),
+ ]
+ .filter((button) => button.getClientRects().length)
+ .every((button) => {
+ const bounds = button.getBoundingClientRect()
+ return (
+ bounds.y >= overlay.height ||
+ (bounds.x >= overlay.x && bounds.right <= overlay.right)
+ )
+ })
+ })
+ )
+ .toBe(true)
+}
+
+// Optional compositor capture bridge: write <id>.png and <id>.done, or
+// <id>.jpg with { format: 'jpeg' } in the done file. Page screenshots omit
+// native controls. No particular hypervisor or machine path is required.
+async function captureNative(page: Page, info: TestInfo, label: string) {
+ const state = await geometry(page)
+ await info.attach(`${label}-geometry`, {
+ body: JSON.stringify(state, null, 2),
+ contentType: 'application/json',
+ })
+ const directory = process.env.MOTRIX_NATIVE_CAPTURE_DIR
+ if (!directory) return
+ await mkdir(directory, { recursive: true })
+ const id = randomUUID()
+ const pending = path.join(directory, `${id}.request.tmp`)
+ await writeFile(pending, JSON.stringify({ id, label, state }))
+ // Shared-folder guest and host UIDs can differ. Publish only non-secret
+ // capture metadata, and only after it is readable by the capture runner.
+ await chmod(pending, 0o644)
+ await rename(pending, path.join(directory, `${id}.request.json`))
+ await expect
+ .poll(
+ async () => {
+ try {
+ await access(path.join(directory, `${id}.done`))
+ return true
+ } catch {
+ return false
+ }
+ },
+ { timeout: 30_000 }
+ )
+ .toBe(true)
+ const result = JSON.parse(
+ await readFile(path.join(directory, `${id}.done`), 'utf8')
+ )
+ if (result.error) throw new Error(result.error)
+ await info.attach(`${label}-native-desktop`, {
+ path: path.join(
+ directory,
+ `${id}.${result.format === 'jpeg' ? 'jpg' : 'png'}`
+ ),
+ contentType: result.format === 'jpeg' ? 'image/jpeg' : 'image/png',
+ })
+}
+
+for (const [layout, value] of [
+ ['right', ':minimize,maximize,close'],
+ ['left', 'close,minimize,maximize:'],
+ ['split', 'close:minimize,maximize'],
+] as const) {
+ test.describe(`native ${layout} controls`, () => {
+ test.use({ desktopLayout: value })
+ test('matches actual native geometry and keeps downloads menus usable', async ({
+ electronApp,
+ mainWindow,
+ }, info) => {
+ await waitForQueryHandlers(mainWindow)
+ await waitForEngineReady(mainWindow)
+ await expectNativeControls(mainWindow, layout)
+ await mainWindow
+ .getByRole('link', { name: 'Downloads', exact: true })
+ .click()
+ await mainWindow
+ .getByRole('button', { name: 'Toggle sidebar', exact: true })
+ .click()
+ await expectNativeControls(mainWindow, layout)
+ const win = await electronApp.browserWindow(mainWindow)
+ await win.evaluate((window) => window.setSize(640, 360))
+ await expect
+ .poll(async () => (await geometry(mainWindow)).viewportWidth)
+ .toBe(640)
+ const list = mainWindow.getByRole('button', {
+ name: 'List View',
+ exact: true,
+ })
+ if (await list.isVisible()) await list.click()
+ else {
+ await mainWindow
+ .getByRole('button', { name: 'More', exact: true })
+ .click()
+ await mainWindow
+ .getByRole('menuitem', { name: 'List View', exact: true })
+ .hover()
+ }
+ await mainWindow
+ .getByRole('menuitem', { name: 'Sort By', exact: true })
+ .hover()
+ const sort = mainWindow.getByRole('menu', {
+ name: 'Sort By',
+ exact: true,
+ })
+ await expect
+ .poll(async () => (await sort.boundingBox())?.y)
+ .toBeGreaterThanOrEqual(54)
+ await sort
+ .getByRole('menuitemradio', { name: 'Name', exact: true })
+ .click()
+ await expect(
+ sort.getByRole('menuitemradio', { name: 'Name', exact: true })
+ ).toHaveAttribute('aria-checked', 'true')
+ await sort
+ .getByRole('menuitemradio', { name: 'Descending', exact: true })
+ .click()
+ await expect(
+ sort.getByRole('menuitemradio', { name: 'Descending', exact: true })
+ ).toHaveAttribute('aria-checked', 'true')
+ await mainWindow.keyboard.press('Escape')
+ await mainWindow.keyboard.press('Escape')
+ await captureNative(mainWindow, info, `${layout}-downloads`)
+ })
+ })
+}
+
+test('reacts to desktop layout changes and fullscreen on an existing window', async ({
+ electronApp,
+ mainWindow,
+}, info) => {
+ await waitForQueryHandlers(mainWindow)
+ await expectNativeControls(mainWindow, 'right')
+ setSetting(WM_SCHEMA, 'button-layout', 'close,minimize,maximize:')
+ await expectNativeControls(mainWindow, 'left')
+ const win = await electronApp.browserWindow(mainWindow)
+ await win.evaluate((window) => window.setFullScreen(true))
+ await expect
+ .poll(async () => (await geometry(mainWindow)).visible)
+ .toBe(false)
+ await expect(mainWindow.locator('.window-chrome')).toHaveAttribute(
+ 'data-fullscreen',
+ 'true'
+ )
+ await win.evaluate((window) => window.setFullScreen(false))
+ await expectNativeControls(mainWindow, 'left')
+ await captureNative(mainWindow, info, 'restored-from-fullscreen')
+})
+
+test.describe('Breeze GTK3 native rendering', () => {
+ test.use({ desktopGtkTheme: 'Breeze', gtkVersion: '3' })
+ test('updates native and renderer themes together', async ({
+ electronApp,
+ mainWindow,
+ }, info) => {
+ await waitForQueryHandlers(mainWindow)
+ await expectNativeControls(mainWindow, 'right')
+ await expect(
+ mainWindow.getByRole('heading', { name: 'Dashboard', exact: true })
+ ).toBeVisible()
+ await captureNative(mainWindow, info, 'breeze-light')
+ await mainWindow.evaluate(
+ (command) => window.motrix.invoke(command, { app: { theme: 'dark' } }),
+ Commands.UpdateSettings
+ )
+ await expect(mainWindow.locator('html')).toHaveClass(/dark/)
+ await expect
+ .poll(() =>
+ electronApp.evaluate(
+ ({ nativeTheme }) => nativeTheme.shouldUseDarkColors
+ )
+ )
+ .toBe(true)
+ await expectNativeControls(mainWindow, 'right')
+ await captureNative(mainWindow, info, 'breeze-dark')
+ })
+})
+
+test('secondary task window has native controls and survives close/reopen', async ({
+ electronApp,
+ mainWindow,
+}, info) => {
+ await waitForQueryHandlers(mainWindow)
+ await mainWindow
+ .getByRole('button', { name: 'New task', exact: true })
+ .click()
+ await expect
+ .poll(() =>
+ electronApp.windows().some((page) => page.url().includes('w=add-task'))
+ )
+ .toBe(true)
+ const taskPage = electronApp
+ .windows()
+ .find((page) => page.url().includes('w=add-task'))
+ if (!taskPage) throw new Error('Add-task window missing')
+ await expectNativeControls(taskPage, 'right')
+ await expect(taskPage.getByRole('textbox', { name: 'URLs' })).toBeVisible()
+ const taskWindow = await electronApp.browserWindow(taskPage)
+ // isMaximizable() always returns true on Linux; validate the supported
+ // fixed-size window contract instead of the Windows/macOS-only query.
+ expect(await taskWindow.evaluate((window) => window.isResizable())).toBe(
+ false
+ )
+ await captureNative(taskPage, info, 'add-task-window')
+ await taskWindow.evaluate((window) => window.close())
+ await expect.poll(() => taskPage.isClosed()).toBe(true)
+ await mainWindow
+ .getByRole('button', { name: 'New task', exact: true })
+ .click()
+ await expect
+ .poll(async () => {
+ const page = electronApp
+ .windows()
+ .find((candidate) => candidate.url().includes('w=add-task'))
+ if (!page) return false
+ const window = await electronApp.browserWindow(page)
+ return window.evaluate((candidate) => candidate.isVisible())
+ })
+ .toBe(true)
+ const reopened = electronApp
+ .windows()
+ .find((page) => page.url().includes('w=add-task'))
+ if (!reopened) throw new Error('Reopened add-task window missing')
+ await expectNativeControls(reopened, 'right')
+ await expect(reopened.getByRole('textbox', { name: 'URLs' })).toBeVisible()
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 7407264a..29aebf87 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1760,9 +1760,14 @@ async function initializeMainProcess(): Promise<void> {
prewarmAddTask: () => !settingsManager.getApp().lightweightMode,
},
})
- // Apply the persisted theme before opening windows. Renderer-drawn Windows
- // controls inherit the same theme through CSS without native overlay sync.
- setupNativeThemeSync(eventBus, settingsManager)
+ // Apply the persisted theme before opening windows and keep native Linux
+ // caption symbols readable over the renderer's changing title-bar surface.
+ const nativeThemeSync = setupNativeThemeSync(
+ eventBus,
+ settingsManager,
+ (dark) => windowManager.updateWindowControlsTheme(dark)
+ )
+ app.once('will-quit', () => nativeThemeSync.destroy())
const systemAccentSync = setupSystemAccentColorSync(eventBus)
app.once('will-quit', () => systemAccentSync.destroy())
// Install forwarding before the onboarding window becomes interactive.
diff --git a/src/main/platform/native-theme-sync.ts b/src/main/platform/native-theme-sync.ts
index 3e56b519..240baa9e 100644
--- a/src/main/platform/native-theme-sync.ts
+++ b/src/main/platform/native-theme-sync.ts
@@ -12,6 +12,7 @@ export interface NativeThemeSyncHandle {
// This is what makes the user's choice flow into:
// - macOS vibrancy material + traffic-light/titlebar tint
// - Windows custom-title-bar colors through `prefers-color-scheme`
+// - Linux Window Controls Overlay symbols through the resolved-theme callback
// - the OS-reported `prefers-color-scheme` (and thus the renderer's
// own dark-class application via next-themes when in `system` mode)
// - the Linux tray icon picker (reads `nativeTheme.shouldUseDarkColors`)
diff --git a/src/main/window/platform-options.test.ts b/src/main/window/platform-options.test.ts
index 98243bdb..5496a3ca 100644
--- a/src/main/window/platform-options.test.ts
+++ b/src/main/window/platform-options.test.ts
@@ -1,5 +1,8 @@
import { describe, expect, it } from 'vitest'
-import { buildPlatformOptions } from './platform-options'
+import {
+ buildPlatformOptions,
+ buildWindowControlsOverlay,
+} from './platform-options'
describe('buildPlatformOptions', () => {
it('returns hiddenInset titleBarStyle for macOS', () => {
@@ -24,10 +27,14 @@ describe('buildPlatformOptions', () => {
expect(opts.backgroundColor).toBe('#09090b')
})
- it('returns hidden titleBarStyle for Linux', () => {
+ it('uses native Linux controls over the renderer surface', () => {
const opts = buildPlatformOptions('linux')
expect(opts.titleBarStyle).toBe('hidden')
- expect(opts.titleBarOverlay).toBeUndefined()
+ expect(opts.titleBarOverlay).toEqual({
+ color: '#ffffff00',
+ symbolColor: '#262626',
+ height: 54,
+ })
expect(opts.vibrancy).toBeUndefined()
expect(opts.backgroundColor).toBe('#ffffff')
})
@@ -37,6 +44,7 @@ describe('buildPlatformOptions', () => {
shouldUseDarkColors: true,
})
expect(opts.backgroundColor).toBe('#09090b')
+ expect(opts.titleBarOverlay).toMatchObject({ symbolColor: '#fafafa' })
})
it('omits vibrancy and uses solid backgroundColor on macOS when vibrancy: false', () => {
@@ -70,3 +78,29 @@ describe('buildPlatformOptions', () => {
expect(opts.backgroundColor).toBe('#00000000')
})
})
+
+// Electron 45's Freedesktop provider forces overlay RGB opaque and uses it
+// for Breeze hover glyphs, with symbolColor as the hovered button's fill.
+// Guard the effective pair, not just the normal glyph's color on the web UI.
+function luminance(hex: string): number {
+ const channels = [1, 3, 5].map((offset) => {
+ const channel = Number.parseInt(hex.slice(offset, offset + 2), 16) / 255
+ return channel <= 0.04045
+ ? channel / 12.92
+ : ((channel + 0.055) / 1.055) ** 2.4
+ })
+ return channels[0] * 0.2126 + channels[1] * 0.7152 + channels[2] * 0.0722
+}
+
+it.each([false, true])(
+ 'keeps Breeze hover glyph contrast while preserving transparency (dark=%s)',
+ (dark) => {
+ const overlay = buildWindowControlsOverlay(dark)
+ expect(overlay.color.slice(7)).toBe('00')
+ const fill = luminance(overlay.symbolColor)
+ const glyph = luminance(overlay.color)
+ const contrast =
+ (Math.max(fill, glyph) + 0.05) / (Math.min(fill, glyph) + 0.05)
+ expect(contrast).toBeGreaterThanOrEqual(4.5)
+ }
+)
diff --git a/src/main/window/platform-options.ts b/src/main/window/platform-options.ts
index 66e0785e..a2012e23 100644
--- a/src/main/window/platform-options.ts
+++ b/src/main/window/platform-options.ts
@@ -1,3 +1,4 @@
+import { WINDOW_CONTROLS_OVERLAY_HEIGHT } from '@shared/constants/window-chrome'
import type { BrowserWindowConstructorOptions } from 'electron'
export interface PlatformOptionsInput {
@@ -11,6 +12,16 @@ export const WINDOW_BACKGROUND = {
dark: '#09090b',
} as const
+export function buildWindowControlsOverlay(shouldUseDarkColors: boolean) {
+ return {
+ // Electron 45 forces this RGB opaque when deriving Breeze inverse glyphs.
+ // Keep alpha zero for the renderer surface, but supply its resolved tone.
+ color: `${shouldUseDarkColors ? WINDOW_BACKGROUND.dark : WINDOW_BACKGROUND.light}00`,
+ symbolColor: shouldUseDarkColors ? '#fafafa' : '#262626',
+ height: WINDOW_CONTROLS_OVERLAY_HEIGHT,
+ }
+}
+
export function buildPlatformOptions(
platform: string = process.platform,
{
@@ -46,9 +57,10 @@ export function buildPlatformOptions(
backgroundColor: solidBackground,
trafficLightPosition: { x: 20, y: 20 },
}
- case 'win32':
+ case 'linux':
return {
titleBarStyle: 'hidden',
+ titleBarOverlay: buildWindowControlsOverlay(shouldUseDarkColors),
backgroundColor: solidBackground,
}
default:
diff --git a/src/main/window/window-manager.test.ts b/src/main/window/window-manager.test.ts
index c713b1ff..df6b02f3 100644
--- a/src/main/window/window-manager.test.ts
+++ b/src/main/window/window-manager.test.ts
@@ -395,6 +395,73 @@ describe('WindowManager', () => {
expect(options.titleBarOverlay).toBeUndefined()
})
+ it('enables WCO for every Linux window, including prewarmed windows', () => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ platform: 'linux',
+ })
+ wm.open('main')
+ wm.precreate('add-task')
+ wm.open('onboarding')
+
+ for (const win of wm.getAllWindows()) {
+ expect((win as unknown as { options: unknown }).options).toMatchObject({
+ titleBarStyle: 'hidden',
+ titleBarOverlay: {
+ color: '#ffffff00',
+ symbolColor: '#262626',
+ height: 54,
+ },
+ })
+ }
+ expect(wm.get('add-task')!.isVisible()).toBe(false)
+ })
+
+ it('updates visible and prewarmed Linux controls on theme changes without showing windows', () => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ platform: 'linux',
+ })
+ const main = wm.open('main')!
+ wm.precreate('add-task')
+ const addTask = wm.get('add-task')!
+ const destroyed = wm.open('onboarding')!
+ destroyed.destroy()
+
+ for (const dark of [true, false]) {
+ wm.updateWindowControlsTheme(dark)
+ for (const win of [main, addTask]) {
+ expect(win.setTitleBarOverlay).toHaveBeenLastCalledWith({
+ color: dark ? '#09090b00' : '#ffffff00',
+ symbolColor: dark ? '#fafafa' : '#262626',
+ height: 54,
+ })
+ expect(win.show).not.toHaveBeenCalled()
+ }
+ }
+ expect(destroyed.setTitleBarOverlay).not.toHaveBeenCalled()
+ expect(addTask.isVisible()).toBe(false)
+ })
+
+ it.each(['darwin', 'win32'])(
+ 'does not apply Linux overlays on %s',
+ (platform) => {
+ const wm = new WindowManager({
+ settingsManager: createMockSettingsManager(),
+ preloadPath: '/fake/preload.cjs',
+ loadUrl: vi.fn(),
+ platform,
+ })
+ const win = wm.open('main')!
+ wm.updateWindowControlsTheme(true)
+ expect(win.setTitleBarOverlay).not.toHaveBeenCalled()
+ }
+ )
+
it('matches the first-paint window background to the resolved native theme', () => {
;(
nativeTheme as unknown as { shouldUseDarkColors: boolean }
diff --git a/src/main/window/window-manager.ts b/src/main/window/window-manager.ts
index 3c4a2e56..f7911d1e 100644
--- a/src/main/window/window-manager.ts
+++ b/src/main/window/window-manager.ts
@@ -9,7 +9,10 @@ import type { AddTaskUrlParams } from '@shared/schemas/add-task'
import type { WindowBounds, WindowState } from '@shared/types/settings'
import { app, BrowserWindow, nativeTheme, screen, shell } from 'electron'
import type { LiquidGlassController } from './liquid-glass'
-import { buildPlatformOptions } from './platform-options'
+import {
+ buildPlatformOptions,
+ buildWindowControlsOverlay,
+} from './platform-options'
import {
getRendererUrlPolicy,
type RendererUrlPolicy,
@@ -281,6 +284,13 @@ export class WindowManager {
return result
}
+ updateWindowControlsTheme(shouldUseDarkColors: boolean): void {
+ if ((this.deps.platform ?? process.platform) !== 'linux') return
+ for (const win of this.getAllWindows()) {
+ win.setTitleBarOverlay(buildWindowControlsOverlay(shouldUseDarkColors))
+ }
+ }
+
getWindowIdBySender(sender: Electron.WebContents): WindowId | null {
for (const [id, win] of this.windows.entries()) {
if (win && !win.isDestroyed() && win.webContents === sender) {
diff --git a/src/renderer/app-root.tsx b/src/renderer/app-root.tsx
index e5c05c42..b3c662df 100644
--- a/src/renderer/app-root.tsx
+++ b/src/renderer/app-root.tsx
@@ -4,6 +4,7 @@ import { LocaleDirectionProvider } from '@renderer/components/locale-direction-p
import { OperatorUnlockGate } from '@renderer/components/operator-unlock-gate'
import { ReducedMotionSync } from '@renderer/components/reduced-motion-sync'
import { ThemeSync } from '@renderer/components/theme-sync'
+import { WindowControlsOverlayProvider } from '@renderer/components/window-chrome/window-controls-overlay-provider'
import {
bootstrapRendererLocale,
type RendererWindowId,
@@ -71,7 +72,9 @@ function Root({
{syncSettings && <ByteUnitSync />}
<ReducedMotionSync syncSettings={syncSettings} />
<LanguageSync windowId={windowId} />
- {children}
+ <WindowControlsOverlayProvider>
+ {children}
+ </WindowControlsOverlayProvider>
</LocaleDirectionProvider>
</ThemeProvider>
)
diff --git a/src/renderer/components/onboarding/onboarding-language-select.tsx b/src/renderer/components/onboarding/onboarding-language-select.tsx
index 58fdeb98..cbc69789 100644
--- a/src/renderer/components/onboarding/onboarding-language-select.tsx
+++ b/src/renderer/components/onboarding/onboarding-language-select.tsx
@@ -14,6 +14,7 @@ import {
type LanguagePreference,
SUPPORTED_LOCALES,
} from '@shared/constants/locales'
+import { WINDOW_CONTROLS_OVERLAY_HEIGHT } from '@shared/constants/window-chrome'
import { Commands } from '@shared/protocol/commands'
import { Queries } from '@shared/protocol/queries'
import { useEffect, useRef, useState } from 'react'
@@ -26,6 +27,8 @@ const LANGUAGE_OPTIONS = SUPPORTED_LOCALES.map(({ code, nativeName }) => ({
export function OnboardingLanguageSelect() {
const { i18n, t } = useTranslation()
+ const usesWindowControlsOverlay =
+ __MOTRIX_TARGET__ === 'electron' && transport.platform === 'linux'
const [preference, setPreference] = useState<LanguagePreference | null>(null)
const revision = useRef(0)
const languageOptions = [
@@ -87,7 +90,16 @@ export function OnboardingLanguageSelect() {
>
<SelectValue />
</SelectTrigger>
- <SelectContent align="end">
+ <SelectContent
+ align="end"
+ position={usesWindowControlsOverlay ? 'popper' : 'item-aligned'}
+ sideOffset={
+ usesWindowControlsOverlay
+ ? ({ anchor }) =>
+ (WINDOW_CONTROLS_OVERLAY_HEIGHT - anchor.height) / 2 + 4
+ : undefined
+ }
+ >
<SelectGroup>
{languageOptions.map((option) => (
<SelectItem key={option.value} value={option.value}>
diff --git a/src/renderer/components/ui/autocomplete.tsx b/src/renderer/components/ui/autocomplete.tsx
index 3acb8fca..1ec7001d 100644
--- a/src/renderer/components/ui/autocomplete.tsx
+++ b/src/renderer/components/ui/autocomplete.tsx
@@ -9,6 +9,7 @@ import {
InputGroupInput,
} from '@renderer/components/ui/input-group'
import { cn } from '@renderer/lib/utils'
+import { usePopupPositioning } from './popup-positioning'
const Autocomplete = AutocompletePrimitive.Root
@@ -72,9 +73,11 @@ function AutocompleteContent({
AutocompletePrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset'
>) {
+ const positioning = usePopupPositioning()
return (
<AutocompletePrimitive.Portal>
<AutocompletePrimitive.Positioner
+ {...positioning}
side={side}
sideOffset={sideOffset}
align={align}
diff --git a/src/renderer/components/ui/combobox.tsx b/src/renderer/components/ui/combobox.tsx
index b21ed8ad..e71f0c39 100644
--- a/src/renderer/components/ui/combobox.tsx
+++ b/src/renderer/components/ui/combobox.tsx
@@ -15,6 +15,7 @@ import {
} from '@renderer/components/ui/input-group'
import { cn } from '@renderer/lib/utils'
import * as React from 'react'
+import { usePopupPositioning } from './popup-positioning'
const Combobox = ComboboxPrimitive.Root
@@ -103,9 +104,11 @@ function ComboboxContent({
ComboboxPrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
>) {
+ const positioning = usePopupPositioning()
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Positioner
+ {...positioning}
side={side}
sideOffset={sideOffset}
align={align}
diff --git a/src/renderer/components/ui/context-menu.tsx b/src/renderer/components/ui/context-menu.tsx
index 7acff1a4..48463bd0 100644
--- a/src/renderer/components/ui/context-menu.tsx
+++ b/src/renderer/components/ui/context-menu.tsx
@@ -1,6 +1,7 @@
import { ContextMenu as ContextMenuPrimitive } from '@base-ui/react/context-menu'
import { cn } from '@renderer/lib/utils'
import type * as React from 'react'
+import { usePopupPositioning } from './popup-positioning'
// Base UI context menus share the Menu item primitives. Keep the same shadcn
// styling and keyboard behavior as the application's dropdown menus.
@@ -36,11 +37,13 @@ export function ContextMenuContent({
className,
...props
}: React.ComponentProps<typeof ContextMenuPrimitive.Popup>) {
+ const positioning = usePopupPositioning()
return (
<ContextMenuPrimitive.Portal>
<ContextMenuPrimitive.Positioner
className="isolate z-50 outline-none"
sideOffset={2}
+ {...positioning}
>
<ContextMenuPrimitive.Popup
data-slot="context-menu-content"
diff --git a/src/renderer/components/ui/dropdown-menu.tsx b/src/renderer/components/ui/dropdown-menu.tsx
index efd2caaa..882488ef 100644
--- a/src/renderer/components/ui/dropdown-menu.tsx
+++ b/src/renderer/components/ui/dropdown-menu.tsx
@@ -7,6 +7,7 @@ import {
} from '@renderer/components/icons'
import { cn } from '@renderer/lib/utils'
import type * as React from 'react'
+import { usePopupPositioning } from './popup-positioning'
function DropdownMenu({
...props
@@ -39,12 +40,14 @@ function DropdownMenuContent({
align,
alignOffset,
side,
+ collisionPadding,
...props
}: DropdownMenuPrimitive.Popup.Props &
Pick<
DropdownMenuPrimitive.Positioner.Props,
- 'align' | 'alignOffset' | 'side' | 'sideOffset'
+ 'align' | 'alignOffset' | 'side' | 'sideOffset' | 'collisionPadding'
>) {
+ const positioning = usePopupPositioning(collisionPadding)
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Positioner
@@ -52,6 +55,7 @@ function DropdownMenuContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
+ {...positioning}
className="isolate z-50 outline-none"
>
<DropdownMenuPrimitive.Popup
@@ -252,20 +256,24 @@ function DropdownMenuSubTrigger({
function DropdownMenuSubContent({
className,
+ collisionPadding,
...props
-}: DropdownMenuPrimitive.Popup.Props) {
+}: DropdownMenuPrimitive.Popup.Props &
+ Pick<DropdownMenuPrimitive.Positioner.Props, 'collisionPadding'>) {
+ const positioning = usePopupPositioning(collisionPadding)
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Positioner
side="inline-end"
align="start"
+ {...positioning}
className="isolate z-50 outline-none"
>
<DropdownMenuPrimitive.Popup
data-slot="dropdown-menu-sub-content"
style={{ outline: 'none' }}
className={cn(
- 'z-50 min-w-[8rem] origin-(--transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
+ 'z-50 max-h-(--available-height) min-w-[8rem] origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
className
)}
{...props}
diff --git a/src/renderer/components/ui/popover.tsx b/src/renderer/components/ui/popover.tsx
index a535fc98..c3a68400 100644
--- a/src/renderer/components/ui/popover.tsx
+++ b/src/renderer/components/ui/popover.tsx
@@ -1,6 +1,7 @@
import { Popover as PopoverPrimitive } from '@base-ui/react/popover'
import { cn } from '@renderer/lib/utils'
import type * as React from 'react'
+import { usePopupPositioning } from './popup-positioning'
function Popover({
...props
@@ -27,6 +28,7 @@ function PopoverContent({
PopoverPrimitive.Positioner.Props,
'align' | 'alignOffset' | 'side' | 'sideOffset' | 'anchor'
>) {
+ const positioning = usePopupPositioning()
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Positioner
@@ -35,12 +37,13 @@ function PopoverContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
+ {...positioning}
className="isolate z-50 outline-none"
>
<PopoverPrimitive.Popup
data-slot="popover-content"
className={cn(
- 'z-50 w-72 origin-(--transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
+ 'z-50 max-h-(--available-height) w-72 origin-(--transform-origin) overflow-y-auto rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
className
)}
{...props}
diff --git a/src/renderer/components/ui/popup-positioning.test.tsx b/src/renderer/components/ui/popup-positioning.test.tsx
new file mode 100644
index 00000000..f42ea343
--- /dev/null
+++ b/src/renderer/components/ui/popup-positioning.test.tsx
@@ -0,0 +1,45 @@
+import { renderHook } from '@testing-library/react'
+import type { ReactNode } from 'react'
+import { describe, expect, it } from 'vitest'
+import { PopupTopInsetContext, usePopupPositioning } from './popup-positioning'
+
+const wrapper = ({ children }: { children: ReactNode }) => (
+ <PopupTopInsetContext.Provider value={54}>
+ {children}
+ </PopupTopInsetContext.Provider>
+)
+
+describe('popup positioning', () => {
+ it('preserves the library defaults outside native chrome', () => {
+ const { result } = renderHook(() => usePopupPositioning())
+ expect(result.current).toEqual({ collisionPadding: undefined })
+ })
+
+ it('preserves explicit padding without a reserved band', () => {
+ const padding = { top: 80, left: 10 }
+ const { result } = renderHook(() => usePopupPositioning(padding))
+ expect(result.current.collisionPadding).toBe(padding)
+ expect(result.current).not.toHaveProperty('sticky')
+ })
+
+ it('applies the native minimum without losing caller edge padding', () => {
+ const { result } = renderHook(() => usePopupPositioning(12), { wrapper })
+ expect(result.current).toEqual({
+ collisionPadding: { top: 54, right: 12, bottom: 12, left: 12 },
+ sticky: true,
+ })
+ })
+
+ it('keeps larger caller top padding and defaults omitted edges', () => {
+ const { result } = renderHook(
+ () => usePopupPositioning({ top: 80, left: 0 }),
+ { wrapper }
+ )
+ expect(result.current.collisionPadding).toEqual({
+ top: 80,
+ right: 5,
+ bottom: 5,
+ left: 0,
+ })
+ })
+})
diff --git a/src/renderer/components/ui/popup-positioning.ts b/src/renderer/components/ui/popup-positioning.ts
new file mode 100644
index 00000000..091b6ebf
--- /dev/null
+++ b/src/renderer/components/ui/popup-positioning.ts
@@ -0,0 +1,30 @@
+import { createContext, useContext, useMemo } from 'react'
+
+type CollisionPadding =
+ | number
+ | Partial<Record<'top' | 'right' | 'bottom' | 'left', number>>
+
+/** null means no host boundary; zero keeps its identity while fullscreen. */
+export const PopupTopInsetContext = createContext<number | null>(null)
+
+export function usePopupPositioning(padding?: CollisionPadding) {
+ const topInset = useContext(PopupTopInsetContext) ?? 0
+ return useMemo(() => {
+ if (topInset <= 0) return { collisionPadding: padding }
+ const sides =
+ typeof padding === 'number'
+ ? { top: padding, right: padding, bottom: padding, left: padding }
+ : padding
+ return {
+ collisionPadding: {
+ top: Math.max(topInset, sides?.top ?? 5),
+ right: sides?.right ?? 5,
+ bottom: sides?.bottom ?? 5,
+ left: sides?.left ?? 5,
+ },
+ // Permit cross-axis shifting when an anchor is inside the reserved band.
+ // Padding alone still lets a bottom popup remain above the safe boundary.
+ sticky: true,
+ }
+ }, [padding, topInset])
+}
diff --git a/src/renderer/components/ui/select.tsx b/src/renderer/components/ui/select.tsx
index 9bc8d9ca..ed4a1966 100644
--- a/src/renderer/components/ui/select.tsx
+++ b/src/renderer/components/ui/select.tsx
@@ -6,6 +6,8 @@ import {
} from '@renderer/components/icons'
import { cn } from '@renderer/lib/utils'
import type * as React from 'react'
+import { useContext } from 'react'
+import { PopupTopInsetContext, usePopupPositioning } from './popup-positioning'
const Select = SelectPrimitive.Root
@@ -62,13 +64,16 @@ function SelectContent({
alignOffset,
side,
sideOffset,
+ collisionPadding,
...props
}: SelectPrimitive.Popup.Props & {
position?: 'item-aligned' | 'popper'
} & Pick<
SelectPrimitive.Positioner.Props,
- 'align' | 'alignOffset' | 'side' | 'sideOffset'
+ 'align' | 'alignOffset' | 'side' | 'sideOffset' | 'collisionPadding'
>) {
+ const positioning = usePopupPositioning(collisionPadding)
+ const hasNativeBoundary = useContext(PopupTopInsetContext) !== null
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Positioner
@@ -76,7 +81,10 @@ function SelectContent({
alignOffset={alignOffset}
side={side}
sideOffset={sideOffset}
- alignItemWithTrigger={position === 'item-aligned'}
+ {...positioning}
+ // Item alignment bypasses collision padding. Keep anchored positioning
+ // through fullscreen so an open list can follow restored native chrome.
+ alignItemWithTrigger={position === 'item-aligned' && !hasNativeBoundary}
className="isolate z-50 outline-none"
>
<SelectPrimitive.Popup
@@ -84,6 +92,7 @@ function SelectContent({
className={cn(
'relative z-50 max-h-(--available-height) min-w-[8rem] origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95',
position === 'popper' &&
+ !hasNativeBoundary &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className
)}
diff --git a/src/renderer/components/ui/tooltip.tsx b/src/renderer/components/ui/tooltip.tsx
index dcf68550..b2cfdb10 100644
--- a/src/renderer/components/ui/tooltip.tsx
+++ b/src/renderer/components/ui/tooltip.tsx
@@ -1,6 +1,7 @@
import { Tooltip as TooltipPrimitive } from '@base-ui/react/tooltip'
import { cn } from '@renderer/lib/utils'
+import { usePopupPositioning } from './popup-positioning'
function TooltipProvider({
delay = 0,
@@ -43,6 +44,7 @@ function TooltipContent({
| 'side'
| 'sideOffset'
>) {
+ const positioning = usePopupPositioning()
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Positioner
@@ -52,6 +54,7 @@ function TooltipContent({
disableAnchorTracking={disableAnchorTracking}
side={side}
sideOffset={sideOffset}
+ {...positioning}
className="isolate z-50"
>
<TooltipPrimitive.Popup
diff --git a/src/renderer/components/window-chrome/motrix-menu-button.tsx b/src/renderer/components/window-chrome/motrix-menu-button.tsx
index 19536b05..d17ebb8c 100644
--- a/src/renderer/components/window-chrome/motrix-menu-button.tsx
+++ b/src/renderer/components/window-chrome/motrix-menu-button.tsx
@@ -19,6 +19,7 @@ import { WebMenuButton } from '@renderer/features/application-menu/web-menu-butt
import { useApplicationMenu } from '@renderer/hooks/use-application-menu'
import { useSelectedTask } from '@renderer/hooks/use-selected-task'
import { transport } from '@renderer/lib/transport'
+import { WINDOW_CONTROLS_OVERLAY_HEIGHT } from '@shared/constants/window-chrome'
import type {
ApplicationMenuNode,
ExecuteApplicationMenuItemRequest,
@@ -396,6 +397,12 @@ function ElectronMotrixMenuButton() {
<DropdownMenuContent
ref={contentRef}
align="start"
+ sideOffset={
+ transport.platform === 'linux'
+ ? ({ anchor }) =>
+ (WINDOW_CONTROLS_OVERLAY_HEIGHT - anchor.height) / 2 + 4
+ : undefined
+ }
onKeyDownCapture={(event) => {
if (narrow && stack.length && event.key === 'ArrowLeft') {
event.preventDefault()
diff --git a/src/renderer/components/window-chrome/window-chrome.test.tsx b/src/renderer/components/window-chrome/window-chrome.test.tsx
index d6fafc18..59012545 100644
--- a/src/renderer/components/window-chrome/window-chrome.test.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.test.tsx
@@ -61,7 +61,7 @@ describe('WindowChrome', () => {
expect(shouldShowDesktopWindowControls('darwin', false)).toBe(false)
expect(shouldShowDesktopWindowControls('darwin', true)).toBe(true)
expect(shouldShowDesktopWindowControls('win32', false)).toBe(true)
- expect(shouldShowDesktopWindowControls('linux', false)).toBe(true)
+ expect(shouldShowDesktopWindowControls('linux', false)).toBe(false)
})
it('renders no title text in overlay variant', () => {
@@ -69,6 +69,63 @@ describe('WindowChrome', () => {
expect(screen.queryByText('ignored')).toBeNull()
})
+ it.each(['overlay', 'titled'] as const)(
+ 'reserves the native Linux safe area without duplicate %s caption buttons',
+ (variant) => {
+ setPlatform('linux')
+ const { container } = render(
+ <WindowChrome
+ variant={variant}
+ title="New task"
+ leading={<button type="button">Menu</button>}
+ >
+ <button type="button">App action</button>
+ </WindowChrome>
+ )
+ const chrome = container.firstChild as HTMLElement
+ expect(chrome).toHaveAttribute('data-window-controls-overlay', 'true')
+ expect(chrome.style.height).toBe('54px')
+ expect(chrome.style.paddingInlineStart).toBe(
+ 'calc(var(--window-controls-overlay-start) + 12px)'
+ )
+ expect(chrome.style.paddingInlineEnd).toBe(
+ 'calc(var(--window-controls-overlay-end) + 20px)'
+ )
+ expect(screen.queryByRole('button', { name: 'Close' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Minimize' })).toBeNull()
+ expect(screen.queryByRole('button', { name: 'Maximize' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'App action' })).toBeVisible()
+ expect(
+ container.querySelector('[data-slot="window-chrome-actions"]')
+ ).not.toHaveClass('pt-3.5')
+ expect(
+ container.querySelector('[data-slot="window-chrome-leading"]')
+ ).not.toHaveClass('pt-3.5')
+
+ act(() => {
+ emit(Events.WindowMaximizedChanged, {
+ maximized: false,
+ fullscreen: true,
+ })
+ })
+ expect(chrome.style.paddingInlineStart).toBe('12px')
+ expect(chrome.style.paddingInlineEnd).toBe('20px')
+ expect(chrome).not.toHaveClass('app-drag')
+ expect(screen.getByRole('button', { name: 'App action' })).toBeVisible()
+
+ act(() => {
+ emit(Events.WindowMaximizedChanged, {
+ maximized: false,
+ fullscreen: false,
+ })
+ })
+ expect(chrome).toHaveClass('app-drag')
+ expect(chrome.style.paddingInlineStart).toContain(
+ '--window-controls-overlay-start'
+ )
+ }
+ )
+
it('pins to viewport in overlay variant', () => {
const { container } = render(<WindowChrome variant="overlay" />)
const el = container.firstChild as HTMLElement
@@ -191,7 +248,7 @@ describe('WindowChrome', () => {
)
})
- it.each(['linux', 'win32'] as const)(
+ it.each(['win32'] as const)(
'aligns the %s menu-state sidebar toggle 94 px from the left edge',
(platform) => {
setPlatform(platform)
@@ -217,7 +274,7 @@ describe('WindowChrome', () => {
}
)
- it.each(['linux', 'win32'] as const)(
+ it.each(['win32'] as const)(
'keeps %s controls at the logical end for start-positioned actions',
(platform) => {
setPlatform(platform)
@@ -251,7 +308,7 @@ describe('WindowChrome', () => {
}
)
- it.each(['linux', 'win32'] as const)(
+ it.each(['win32'] as const)(
'renders aligned 28 px %s caption hit targets with 10 px glyphs',
(platform) => {
setPlatform(platform)
@@ -307,7 +364,7 @@ describe('WindowChrome', () => {
)
})
- it.each(['win32', 'linux'] as const)(
+ it.each(['win32'] as const)(
'keeps %s app actions but hides caption controls while full-screen',
(platform) => {
setPlatform(platform)
@@ -415,7 +472,7 @@ describe('WindowChrome', () => {
expect(close).not.toHaveClass('hover:text-destructive-foreground')
})
- it.each(['linux', 'win32'] as const)(
+ it.each(['win32'] as const)(
'routes %s caption controls to sender-bound window commands',
(platform) => {
setPlatform(platform)
diff --git a/src/renderer/components/window-chrome/window-chrome.tsx b/src/renderer/components/window-chrome/window-chrome.tsx
index d979d49e..ebb23e52 100644
--- a/src/renderer/components/window-chrome/window-chrome.tsx
+++ b/src/renderer/components/window-chrome/window-chrome.tsx
@@ -1,7 +1,10 @@
import { useIpcEvent } from '@renderer/hooks/use-ipc-event'
import { transport } from '@renderer/lib/transport'
import { cn } from '@renderer/lib/utils'
-import { DESKTOP_WINDOW_CHROME_HEIGHT } from '@shared/constants/window-chrome'
+import {
+ DESKTOP_WINDOW_CHROME_HEIGHT,
+ WINDOW_CONTROLS_OVERLAY_HEIGHT,
+} from '@shared/constants/window-chrome'
import { Commands } from '@shared/protocol/commands'
import {
Events,
@@ -148,11 +151,7 @@ export function shouldShowDesktopWindowControls(
platform: NodeJS.Platform | 'web',
previewMacMenu: boolean
): boolean {
- return (
- platform === 'linux' ||
- platform === 'win32' ||
- (platform === 'darwin' && previewMacMenu)
- )
+ return platform === 'win32' || (platform === 'darwin' && previewMacMenu)
}
export function WindowChrome({
@@ -185,6 +184,10 @@ export function WindowChrome({
)
const isOverlay = variant === 'overlay'
const isMac = platform === 'darwin'
+ const usesWindowControlsOverlay =
+ __MOTRIX_TARGET__ === 'electron' && platform === 'linux'
+ const reserveWindowControlsOverlay =
+ usesWindowControlsOverlay && !windowState.fullscreen
const showTrafficLight =
__MOTRIX_TARGET__ === 'electron' &&
isMac &&
@@ -194,17 +197,25 @@ export function WindowChrome({
leading != null && actionsPosition === 'start'
const containerStyle: React.CSSProperties = {
- height: DESKTOP_WINDOW_CHROME_HEIGHT,
+ height: usesWindowControlsOverlay
+ ? WINDOW_CONTROLS_OVERLAY_HEIGHT
+ : DESKTOP_WINDOW_CHROME_HEIGHT,
display: 'flex',
alignItems: 'center',
paddingLeft: showTrafficLight ? 94 : undefined,
paddingRight: showTrafficLight ? 20 : undefined,
- paddingInlineStart: showTrafficLight ? undefined : 12,
+ paddingInlineStart: showTrafficLight
+ ? undefined
+ : reserveWindowControlsOverlay
+ ? 'calc(var(--window-controls-overlay-start) + 12px)'
+ : 12,
paddingInlineEnd: showTrafficLight
? undefined
- : showDesktopControls
- ? 0
- : 20,
+ : reserveWindowControlsOverlay
+ ? 'calc(var(--window-controls-overlay-end) + 20px)'
+ : showDesktopControls
+ ? 0
+ : 20,
flexShrink: 0,
userSelect: 'none',
...(isOverlay && {
@@ -221,7 +232,8 @@ export function WindowChrome({
<div
data-slot="window-chrome-actions"
className={cn(
- 'app-no-drag relative z-[60] flex shrink-0 items-center gap-2 pt-3.5 empty:hidden',
+ 'app-no-drag relative z-[60] flex shrink-0 items-center gap-2 empty:hidden',
+ !usesWindowControlsOverlay && 'pt-3.5',
offsetStartActionsForDesktopMenu && 'ms-1'
)}
>
@@ -233,15 +245,26 @@ export function WindowChrome({
<div
className={cn('window-chrome', !windowState.fullscreen && 'app-drag')}
data-fullscreen={windowState.fullscreen}
+ data-window-controls-overlay={usesWindowControlsOverlay}
style={containerStyle}
>
{!isOverlay && title && (
- <div className="pt-[14px] text-[13px] font-[600]">{title}</div>
+ <div
+ className={cn(
+ 'text-[13px] font-[600]',
+ !usesWindowControlsOverlay && 'pt-[14px]'
+ )}
+ >
+ {title}
+ </div>
)}
{leading && (
<div
data-slot="window-chrome-leading"
- className="app-no-drag relative z-[60] me-1.5 flex shrink-0 items-center pt-3.5 empty:hidden"
+ className={cn(
+ 'app-no-drag relative z-[60] me-1.5 flex shrink-0 items-center empty:hidden',
+ !usesWindowControlsOverlay && 'pt-3.5'
+ )}
>
{leading}
</div>
@@ -250,7 +273,10 @@ export function WindowChrome({
<div
aria-hidden
data-slot="window-chrome-drag-region"
- className="min-w-16 flex-1"
+ className={cn(
+ 'flex-1',
+ usesWindowControlsOverlay ? 'min-w-0' : 'min-w-16'
+ )}
/>
{actionsPosition === 'end' && actionSlot}
{showDesktopControls && !windowState.fullscreen && (
diff --git a/src/renderer/components/window-chrome/window-controls-overlay-provider.test.tsx b/src/renderer/components/window-chrome/window-controls-overlay-provider.test.tsx
new file mode 100644
index 00000000..993b1ce4
--- /dev/null
+++ b/src/renderer/components/window-chrome/window-controls-overlay-provider.test.tsx
@@ -0,0 +1,120 @@
+import '@testing-library/jest-dom/vitest'
+import { usePopupPositioning } from '@renderer/components/ui/popup-positioning'
+import { act, render, screen } from '@testing-library/react'
+import { createPortal } from 'react-dom'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { WindowControlsOverlayProvider } from './window-controls-overlay-provider'
+
+const mocks = vi.hoisted(() => ({
+ platform: 'linux',
+ on: vi.fn(),
+ off: vi.fn(),
+}))
+vi.mock('@renderer/lib/transport', () => ({
+ transport: {
+ get platform() {
+ return mocks.platform
+ },
+ on: mocks.on,
+ off: mocks.off,
+ },
+}))
+
+function PortalProbe() {
+ const positioning = usePopupPositioning(8)
+ return createPortal(
+ <output data-testid="positioning">{JSON.stringify(positioning)}</output>,
+ document.body
+ )
+}
+
+class TestOverlay extends EventTarget {
+ visible = true
+ height = 54
+ getTitlebarAreaRect() {
+ return new DOMRect(0, 0, 600, this.height)
+ }
+}
+let overlay: TestOverlay
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.platform = 'linux'
+ overlay = new TestOverlay()
+ Object.defineProperty(navigator, 'windowControlsOverlay', {
+ value: overlay,
+ configurable: true,
+ })
+})
+
+describe('WindowControlsOverlayProvider', () => {
+ it('protects portaled menus and releases the boundary in fullscreen', () => {
+ const remove = vi.spyOn(overlay, 'removeEventListener')
+ const { unmount } = render(
+ <WindowControlsOverlayProvider>
+ <PortalProbe />
+ </WindowControlsOverlayProvider>
+ )
+ const read = () =>
+ JSON.parse(screen.getByTestId('positioning').textContent ?? '{}')
+ expect(read().collisionPadding.top).toBe(54)
+ act(() => {
+ overlay.visible = false
+ overlay.dispatchEvent(new Event('geometrychange'))
+ })
+ expect(read()).toEqual({ collisionPadding: 8 })
+ act(() => {
+ overlay.visible = true
+ overlay.dispatchEvent(new Event('geometrychange'))
+ })
+ expect(read().collisionPadding.top).toBe(54)
+ unmount()
+ expect(remove).toHaveBeenCalledWith('geometrychange', expect.any(Function))
+ expect(mocks.on).not.toHaveBeenCalled()
+ })
+
+ it('reads fullscreen on mount without consuming WindowChrome IPC replay', () => {
+ overlay.visible = false
+ render(
+ <WindowControlsOverlayProvider>
+ <PortalProbe />
+ </WindowControlsOverlayProvider>
+ )
+ expect(screen.getByTestId('positioning')).toHaveTextContent(
+ '{"collisionPadding":8}'
+ )
+ expect(mocks.on).not.toHaveBeenCalled()
+ })
+
+ it('tracks native geometry in CSS pixels after a zoom or frame change', () => {
+ render(
+ <WindowControlsOverlayProvider>
+ <PortalProbe />
+ </WindowControlsOverlayProvider>
+ )
+ act(() => {
+ overlay.height = 43
+ overlay.dispatchEvent(new Event('geometrychange'))
+ })
+ expect(
+ JSON.parse(screen.getByTestId('positioning').textContent ?? '{}')
+ .collisionPadding.top
+ ).toBe(43)
+ })
+
+ it.each(['darwin', 'win32', 'web'])(
+ 'keeps %s popups on their existing rules',
+ (platform) => {
+ mocks.platform = platform
+ render(
+ <WindowControlsOverlayProvider>
+ <PortalProbe />
+ </WindowControlsOverlayProvider>
+ )
+ expect(screen.getByTestId('positioning')).toHaveTextContent(
+ '{"collisionPadding":8}'
+ )
+ expect(mocks.on).not.toHaveBeenCalled()
+ }
+ )
+})
diff --git a/src/renderer/components/window-chrome/window-controls-overlay-provider.tsx b/src/renderer/components/window-chrome/window-controls-overlay-provider.tsx
new file mode 100644
index 00000000..31c76ac2
--- /dev/null
+++ b/src/renderer/components/window-chrome/window-controls-overlay-provider.tsx
@@ -0,0 +1,52 @@
+import { PopupTopInsetContext } from '@renderer/components/ui/popup-positioning'
+import { transport } from '@renderer/lib/transport'
+import { WINDOW_CONTROLS_OVERLAY_HEIGHT } from '@shared/constants/window-chrome'
+import { type ReactNode, useSyncExternalStore } from 'react'
+
+interface WindowControlsOverlay extends EventTarget {
+ readonly visible: boolean
+ getTitlebarAreaRect(): DOMRect
+}
+
+function getOverlay() {
+ return (
+ navigator as Navigator & { windowControlsOverlay?: WindowControlsOverlay }
+ ).windowControlsOverlay
+}
+
+function subscribe(listener: () => void) {
+ const overlay = getOverlay()
+ overlay?.addEventListener('geometrychange', listener)
+ return () => overlay?.removeEventListener('geometrychange', listener)
+}
+
+function getSnapshot() {
+ const overlay = getOverlay()
+ if (!overlay) return WINDOW_CONTROLS_OVERLAY_HEIGHT
+ if (!overlay.visible) return 0
+ const rect = overlay.getTitlebarAreaRect()
+ return Math.max(0, rect.y + rect.height)
+}
+
+function LinuxOverlayPopupBoundary({ children }: { children: ReactNode }) {
+ // Read native geometry, including initial fullscreen/zoom state. Subscribing
+ // again to the IPC replay channel would compete with WindowChrome's snapshot.
+ const topInset = useSyncExternalStore(subscribe, getSnapshot)
+ return (
+ <PopupTopInsetContext.Provider value={topInset}>
+ {children}
+ </PopupTopInsetContext.Provider>
+ )
+}
+
+export function WindowControlsOverlayProvider({
+ children,
+}: {
+ children: ReactNode
+}) {
+ return __MOTRIX_TARGET__ === 'electron' && transport.platform === 'linux' ? (
+ <LinuxOverlayPopupBoundary>{children}</LinuxOverlayPopupBoundary>
+ ) : (
+ children
+ )
+}
diff --git a/src/renderer/styles/globals.css b/src/renderer/styles/globals.css
index 7afea763..75052578 100644
--- a/src/renderer/styles/globals.css
+++ b/src/renderer/styles/globals.css
@@ -121,6 +121,21 @@
--dashboard-tile-radius: 18px;
--window-chrome-safe-area-leading: 77px;
--window-chrome-safe-area-trailing: 24px;
+ /* WCO reports a physical rectangle, independently of the app's direction.
+ Keep its inputs separate so left, right and split layouts use one formula. */
+ --window-controls-overlay-x: env(titlebar-area-x, 0px);
+ --window-controls-overlay-width: env(titlebar-area-width, 100vw);
+ --window-controls-overlay-left: var(--window-controls-overlay-x);
+ --window-controls-overlay-right: max(
+ 0px,
+ calc(
+ 100vw -
+ var(--window-controls-overlay-x) -
+ var(--window-controls-overlay-width)
+ )
+ );
+ --window-controls-overlay-start: var(--window-controls-overlay-left);
+ --window-controls-overlay-end: var(--window-controls-overlay-right);
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
--card: oklch(1 0 0);
@@ -230,15 +245,46 @@
.platform-darwin.window-main
.electron-window-chrome.preview-desktop-window-controls,
-.platform-linux.window-main .electron-window-chrome,
.platform-win32.window-main .electron-window-chrome {
--window-chrome-safe-area-trailing: 112px;
}
+:root:dir(rtl) {
+ --window-controls-overlay-start: var(--window-controls-overlay-right);
+ --window-controls-overlay-end: var(--window-controls-overlay-left);
+}
+
+.platform-linux.window-main .electron-window-chrome {
+ --window-chrome-safe-area-leading: calc(
+ 160px +
+ var(--window-controls-overlay-start)
+ );
+ --window-chrome-safe-area-trailing: calc(
+ 24px +
+ var(--window-controls-overlay-end)
+ );
+}
+
+.platform-linux.window-main [data-mobile="true"] [data-slot="sidebar-header"] {
+ min-height: 54px;
+}
+
+/* WCO is 54px high to share the existing y=27 caption/action centerline.
+ Expanded headers start below it; compact headers share the safe rectangle
+ but keep subsequent content below the native buttons' full hit targets. */
+.platform-linux.window-main
+ .electron-window-chrome
+ [data-slot="panel-shell-header"] {
+ padding-block-start: 46px;
+ @variant compact-header {
+ padding-block-start: 5px;
+ padding-block-end: 13px;
+ }
+}
+
/* Fullscreen hides desktop caption controls but retains the Motrix menu and app
- actions. Release only the trailing safe area; the leading 160px still keeps
- compact PanelShell content clear of menu/sidebar/add-task controls. The
- macOS desktop-controls mode previews the same behavior. */
+ actions. Release native safe areas while keeping 160px clear for the app's
+ leading controls. The macOS desktop-controls preview behaves like Windows. */
.platform-linux.window-main
.electron-window-chrome:has(.window-chrome[data-fullscreen="true"]),
.platform-darwin.window-main
@@ -250,6 +296,11 @@
--window-chrome-safe-area-trailing: 24px;
}
+.platform-linux.window-main
+ .electron-window-chrome:has(.window-chrome[data-fullscreen="true"]) {
+ --window-chrome-safe-area-leading: 160px;
+}
+
@media (width >= 48rem) {
.electron-window-chrome.group\/sidebar-wrapper[data-state="expanded"]
.panel-action-align-visual-end {
@@ -683,10 +734,23 @@ html[data-reduced-motion="true"] *::after {
flex-wrap: wrap;
gap: 8px;
}
+
+ .platform-linux.window-main
+ .electron-window-chrome
+ [data-slot="panel-shell-header"] {
+ padding-block-start: 46px;
+ padding-inline: 16px;
+ }
}
@media (pointer: coarse) and (width < 640px) {
.web-window-chrome [data-slot="panel-shell-header"],
.electron-window-chrome [data-slot="panel-shell-header"] {
padding-block-start: 56px;
}
+
+ .platform-linux.window-main
+ .electron-window-chrome
+ [data-slot="panel-shell-header"] {
+ padding-block-start: 56px;
+ }
}
diff --git a/src/shared/constants/window-chrome.ts b/src/shared/constants/window-chrome.ts
index cc9a8aaa..d1bfdafc 100644
--- a/src/shared/constants/window-chrome.ts
+++ b/src/shared/constants/window-chrome.ts
@@ -1,3 +1,5 @@
-/** Custom Windows/Linux title-bar geometry shared across renderer surfaces. */
+/** Renderer-drawn title-bar geometry for surfaces without native WCO. */
export const DESKTOP_WINDOW_CHROME_HEIGHT = 40
+/** Centers native Linux controls on the app's existing y=27 action row. */
+export const WINDOW_CONTROLS_OVERLAY_HEIGHT = 54
export const WINDOW_CHROME_EDGE_GAP = 16