The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): working WSLg window controls and native Wayland launch (#113247)
Austin Pickett8ffc2f03693f
diff --git a/apps/desktop/electron/entry.ts b/apps/desktop/electron/entry.tsnew file mode 100644index 00000000000..3830b95a429--- /dev/null+++ b/apps/desktop/electron/entry.ts@@ -0,0 +1,26 @@+import { app } from 'electron'++import { wslgLaunchArgs } from './wslg-launch'+import { spawnWslgLaunch } from './wslg-launch-process'++const args = wslgLaunchArgs(process.argv.slice(1), process.env, process.platform)++if (args) {+ // Keep the launcher alive until the child exits: npm's concurrently must not+ // tear down Vite during this handoff. No backend, windows or single-instance+ // lock are created in this parent. The child has an explicit platform flag,+ // so it goes straight into main on its first pass.+ const child = spawnWslgLaunch(args)++ child.once('error', error => {+ console.error('[hermes] WSLg launch failed:', error)+ app.exit(1)+ })+ child.once('exit', code => app.exit(code ?? 1))++ for (const signal of ['SIGINT', 'SIGTERM'] as const) {+ process.once(signal, () => child.kill(signal))+ }+} else {+ await import('./main')+}diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 592e9f43ffa..b9c4033bf0f 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -405,7 +405,7 @@ import { createSshIsolatedKeepaliveRegistry } from './ssh-isolated-keepalive'import { createSshTeardownTracker } from './ssh-teardown'import { createStreamThrottle } from './stream-throttle'import { registerTerminalIpc } from './terminal-ipc'-import { nativeOverlayWidth as computeNativeOverlayWidth, macTitleBarOverlayHeight } from './titlebar-overlay-width'+import { nativeOverlayWidth as computeNativeOverlayWidth, titleBarOverlayOptions } from './titlebar-overlay-width'import {backgroundMaterialFor,defaultTranslucencyState,@@ -455,11 +455,13 @@ import { isHermesOwnedVenvDaemon } from './venv-holder-select'import { fetchMarketplaceThemes, searchMarketplaceThemes } from './vscode-marketplace'import { createWakeIndicatorWindowController } from './wake-indicator-window'import { enumerateWindowsFrontToBack, enumerationFailed, readWindowBelow } from './window-below'+import { bindWindowChromeEvents } from './window-chrome-events'import {registrySshPoolScopeByConnectionId,registrySshScopeForWindowRoute,WindowConnectionRouteRegistry} from './window-connection-route'+import { registerWindowControlIpc, windowControlState } from './window-controls'import { createWindowOpenHandler } from './window-open-policy'import { installWindowRendererLifecycle } from './window-renderer-lifecycle'import { createWindowRevealController } from './window-reveal'@@ -1202,31 +1204,19 @@ function getWindowBackgroundColor() {// to GetFrameColor() on some Electron builds; rgba(1,0,0,0) is the escape hatch.const TITLEBAR_OVERLAY_COLOR = 'rgba(1, 0, 0, 0)'+// WSLg returns false: the RDP host paints nothing for a frameless window and+// Electron's own overlay drifts its hit-region under RAIL, so the renderer+// paints its own min/max/close (wslg-window-controls.tsx) over the+// hermes:window-control IPC channel. See titleBarOverlayOptions.function getTitleBarOverlayOptions() {- if (IS_MAC) {- // Tahoe (Darwin 25+) misplaces the traffic lights when the overlay has a- // nonzero height (electron#49183); 0 there keeps them at the configured- // inset. See macTitleBarOverlayHeight.- return { height: macTitleBarOverlayHeight({ darwinMajor: DARWIN_MAJOR, titlebarHeight: TITLEBAR_HEIGHT }) }- }-- // WSLg paints WCO via the RDP host's own min/max/close, so requesting- // an Electron overlay there just leaves a dead gap. Plain Linux (KDE,- // GNOME) can use the native overlay — let it through.- if (!IS_WINDOWS && IS_WSL) {- return false- }-- return {+ return titleBarOverlayOptions({+ platform: IS_MAC ? 'mac' : IS_WINDOWS ? 'windows' : IS_WSL ? 'wslg' : 'linux',+ darwinMajor: DARWIN_MAJOR,+ titlebarHeight: TITLEBAR_HEIGHT,color: TITLEBAR_OVERLAY_COLOR,- height: TITLEBAR_HEIGHT,- symbolColor:- rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.foreground)- ? rendererTitleBarTheme.foreground- : nativeTheme.shouldUseDarkColors- ? '#f7f7f7'- : '#242424'- }+ foreground: rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.foreground) ? rendererTitleBarTheme.foreground : null,+ dark: nativeTheme.shouldUseDarkColors+ })}// Push refreshed overlay options to a live window after a theme/appearance@@ -6683,7 +6673,8 @@ function getWindowState(win = mainWindow) {isVisible: Boolean(win?.isVisible?.()),nativeOverlayWidth: getNativeOverlayWidth(),windowButtonPosition: getWindowButtonPosition(win),- darwinMajor: IS_MAC ? DARWIN_MAJOR : 0+ darwinMajor: IS_MAC ? DARWIN_MAJOR : 0,+ ...windowControlState(win, !IS_WINDOWS && IS_WSL)}}@@ -13749,8 +13740,7 @@ function spawnSecondaryWindow({wireWindowReveal(win)- win.on('enter-full-screen', () => sendWindowStateChanged(true))- win.on('leave-full-screen', () => sendWindowStateChanged(false))+ bindWindowChromeEvents(win, sendWindowStateChanged)streamThrottle.register(win)wireCommonWindowHandlers(win, zoomWiringForWindowKind('chat'))@@ -13835,8 +13825,7 @@ function spawnBrowserWindow(tabId) {wireWindowReveal(win)- win.on('enter-full-screen', () => sendWindowStateChanged(true))- win.on('leave-full-screen', () => sendWindowStateChanged(false))+ bindWindowChromeEvents(win, sendWindowStateChanged)streamThrottle.register(win)wireCommonWindowHandlers(win, zoomWiringForWindowKind('chat'))@@ -13938,10 +13927,7 @@ function createInstanceWindow(wireWindowReveal(win)- // Per-window fullscreen chrome: send this window its own titlebar inset so its- // traffic lights hide/show independently of the primary.- win.on('enter-full-screen', () => sendWindowStateChanged(true, win))- win.on('leave-full-screen', () => sendWindowStateChanged(false, win))+ bindWindowChromeEvents(win, sendWindowStateChanged)streamThrottle.register(win)wireCommonWindowHandlers(win, zoomWiringForWindowKind('chat'))@@ -15000,14 +14986,7 @@ function createWindow() {revealController.reveal()}- mainWindow.on('will-enter-full-screen', () => sendWindowStateChanged(true))- mainWindow.on('enter-full-screen', () => sendWindowStateChanged(true))- mainWindow.on('will-leave-full-screen', () => sendWindowStateChanged(false))- mainWindow.on('leave-full-screen', () => sendWindowStateChanged(false))- mainWindow.on('minimize', () => sendWindowStateChanged())- mainWindow.on('restore', () => sendWindowStateChanged())- mainWindow.on('hide', () => sendWindowStateChanged())- mainWindow.on('show', () => sendWindowStateChanged())+ bindWindowChromeEvents(mainWindow, sendWindowStateChanged)// Reopen where the user left off. close is the backstop, flushed// synchronously before the window is gone.@@ -15388,6 +15367,7 @@ ipcMain.handle('hermes:window:openInstance', async (event, options) => {return { ok: true }})+registerWindowControlIpc(ipcMain, sender => BrowserWindow.fromWebContents(sender))ipcMain.handle('hermes:window:openBrowser', async (_event, tabId) => {if (typeof tabId !== 'string' || !tabId.trim()) {return { ok: false, error: 'invalid-tab-id' }diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex ac579c66133..542019576c2 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -1,6 +1,7 @@import { contextBridge, ipcRenderer, webFrame, webUtils } from 'electron'import type { DesktopProfileRoute } from './desktop-profile'+import { customWindowControlsEnabled } from './window-controls'// Which translucency the OS can back. Asked synchronously because the renderer// needs it before its first paint, and answered by main because deciding it@@ -52,6 +53,12 @@ contextBridge.exposeInMainWorld('hermesDesktop', {return () => ipcRenderer.removeListener('hermes:browser-popout:closed', listener)},claimAmbientCue: key => ipcRenderer.invoke('hermes:ambient:claim', key),+ windowControls: {+ custom: customWindowControlsEnabled(),+ minimize: () => ipcRenderer.send('hermes:window-control', 'minimize'),+ toggleMaximize: () => ipcRenderer.send('hermes:window-control', 'toggle-maximize'),+ close: () => ipcRenderer.send('hermes:window-control', 'close')+ },wakeIndicator: {getState: () => ipcRenderer.invoke('hermes:wake-indicator:get'),setState: state => ipcRenderer.send('hermes:wake-indicator:set', state),diff --git a/apps/desktop/electron/titlebar-overlay-width.test.ts b/apps/desktop/electron/titlebar-overlay-width.test.tsindex 0e424fd5c3e..72aa8e2e87a 100644--- a/apps/desktop/electron/titlebar-overlay-width.test.ts+++ b/apps/desktop/electron/titlebar-overlay-width.test.ts@@ -6,7 +6,8 @@ import {MACOS_TAHOE_DARWIN_MAJOR,macTitleBarOverlayHeight,nativeOverlayWidth,- OVERLAY_FALLBACK_WIDTH+ OVERLAY_FALLBACK_WIDTH,+ titleBarOverlayOptions} from './titlebar-overlay-width'// This static reservation is only the pre-layout FALLBACK. Once laid out the@@ -18,12 +19,60 @@ test('Windows reserves the overlay fallback width', () => {assert.equal(nativeOverlayWidth({ isWindows: true }), OVERLAY_FALLBACK_WIDTH)})-test('WSLg paints the same WCO, so it reserves the same fallback width', () => {+test('WSLg custom controls reserve the same fallback width', () => {// The original bug: WSL fell through to 0, so the right tools sat under the// controls and the title overran into them.assert.equal(nativeOverlayWidth({ isWsl: true }), OVERLAY_FALLBACK_WIDTH)})+test('WSLg disables the undersized native overlay in favor of renderer controls', () => {+ assert.equal(+ titleBarOverlayOptions({+ platform: 'wslg',+ titlebarHeight: 34,+ color: 'transparent',+ foreground: '#ffffff',+ dark: true+ }),+ false+ )+})++test('native Windows and Linux keep the same window-controls overlay', () => {+ const input = { titlebarHeight: 34, color: 'transparent', foreground: '#ffffff', dark: false }+ const expected = { color: 'transparent', height: 34, symbolColor: '#ffffff' }++ for (const platform of ['windows', 'linux'] as const) {+ assert.deepEqual(titleBarOverlayOptions({ platform, ...input }), expected)+ }+})++test('macOS keeps its height-only traffic-light overlay', () => {+ assert.deepEqual(+ titleBarOverlayOptions({+ platform: 'mac',+ darwinMajor: MACOS_TAHOE_DARWIN_MAJOR,+ titlebarHeight: 34,+ color: 'transparent',+ foreground: '#ffffff'+ }),+ { height: 0 }+ )+})++test('native overlays fall back to the active theme color', () => {+ assert.deepEqual(titleBarOverlayOptions({ platform: 'windows', foreground: null, dark: true }), {+ color: undefined,+ height: 0,+ symbolColor: '#f7f7f7'+ })+ assert.deepEqual(titleBarOverlayOptions({ platform: 'linux', foreground: null, dark: false }), {+ color: undefined,+ height: 0,+ symbolColor: '#242424'+ })+})+test('plain Linux paints the WCO too, so it reserves the fallback width', () => {// Regression #53185: re-enabling the overlay on plain Linux (KDE/GNOME)// without reserving its width left the native min/max/close buttons paintingdiff --git a/apps/desktop/electron/titlebar-overlay-width.ts b/apps/desktop/electron/titlebar-overlay-width.tsindex d6a4c5d1f24..ddb65e36ef7 100644--- a/apps/desktop/electron/titlebar-overlay-width.ts+++ b/apps/desktop/electron/titlebar-overlay-width.ts@@ -1,5 +1,14 @@export const OVERLAY_FALLBACK_WIDTH = 144+interface TitleBarOverlayOptionsInput {+ platform?: 'linux' | 'mac' | 'windows' | 'wslg'+ darwinMajor?: number+ titlebarHeight?: number+ color?: string+ foreground?: string | null+ dark?: boolean+}+/*** Static pre-layout reservation (px) for the right-side native window-controls* overlay (min/max/close). Only a FALLBACK — once laid out the renderer reads@@ -8,9 +17,9 @@ export const OVERLAY_FALLBACK_WIDTH = 144* API is unavailable.** macOS uses traffic lights positioned via trafficLightPosition, not a WCO- * overlay, so it reserves nothing here. Every other desktop platform now paints- * the Electron overlay (Windows, WSLg, and plain Linux KDE/GNOME), so they all- * reserve the fallback width — the split is simply mac vs. not.+ * overlay, so it reserves nothing here. Every other desktop platform reserves+ * the same right-side footprint: Electron paints it on Windows/plain Linux,+ * while the renderer paints larger controls on WSLg.** @param {{ isMac?: boolean }} opts*/@@ -22,6 +31,38 @@ export function nativeOverlayWidth({ isWindows = false, isWsl = false, isMac = freturn OVERLAY_FALLBACK_WIDTH}+/**+ * Build Electron's Window Controls Overlay options for every desktop host.+ * With `titleBarStyle: hidden`, Windows and Linux show no window controls+ * unless an overlay object is provided. WSLg deliberately returns false so+ * the renderer can paint correctly scaled Windows-style controls instead.+ */+export function titleBarOverlayOptions({+ platform = 'linux',+ darwinMajor = 0,+ titlebarHeight = 0,+ color,+ foreground,+ dark = false+}: TitleBarOverlayOptionsInput = {}) {+ // Electron's Linux overlay keeps a narrow, unscaled three-button cluster+ // under WSLg. The renderer owns larger Windows-shaped controls there while+ // the host's RAIL local-move path continues to own edge dragging and Snap.+ if (platform === 'wslg') {+ return false+ }++ if (platform === 'mac') {+ return { height: macTitleBarOverlayHeight({ darwinMajor, titlebarHeight }) }+ }++ return {+ color,+ height: titlebarHeight,+ symbolColor: foreground || (dark ? '#f7f7f7' : '#242424')+ }+}+// macOS Tahoe ships as Darwin 25 (Sequoia is 24); the Darwin number is truthful,// unlike the product version which macOS reports as 16 or 26 depending on the// build SDK.diff --git a/apps/desktop/electron/window-chrome-events.test.ts b/apps/desktop/electron/window-chrome-events.test.tsnew file mode 100644index 00000000000..41da9d6e84f--- /dev/null+++ b/apps/desktop/electron/window-chrome-events.test.ts@@ -0,0 +1,39 @@+import { EventEmitter } from 'node:events'++import { describe, expect, it, vi } from 'vitest'++import { bindWindowChromeEvents } from './window-chrome-events'++describe('window chrome events', () => {+ it.each(['maximize', 'unmaximize', 'minimize', 'restore', 'hide', 'show'])(+ 'publishes %s for the emitting window only',+ event => {+ const primary = new EventEmitter()+ const secondary = new EventEmitter()+ const publish = vi.fn()+ bindWindowChromeEvents(primary, publish)+ bindWindowChromeEvents(secondary, publish)++ secondary.emit(event)++ expect(publish).toHaveBeenCalledExactlyOnceWith(undefined, secondary)+ }+ )++ it.each([+ ['will-enter-full-screen', true],+ ['enter-full-screen', true],+ ['will-leave-full-screen', false],+ ['leave-full-screen', false]+ ] as const)('routes %s to its owner with the transition state', (event, fullscreen) => {+ const primary = new EventEmitter()+ const secondary = new EventEmitter()+ const publish = vi.fn()+ bindWindowChromeEvents(primary, publish)+ bindWindowChromeEvents(secondary, publish)++ secondary.emit(event)++ expect(publish).toHaveBeenCalledExactlyOnceWith(fullscreen, secondary)+ })+})diff --git a/apps/desktop/electron/window-chrome-events.ts b/apps/desktop/electron/window-chrome-events.tsnew file mode 100644index 00000000000..520bdde655a--- /dev/null+++ b/apps/desktop/electron/window-chrome-events.ts@@ -0,0 +1,21 @@+interface WindowChromeEvents {+ on(event: string, listener: () => void): unknown+}++/** Every window publishes its own chrome state, never the primary's. */+export function bindWindowChromeEvents<T extends WindowChromeEvents>(+ win: T,+ publish: (isFullscreen: boolean | undefined, target: T) => void+): void {+ for (const event of ['will-enter-full-screen', 'enter-full-screen']) {+ win.on(event, () => publish(true, win))+ }++ for (const event of ['will-leave-full-screen', 'leave-full-screen']) {+ win.on(event, () => publish(false, win))+ }++ for (const event of ['maximize', 'unmaximize', 'minimize', 'restore', 'hide', 'show']) {+ win.on(event, () => publish(undefined, win))+ }+}diff --git a/apps/desktop/electron/window-controls.test.ts b/apps/desktop/electron/window-controls.test.tsnew file mode 100644index 00000000000..a7fc9c873fe--- /dev/null+++ b/apps/desktop/electron/window-controls.test.ts@@ -0,0 +1,166 @@+import assert from 'node:assert/strict'++import { describe, test } from 'vitest'++import {+ customWindowControlsEnabled,+ performWindowControl,+ registerWindowControlIpc,+ windowControlState+} from './window-controls'++class FakeWindow {+ closed = false+ focusCalls = 0+ maximized = false+ minimized = false++ close() {+ this.closed = true+ }++ focus() {+ this.focusCalls += 1+ }++ isDestroyed() {+ return false+ }++ isMaximized() {+ return this.maximized+ }++ maximize() {+ this.maximized = true+ }++ minimize() {+ this.minimized = true+ }++ unmaximize() {+ this.maximized = false+ }+}++describe('performWindowControl', () => {+ test('minimizes the sender window', () => {+ const win = new FakeWindow()++ assert.equal(performWindowControl(win, 'minimize'), true)+ assert.equal(win.minimized, true)+ })++ test('toggles maximize and restore', () => {+ const win = new FakeWindow()++ assert.equal(performWindowControl(win, 'toggle-maximize'), true)+ assert.equal(win.maximized, true)++ assert.equal(performWindowControl(win, 'toggle-maximize'), true)+ assert.equal(win.maximized, false)+ })++ test('restores keyboard focus after maximize and restore', () => {+ const win = new FakeWindow()++ performWindowControl(win, 'toggle-maximize')+ assert.equal(win.focusCalls, 1)++ performWindowControl(win, 'toggle-maximize')+ assert.equal(win.focusCalls, 2)+ })++ test('closes the sender window', () => {+ const win = new FakeWindow()++ assert.equal(performWindowControl(win, 'close'), true)+ assert.equal(win.closed, true)+ })++ test('rejects unknown actions and destroyed windows', () => {+ const win = new FakeWindow()++ assert.equal(performWindowControl(win, 'unknown'), false)+ assert.equal(performWindowControl({ ...win, isDestroyed: () => true }, 'minimize'), false)+ })+})++test('windowControlState exposes the custom-control and maximize state', () => {+ const win = new FakeWindow()+ win.maximized = true++ assert.deepEqual(windowControlState(win, true), {+ customWindowControls: true,+ isMaximized: true+ })+})++test('custom window controls use the same WSL kernel fallback as the main process', () => {+ assert.equal(+ customWindowControlsEnabled({ env: {}, kernelRelease: '6.6.87.2-microsoft-standard-WSL2', platform: 'linux' }),+ true+ )+})++test('custom window controls read WSL env vars without touching the filesystem', () => {+ assert.equal(customWindowControlsEnabled({ env: { WSL_INTEROP: '/run/WSL/1_interop' }, platform: 'linux' }), true)+ assert.equal(customWindowControlsEnabled({ env: {}, platform: 'linux' }), false)+ assert.equal(customWindowControlsEnabled({ env: { WSL_DISTRO_NAME: 'Ubuntu' }, platform: 'darwin' }), false)+})++describe('registerWindowControlIpc', () => {+ function fakeIpc() {+ const handlers = new Map<string, (event: { sender: unknown }, action: unknown) => void>()++ return {+ handlers,+ on(channel: string, listener: (event: { sender: unknown }, action: unknown) => void) {+ handlers.set(channel, listener)+ }+ }+ }++ test('registers the hermes:window-control channel', () => {+ const ipc = fakeIpc()++ registerWindowControlIpc(ipc as Parameters<typeof registerWindowControlIpc>[0], () => new FakeWindow())++ assert.equal(ipc.handlers.has('hermes:window-control'), true)+ })++ test('dispatches the incoming action to performWindowControl on the resolved window', () => {+ const ipc = fakeIpc()+ const win = new FakeWindow()+ const senders: unknown[] = []++ registerWindowControlIpc(ipc as Parameters<typeof registerWindowControlIpc>[0], sender => {+ senders.push(sender)++ return win+ })++ const handler = ipc.handlers.get('hermes:window-control')++ assert.ok(handler)++ const sender = { id: 7 }++ handler({ sender }, 'toggle-maximize')+ assert.equal(win.maximized, true)+ assert.deepEqual(senders, [sender])++ handler({ sender }, 'minimize')+ assert.equal(win.minimized, true)+ })++ test('ignores non-string actions instead of dispatching them', () => {+ const ipc = fakeIpc()+ const win = new FakeWindow()++ registerWindowControlIpc(ipc as Parameters<typeof registerWindowControlIpc>[0], () => win)+ ipc.handlers.get('hermes:window-control')({ sender: {} }, { action: 'minimize' })+ assert.equal(win.minimized, false)+ })+})diff --git a/apps/desktop/electron/window-controls.ts b/apps/desktop/electron/window-controls.tsnew file mode 100644index 00000000000..bdab7f6c98f--- /dev/null+++ b/apps/desktop/electron/window-controls.ts@@ -0,0 +1,101 @@+export type WindowControlAction = 'close' | 'minimize' | 'toggle-maximize'++interface CustomWindowControlsOptions {+ env?: NodeJS.ProcessEnv+ kernelRelease?: string | null+ platform?: NodeJS.Platform+}++// WSL detection kept fs-free on purpose: this module is bundled into the+// sandboxed preload (sandbox: true), where importing node:fs — even+// transitively via bootstrap-platform — throws when the preload module loads+// and tears down the whole `window.hermesDesktop` bridge. The preload only+// needs the env-var signal (WSLg always sets WSL_INTEROP/WSL_DISTRO_NAME), and+// the authoritative flag still reaches the renderer through the main process's+// getWindowState (IS_WSL, which keeps the /proc kernel-release fallback). The+// kernelRelease branch mirrors bootstrap-platform's isWslEnvironment so tests+// and the main process agree; window-controls.test.ts guards that parity.+export function customWindowControlsEnabled(options: CustomWindowControlsOptions = {}): boolean {+ const platform = options.platform ?? process.platform++ if (platform !== 'linux') {+ return false+ }++ const env = options.env ?? process.env++ if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) {+ return true+ }++ return options.kernelRelease ? /microsoft|wsl/i.test(options.kernelRelease) : false+}++interface ControllableWindow {+ close?: () => void+ focus?: () => void+ isDestroyed?: () => boolean+ isMaximized?: () => boolean+ maximize?: () => void+ minimize?: () => void+ unmaximize?: () => void+}++export function performWindowControl(win: ControllableWindow | null | undefined, action: string): boolean {+ if (!win || win.isDestroyed?.()) {+ return false+ }++ if (action === 'minimize' && win.minimize) {+ win.minimize()++ return true+ }++ if (action === 'toggle-maximize' && win.maximize && win.unmaximize) {+ if (win.isMaximized?.()) {+ win.unmaximize()+ } else {+ win.maximize()+ }++ // WSLg's RAIL host can keep pointer activation while dropping the keyboard+ // focus after a renderer-owned maximize/restore button invokes Electron.+ // Reassert the BrowserWindow immediately so typing and Ctrl+V continue to+ // reach the existing focused editor instead of requiring an app restart.+ win.focus?.()++ return true+ }++ if (action === 'close' && win.close) {+ win.close()++ return true+ }++ return false+}++export function windowControlState(win: ControllableWindow | null | undefined, customWindowControls: boolean) {+ return {+ customWindowControls,+ isMaximized: Boolean(win && !win.isDestroyed?.() && win.isMaximized?.())+ }+}++interface WindowControlIpc {+ on(channel: string, listener: (event: { sender: Electron.WebContents }, action: unknown) => void): unknown+}++// Registers the renderer → main channel that the WSLg window-control buttons+// send on. Kept here (not inline in main.ts) so the registration + dispatch is+// unit-testable without importing the electron entry module.+export function registerWindowControlIpc(+ ipcMain: WindowControlIpc,+ resolveWindow: (sender: Electron.WebContents) => ControllableWindow | null | undefined+): void {+ ipcMain.on('hermes:window-control', (event, action) => {+ performWindowControl(resolveWindow(event.sender), typeof action === 'string' ? action : '')+ })+}diff --git a/apps/desktop/electron/wslg-launch-process.test.ts b/apps/desktop/electron/wslg-launch-process.test.tsnew file mode 100644index 00000000000..2ec6e5e104b--- /dev/null+++ b/apps/desktop/electron/wslg-launch-process.test.ts@@ -0,0 +1,242 @@+import assert from 'node:assert/strict'+import { type ChildProcess, spawn } from 'node:child_process'+import { once } from 'node:events'+import { mkdtemp, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import path from 'node:path'+import { createInterface } from 'node:readline'+import type { Readable } from 'node:stream'+import { fileURLToPath } from 'node:url'++import { build } from 'esbuild'+import { afterAll, beforeAll, test } from 'vitest'++let fixtureDir: string++beforeAll(async () => {+ fixtureDir = await mkdtemp(path.join(tmpdir(), 'hermes-wslg-process-'))+ await build({+ entryPoints: [+ fileURLToPath(new URL('./wslg-launch-process.ts', import.meta.url)),+ fileURLToPath(new URL('./linux-launcher-ready.ts', import.meta.url))+ ],+ outdir: fixtureDir,+ outExtension: { '.js': '.mjs' },+ bundle: true,+ platform: 'node',+ format: 'esm'+ })+ await writeFile(+ path.join(fixtureDir, 'app.mjs'),+ `+ import inspector from 'node:inspector'+ import { notifyLauncherWindowRevealed } from './linux-launcher-ready.mjs'+ console.log(JSON.stringify({+ kind: 'app', pid: process.pid, url: inspector.url(),+ ready: notifyLauncherWindowRevealed(), argv: process.execArgv+ }))+ setInterval(() => {}, 1000)+ `+ )+ await writeFile(+ path.join(fixtureDir, 'launcher.mjs'),+ `+ import { fstatSync } from 'node:fs'+ import inspector from 'node:inspector'+ import { spawnWslgLaunch } from './wslg-launch-process.mjs'+ const fd = Number(process.env.HERMES_DESKTOP_READY_FD)+ const originalUrl = inspector.url()+ const args = originalUrl ? ['--inspect=' + new URL(originalUrl).host] : []+ args.push(new URL('./app.mjs', import.meta.url).pathname)+ if (process.env.TEST_FAIL_SPAWN) process.execPath += '.missing'+ const child = spawnWslgLaunch(args)+ let fdClosed = false+ try { fstatSync(fd) } catch { fdClosed = true }+ console.log(JSON.stringify({ kind: 'launcher', pid: process.pid,+ originalUrl, url: inspector.url(), fdClosed,+ readyEnv: process.env.HERMES_DESKTOP_READY_FD+ }))+ child.once('error', error => { console.error(error); process.exit(1) })+ child.once('exit', (code, signal) => {+ console.log(JSON.stringify({ kind: 'exit', code, signal }))+ process.exit(code ?? 1)+ })+ process.stdin.on('data', () => child.kill('SIGTERM'))+ `+ )+})++afterAll(async () => {+ if (fixtureDir) {+ await rm(fixtureDir, { recursive: true, force: true })+ }+})++async function withLauncher(+ inspect: boolean,+ run: (launcher: ChildProcess, messages: AsyncIterator<string>, stderr: () => string) => Promise<void>,+ readyFd: string | undefined = '7',+ failSpawn = false+) {+ const launcher = spawn(+ process.execPath,+ [...(inspect ? ['--inspect=127.0.0.1:0'] : []), path.join(fixtureDir, 'launcher.mjs')],+ {+ detached: true,+ env: {+ ...process.env,+ NODE_OPTIONS: '',+ HERMES_DESKTOP_READY_FD: readyFd,+ TEST_FAIL_SPAWN: failSpawn ? '1' : ''+ },+ stdio: ['pipe', 'pipe', 'pipe', 'ignore', 'ignore', 'ignore', 'ignore', 'pipe']+ }+ )++ let stderr = ''+ launcher.stderr!.on('data', chunk => {+ stderr += chunk+ })+ const lines = createInterface({ input: launcher.stdout! })++ let timer: ReturnType<typeof setTimeout>++ try {+ await Promise.race([+ run(launcher, lines[Symbol.asyncIterator](), () => stderr),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Launcher lifecycle timed out: ' + stderr)), 10_000)+ })+ ])+ } finally {+ clearTimeout(timer!)+ lines.close()++ // Include the app child even if an assertion fails before orderly shutdown.+ try {+ process.kill(-launcher.pid!, 'SIGKILL')+ } catch (error) {+ assert.equal((error as NodeJS.ErrnoException).code, 'ESRCH')+ }++ if (launcher.exitCode === null && launcher.signalCode === null) {+ await once(launcher, 'exit')+ }+ }+}++async function startup(messages: AsyncIterator<string>) {+ const results: Record<string, any> = {}++ for (let i = 0; i < 2; i++) {+ const line = await messages.next()+ assert.equal(line.done, false, 'launcher exited before app startup')+ const message = JSON.parse(line.value)+ results[message.kind] = message+ }++ return results+}++test.skipIf(process.platform !== 'linux')(+ 'hands the ready pipe to the app and closes the waiting parent copy',+ async () => {+ await withLauncher(false, async (launcher, messages) => {+ let ready = ''+ const pipe = (launcher.stdio as Array<Readable | null>)[7]!+ pipe.on('data', chunk => {+ ready += chunk+ })+ const eof = once(pipe, 'end')+ const state = await startup(messages)+ assert.equal(state.app.ready, true)+ assert.equal(state.launcher.fdClosed, true)+ assert.equal(state.launcher.readyEnv, undefined)+ await eof+ assert.equal(ready, 'r')+ // EOF must arrive while both the waiting launcher and app still live.+ assert.equal(launcher.exitCode, null)+ process.kill(state.app.pid, 0)+ const exited = once(launcher, 'exit')+ launcher.stdin!.write('stop')+ assert.deepEqual(await exited, [1, null])+ const exit = JSON.parse((await messages.next()).value)+ assert.equal(exit.signal, 'SIGTERM')+ })+ },+ 15_000+)++test.skipIf(process.platform !== 'linux')(+ 'releases the launcher inspector so the app owns the requested port',+ async () => {+ await withLauncher(true, async (launcher, messages, stderr) => {+ ;(launcher.stdio as Array<Readable | null>)[7]!.resume()+ const state = await startup(messages)+ assert.ok(state.launcher.originalUrl)+ assert.equal(state.launcher.url, undefined)+ assert.ok(state.app.url, stderr())+ const requested = new URL(state.launcher.originalUrl).host+ assert.equal(new URL(state.app.url).host, requested)+ assert.deepEqual(state.app.argv, ['--inspect=' + requested])+ const targets = await fetch('http://' + requested + '/json/list').then(response => response.json())+ assert.equal(targets[0].webSocketDebuggerUrl, state.app.url)+ assert.notEqual(targets[0].webSocketDebuggerUrl, state.launcher.originalUrl)+ assert.doesNotMatch(stderr(), /address already in use/i)+ // The supervisor remains alive but is no longer the debug target.+ assert.equal(launcher.exitCode, null)+ process.kill(state.app.pid, 0)+ })+ },+ 15_000+)++test+ .skipIf(process.platform !== 'linux')+ .each(['', 'seven', '0', '1', '2', '-1', '3.5', '0x7', '999999999999999999', '100000'])(+ 'ignores invalid or closed ready fd %j without breaking child stdio',+ async readyFd => {+ await withLauncher(+ false,+ async (launcher, messages) => {+ const state = await startup(messages)+ assert.equal(state.app.ready, false)+ assert.equal(state.launcher.readyEnv, undefined)+ const exited = once(launcher, 'exit')+ launcher.stdin!.write('stop')+ assert.deepEqual(await exited, [1, null])+ },+ readyFd+ )+ },+ 15_000+)++test.skipIf(process.platform !== 'linux')(+ 'closes the ready pipe even when the app cannot be spawned',+ async () => {+ await withLauncher(+ false,+ async (launcher, messages, stderr) => {+ const pipe = (launcher.stdio as Array<Readable | null>)[7]!+ let ready = ''+ pipe.on('data', chunk => {+ ready += chunk+ })+ const eof = once(pipe, 'end')+ const exited = once(launcher, 'exit')+ const state = JSON.parse((await messages.next()).value)+ assert.equal(state.kind, 'launcher')+ assert.equal(state.fdClosed, true)+ assert.equal(state.readyEnv, undefined)+ await eof+ assert.equal(ready, '')+ assert.deepEqual(await exited, [1, null])+ assert.match(stderr(), /ENOENT/)+ },+ '7',+ true+ )+ },+ 15_000+)diff --git a/apps/desktop/electron/wslg-launch-process.ts b/apps/desktop/electron/wslg-launch-process.tsnew file mode 100644index 00000000000..01c2fd35a2e--- /dev/null+++ b/apps/desktop/electron/wslg-launch-process.ts@@ -0,0 +1,53 @@+import { spawn, type StdioOptions } from 'node:child_process'+import { closeSync, fstatSync } from 'node:fs'+import * as inspector from 'node:inspector'++import { LAUNCHER_READY_FD_ENV } from './linux-launcher-ready'++/** Spawn the app while leaving this process alive only as its supervisor. */+export function spawnWslgLaunch(args: string[]) {+ const env = { ...process.env }+ const raw = env[LAUNCHER_READY_FD_ENV]+ delete env[LAUNCHER_READY_FD_ENV]+ delete process.env[LAUNCHER_READY_FD_ENV]++ let readyFd: number | undefined++ // Do not reinterpret empty/hex/fractional values, inherit stdio as a ready+ // pipe, or allocate a sparse stdio array from an untrusted descriptor number.+ if (raw !== undefined && /^\d+$/.test(raw)) {+ const fd = Number(raw)++ if (Number.isSafeInteger(fd) && fd >= 3) {+ try {+ fstatSync(fd)+ readyFd = fd+ } catch {+ // A stale descriptor must not prevent the desktop from starting.+ }+ }+ }++ const stdio: StdioOptions = ['inherit', 'inherit', 'inherit']++ if (readyFd !== undefined) {+ stdio.push(readyFd)+ env[LAUNCHER_READY_FD_ENV] = '3'+ }++ try {+ // Keep the original inspector argv/env for the app, but release the port+ // synchronously first: the waiting supervisor must not own its debugger.+ if (inspector.url()) {+ inspector.close()+ }++ return spawn(process.execPath, args, { stdio, env })+ } finally {+ // spawn duplicates the fd synchronously. Keeping our copy would suppress+ // EOF at the outer launcher until the entire desktop exits (also on error).+ if (readyFd !== undefined) {+ closeSync(readyFd)+ }+ }+}diff --git a/apps/desktop/electron/wslg-launch.test.ts b/apps/desktop/electron/wslg-launch.test.tsnew file mode 100644index 00000000000..1433f213422--- /dev/null+++ b/apps/desktop/electron/wslg-launch.test.ts@@ -0,0 +1,42 @@+import { describe, expect, it } from 'vitest'++import { wslgLaunchArgs } from './wslg-launch'++const env = { WSL_DISTRO_NAME: 'Ubuntu', WAYLAND_DISPLAY: 'wayland-0', DISPLAY: ':0' }++describe('WSLg launch arguments', () => {+ it('preserves the invocation and restarts only once with native Wayland', () => {+ const args = ['.', '--inspect=9229', 'hermes://session/example']+ const next = wslgLaunchArgs(args, env, 'linux')!++ expect(next).toEqual([...args, '--ozone-platform=wayland'])+ expect(wslgLaunchArgs(next, env, 'linux')).toBeNull()+ expect(args).toEqual(['.', '--inspect=9229', 'hermes://session/example'])+ })++ it('respects explicit backends and the existing config-bridged X11 hint', () => {+ for (const args of [['--ozone-platform=x11'], ['--ozone-platform', 'x11']]) {+ expect(wslgLaunchArgs(args, env, 'linux')).toBeNull()+ }++ expect(wslgLaunchArgs(['--ozone-platform-hint=x11'], env, 'linux')).toEqual([+ '--ozone-platform-hint=x11',+ '--ozone-platform=x11'+ ])+ expect(wslgLaunchArgs([], { ...env, HERMES_DESKTOP_DISABLE_GPU: 'true' }, 'linux')).toEqual([+ '--ozone-platform=wayland'+ ])+ expect(wslgLaunchArgs([], { ...env, ELECTRON_OZONE_PLATFORM_HINT: 'x11' }, 'linux')).toEqual([+ '--ozone-platform=x11'+ ])+ })++ it('leaves other platforms, missing Wayland displays and forwarded sessions alone', () => {+ expect(wslgLaunchArgs([], env, 'win32')).toBeNull()+ expect(wslgLaunchArgs([], env, 'darwin')).toBeNull()+ expect(wslgLaunchArgs([], { DISPLAY: ':0' }, 'linux', false)).toBeNull()+ expect(wslgLaunchArgs([], { WSL_DISTRO_NAME: 'Ubuntu' }, 'linux')).toBeNull()+ expect(wslgLaunchArgs([], { ...env, SSH_CONNECTION: 'remote' }, 'linux')).toBeNull()+ expect(wslgLaunchArgs([], { ...env, DISPLAY: 'localhost:10.0' }, 'linux')).toBeNull()+ })+})diff --git a/apps/desktop/electron/wslg-launch.ts b/apps/desktop/electron/wslg-launch.tsnew file mode 100644index 00000000000..3ec1accbf49--- /dev/null+++ b/apps/desktop/electron/wslg-launch.ts@@ -0,0 +1,26 @@+import { detectRemoteDisplay, isWslEnvironment } from './bootstrap-platform'++// Ozone is selected before application JavaScript. Never appendSwitch here:+// that leaves the browser on X11 while GPU children receive Wayland.+export function wslgLaunchArgs(+ argv: readonly string[],+ env: NodeJS.ProcessEnv,+ platform: NodeJS.Platform,+ isWsl = isWslEnvironment(env, platform)+): string[] | null {+ const displayEnv = { ...env, HERMES_DESKTOP_DISABLE_GPU: undefined }++ if (platform !== 'linux' || !isWsl || !env.WAYLAND_DISPLAY || detectRemoteDisplay({ env: displayEnv, platform })) {+ return null+ }++ if (argv.some(arg => arg === '--ozone-platform' || arg.startsWith('--ozone-platform='))) {+ return null+ }++ const hintArg = argv.findLast(arg => arg.startsWith('--ozone-platform-hint='))+ const hint = hintArg?.split('=')[1] ?? env.ELECTRON_OZONE_PLATFORM_HINT+ const backend = hint === 'x11' ? 'x11' : 'wayland'++ return [...argv, `--ozone-platform=${backend}`]+}diff --git a/apps/desktop/scripts/bundle-electron-main.mjs b/apps/desktop/scripts/bundle-electron-main.mjsindex a119f4a9d40..23f23d261c5 100644--- a/apps/desktop/scripts/bundle-electron-main.mjs+++ b/apps/desktop/scripts/bundle-electron-main.mjs@@ -23,7 +23,7 @@ mkdirSync(distDir, { recursive: true })// Stage for both --dev and release bundles; non-mac hosts skip this helper.buildCommandScreenshotMonitor({ distDir })-const mainEntry = resolve(root, 'electron/main.ts')+const mainEntry = resolve(root, 'electron/entry.ts')const mainOut = resolve(distDir, 'electron-main.mjs')const preloadEntry = resolve(root, 'electron/preload.ts')const preloadOut = resolve(distDir, 'electron-preload.js')diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex a738e1ad7a6..25fbb64a9a0 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -149,6 +149,7 @@ import {titlebarToolsWidthCss} from '../shell/titlebar'import { TitlebarControls } from '../shell/titlebar-controls'+import { WslgWindowControls } from '../shell/wslg-window-controls'import { UpdatesOverlay } from '../updates-overlay'import { ContribWiringContext } from './context'@@ -1272,6 +1273,9 @@ export function ContribWiring({ children }: { children: ReactNode }) {}const titlebarToolsRight = titlebarToolsRightCss(nativeOverlayWidth, titlebarChrome)+ // WSLg: Electron's native overlay drifts its hit-region under RAIL, so the+ // renderer paints its own min/max/close (main decides via customWindowControls).+ const customWindowControls = connection?.customWindowControls ?? window.hermesDesktop?.windowControls?.custom ?? falseconst appActionsSide = useStore($titlebarAppActionsSide)const paneToolCount = rightTitlebarTools.filter(tool => !tool.hidden).lengthconst leftExtraCount = leftTitlebarTools.filter(tool => !tool.hidden).length@@ -1314,6 +1318,9 @@ export function ContribWiring({ children }: { children: ReactNode }) {tools={rightTitlebarTools}/>)}+ {!isHudWindow() && customWindowControls && (+ <WslgWindowControls isFullscreen={Boolean(connection?.isFullscreen)} isMaximized={Boolean(connection?.isMaximized)} />+ )}{children}</div>diff --git a/apps/desktop/src/app/shell/wslg-window-controls.test.tsx b/apps/desktop/src/app/shell/wslg-window-controls.test.tsxnew file mode 100644index 00000000000..c81e6242cbb--- /dev/null+++ b/apps/desktop/src/app/shell/wslg-window-controls.test.tsx@@ -0,0 +1,110 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { WslgWindowControls } from './wslg-window-controls'++const windowControls = {+ close: vi.fn(),+ custom: true,+ minimize: vi.fn(),+ toggleMaximize: vi.fn()+}++const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }+const originalHermesDesktop = desktopWindow.hermesDesktop++function renderControls(isMaximized = false, path = '/', isFullscreen = false) {+ return render(+ <MemoryRouter initialEntries={[path]}>+ <WslgWindowControls isFullscreen={isFullscreen} isMaximized={isMaximized} />+ </MemoryRouter>+ )+}++afterEach(() => {+ cleanup()+ vi.clearAllMocks()++ if (originalHermesDesktop) {+ desktopWindow.hermesDesktop = originalHermesDesktop+ } else {+ delete desktopWindow.hermesDesktop+ }+})++describe('WslgWindowControls', () => {+ it('routes minimize, maximize and close through the desktop bridge', () => {+ desktopWindow.hermesDesktop = { windowControls } as unknown as Window['hermesDesktop']++ renderControls()++ fireEvent.click(screen.getByRole('button', { name: 'Minimize window' }))+ fireEvent.click(screen.getByRole('button', { name: 'Maximize window' }))+ fireEvent.click(screen.getByRole('button', { name: 'Close window' }))++ // Argument-free on purpose: contextBridge structured-clones arguments and a+ // React SyntheticEvent is not cloneable, so passing the event would throw+ // before the IPC send and the buttons would silently do nothing.+ expect(windowControls.minimize).toHaveBeenCalledExactlyOnceWith()+ expect(windowControls.toggleMaximize).toHaveBeenCalledExactlyOnceWith()+ expect(windowControls.close).toHaveBeenCalledExactlyOnceWith()+ })++ it('exposes restore semantics while maximized', () => {+ desktopWindow.hermesDesktop = { windowControls } as unknown as Window['hermesDesktop']++ renderControls(true)++ expect(screen.getByRole('button', { name: 'Restore window' })).toBeTruthy()+ })++ it.each(['/settings', '/agents', '/command-center'])('keeps OS controls available on %s', path => {+ desktopWindow.hermesDesktop = { windowControls } as unknown as Window['hermesDesktop']++ renderControls(false, path)++ fireEvent.click(screen.getByRole('button', { name: 'Minimize window' }))+ fireEvent.click(screen.getByRole('button', { name: 'Maximize window' }))+ fireEvent.click(screen.getByRole('button', { name: 'Close window' }))+ expect(windowControls.minimize).toHaveBeenCalledExactlyOnceWith()+ expect(windowControls.toggleMaximize).toHaveBeenCalledExactlyOnceWith()+ expect(windowControls.close).toHaveBeenCalledExactlyOnceWith()+ })++ it('stays hidden while the BrowserWindow is fullscreen', () => {+ desktopWindow.hermesDesktop = { windowControls } as unknown as Window['hermesDesktop']++ renderControls(false, '/', true)++ expect(screen.queryByLabelText('Window controls')).toBeNull()+ })++ it('stops pointerdown propagation without cancelling the click', () => {+ desktopWindow.hermesDesktop = { windowControls } as unknown as Window['hermesDesktop']+ renderControls()+ const event = new MouseEvent('pointerdown', { bubbles: true, cancelable: true })++ const button = screen.getByRole('button', { name: 'Maximize window' })+ fireEvent(button, event)+ fireEvent.click(button)++ // preventDefault on pointerdown kills the synthesized click under WSLg's+ // RAIL compositor, so the button must NOT cancel the default — only stop+ // propagation so the drag region doesn't swallow the press.+ expect(event.defaultPrevented).toBe(false)+ expect(windowControls.toggleMaximize).toHaveBeenCalledOnce()+ })++ it('pins an explicit pixel height instead of the contextually-zeroed titlebar var', () => {+ desktopWindow.hermesDesktop = { windowControls } as unknown as Window['hermesDesktop']++ renderControls()++ // The contrib shell zeroes --titlebar-height for content subtrees; the+ // cluster must set its own height in px so the buttons don't collapse.+ const cluster = screen.getByLabelText('Window controls')+ expect(cluster.style.height).toMatch(/^\d+px$/)+ expect(cluster.className).not.toContain('h-(--titlebar-height)')+ })+})diff --git a/apps/desktop/src/app/shell/wslg-window-controls.tsx b/apps/desktop/src/app/shell/wslg-window-controls.tsxnew file mode 100644index 00000000000..afdce85a1e1--- /dev/null+++ b/apps/desktop/src/app/shell/wslg-window-controls.tsx@@ -0,0 +1,81 @@+import type { CSSProperties, PointerEvent } from 'react'++import { Codicon } from '@/components/ui/codicon'+import { cn } from '@/lib/utils'++import { TITLEBAR_HEIGHT } from './titlebar'++interface WslgWindowControlsProps {+ isFullscreen: boolean+ isMaximized: boolean+}++// Full-height caption buttons sized to match the native Windows cluster+// (~46px wide × full titlebar height). `h-full` fills the cluster box, whose+// height is pinned to TITLEBAR_HEIGHT below — NOT var(--titlebar-height), which+// the contrib shell zeroes for content subtrees (controller.tsx), collapsing+// the buttons if inherited.+const buttonClass =+ 'grid h-full w-[46px] place-items-center border-0 bg-transparent p-0 text-muted-foreground transition-colors duration-75 select-none [-webkit-app-region:no-drag] focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring hover:bg-white/10 hover:text-foreground active:bg-white/15'++// Match the native titlebar tools: stopPropagation (NOT preventDefault) on+// pointerdown. preventDefault on pointerdown suppresses the synthesized click+// under WSLg's XWayland/RAIL compositor, so the buttons render but never fire.+// stopPropagation keeps the drag region from swallowing the press while leaving+// the click intact; keyboard-focus reassertion after maximize is handled on the+// main side in performWindowControl (win.focus()).+const stopTitlebarDrag = (event: PointerEvent<HTMLButtonElement>) => event.stopPropagation()++export function WslgWindowControls({ isFullscreen, isMaximized }: WslgWindowControlsProps) {+ const controls = window.hermesDesktop?.windowControls++ if (!controls || isFullscreen) {+ return null+ }++ // Call the bridge with NO arguments: contextBridge structured-clones every+ // argument into the preload world and a React SyntheticEvent (DOM nodes,+ // nativeEvent, functions) is not cloneable, so `onClick={controls.minimize}`+ // throws "An object could not be cloned" before ipcRenderer.send ever runs+ // and the button silently does nothing.+ return (+ <div+ aria-label="Window controls"+ className="fixed right-0 top-0 z-80 flex items-stretch overflow-hidden bg-(--ui-chat-surface-background) text-[10px]"+ // Pin the real titlebar height: the shared --titlebar-height var is+ // contextually zeroed inside the contrib shell, so read the constant.+ style={{ height: `${TITLEBAR_HEIGHT}px` } as CSSProperties}+ >+ <button+ aria-label="Minimize window"+ className={buttonClass}+ onClick={() => controls.minimize()}+ onPointerDown={stopTitlebarDrag}+ type="button"+ >+ <Codicon name="chrome-minimize" size={10} />+ </button>+ <button+ aria-label={isMaximized ? 'Restore window' : 'Maximize window'}+ className={buttonClass}+ onClick={() => controls.toggleMaximize()}+ onPointerDown={stopTitlebarDrag}+ type="button"+ >+ <Codicon name={isMaximized ? 'chrome-restore' : 'chrome-maximize'} size={10} />+ </button>+ <button+ aria-label="Close window"+ className={cn(+ buttonClass,+ 'hover:bg-[#c42b1c] hover:text-white active:bg-[#b3271a] active:text-white dark:hover:bg-[#c42b1c]'+ )}+ onClick={() => controls.close()}+ onPointerDown={stopTitlebarDrag}+ type="button"+ >+ <Codicon name="chrome-close" size={10} />+ </button>+ </div>+ )+}diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex 34f15f1ebf9..5bb900e3053 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -93,6 +93,14 @@ declare global {// reply). Resolves true for the first window to claim a key, false for// peers — so N open windows don't all fire the same cue.claimAmbientCue: (key: string) => Promise<boolean>+ // Renderer-drawn min/max/close for WSLg (`custom` true there only), sent+ // over hermes:window-control; Electron/OS chrome owns them elsewhere.+ windowControls: {+ custom: boolean+ minimize: () => void+ toggleMaximize: () => void+ close: () => void+ }wakeIndicator?: {getState: () => Promise<WakeIndicatorState>setState: (state: WakeIndicatorState) => void@@ -813,8 +821,10 @@ export interface DesktopPluginProfileRoute {export interface HermesConnection {baseUrl: string+ customWindowControls?: booleandarwinMajor?: numberisFullscreen: boolean+ isMaximized?: boolean// The live, RESOLVED connection mode. Only ever 'local' or 'remote' — a// 'cloud' saved-config entry resolves to a 'remote' connection under the hood// (cloud-auto-discovery Q3/Q6), so this never carries 'cloud'.@@ -862,8 +872,10 @@ export interface HermesActiveWork {}export interface HermesWindowState {+ customWindowControls?: booleandarwinMajor?: numberisFullscreen: boolean+ isMaximized?: booleanisMinimized?: booleanisVisible?: booleannativeOverlayWidth: numberdiff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.mdindex 9b479db3257..f02f792ba43 100644--- a/website/docs/user-guide/desktop.md+++ b/website/docs/user-guide/desktop.md@@ -182,6 +182,8 @@ That bridges to `ELECTRON_OZONE_PLATFORM_HINT` at launch (an explicit env var st#### WSLg (Windows GPU from WSL2)+Under local WSLg, Hermes launches with `--ozone-platform=wayland` to avoid the XWayland maximized-window offset and shifted mouse hit-testing ([microsoft/wslg#1015](https://github.com/microsoft/wslg/issues/1015)). The platform must be selected at process launch, before Electron loads application JavaScript. Explicit `--ozone-platform=x11` and `desktop.ozone_platform_hint: x11` remain available. The app draws its own minimize, maximize and close controls on WSLg.+When `hermes gui` runs inside WSL2 with `/dev/dxg` present and Mesa's `d3d12_dri.so` installed, the launcher sets `GALLIUM_DRIVER=d3d12` for Electron so rendering uses the Windows GPU instead of the llvmpipe software rasterizer; an explicit `GALLIUM_DRIVER`, `MESA_LOADER_DRIVER_OVERRIDE`, `LIBGL_ALWAYS_SOFTWARE`, or `LIBGL_DRIVERS_PATH` in your environment is left untouched (for example `GALLIUM_DRIVER=llvmpipe hermes gui` keeps software rendering).### Settings & onboarding