diff --git a/Directory.Packages.props b/Directory.Packages.props
index b486d76..315b395 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -10,6 +10,7 @@
+
diff --git a/src/Bermuda.AppHost/AppHost.cs b/src/Bermuda.AppHost/AppHost.cs
index 96a9b17..f731580 100644
--- a/src/Bermuda.AppHost/AppHost.cs
+++ b/src/Bermuda.AppHost/AppHost.cs
@@ -24,6 +24,8 @@
var host = builder.AddProject("host")
.WithEnvironment("WEB_URL", web.GetEndpoint("http"))
.WithEnvironment("CDP_PORT", cdpPort)
+ // Keep this run from handing over to (or being taken over by) an installed Bermuda.
+ .WithEnvironment("SINGLE_INSTANCE_KEY", "Bermuda.AppHost")
.WaitFor(web)
.WaitFor(api);
if (!string.IsNullOrWhiteSpace(pipeName)) host.WithEnvironment("FDC3_GRPC_PIPE", pipeName);
diff --git a/src/Bermuda.Web/e2e/hostProcess.ts b/src/Bermuda.Web/e2e/hostProcess.ts
new file mode 100644
index 0000000..355b29c
--- /dev/null
+++ b/src/Bermuda.Web/e2e/hostProcess.ts
@@ -0,0 +1,38 @@
+import { spawn } from 'node:child_process'
+import { existsSync, statSync } from 'node:fs'
+import { dirname, resolve } from 'node:path'
+import { fileURLToPath } from 'node:url'
+
+// The key the Aspire host gives the app under test (AppHost.cs: SINGLE_INSTANCE_KEY). A second process must use
+// the same one to find it.
+const SINGLE_INSTANCE_KEY = 'Bermuda.AppHost'
+
+/** The Bermuda.exe Aspire started: BERMUDA_EXE, else the newest build of the host project. */
+function findHostExe(): string {
+ if (process.env.BERMUDA_EXE) return process.env.BERMUDA_EXE
+ const candidates = ['Debug', 'Release']
+ .map((config) => resolve(dirname(fileURLToPath(import.meta.url)), `../../Bermuda/bin/${config}/net10.0-windows10.0.19041.0/Bermuda.exe`))
+ .filter(existsSync)
+ .sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)
+ if (candidates.length === 0) throw new Error('Bermuda.exe not found; build src/Bermuda or set BERMUDA_EXE.')
+ return candidates[0]
+}
+
+/** Starts a second Bermuda process and resolves with its exit code (it must exit by itself). */
+export function launchSecondInstance(args: string[]): Promise {
+ return new Promise((resolveExit, reject) => {
+ const child = spawn(findHostExe(), args, {
+ env: { ...process.env, SINGLE_INSTANCE_KEY, FDC3_GRPC_ENABLED: 'false', NATIVE_APP_AUTOSTART: 'false' },
+ stdio: 'ignore',
+ })
+ const timer = setTimeout(() => {
+ child.kill()
+ reject(new Error('The second Bermuda did not exit: it did not hand over to the running instance.'))
+ }, 20_000)
+ child.once('error', reject)
+ child.once('exit', (code) => {
+ clearTimeout(timer)
+ resolveExit(code)
+ })
+ })
+}
diff --git a/src/Bermuda.Web/e2e/single-instance.spec.ts b/src/Bermuda.Web/e2e/single-instance.spec.ts
new file mode 100644
index 0000000..30969ce
--- /dev/null
+++ b/src/Bermuda.Web/e2e/single-instance.spec.ts
@@ -0,0 +1,41 @@
+import { test, expect } from './fixtures'
+import { launchSecondInstance } from './hostProcess'
+
+// Bermuda is one process per user: a second launch (jump list task, startup relaunch) hands its activation to
+// the running one and exits. These specs launch that second process for real and check what the running
+// instance did with it.
+
+test.describe('Single instance', () => {
+ test('a second launch with --open opens that app in the running instance', async ({ page }) => {
+ const context = page.context()
+ const probeOpened = context.waitForEvent('page')
+
+ await launchSecondInstance(['--open', 'fdc3-probe'])
+
+ const probe = await probeOpened
+ try {
+ await expect(probe).toHaveURL(/fdc3-probe\.html$/)
+ await expect(probe.locator('#status')).toHaveText('fdc3 ready')
+ } finally {
+ // The shared fixture drives pages()[0], so the extra window must really be gone.
+ const closed = probe.waitForEvent('close')
+ await probe.evaluate(() => window.chrome.webview.hostObjects.windowController.Close()).catch(() => {})
+ await closed
+ }
+
+ // Closing a window that is not the last must not end the app.
+ await expect(page.locator('tbody tr').first()).toBeVisible()
+ })
+
+ test('a plain second launch opens no new window and leaves the first one running', async ({ page }) => {
+ const context = page.context()
+ const pagesBefore = context.pages().length
+
+ await launchSecondInstance([])
+ // Give a wrongly started second window time to appear.
+ await page.waitForTimeout(1500)
+
+ expect(context.pages()).toHaveLength(pagesBefore)
+ await expect(page.locator('tbody tr').first()).toBeVisible()
+ })
+})
diff --git a/src/Bermuda.Web/e2e/tray.spec.ts b/src/Bermuda.Web/e2e/tray.spec.ts
new file mode 100644
index 0000000..7cd8ed4
--- /dev/null
+++ b/src/Bermuda.Web/e2e/tray.spec.ts
@@ -0,0 +1,26 @@
+import type { Page } from '@playwright/test'
+import { test, expect } from './fixtures'
+import { launchSecondInstance } from './hostProcess'
+
+// With the tray icon on (the default), closing the main window only hides it: Bermuda keeps running and its
+// page stays alive. A second launch (or the tray's Show) brings the window back.
+
+const isVisible = (page: Page) => page.evaluate(async () => await window.chrome.webview.hostObjects.windowController.IsVisible)
+
+test.describe('Tray icon', () => {
+ test('closing the main window hides it to the tray instead of ending the app', async ({ page }) => {
+ expect(await isVisible(page)).toBe(true)
+
+ try {
+ await page.evaluate(() => window.chrome.webview.hostObjects.windowController.Close())
+ await expect.poll(() => isVisible(page)).toBe(false)
+
+ // Still running: the page answers and has not been disposed.
+ await expect(page.locator('tbody tr').first()).toBeAttached()
+ } finally {
+ // A second launch asks the running instance to bring its window forward.
+ await launchSecondInstance([])
+ await expect.poll(() => isVisible(page)).toBe(true)
+ }
+ })
+})
diff --git a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts
index b20e37f..ca23371 100644
--- a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts
+++ b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts
@@ -259,6 +259,7 @@ export interface WindowControllerHostObject {
readonly IsMaximized: Promise;
readonly IsMinimized: Promise;
readonly IsFocused: Promise;
+ readonly IsVisible: Promise;
readonly Left: Promise;
readonly Top: Promise;
readonly Width: Promise;
diff --git a/src/Bermuda/App.xaml.cs b/src/Bermuda/App.xaml.cs
index 217b515..35d9f10 100644
--- a/src/Bermuda/App.xaml.cs
+++ b/src/Bermuda/App.xaml.cs
@@ -3,6 +3,9 @@
using Bermuda.Fdc3;
using Bermuda.Fdc3.Grpc;
using Microsoft.Extensions.Configuration;
+using Microsoft.Windows.AppLifecycle;
+using Microsoft.Windows.AppNotifications;
+using Windows.ApplicationModel.Activation;
namespace Bermuda;
@@ -11,8 +14,17 @@ public partial class App : Application
/// The App Directory appId the main window's page runs as (see fdc3-appd.json).
public const string MainAppId = "bermuda-incidents";
+ private AppDirectory _directory = AppDirectory.Empty;
+ private WindowAppLauncher? _launcher;
+
+ // False for a second launch that handed over to the running Bermuda: it must not tear down that one's toasts.
+ private bool _isPrimary;
+
protected override void OnStartup(StartupEventArgs e)
{
+ // Closing the last window no longer ends the app by itself: WindowRegistry decides (and the tray
+ // icon will keep the app alive with no window).
+ ShutdownMode = ShutdownMode.OnExplicitShutdown;
base.OnStartup(e);
var config = new ConfigurationBuilder()
@@ -20,9 +32,14 @@ protected override void OnStartup(StartupEventArgs e)
.AddEnvironmentVariables()
.Build();
+ // One Bermuda per user: a second launch (jump list task, startup relaunch, toast click) hands its
+ // activation to the running one and exits before it opens anything.
+ if (!BecomeSingleInstance(config)) return;
+ _isPrimary = true;
+
NotificationService.Initialize();
- var directory = AppDirectory.Load(Path.Combine(AppContext.BaseDirectory, "fdc3-appd.json"));
- var launcher = new WindowAppLauncher(config);
+ var directory = _directory = AppDirectory.Load(Path.Combine(AppContext.BaseDirectory, "fdc3-appd.json"));
+ var launcher = _launcher = new WindowAppLauncher(config);
var fdc3 = new DesktopAgent(directory, launcher);
launcher.Agent = fdc3;
@@ -34,8 +51,127 @@ protected override void OnStartup(StartupEventArgs e)
StartNativeApps(config, directory);
}
+ // Tray icon (TRAY_ENABLED, default true): the app then lives on with no window, so it also keeps
+ // running when the last window is hidden.
+ WindowRegistry.TrayEnabled = !(bool.TryParse(config["TRAY_ENABLED"], out var trayEnabled) && !trayEnabled);
+ if (WindowRegistry.TrayEnabled)
+ {
+ try
+ {
+ _tray = new TrayService(() => { if (directory.Find(MainAppId) is { } main) launcher.Open(main); });
+ // Logging off or shutting down must not be stopped by the main window hiding itself.
+ SessionEnding += (_, _) => WindowRegistry.MarkQuitting();
+ }
+ catch (Exception ex)
+ {
+ // No tray means no way to bring a hidden window back, so fall back to closing normally.
+ System.Diagnostics.Debug.WriteLine($"Tray icon failed to start: {ex}");
+ WindowRegistry.TrayEnabled = false;
+ }
+ }
+
var window = new MainWindow(config, fdc3, MainAppId);
+ window.ShowActivated = !StartsInBackground();
window.Show();
+ // Started at sign-in (or with --background): sit in the tray, no window until the user asks for it.
+ if (!window.ShowActivated) window.HideWindow();
+
+ // The launch itself may ask for an app on top of the main window (e.g. a jump list task).
+ HandleLaunchArguments(Environment.GetCommandLineArgs().Skip(1).ToArray(), activateMainOtherwise: false);
+ }
+
+ private TrayService? _tray;
+
+ ///
+ /// True when this launch should start hidden in the tray: the MSIX startup task (sign-in) or --background.
+ /// Never without the tray, since there would be no way to bring the window back.
+ ///
+ private static bool StartsInBackground()
+ {
+ if (!WindowRegistry.TrayEnabled) return false;
+ if (Environment.GetCommandLineArgs().Any(a => string.Equals(a, "--background", StringComparison.OrdinalIgnoreCase)))
+ return true;
+ try
+ {
+ return AppInstance.GetCurrent().GetActivatedEventArgs().Kind == ExtendedActivationKind.StartupTask;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ ///
+ /// Registers this process as the user's Bermuda, or — when one is already running — forwards this launch's
+ /// activation to it, shuts this process down and returns false. SINGLE_INSTANCE=false turns it off;
+ /// SINGLE_INSTANCE_KEY isolates a dev/test run (the Aspire host sets one) from an installed Bermuda.
+ ///
+ private bool BecomeSingleInstance(IConfiguration config)
+ {
+ if (bool.TryParse(config["SINGLE_INSTANCE"], out var enabled) && !enabled) return true;
+
+ var key = config["SINGLE_INSTANCE_KEY"] is { Length: > 0 } custom ? custom : "Bermuda";
+ var instance = AppInstance.FindOrRegisterForKey(key);
+ if (instance.IsCurrent)
+ {
+ instance.Activated += OnActivatedByAnotherLaunch;
+ return true;
+ }
+
+ try
+ {
+ // Off the UI thread: redirecting waits on the other process, and an STA that blocks can deadlock.
+ var activation = AppInstance.GetCurrent().GetActivatedEventArgs();
+ Task.Run(() => instance.RedirectActivationToAsync(activation).AsTask()).Wait(TimeSpan.FromSeconds(10));
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"Could not hand this launch to the running Bermuda: {ex}");
+ }
+
+ Shutdown();
+ return false;
+ }
+
+ // Another Bermuda process was launched and handed its activation here (on a background thread).
+ private void OnActivatedByAnotherLaunch(object? sender, AppActivationArguments args) => Dispatcher.BeginInvoke(() =>
+ {
+ switch (args.Data)
+ {
+ case AppNotificationActivatedEventArgs toast:
+ NotificationService.HandleForwarded(toast);
+ break;
+ case ILaunchActivatedEventArgs launch:
+ HandleLaunchArguments(launch.Arguments.Split(' ', StringSplitOptions.RemoveEmptyEntries), activateMainOtherwise: true);
+ break;
+ default:
+ WindowRegistry.ActivateMain();
+ break;
+ }
+ });
+
+ ///
+ /// --open <appId> opens that App Directory app's window; anything else just brings the main window
+ /// forward. Used for the first launch and for activations forwarded from a second launch.
+ ///
+ private void HandleLaunchArguments(string[] args, bool activateMainOtherwise)
+ {
+ var index = Array.FindIndex(args, a => string.Equals(a, "--open", StringComparison.OrdinalIgnoreCase));
+ if (index < 0 || index + 1 >= args.Length || _directory.Find(args[index + 1]) is not { } app || _launcher is null)
+ {
+ if (activateMainOtherwise) WindowRegistry.ActivateMain();
+ return;
+ }
+
+ try
+ {
+ _launcher.Open(app);
+ }
+ catch (Exception ex)
+ {
+ System.Diagnostics.Debug.WriteLine($"Could not open {app.AppId}: {ex.Message}");
+ if (activateMainOtherwise) WindowRegistry.ActivateMain();
+ }
}
///
@@ -83,13 +219,14 @@ private void StartNativeApps(IConfiguration config, AppDirectory directory)
protected override void OnExit(ExitEventArgs e)
{
+ _tray?.Dispose();
_nativeApps?.Dispose();
if (_grpcHost is { } grpcHost)
{
Task.Run(() => grpcHost.DisposeAsync().AsTask()).Wait(TimeSpan.FromSeconds(6));
}
- NotificationService.Clear();
+ if (_isPrimary) NotificationService.Clear();
base.OnExit(e);
}
}
diff --git a/src/Bermuda/Bermuda.csproj b/src/Bermuda/Bermuda.csproj
index a5a0644..5553880 100644
--- a/src/Bermuda/Bermuda.csproj
+++ b/src/Bermuda/Bermuda.csproj
@@ -40,6 +40,7 @@
+
diff --git a/src/Bermuda/IWindowController.cs b/src/Bermuda/IWindowController.cs
index 84176a1..56acb07 100644
--- a/src/Bermuda/IWindowController.cs
+++ b/src/Bermuda/IWindowController.cs
@@ -19,6 +19,9 @@ public interface IWindowController
bool IsMinimized { get; }
bool IsFocused { get; }
+ /// False while the window is hidden (for example in the tray).
+ bool IsVisible { get; }
+
int Left { get; }
int Top { get; }
int Width { get; }
diff --git a/src/Bermuda/MainWindow.xaml.cs b/src/Bermuda/MainWindow.xaml.cs
index fa8f5c3..8adcf38 100644
--- a/src/Bermuda/MainWindow.xaml.cs
+++ b/src/Bermuda/MainWindow.xaml.cs
@@ -85,6 +85,14 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap
// A toast (or one of its buttons) was clicked: surface the window and tell the web app.
NotificationService.Activated += OnNotificationActivated;
+ WindowRegistry.Add(this);
+ // With the tray icon on, closing the main window only hides it; the tray's Quit is the way out.
+ Closing += (_, e) =>
+ {
+ if (!WindowRegistry.HidesToTray(this)) return;
+ e.Cancel = true;
+ HideWindow();
+ };
Closed += (_, _) =>
{
_closed = true;
@@ -95,13 +103,15 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap
// this one, so release its page explicitly — otherwise it lingers
// as an orphaned, never-rendering CDP target.
_webView.Dispose();
+ // Last: may end the app, which tears down everything above.
+ WindowRegistry.Remove(this);
};
}
// Only the app's main window reacts to toast clicks (every window is subscribed to the static event).
private void OnNotificationActivated(NotificationActivation activation) => Dispatcher.Invoke(() =>
{
- if (_closed || Application.Current.MainWindow != this) return;
+ if (_closed || WindowRegistry.Main != this) return;
ShowWindow();
Activate();
diff --git a/src/Bermuda/NotificationService.cs b/src/Bermuda/NotificationService.cs
index a58389f..5af0970 100644
--- a/src/Bermuda/NotificationService.cs
+++ b/src/Bermuda/NotificationService.cs
@@ -48,6 +48,12 @@ public static void Initialize()
private static string? _registrationError;
+ ///
+ /// A toast click that Windows delivered to a second Bermuda process, which forwarded it to this one
+ /// (see 's single-instance handling), as if it had arrived through the manager here.
+ ///
+ public static void HandleForwarded(AppNotificationActivatedEventArgs args) => Dispatch(args.Arguments, args.UserInput);
+
///
/// Turns what Windows hands back on a click (the clicked element's arguments plus any reply text)
/// into the event pushed to the web app. Shared by real clicks and .
diff --git a/src/Bermuda/TrayService.cs b/src/Bermuda/TrayService.cs
new file mode 100644
index 0000000..a5844e9
--- /dev/null
+++ b/src/Bermuda/TrayService.cs
@@ -0,0 +1,39 @@
+using System.Windows;
+using System.Windows.Controls;
+using H.NotifyIcon;
+using H.NotifyIcon.Core;
+
+namespace Bermuda;
+
+///
+/// The notification-area icon. Left-click shows or hides the main window; the menu offers Show, New window and
+/// Quit. Together with it is what lets Bermuda keep running with no
+/// window: closing the main window only hides it.
+///
+internal sealed class TrayService : IDisposable
+{
+ private readonly TaskbarIcon _icon;
+
+ public TrayService(Action newWindow)
+ {
+ var show = new MenuItem { Header = "Show Bermuda" };
+ show.Click += (_, _) => WindowRegistry.ActivateMain();
+ var window = new MenuItem { Header = "New window" };
+ window.Click += (_, _) => newWindow();
+ var quit = new MenuItem { Header = "Quit" };
+ quit.Click += (_, _) => WindowRegistry.Quit();
+
+ _icon = new TaskbarIcon
+ {
+ ToolTipText = "Bermuda",
+ // The exe's own multi-size icon, copied next to it (read from disk: a pack URI does not resolve this early).
+ Icon = new System.Drawing.Icon(System.IO.Path.Combine(AppContext.BaseDirectory, "Assets", "app.ico")),
+ ContextMenu = new ContextMenu { Items = { show, window, new Separator(), quit } },
+ MenuActivation = PopupActivationMode.RightClick,
+ };
+ _icon.TrayLeftMouseUp += (_, _) => WindowRegistry.ToggleMain();
+ _icon.ForceCreate();
+ }
+
+ public void Dispose() => _icon.Dispose();
+}
diff --git a/src/Bermuda/WindowAppLauncher.cs b/src/Bermuda/WindowAppLauncher.cs
index f92afaf..a8fdffc 100644
--- a/src/Bermuda/WindowAppLauncher.cs
+++ b/src/Bermuda/WindowAppLauncher.cs
@@ -17,7 +17,14 @@ public sealed class WindowAppLauncher(IConfiguration configuration) : IFdc3AppLa
/// Starts native apps; null while the gRPC pipe is off, because they could not connect anyway.
public NativeAppHost? NativeApps { get; set; }
- public void Launch(AppDefinition app, string instanceId)
+ public void Launch(AppDefinition app, string instanceId) => Open(app, instanceId);
+
+ ///
+ /// Opens an app's window (or starts its native exe). is set when FDC3 is
+ /// waiting for the app to connect; it is null when the user opens the app directly (jump list, second
+ /// launch), in which case the app simply connects as a new instance.
+ ///
+ public void Open(AppDefinition app, string? instanceId = null)
{
if (Agent is null) throw new InvalidOperationException("Launcher not attached to a desktop agent.");
if (app.Type == "native" && NativeApps is not null)
diff --git a/src/Bermuda/WindowRegistry.cs b/src/Bermuda/WindowRegistry.cs
new file mode 100644
index 0000000..2e666c1
--- /dev/null
+++ b/src/Bermuda/WindowRegistry.cs
@@ -0,0 +1,70 @@
+using System.Windows;
+
+namespace Bermuda;
+
+///
+/// The open s, in the order they were created. The app no longer exits just because
+/// the last window closed (ShutdownMode=OnExplicitShutdown); this registry decides when it does, and
+/// is what the tray icon, jump list and child windows build on. Touch it from the UI thread only.
+///
+internal static class WindowRegistry
+{
+ private static readonly List Windows = [];
+
+ ///
+ /// Whether the app quits once the last window has closed. True today; the tray icon turns it off so the
+ /// app can live on with no window.
+ ///
+ public static bool QuitWhenLastWindowCloses { get; set; } = true;
+
+ ///
+ /// Whether the notification-area icon is on (TRAY_ENABLED, default true). When it is, closing the main window
+ /// hides it instead, and Quit in the tray menu is the way out.
+ ///
+ public static bool TrayEnabled { get; set; }
+
+ /// Set once the app is ending (Quit, sign-out), so closing a window really closes it.
+ public static bool Quitting { get; private set; }
+
+ /// True when closing should only hide it: it is the main window and the tray can bring it back.
+ public static bool HidesToTray(MainWindow window) => TrayEnabled && !Quitting && Main == window;
+
+ public static IReadOnlyList All => Windows;
+
+ /// The app's main window: the oldest one still open, or null when none is.
+ public static MainWindow? Main => Windows.Count > 0 ? Windows[0] : null;
+
+ public static void Add(MainWindow window) => Windows.Add(window);
+
+ public static void Remove(MainWindow window)
+ {
+ if (!Windows.Remove(window)) return;
+ if (Windows.Count == 0 && QuitWhenLastWindowCloses) Quit();
+ }
+
+ /// Brings the main window to the front, restoring it if minimized or hidden.
+ public static void ActivateMain()
+ {
+ if (Main is not { } window) return;
+ window.ShowWindow();
+ window.Activate();
+ }
+
+ /// Ends the app (runs App.OnExit), whatever windows are still open.
+ public static void Quit()
+ {
+ Quitting = true;
+ Application.Current?.Dispatcher.BeginInvoke(() => Application.Current.Shutdown());
+ }
+
+ /// Tray left-click: hides the main window when it is showing (the click itself takes focus, so focus is no signal), otherwise brings it forward.
+ public static void ToggleMain()
+ {
+ if (Main is not { } window) return;
+ if (window.IsVisible && !window.IsMinimized) window.HideWindow();
+ else ActivateMain();
+ }
+
+ /// Marks the app as ending without shutting it down (the OS session is ending).
+ public static void MarkQuitting() => Quitting = true;
+}
diff --git a/src/Bermuda/WindowScriptHost.cs b/src/Bermuda/WindowScriptHost.cs
index 919aae8..8ef3f41 100644
--- a/src/Bermuda/WindowScriptHost.cs
+++ b/src/Bermuda/WindowScriptHost.cs
@@ -27,6 +27,7 @@ public WindowScriptHost(IWindowController window)
public bool IsMaximized => _window.IsMaximized;
public bool IsMinimized => _window.IsMinimized;
public bool IsFocused => _window.IsFocused;
+ public bool IsVisible => _window.IsVisible;
public int Left => _window.Left;
public int Top => _window.Top;