`[Feature Request / Bug]: Decouple Deno.Tray from BrowserWindow & fix tray menu interactivity when host window is hidden on Windows (WebView2 backend)`
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:
- 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.exeruntime 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.
- 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.
- 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:
Deno.serveAuto-Binds & Forces the Embedded Webview Visible: Whendeno desktopstarts, it injectsDENO_SERVE_ADDRESS. CallingDeno.serve()automatically binds to this address and causes the desktop runtime to navigate its embeddedBrowserWindowto that URL and invokeShowWindow(hWnd, SW_SHOW), overriding any programmaticwin.hide().- Hidden Window Breaks System Tray Interactivity in Default WebView2 Backend:
If
DENO_SERVE_ADDRESSis 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-clicksetMenucontext menus do not open or fire events). - Critical Discovery — Backend Divergence (
cefvswebview2):- 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 dropWM_NOTIFYICON,WM_RBUTTONUP, andWM_CONTEXTMENUmessage processing. In contrast, CEF maintains its own dedicated UI message loop thread independent of window visibility, allowing WindowsShell_NotifyIconcallbacks to continue routing to Deno's event listeners.
- WebView2 Backend (
- Unhandled Webview Navigation Timeout (
ERR_CONNECTION_REFUSED): Initially, the startup window was hidden and the local server started on port 8000. However, becauseDENO_SERVE_ADDRESSwas 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 fatalERR_CONNECTION_REFUSEDnavigation failure and unexpectedly surfaced the window with a connection error screen. - 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. - Process Spawning in GUI Subsystem Fails with
Invalid handle: In Windows GUI binaries (SUBSYSTEM_WINDOWS), callingnew Deno.Command(...).spawn()fails withTypeError: Failed to spawn: Invalid handle (os error 6)unlessstdin,stdout, andstderrare 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:
- Server 1 (Internal Webview): Listens on
DENO_SERVE_ADDRESSto satisfy the embedded webview's startup navigation immediately with HTTP 200, preventing the 30-secondERR_CONNECTION_REFUSEDtimeout. The webview remains available strictly as a secondary informational / health panel (uptime, memory usage, PID, and exit button). - Server 2 (Browser Portal): Listens on
http://localhost:8000to serve the primary application UI to the user's default browser. - 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. - Single-Instance Detection: On launch, a quick probe to
/api/pingchecks 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
- Standalone
Deno.TraySupport (Decoupled fromBrowserWindow): AllowDeno.Trayto be used in standalone binaries compiled viadeno compile --no-terminal(or standarddeno 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). - First-Class Headless / Tray-Only App Mode in
deno desktop: Provide a configuration option indeno.jsonor CLI (e.g.--headlessor"desktop": { "window": false }) that prevents the creation of the default startup window while keeping the runtime message loop alive for tray events. - Fix
WndProc/ Tray Message Dispatching in Windows WebView2 Backend: Ensure that callingwin.hide()on Windows does not pauseShell_NotifyIconcallback handling (WM_RBUTTONUP,WM_LBUTTONUP,WM_CONTEXTMENU) in the default WebView2 backend, matching the functional behavior already present in the--backend cefrunner. - Default Stdio Handling in GUI Subsystem:
When running inside a GUI subsystem binary where standard handles are invalid,
Deno.Commandshould automatically default standard streams to null/piped instead of throwingInvalid handle (os error 6).
Minimal Reproduction Code
// 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
Compile with default WebView2 backend:
deno desktop --allow-all --output tray-webview main.ts .\tray-webview\tray-webview.exeResult (Bug): The tray icon appears, but left-clicking or right-clicking has zero response. No menu appears and no events fire.
Compile with CEF backend:
deno desktop --allow-all --backend cef --output tray-cef main.ts .\tray-cef\tray-cef.exeResult (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)
Source: denoland/deno