Skip to content

The agent that grows with you

fix(desktop): app-grid launches write hermes.desktop only after the window is on screen

teknium1169c48fa1357
diff --git a/apps/desktop/electron/linux-launcher-ready.ts b/apps/desktop/electron/linux-launcher-ready.ts
new file mode 100644
index 00000000000..22645ade208
--- /dev/null
+++ b/apps/desktop/electron/linux-launcher-ready.ts
@@ -0,0 +1,48 @@
+/**
+ * Tells the `hermes desktop` launcher that the main window is on screen.
+ *
+ * On Linux an app-grid launch defers writing the app's own `.desktop` entry
+ * until the window has mapped: unpatched gnome-shell (before GNOME MR !4428)
+ * drops a STARTING ShellApp's last reference when its entry changes, and the
+ * next idle GC takes down the whole Wayland session (#111906). The launcher
+ * hands us the write end of a pipe in `HERMES_DESKTOP_READY_FD`; one byte means
+ * "mapped, safe to heal". A launch without the variable is a no-op.
+ */
+
+import fs from 'node:fs'
+
+export const LAUNCHER_READY_FD_ENV = 'HERMES_DESKTOP_READY_FD'
+
+type ReadyFdIo = {
+ writeSync: (fd: number, data: string) => number
+ closeSync: (fd: number) => void
+}
+
+/**
+ * Signal the launcher once. The fd is closed after the write and the variable
+ * removed from `env`, so a second reveal (or a child inheriting the env) can
+ * never write into whatever file later reuses that descriptor number.
+ */
+export function notifyLauncherWindowRevealed(env: NodeJS.ProcessEnv = process.env, io: ReadyFdIo = fs): boolean {
+ const raw = env[LAUNCHER_READY_FD_ENV]
+
+ if (raw === undefined) {
+ return false
+ }
+
+ delete env[LAUNCHER_READY_FD_ENV]
+ const fd = Number(raw)
+
+ if (!Number.isInteger(fd) || fd < 0) {
+ return false
+ }
+
+ try {
+ io.writeSync(fd, 'r')
+ io.closeSync(fd)
+
+ return true
+ } catch {
+ return false
+ }
+}
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.ts
index 5588f5961a4..28a7f367319 100644
--- a/apps/desktop/electron/main.ts
+++ b/apps/desktop/electron/main.ts
@@ -238,6 +238,7 @@ import { buildHudWindowUrl } from './hud-url'
import { resolveHudWindowing } from './hud-windowing'
import { createIntroRevealWindowController } from './intro-reveal-window'
import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'
+import { notifyLauncherWindowRevealed } from './linux-launcher-ready'
import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'
import { ensureMainWindow } from './main-window-lifecycle'
import {
@@ -14672,6 +14673,10 @@ function createWindow() {
// first clean resize/move/close still captures the restored bounds (#56726).
schedulePersistWindowState()
+ // #111906: the Linux launcher holds back its .desktop entry write until the
+ // window is on screen (a STARTING gnome-shell app must not see its entry change).
+ notifyLauncherWindowRevealed()
+
// #38216: clear the mid-boot marker only after a window is actually usable.
// Keep sticky `fallback` when we launched with --no-sandbox so the next
// Start Menu click does not re-enter the GPU FATAL crash loop. The marker
diff --git a/hermes_cli/linux_desktop_entry.py b/hermes_cli/linux_desktop_entry.py
index aa4ff4d600b..d866321f356 100644
--- a/hermes_cli/linux_desktop_entry.py
+++ b/hermes_cli/linux_desktop_entry.py
@@ -16,11 +16,19 @@ import shutil
import struct
import subprocess
import sys
+import threading
+import time
from pathlib import Path
-from typing import Optional
+from typing import Callable, Mapping, Optional
DESKTOP_ENTRY_NAME = "hermes.desktop"
+# XDG startup notification: set by an app-grid / menu launch, absent for terminal and detached
+# (updater relaunch) launches. See launched_from_shell().
+SHELL_LAUNCH_ENV_VAR = "DESKTOP_STARTUP_ID"
+# Write end of the reveal pipe handed to Electron; one byte means "main window is on screen".
+READY_FD_ENV_VAR = "HERMES_DESKTOP_READY_FD"
+
_SHELL_NAMES = ("bash", "sh", "dash", "zsh", "ksh")
@@ -619,3 +627,92 @@ def install_desktop_entry(project_root: Path) -> Optional[Path]:
refresh_desktop_databases(entry_path.parent)
return entry_path
+
+
+def launched_from_shell(environ: Optional[Mapping[str, str]] = None) -> bool:
+ """True when this process was started from the app grid / menu (XDG startup notification).
+
+ A grid launch has a gnome-shell ShellApp in STARTING until our window maps; unpatched
+ shells (before GNOME MR !4428) drop that app's last reference when its own ``.desktop``
+ entry changes, and the next idle GC kills the whole Wayland session (#111906). A false
+ negative degrades to the pre-#111906 behaviour; a false positive only delays a heal.
+ """
+ env = os.environ if environ is None else environ
+ return bool(env.get(SHELL_LAUNCH_ENV_VAR))
+
+
+class DeferredDesktopEntryInstall:
+ """Install the entry once the desktop window is on screen — never while the shell's
+ ShellApp is STARTING.
+
+ The launcher hands Electron the write end of a pipe (``HERMES_DESKTOP_READY_FD``); Electron
+ writes one byte when the main window is revealed and a worker thread then installs the entry.
+ ``finish()`` runs after Electron exits and covers the app never revealing a window (a STOPPED
+ app has no STARTING object, so writing there is safe). Terminal and detached launches never
+ build one of these: they install immediately, as before.
+ """
+
+ def __init__(
+ self,
+ project_root: Path,
+ install: Optional[Callable[[Path], Optional[Path]]] = None,
+ settle_seconds: float = 2.0,
+ ) -> None:
+ self._project_root = project_root
+ self._install = install or install_desktop_entry
+ # Electron reports the reveal before the compositor has necessarily mapped the surface;
+ # a short settle after the signal keeps the write on the RUNNING side. It is a margin
+ # after the condition, not a substitute for it.
+ self._settle_seconds = settle_seconds
+ self._read_fd, self.write_fd = os.pipe()
+ self._lock = threading.Lock()
+ self._done = False
+ self._thread = threading.Thread(target=self._wait_for_reveal, name="desktop-entry-install", daemon=True)
+
+ def child_env(self, env: dict) -> dict:
+ env[READY_FD_ENV_VAR] = str(self.write_fd)
+ return env
+
+ @property
+ def pass_fds(self) -> tuple[int, ...]:
+ return (self.write_fd,)
+
+ def start(self) -> None:
+ self._thread.start()
+
+ def _wait_for_reveal(self) -> None:
+ try:
+ data = os.read(self._read_fd, 1)
+ except OSError:
+ return
+ if self._done: # woken by finish(): the app already exited, finish() owns the heal
+ return
+ if data and self._settle_seconds:
+ time.sleep(self._settle_seconds)
+ self._heal()
+
+ def _heal(self) -> None:
+ with self._lock:
+ if self._done:
+ return
+ self._done = True
+ try:
+ entry = self._install(self._project_root)
+ if entry:
+ print(f"✓ Desktop launcher entry installed: {entry}")
+ except Exception as exc: # never fail a launch on launcher plumbing
+ print(f"⚠ Could not install the desktop launcher entry: {exc}")
+
+ def finish(self) -> None:
+ """Electron exited: heal now if the reveal never came, and let an in-flight heal complete."""
+ self._heal()
+ try:
+ os.write(self.write_fd, b"x") # wake the reader so join() returns promptly
+ except OSError:
+ pass
+ self._thread.join(timeout=15)
+ for fd in (self._read_fd, self.write_fd):
+ try:
+ os.close(fd)
+ except OSError:
+ pass
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index 6776b6f7fef..48aa89633fd 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -1227,22 +1227,31 @@ def _desktop_launch_options() -> tuple[list[str], str, str, str]:
return flags, disable_gpu, password_store, ozone_hint
-def _register_linux_desktop_entry() -> None:
+def _register_linux_desktop_entry(defer: bool = False):
"""Install the XDG desktop entry for Hermes Desktop (Linux only, best-effort).
``Exec`` and ``Icon`` are absolute so the entry works outside a login shell.
``hermes uninstall --gui`` removes it.
+
+ ``defer=True`` (app-grid launch) returns a ``DeferredDesktopEntryInstall`` that writes the
+ entry only once the Electron window is on screen (#111906); ``None`` when nothing is
+ pending. Terminal, detached and ``--build-only`` launches install synchronously.
"""
from hermes_cli.main import PROJECT_ROOT
try:
- from hermes_cli.linux_desktop_entry import install_desktop_entry, is_supported
+ from hermes_cli.linux_desktop_entry import DeferredDesktopEntryInstall, install_desktop_entry, is_supported
if not is_supported():
- return
+ return None
+ if defer:
+ deferred = DeferredDesktopEntryInstall(PROJECT_ROOT)
+ deferred.start()
+ return deferred
entry = install_desktop_entry(PROJECT_ROOT)
if entry:
print(f"✓ Desktop launcher entry installed: {entry}")
except Exception as exc: # never block a launch on launcher plumbing
print(f"⚠ Could not install the desktop launcher entry: {exc}")
+ return None
def _install_desktop_workspace_deps(npm: str, env: dict) -> None:
@@ -1547,14 +1556,19 @@ def cmd_gui(args: argparse.Namespace):
print(f"✓ Desktop {build_label} is up to date (content stamp matches)")
# Best-effort and idempotent; a failure must never stop the app from launching.
- _register_linux_desktop_entry()
+ # An app-grid launch (DESKTOP_STARTUP_ID) must not write its own entry while the
+ # shell still has the app in STARTING, so it defers the write until Electron
+ # reports the window on screen (#111906). --build-only spawns no app: write now.
+ from hermes_cli.linux_desktop_entry import launched_from_shell
+ build_only = bool(getattr(args, "build_only", False))
+ deferred_entry = _register_linux_desktop_entry(defer=launched_from_shell() and not build_only)
# --build-only: produce the artifact but do NOT launch. The installer's
# --update flow drives the rebuild headlessly and launches the desktop
# itself (detached, after the old exe has exited); launching here would
# block the installer. Verify the artifact exists so a silent "built
# nothing" can't slip past.
- if getattr(args, "build_only", False):
+ if build_only:
if source_mode:
if not _desktop_dist_exists(desktop_dir):
print(f"✗ --build-only --source produced no dist at: {desktop_dir / 'dist'}")
@@ -1582,5 +1596,11 @@ def cmd_gui(args: argparse.Namespace):
launch_command.append("--local")
if not source_mode:
print(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")
- launch_result = subprocess.run(launch_command, cwd=desktop_dir, env=env, check=False)
+ pass_fds: tuple[int, ...] = ()
+ if deferred_entry is not None:
+ env = deferred_entry.child_env(env)
+ pass_fds = deferred_entry.pass_fds
+ launch_result = subprocess.run(launch_command, cwd=desktop_dir, env=env, check=False, pass_fds=pass_fds)
+ if deferred_entry is not None:
+ deferred_entry.finish()
sys.exit(launch_result.returncode)