#36778·deno

`[Feature Request / Bug]: Decouple Deno.Tray from BrowserWindow & fix tray menu interactivity when host window is hidden on Windows (WebView2 backend)`

Author: SelexoCreated Sep 6, 2026Updated Sep 26, 2026

Disclaimer & Context

Disclaimer: These observations are based on personal experience while attempting to build a background Deno system-tray application on Windows that does not depend on an embedded webview. The technical explanations below—particularly those concerning WebView2's message pump—are working hypotheses and may be incomplete or incorrect. The behavioral difference between the WebView2 and CEF backends is consistently reproducible, but the precise internal cause requires investigation and confirmation from the Deno maintainers. PS: and yes I have looked at Deno RAW support, it still brings it's own challenges.


Motivation & Real-World Background

There is a major use case for building background / system tray services in Deno: applications that sit in the OS system status area (Windows notification tray / macOS menu bar), run a background task or local HTTP server (Deno.serve), and allow users to interact with a web UI in their system default browser (Chrome, Edge, Firefox) rather than rendering an embedded desktop webview.

In enterprise and real-world Windows environments, there is significant motivation to avoid coupling background services to an embedded WebView2:

  1. Severe WebView2 Startup Delays & Process Freezes: In production environments, applications depending on WebView2 have been observed taking up to ten minutes or more to display their windows. These stalls frequently correlate with:
    • OneDrive file hydration states and virtual filesystem filters.
    • Enterprise EDR / Heuristic security scanners (e.g. CrowdStrike Falcon, Windows Defender ATP) deeply inspecting spawned msedgewebview2.exe runtime trees, even when the application binaries and assets have not changed.
    • Scenarios where the WebView2 process appears in Task Manager with active threads but never renders or surfaces its GUI interface.
  2. Shared WebView2 State Pollution Across Applications: When building Windows applications using frameworks like Wails or Tauri that rely on WebView2, if an existing application crashes, windows sleep recovery failures or something else leaves WebView2 user data or runtime state in an unclean/unhealthy condition, other WebView2-dependent applications can inherit startup stalls or fail to launch completely.
  3. The Web-Browser-First Architecture: Serving the primary user interface through a standard local web server (Deno.serve) and opening the user's default browser provides maximum reliability, bypasses embedded webview initialization overhead, and eliminates security scanner interference. The system tray should ideally serve as a lightweight lifecycle controller for this workflow without being forced to host an embedded webview.

Description of Issues Encountered

When attempting to build a decoupled system tray service using Deno.Tray on Windows, several roadblocks arise:

  1. Deno.serve Auto-Binds & Forces the Embedded Webview Visible: When deno desktop starts, it injects DENO_SERVE_ADDRESS. Calling Deno.serve() automatically binds to this address and causes the desktop runtime to navigate its embedded BrowserWindow to that URL and invoke ShowWindow(hWnd, SW_SHOW), overriding any programmatic win.hide().
  2. Hidden Window Breaks System Tray Interactivity in Default WebView2 Backend: If DENO_SERVE_ADDRESS is deleted to prevent the webview from auto-showing, and the initial startup window is hidden (win.hide()), the system tray icon (Deno.Tray) appears in the Windows notification area, but has zero interactivity (left-clicks, double-clicks, and right-click setMenu context menus do not open or fire events).
  3. Critical Discovery — Backend Divergence (cef vs webview2):
    • WebView2 Backend (deno desktop main.ts): The tray icon has zero click or menu interactivity on Windows when the host window is hidden.
    • CEF Backend (deno desktop --backend cef main.ts): The tray icon and its context menus work as expected even with the host window hidden!
    • Working Hypothesis: In the default WebView2 backend on Windows, message dispatching appears closely tied to the host window's HWND; calling win.hide() (SW_HIDE) seems to suspend or drop WM_NOTIFYICON, WM_RBUTTONUP, and WM_CONTEXTMENU message processing. In contrast, CEF maintains its own dedicated UI message loop thread independent of window visibility, allowing Windows Shell_NotifyIcon callbacks to continue routing to Deno's event listeners.
  4. Unhandled Webview Navigation Timeout (ERR_CONNECTION_REFUSED): Initially, the startup window was hidden and the local server started on port 8000. However, because DENO_SERVE_ADDRESS was deleted, the native runner's embedded webview still attempted to connect to the allocated ephemeral port in the background. After ~30 seconds, Chromium/CEF encountered a fatal ERR_CONNECTION_REFUSED navigation failure and unexpectedly surfaced the window with a connection error screen.
  5. Closing the Window Terminates the Process: Calling win.close() cannot be used to discard the unwanted window because closing all windows signals the Deno desktop runtime to exit immediately.
  6. Process Spawning in GUI Subsystem Fails with Invalid handle: In Windows GUI binaries (SUBSYSTEM_WINDOWS), calling new Deno.Command(...).spawn() fails with TypeError: Failed to spawn: Invalid handle (os error 6) unless stdin, stdout, and stderr are explicitly set to "null" (because standard console streams are unallocated in GUI mode).

Current Workaround: Dual-Server Architecture

To work around these constraints in Deno 2.9, an unconventional dual-stream / dual-server architecture was required:

  1. Server 1 (Internal Webview): Listens on DENO_SERVE_ADDRESS to satisfy the embedded webview's startup navigation immediately with HTTP 200, preventing the 30-second ERR_CONNECTION_REFUSED timeout. The webview remains available strictly as a secondary informational / health panel (uptime, memory usage, PID, and exit button).
  2. Server 2 (Browser Portal): Listens on http://localhost:8000 to serve the primary application UI to the user's default browser.
  3. Window Close Interception: The window's close event is intercepted via win.addEventListener("close", (e) => { e.preventDefault(); win.hide(); }) so closing the informational panel sends the window back to the system tray rather than terminating the service.
  4. Single-Instance Detection: On launch, a quick probe to /api/ping checks if an instance is already active. If so, it launches the browser portal and exits immediately, avoiding port collisions.

While this workaround functions, it is an unnecessarily complex compromise for utilities that simply want a lightweight system-tray icon and a local background server without any webview overhead.


Proposed Solutions / Enhancements

  1. Standalone Deno.Tray Support (Decoupled from BrowserWindow): Allow Deno.Tray to be used in standalone binaries compiled via deno compile --no-terminal (or standard deno run) without requiring an embedded WebView2 or CEF webview runtime. On Windows, the tray icon can register against an invisible, lightweight message-only window (HWND_MESSAGE).
  2. First-Class Headless / Tray-Only App Mode in deno desktop: Provide a configuration option in deno.json or CLI (e.g. --headless or "desktop": { "window": false }) that prevents the creation of the default startup window while keeping the runtime message loop alive for tray events.
  3. Fix WndProc / Tray Message Dispatching in Windows WebView2 Backend: Ensure that calling win.hide() on Windows does not pause Shell_NotifyIcon callback handling (WM_RBUTTONUP, WM_LBUTTONUP, WM_CONTEXTMENU) in the default WebView2 backend, matching the functional behavior already present in the --backend cef runner.
  4. Default Stdio Handling in GUI Subsystem: When running inside a GUI subsystem binary where standard handles are invalid, Deno.Command should automatically default standard streams to null/piped instead of throwing Invalid handle (os error 6).

Minimal Reproduction Code

typescript
// main.ts

// 1. Prevent webview from auto-navigating and revealing itself
Deno.env.delete("DENO_SERVE_ADDRESS");

// 2. Hide the implicit startup window so no GUI window shows
const win = new Deno.BrowserWindow({ title: "Tray Host" });
win.hide();

// 3. Start a local server for the web portal
Deno.serve({ port: 8000, hostname: "127.0.0.1" }, () => {
  return new Response("<h1>Portal Running</h1>", {
    headers: { "content-type": "text/html" },
  });
});

// 4. Setup Tray
const tray = new Deno.Tray();

// 16x16 PNG icon bytes
const base64 = "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAUSURBVDhPY/wPBAxUABs1YNSAUQMABf4BAdKz9S0AAAAASUVORK5CYII=";
tray.setIcon(Uint8Array.from(atob(base64), c => c.charCodeAt(0)));
tray.setTooltip("My Tray Service");

tray.setMenu([
  { item: { label: "Open Portal", id: "open", enabled: true } },
  "separator",
  { item: { label: "Quit", id: "quit", enabled: true } },
]);

// 5. Event listeners
tray.addEventListener("click", () => {
  console.log("Tray left-clicked");
});

tray.addEventListener("menuclick", (e) => {
  console.log("Menu item clicked:", e.detail.id);
  if (e.detail.id === "quit") Deno.exit(0);
});

Steps to Reproduce & Divergent Results

  1. Compile with default WebView2 backend:

    powershell
    deno desktop --allow-all --output tray-webview main.ts
    .\tray-webview\tray-webview.exe

    Result (Bug): The tray icon appears, but left-clicking or right-clicking has zero response. No menu appears and no events fire.

  2. Compile with CEF backend:

    powershell
    deno desktop --allow-all --backend cef --output tray-cef main.ts
    .\tray-cef\tray-cef.exe

    Result (Working): The tray icon appears and context menus and click events work completely as expected, proving that the bug is specific to message-pump handling in the Windows WebView2 implementation.


Environment

  • OS: Windows 11 / 10 (x86_64)
  • Deno version: 2.9.6
  • Affected Backend: WebView2 (default)
  • Unaffected Backend: CEF (--backend cef)