The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): guarantee an exit path for a fullscreened preview pane
Brooklyn Nicholsond2b9a49e63ef
diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 56a06b23134..c3951f5aad8 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -417,6 +417,7 @@ import { createKeepAwake } from './power-save'import { readPreUpdateBackupEnabled } from './pre-update-backup-config'import { capturePreviewContents } from './preview-capture'import { onPreviewWatchOwnerDestroyed, sendPreviewFileChangedToOwner } from './preview-file-watch'+import { hasClosePreviewFlag, previewGuestInputAction } from './preview-guest-escape'import { PreviewReachRegistry } from './preview-reach'import {createPrimaryRemoteConnection,@@ -13499,6 +13500,47 @@ function wireCommonWindowHandlers(win, { zoom = true }: { zoom?: boolean } = {})})}+/**+ * The guaranteed exit path for a fullscreened preview guest (#97213).+ *+ * `before-input-event` fires on the guest's own webContents before the page+ * sees the key, so this works even while the guest holds fullscreen input+ * focus — the one interception point neither the renderer (no focus+ * visibility into the guest) nor the OS (Wayland has no xdotool/wmctrl) can+ * provide. The routing decision lives in preview-guest-escape.ts.+ */+function installPreviewGuestEscapeHatch() {+ app.on('web-contents-created', (_event, contents) => {+ if (contents.getType() !== 'webview') {+ return+ }++ contents.on('before-input-event', (event, input) => {+ const owner = BrowserWindow.fromWebContents(contents.hostWebContents ?? contents)++ switch (previewGuestInputAction(input, Boolean(owner?.isFullScreen()))) {+ case 'exit-fullscreen': {+ event.preventDefault()++ if (owner && !owner.isDestroyed()) {+ owner.setFullScreen(false)+ }++ break+ }+ case 'close-preview': {+ event.preventDefault()+ sendClosePreviewRequested()++ break+ }+ default:+ break+ }+ })+ })+}+/*** Give the preview pane's `<webview>` guests a preload — and ONLY those* guests. The pane's webview is the one `webview` tag in the app and it@@ -18711,6 +18753,29 @@ function handleDeepLink(url) {return}+ // hermes://close-preview — the out-of-band exit hatch for a preview pane+ // that fullscreened itself and now owns all input (#97213). Handled here+ // rather than in the renderer because the whole point is to work when the+ // renderer cannot hear anything: exit the fullscreen window and close the+ // pane from the main process.+ if (kind === 'close-preview') {+ if (mainWindow && !mainWindow.isDestroyed()) {+ if (mainWindow.isMinimized()) {+ mainWindow.restore()+ }++ mainWindow.focus()++ if (mainWindow.isFullScreen()) {+ mainWindow.setFullScreen(false)+ }++ sendClosePreviewRequested()+ }++ return+ }+if (!_rendererReadyForDeepLink || !mainWindow || mainWindow.isDestroyed()) {_pendingDeepLink = payload@@ -18806,6 +18871,14 @@ if (!isPrimaryInstance) {}app.on('second-instance', (_event, argv) => {+ // --close-preview: the same escape hatch as hermes://close-preview, for+ // environments where spawning a URL is harder than a flag (kiosk launchers,+ // SSH-started sessions). Checked before deep links so a carried `hermes://`+ // URL still routes normally when no flag is present.+ if (hasClosePreviewFlag(argv)) {+ handleDeepLink('hermes://close-preview')+ }+const url = _extractDeepLink(argv)if (url) {@@ -18892,6 +18965,7 @@ app.whenReady().then(() => {registerDeepLinkProtocol()}+ installPreviewGuestEscapeHatch()installPreviewGuestPreload()ensureWslWindowsFonts()diff --git a/apps/desktop/electron/preview-guest-escape.test.ts b/apps/desktop/electron/preview-guest-escape.test.tsnew file mode 100644index 00000000000..8142963f55e--- /dev/null+++ b/apps/desktop/electron/preview-guest-escape.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from 'vitest'++import { hasClosePreviewFlag, previewGuestInputAction } from './preview-guest-escape'++describe('previewGuestInputAction', () => {+ it('exits fullscreen on Escape only while the host window is fullscreen', () => {+ expect(previewGuestInputAction({ key: 'Escape', type: 'keyDown' }, true)).toBe('exit-fullscreen')+ // A pane in normal mode keeps passing Esc through to the page.+ expect(previewGuestInputAction({ key: 'Escape', type: 'keyDown' }, false)).toBeNull()+ })++ it('closes the preview on Ctrl+Shift+W regardless of fullscreen state', () => {+ expect(previewGuestInputAction({ control: true, shift: true, key: 'w', type: 'keyDown' }, true)).toBe(+ 'close-preview'+ )+ expect(previewGuestInputAction({ control: true, shift: true, key: 'w', type: 'keyDown' }, false)).toBe(+ 'close-preview'+ )+ })++ it('also accepts the Cmd+Shift+W (macOS) form', () => {+ expect(previewGuestInputAction({ meta: true, shift: true, key: 'W', type: 'keyDown' }, true)).toBe(+ 'close-preview'+ )+ })++ it('leaves every other key for the page', () => {+ expect(previewGuestInputAction({ key: 'a', type: 'keyDown' }, true)).toBeNull()+ // Bare W / Ctrl+W without Shift is not the close chord.+ expect(previewGuestInputAction({ control: true, key: 'w', type: 'keyDown' }, true)).toBeNull()+ // Shift+W without the modifier is typing, not closing.+ expect(previewGuestInputAction({ shift: true, key: 'W', type: 'keyDown' }, true)).toBeNull()+ })++ it('ignores key releases and auto-repeats', () => {+ expect(previewGuestInputAction({ key: 'Escape', type: 'keyUp' }, true)).toBeNull()+ expect(previewGuestInputAction({ isAutoRepeat: true, key: 'Escape', type: 'keyDown' }, true)).toBeNull()+ })+})++describe('hasClosePreviewFlag', () => {+ it('detects the flag in both forms', () => {+ expect(hasClosePreviewFlag(['Hermes', '--close-preview'])).toBe(true)+ expect(hasClosePreviewFlag(['Hermes', '--close-preview=1'])).toBe(true)+ })++ it('ignores other argv and empty argv', () => {+ expect(hasClosePreviewFlag(['Hermes'])).toBe(false)+ expect(hasClosePreviewFlag(['--close'])).toBe(false)+ expect(hasClosePreviewFlag([])).toBe(false)+ })+})diff --git a/apps/desktop/electron/preview-guest-escape.ts b/apps/desktop/electron/preview-guest-escape.tsnew file mode 100644index 00000000000..c9cd297add8--- /dev/null+++ b/apps/desktop/electron/preview-guest-escape.ts@@ -0,0 +1,67 @@+/**+ * The preview pane's escape hatch (#97213).+ *+ * A `<webview>` guest is its own out-of-process webContents: once a guest+ * page takes HTML5 fullscreen it owns the input focus, and nothing in the+ * host renderer — menus, HUD chords, the app's own keybinds — can reach+ * the user while the guest holds the screen. On Wayland there is no+ * xdotool/wmctrl to force a window change from outside either, so a page+ * that swallows Esc (or simply never offers one) locks the whole display.+ *+ * Electron's `before-input-event` fires on the guest's webContents BEFORE+ * the page sees the key, which is the one interception point the host+ * always owns. This module holds the pure routing decision so the policy+ * is unit-testable without a live guest.+ */++export type PreviewGuestInputAction = 'close-preview' | 'exit-fullscreen'++/** The subset of Electron's `Input` the decision needs. */+export interface PreviewGuestInput {+ control?: boolean+ isAutoRepeat?: boolean+ key: string+ meta?: boolean+ shift?: boolean+ type: string+}++/**+ * Decide what a keypress inside a preview guest must trigger on the host.+ *+ * - Escape while the host window is fullscreen: exit fullscreen. Gated on+ * the fullscreen state so a pane in normal mode keeps passing Esc through+ * to the page (video players and web UIs use it for their own exits).+ * - Ctrl/Cmd+Shift+W: close the preview pane. This mirrors the host's+ * close-tab chord so muscle memory works no matter who has focus.+ *+ * Returns null when the page should see the key unchanged.+ */+export function previewGuestInputAction(+ input: PreviewGuestInput,+ hostIsFullscreen: boolean+): PreviewGuestInputAction | null {+ if (input.type !== 'keyDown' || input.isAutoRepeat) {+ return null+ }++ if (input.key === 'Escape') {+ return hostIsFullscreen ? 'exit-fullscreen' : null+ }++ if ((input.control || input.meta) && input.shift && input.key.toLowerCase() === 'w') {+ return 'close-preview'+ }++ return null+}++/**+ * Recognize the `--close-preview` summon flag in an argv, accepting both+ * the bare form and the `--close-preview=<value>` form Electron may pass+ * through verbatim. Mirrors `hasQuickEntryFlag` so the CLI can forward the+ * same flag shape (#82654's compositor-keybind path).+ */+export function hasClosePreviewFlag(argv: readonly string[]): boolean {+ return argv.some(arg => arg === '--close-preview' || arg.startsWith('--close-preview='))+}diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.pyindex 5e8f6f1d8b2..05da449f17f 100644--- a/hermes_cli/main_desktop.py+++ b/hermes_cli/main_desktop.py@@ -1736,6 +1736,12 @@ def cmd_gui(args: argparse.Namespace):launch_command.extend(config_electron_flags)if getattr(args, "local", False):launch_command.append("--local")+ # Out-of-band preview escape hatch (#97213): a fullscreened preview pane+ # owns all input, and Wayland has no xdotool/wmctrl to break out from a+ # terminal. `hermes desktop --close-preview` rides the single-instance+ # argv so a second CLI invocation unlocks the running app.+ if getattr(args, "close_preview", False):+ launch_command.append("--close-preview")launch_command.extend(_explicit_profile_args())if not source_mode:desktop_launch_notice(f"→ Launching packaged Hermes Desktop: {' '.join(launch_command)}")diff --git a/hermes_cli/subcommands/gui.py b/hermes_cli/subcommands/gui.pyindex b08df0f55d6..a4dd29d50af 100644--- a/hermes_cli/subcommands/gui.py+++ b/hermes_cli/subcommands/gui.py@@ -54,4 +54,9 @@ def build_gui_parser(subparsers, *, cmd_gui: Callable) -> None:"--identity", default="Hermes Local Signing",help="Certificate name to create/use for --setup-tcc-identity (default: Hermes Local Signing)",)+ gui_parser.add_argument(+ "--close-preview",+ action="store_true",+ help="Close the preview pane and exit its fullscreen (out-of-band escape hatch when the pane captured all input)",+ )gui_parser.set_defaults(func=cmd_gui)diff --git a/tests/hermes_cli/test_gui_command.py b/tests/hermes_cli/test_gui_command.pyindex e82b4e86659..8f4488879f5 100644--- a/tests/hermes_cli/test_gui_command.py+++ b/tests/hermes_cli/test_gui_command.py@@ -71,6 +71,7 @@ def _ns(**kw):cwd=None,setup_tcc_identity=False,identity=None,+ close_preview=False,)defaults.update(kw)return argparse.Namespace(**defaults)@@ -292,6 +293,41 @@ def test_gui_brew_install_launches_installed_app_when_present(tmp_path, monkeypaassert launched == [1]+def test_gui_close_preview_flag_forwards_to_packaged_exe(tmp_path, monkeypatch):+ """`hermes desktop --close-preview` must reach the Electron binary so the+ running instance's single-instance handler can close a fullscreened+ preview pane the user cannot otherwise escape (#97213)."""+ root = _make_desktop_tree(tmp_path)+ monkeypatch.setattr(cli_main, "PROJECT_ROOT", root)+ # Patching hermes_cli.main_desktop.subprocess.run swaps the shared stdlib+ # module's attribute, so the desktop-entry install's interpreter probe+ # (`<python> -I -c 'import hermes_cli.main'`) would be captured as a+ # launch too. Neutralize the entry install the way the other foreground+ # tests do; this test is only about the flag reaching the packaged exe.+ monkeypatch.setattr(main_desktop, "_register_linux_desktop_entry", lambda **kw: None)+ packaged_exe = _make_packaged_executable(root, monkeypatch)++ launched: list[list[str]] = []++ def fake_run(cmd, **kw):+ launched.append(list(cmd))+ return subprocess.CompletedProcess(cmd, 0)++ with patch("hermes_cli.main_desktop._desktop_build_needed", return_value=False), \+ patch("hermes_cli.main_desktop._desktop_linux_sandbox_fixup", return_value=True), \+ patch("hermes_cli.main_desktop.subprocess.run", side_effect=fake_run), \+ pytest.raises(SystemExit) as exc:+ cli_main.cmd_gui(_ns(close_preview=True))++ assert exc.value.code == 0+ if sys.platform.startswith("linux"):+ # A present non-setuid chrome-sandbox makes the launcher pass+ # --disable-setuid-sandbox before the forwarded flag.+ assert launched == [[str(packaged_exe), "--disable-setuid-sandbox", "--close-preview"]]+ else:+ assert launched == [[str(packaged_exe), "--close-preview"]]++@pytest.mark.parametrize("exists,platform", [(True, "darwin"), (False, "darwin"), (True, "linux")])def test_launch_installed_macos_desktop_app_gates_on_bundle_and_platform(tmp_path, monkeypatch, exists, platform):monkeypatch.setattr(main_desktop.sys, "platform", platform)