2 Commits
Author SHA1 Message Date
poli0981 e2f001baf7 Merge pull request #47 from poli0981/claude/multiple-windows-app-launch-530c62
fix(wpf): enforce single instance (relaunch focuses existing window)
2026-07-09 09:03:01 +07:00
poli0981andClaude Opus 4.8 c65a5aa021 fix(wpf): enforce single instance so relaunching focuses the existing window
Launching CommandForge.Wpf.exe repeatedly opened a new window each time
because there was no single-instance guard. Add SingleInstanceGuard (a
WPF-free Infrastructure primitive) that owns a session-scoped named mutex;
a later launch signals the primary via a named auto-reset event and exits,
and the primary restores + foregrounds its existing window.

- Guard is created right after VelopackApp.Build().Run() so install/update
  hook processes are never counted as a second instance.
- Activation marshals to the UI dispatcher; SetForegroundWindow beats the
  Windows foreground lock. MainWindow is NoResize so Normal fully restores it.
- Adds unit tests for primary/secondary detection, activation signalling and
  name reclamation; CHANGELOG updated for 1.5.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 08:55:52 +07:00
4 changed files with 226 additions and 0 deletions

No files matched your search

+7
View File
@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [1.5.1] — 2026-07-09
### Fixed
- **Single instance:** launching the app while it is already running no longer opens a second
window. Later launches bring the existing window to the foreground (restoring it if minimized)
and then exit.
## [1.5.0] — 2026-07-08
### Added
@@ -0,0 +1,119 @@
namespace CommandForge.Infrastructure;
/// <summary>
/// Enforces a single running application instance per user session. The first instance owns a
/// named <see cref="Mutex"/>; later instances detect it, signal the primary (via a named
/// auto-reset event) to bring its window to the foreground, and then exit.
/// </summary>
/// <remarks>
/// Intentionally WPF- and logging-free so it can be constructed before the host/UI are built and
/// unit-tested without a UI thread. The named objects are session-scoped (<c>Local\</c>), which is
/// correct for a per-user install: it isolates different Windows users / RDP sessions and
/// self-recovers if a process crashes (the kernel object dies when its last handle closes).
/// </remarks>
public sealed class SingleInstanceGuard : IDisposable
{
private readonly Mutex _mutex;
private readonly EventWaitHandle _activateEvent;
private readonly ManualResetEventSlim _stopEvent = new(initialState: false);
private Thread? _listener;
private bool _disposed;
/// <summary>
/// Creates the guard, attempting to acquire the single-instance mutex for this session.
/// </summary>
/// <param name="nameSuffix">
/// Optional suffix that isolates the named objects (used by tests to avoid colliding with a
/// real running instance). When omitted, the shared application name is used so every real
/// instance contends on the same objects.
/// </param>
public SingleInstanceGuard(string? nameSuffix = null)
{
var baseName = string.IsNullOrEmpty(nameSuffix)
? AppPaths.AppFolderName
: $"{AppPaths.AppFolderName}.{nameSuffix}";
// Create the activation event FIRST and hold its handle for the process lifetime: by the
// time the mutex exists the primary already owns a live handle to the event, so a second
// instance can neither lose its signal nor destroy the kernel object when it disposes.
_activateEvent = new EventWaitHandle(
initialState: false,
EventResetMode.AutoReset,
$"Local\\{baseName}.SingleInstance.Activate");
_mutex = new Mutex(initiallyOwned: false, $"Local\\{baseName}.SingleInstance", out var createdNew);
IsPrimaryInstance = createdNew;
}
/// <summary>True when this is the first (owning) instance for the current session.</summary>
public bool IsPrimaryInstance { get; }
/// <summary>
/// Primary instance only: starts a background listener that invokes
/// <paramref name="onActivateRequested"/> whenever another instance signals. The callback runs
/// on a background thread; the caller is responsible for marshalling to the UI thread.
/// </summary>
public void StartListening(Action onActivateRequested)
{
ArgumentNullException.ThrowIfNull(onActivateRequested);
ObjectDisposedException.ThrowIf(_disposed, this);
if (_listener is not null)
{
throw new InvalidOperationException("The activation listener has already been started.");
}
_listener = new Thread(() => ListenLoop(onActivateRequested))
{
IsBackground = true,
Name = "SingleInstanceActivationListener",
};
_listener.Start();
}
/// <summary>Secondary instance only: asks the primary instance to activate its window.</summary>
public void SignalPrimaryInstance() => _activateEvent.Set();
private void ListenLoop(Action onActivateRequested)
{
var handles = new WaitHandle[] { _activateEvent, _stopEvent.WaitHandle };
while (true)
{
if (WaitHandle.WaitAny(handles) == 1)
{
return; // Stop requested by Dispose().
}
try
{
onActivateRequested();
}
catch (Exception)
{
// A faulty activation callback must never tear down the listener thread.
}
}
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed)
{
return;
}
_disposed = true;
_stopEvent.Set();
if (_listener is { IsAlive: true } listener)
{
listener.Join(TimeSpan.FromSeconds(2));
}
// The mutex is never owned (initiallyOwned: false), so there is nothing to release —
// closing the handle frees the name once the last instance exits.
_mutex.Dispose();
_activateEvent.Dispose();
_stopEvent.Dispose();
}
}
+46
View File
@@ -1,6 +1,8 @@
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
using CommandForge.Application;
using CommandForge.Application.Ports;
using CommandForge.Application.UseCases;
@@ -26,6 +28,7 @@ namespace CommandForge.Wpf;
public partial class App : System.Windows.Application
{
private IHost? _host;
private SingleInstanceGuard? _guard;
/// <inheritdoc />
protected override void OnStartup(StartupEventArgs e)
@@ -34,6 +37,21 @@ public partial class App : System.Windows.Application
// Called directly in the main assembly so the vpk packager can verify its presence.
VelopackApp.Build().Run();
// Single-instance guard. Placed after Velopack (whose hook invocations exit inside Run())
// so those transient processes are never counted as a second instance. A later launch
// signals the primary to surface its window, then exits silently.
var guard = new SingleInstanceGuard();
if (!guard.IsPrimaryInstance)
{
guard.SignalPrimaryInstance();
guard.Dispose();
Shutdown(); // _guard is left null, so OnExit's _guard?.Dispose() is a no-op.
return;
}
_guard = guard;
_guard.StartListening(OnActivationRequested);
base.OnStartup(e);
// The Legal Gate is shown as a modal dialog before the main window exists.
@@ -144,9 +162,37 @@ public partial class App : System.Windows.Application
}
}
/// <summary>Invoked (on a background thread) when a second instance asks us to surface our window.</summary>
private void OnActivationRequested() => Dispatcher.InvokeAsync(ActivateExistingWindow);
/// <summary>Restores and foregrounds the existing top-level window (main window, or the Legal Gate if it is still open).</summary>
private void ActivateExistingWindow()
{
var window = MainWindow
?? System.Windows.Application.Current.Windows.Cast<Window>().LastOrDefault();
if (window is null)
{
return; // Signalled before any window is shown — the primary is about to show one anyway.
}
if (window.WindowState == WindowState.Minimized)
{
window.WindowState = WindowState.Normal; // MainWindow is NoResize, so Normal fully restores it.
}
window.Show();
window.Activate();
SetForegroundWindow(new WindowInteropHelper(window).Handle);
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetForegroundWindow(IntPtr hWnd);
/// <inheritdoc />
protected override void OnExit(ExitEventArgs e)
{
_guard?.Dispose();
Log.Information("CommandForge shutting down");
Log.CloseAndFlush();
_host?.Dispose();
@@ -0,0 +1,54 @@
using CommandForge.Infrastructure;
namespace CommandForge.Tests;
/// <summary>
/// Verifies the single-instance detection and activation-signalling logic. Each test uses a unique
/// name suffix so the named kernel objects never collide with a real running instance or with each
/// other. The window activation itself lives in the WPF layer and is verified manually.
/// </summary>
public sealed class SingleInstanceGuardTests
{
[Fact]
public void FirstInstanceIsPrimary_SecondIsNot()
{
var name = Guid.NewGuid().ToString("N");
using var first = new SingleInstanceGuard(name);
using var second = new SingleInstanceGuard(name);
Assert.True(first.IsPrimaryInstance);
Assert.False(second.IsPrimaryInstance);
}
[Fact]
public void SignalPrimaryInstance_InvokesPrimaryCallback()
{
var name = Guid.NewGuid().ToString("N");
using var activated = new ManualResetEventSlim(initialState: false);
using var primary = new SingleInstanceGuard(name);
primary.StartListening(() => activated.Set());
using (var secondary = new SingleInstanceGuard(name))
{
Assert.False(secondary.IsPrimaryInstance);
secondary.SignalPrimaryInstance();
}
Assert.True(activated.Wait(TimeSpan.FromSeconds(5)));
}
[Fact]
public void Name_IsReclaimed_AfterPrimaryDisposed()
{
var name = Guid.NewGuid().ToString("N");
var first = new SingleInstanceGuard(name);
Assert.True(first.IsPrimaryInstance);
first.Dispose();
using var second = new SingleInstanceGuard(name);
Assert.True(second.IsPrimaryInstance);
}
}