fix: full verification against the brief — 137 confirmed findings fixed over six passes #4

Merged
Alby96 merged 169 commits from claude/keen-knuth-uhxv8w into main 2026-10-13 12:10:04 +02:00
3 changed files with 224 additions and 17 deletions
Showing only changes of commit bd38cf2e36 - Show all commits

No files matched your search

+37 -6
View File
@@ -15,13 +15,18 @@ namespace Titano.App;
/// then the index and the job engine (<see cref="AppServices"/>) off the UI thread. <c>--capture &lt;dir&gt;</c>
/// renders every screen with synthetic data in a throw-away data folder and exits. A file argument is a
/// <c>.titano</c> project file (Explorer passes it on a double-click) opened once the index is open. One Titano runs
/// per data folder: a second launch hands its file to the running one and exits (<see cref="SingleInstance"/>).
/// per data folder: a second launch hands its file to the running one and exits, or, when the running one is closing,
/// waits for it to exit and starts with the file (<see cref="SingleInstance"/>).
/// </summary>
public partial class App : Application
{
/// <summary>How long a launch waits for a Titano that is closing (it gives its services up to 10 s to stop).</summary>
private static readonly TimeSpan ClosingWait = TimeSpan.FromSeconds(30);
private readonly TaskCompletionSource _started = new(TaskCreationOptions.RunContinuationsAsynchronously);
private FileLogSink? _log;
private SingleInstance? _instance;
private bool _windowClosed;
public AppEnvironment Environment { get; private set; } = null!;
public AppSettings Settings { get; private set; } = null!;
@@ -47,11 +52,24 @@ public partial class App : Application
_instance = SingleInstance.TryAcquire(Environment.DataDirectory);
if (_instance is null)
{
var handed = SingleInstance.HandOver(Environment.DataDirectory, projectFile is null ? [] : [projectFile]);
Log.Info("app", handed ? "Titano already runs on this data folder; arguments handed over" : "Titano already runs on this data folder");
Shutdown();
return;
if (SingleInstance.HandOver(Environment.DataDirectory, projectFile is null ? [] : [projectFile]))
{
Log.Info("app", "Titano already runs on this data folder; arguments handed over");
Shutdown();
return;
}
// No answer: the running Titano is closing (it stops listening first). Start once it has exited.
_instance = SingleInstance.WaitForTurn(Environment.DataDirectory, ClosingWait);
if (_instance is null)
{
Log.Info("app", "Titano already runs on this data folder and did not answer");
Shutdown();
return;
}
Log.Info("app", "The previous Titano on this data folder has exited");
}
// From now on: a launch while the window and the index open is kept until the shell can take it.
_instance.Listen();
}
Settings = capture ? new AppSettings { Language = "en" } : AppSettings.Load(Environment.SettingsPath);
@@ -82,8 +100,14 @@ public partial class App : Application
_ = ScreenCapture.RunAsync(window, shell, sample!, dir);
return;
}
// Closing the main window ends Titano: later launches wait for it instead of handing over a file it cannot open.
window.Closed += (_, _) =>
{
_windowClosed = true;
_instance?.StopListening();
};
window.Show();
_instance?.Listen(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_instance?.Receive(args => Dispatcher.BeginInvoke(() => OnHandOver(shell, args)));
_ = StartAsync(shell, projectFile);
}
@@ -109,6 +133,11 @@ public partial class App : Application
/// <summary>A later launch: its window comes to the front here, and its project file opens.</summary>
private void OnHandOver(ShellViewModel shell, IReadOnlyList<string> args)
{
if (_windowClosed)
{
Log.Warning("app", "A launch arrived while Titano was closing; its arguments are ignored");
return;
}
if (MainWindow is { } window)
{
window.Show();
@@ -163,6 +192,8 @@ public partial class App : Application
protected override void OnExit(ExitEventArgs e)
{
// The mutex stays until the services have stopped, so a launch now waits for this one to exit.
_instance?.StopListening();
SaveSettings();
if (MainWindow?.DataContext is ShellViewModel shell) shell.Dispose();
try
+133 -7
View File
@@ -11,8 +11,10 @@ namespace Titano.App.Infrastructure;
/// <summary>
/// One Titano per data folder in a Windows session (two would share one index and job engine): a named mutex marks
/// the running instance, and a later launch (a double-clicked <c>.titano</c> file, the Start menu) hands its file
/// arguments over a named pipe (current user only), lets the running window come to the front and exits. Same
/// protocol as the Uploader's, kept per program so neither depends on the other.
/// arguments over a named pipe (current user only), lets the running window come to the front and exits. The running
/// instance listens from the moment it holds the mutex, keeping what arrives until its window can take it, and stops
/// listening as soon as it starts closing; a launch that gets no answer waits for it to exit and starts in its place.
/// Same protocol as the Uploader's, kept per program so neither depends on the other.
/// </summary>
public sealed partial class SingleInstance : IDisposable
{
@@ -23,6 +25,11 @@ public sealed partial class SingleInstance : IDisposable
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
private readonly Lock _gate = new();
private readonly Queue<IReadOnlyList<string>> _waiting = new();
private Action<IReadOnlyList<string>>? _received;
private Task? _listening;
private bool _disposed;
private SingleInstance(Mutex mutex, string pipeName)
{
@@ -30,15 +37,59 @@ public sealed partial class SingleInstance : IDisposable
_pipeName = pipeName;
}
/// <summary>The instance guard for <paramref name="dataDirectory"/>, or null when another Titano already uses it in this session.</summary>
/// <summary>
/// The instance guard for <paramref name="dataDirectory"/>, or null when another Titano already uses it in this
/// session (also one running with administrator rights, whose mutex this launch may not even open).
/// </summary>
public static SingleInstance? TryAcquire(string dataDirectory)
{
var mutex = new Mutex(initiallyOwned: true, @"Local\Titano.App." + Key(dataDirectory), out var createdNew);
Mutex mutex;
bool createdNew;
try
{
mutex = new Mutex(initiallyOwned: true, MutexName(dataDirectory), out createdNew);
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Titano runs with administrator rights on this data folder: {ex.Message}");
return null;
}
if (createdNew) return new SingleInstance(mutex, PipeName(dataDirectory));
mutex.Dispose();
return null;
}
/// <summary>
/// Waits up to <paramref name="timeout"/> for the Titano running on <paramref name="dataDirectory"/> to exit (while
/// it closes it no longer answers hand-overs), then becomes the running instance; null when it still runs, or runs
/// with administrator rights.
/// </summary>
public static SingleInstance? WaitForTurn(string dataDirectory, TimeSpan timeout)
{
Mutex mutex;
try
{
mutex = new Mutex(initiallyOwned: false, MutexName(dataDirectory));
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Titano runs with administrator rights on this data folder: {ex.Message}");
return null;
}
try
{
if (mutex.WaitOne(timeout)) return new SingleInstance(mutex, PipeName(dataDirectory));
}
catch (AbandonedMutexException)
{
// The other Titano ended without releasing it (it crashed): this thread owns it now.
Log.Warning("instance", "The previous Titano ended without closing");
return new SingleInstance(mutex, PipeName(dataDirectory));
}
mutex.Dispose();
return null;
}
/// <summary>
/// Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the Titano running on
/// <paramref name="dataDirectory"/>; false when it could not be reached.
@@ -62,12 +113,61 @@ public sealed partial class SingleInstance : IDisposable
}
}
/// <summary>Receives messages from later launches; <paramref name="received"/> runs on a pool thread.</summary>
public void Listen(Action<IReadOnlyList<string>> received) => _ = ListenAsync(_pipeName, received, _stop.Token);
/// <summary>Starts receiving messages from later launches; they wait until <see cref="Receive"/> names who takes them.</summary>
public void Listen()
{
lock (_gate)
{
if (_listening is not null || _disposed) return;
_listening = ListenAsync(_pipeName, OnMessage, _stop.Token);
}
}
/// <summary>
/// Hands the messages received so far, then each later one, to <paramref name="received"/>, in order; it runs on a
/// pool thread.
/// </summary>
public void Receive(Action<IReadOnlyList<string>> received)
{
lock (_gate)
{
_received = received;
while (_waiting.TryDequeue(out var args)) received(args);
}
}
/// <summary>
/// Stops answering later launches while keeping the mutex: from now on they wait for this instance to exit instead
/// of handing over arguments it could no longer open.
/// </summary>
public void StopListening()
{
Task? listening;
lock (_gate)
{
if (_disposed) return;
_stop.Cancel();
listening = _listening;
}
// The pipe closes as the loop ends (cancellation ends it quietly).
try
{
listening?.Wait(TimeSpan.FromSeconds(2));
}
catch (AggregateException ex)
{
Log.Warning("instance", "Hand-over listener ended with an error", ex);
}
}
public void Dispose()
{
_stop.Cancel();
StopListening();
lock (_gate)
{
if (_disposed) return;
_disposed = true;
}
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
@@ -86,10 +186,21 @@ public sealed partial class SingleInstance : IDisposable
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
private void OnMessage(IReadOnlyList<string> args)
{
lock (_gate)
{
if (_received is null) _waiting.Enqueue(args);
else _received(args);
}
}
/// <summary>The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.</summary>
private static string Key(string dataDirectory) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(dataDirectory).TrimEnd('\\', '/').ToUpperInvariant())))[..16];
private static string MutexName(string dataDirectory) => @"Local\Titano.App." + Key(dataDirectory);
private static string PipeName(string dataDirectory)
{
using var process = Process.GetCurrentProcess();
@@ -113,9 +224,24 @@ public sealed partial class SingleInstance : IDisposable
{
return;
}
catch (UnauthorizedAccessException ex)
{
// The pipe name belongs to a Titano running with administrator rights: later launches wait instead.
Log.Warning("instance", "Hand-over pipe not available", ex);
return;
}
catch (IOException ex)
{
// A pipe of the same name still held by a Titano that is exiting, or a broken connection: try again shortly.
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
try
{
await Task.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
@@ -123,15 +123,25 @@ public sealed class ProjectFilesTests(TestContext context)
var first = Assert.NotNull(SingleInstance.TryAcquire(data));
try
{
var received = new TaskCompletionSource<IReadOnlyList<string>>(TaskCreationOptions.RunContinuationsAsynchronously);
first.Listen(args => received.TrySetResult(args));
first.Listen();
Assert.Null(SingleInstance.TryAcquire(data), "one Titano per data folder");
using (var other = SingleInstance.TryAcquire(context.CreateTempDirectory("other-copy")))
Assert.NotNull(other, "a portable copy with its own data folder runs on its own");
// Launches while the first one is still opening its window are kept until the window takes them. The pipe
// takes one launch at a time, so once the second hand-over is through, the first one is already waiting.
Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Early.titano"]));
Assert.True(SingleInstance.HandOver(data, []));
using var received = new System.Collections.Concurrent.BlockingCollection<IReadOnlyList<string>>();
first.Receive(received.Add);
Assert.True(received.TryTake(out var early, TimeSpan.FromSeconds(10)), "the hand-over that came first is delivered");
Assert.SequenceEqual([@"D:\Projects\Early.titano"], early!);
Assert.True(received.TryTake(out var show, TimeSpan.FromSeconds(10)), "then the plain launch");
Assert.Empty(show!);
Assert.True(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]));
Assert.True(received.Task.Wait(TimeSpan.FromSeconds(10)), "the running instance received the hand-over");
Assert.SequenceEqual([@"D:\Projects\Roof.titano"], received.Task.Result);
Assert.True(received.TryTake(out var later, TimeSpan.FromSeconds(10)), "the running instance received the hand-over");
Assert.SequenceEqual([@"D:\Projects\Roof.titano"], later!);
}
finally
{
@@ -139,6 +149,46 @@ public sealed class ProjectFilesTests(TestContext context)
}
}
[Test]
public void ALaunchWhileTitanoClosesWaitsForItAndStartsInItsPlace()
{
var data = context.CreateTempDirectory("closing");
var first = Assert.NotNull(SingleInstance.TryAcquire(data));
first.Listen();
first.Receive(_ => { });
// Closing: it no longer answers, but it still holds the data folder until its services have stopped.
first.StopListening();
Assert.False(SingleInstance.HandOver(data, [@"D:\Projects\Roof.titano"]), "a closing Titano takes no file it could not open");
Assert.Null(SingleInstance.TryAcquire(data));
// The next launch waits (the mutex belongs to a thread, so it waits on its own) and gets its turn once the first exits.
var next = Task.Run(() =>
{
using var instance = SingleInstance.WaitForTurn(data, TimeSpan.FromSeconds(20));
return instance is not null;
});
Assert.False(next.Wait(TimeSpan.FromMilliseconds(300)), "it waits while the first one still runs");
first.Dispose();
Assert.True(next.Wait(TimeSpan.FromSeconds(20)) && next.Result, "it starts once the first one has exited");
// Nobody exits in time: the launch gives up.
var holder = Assert.NotNull(SingleInstance.TryAcquire(data));
try
{
Assert.False(Task.Run(() => SingleInstance.WaitForTurn(data, TimeSpan.FromMilliseconds(200)) is { } got && Dispose(got)).Result);
}
finally
{
holder.Dispose();
}
static bool Dispose(SingleInstance instance)
{
instance.Dispose();
return true;
}
}
/// <summary>Dialogs that pick one folder and cancel everything else.</summary>
private sealed class FolderDialogs(string folder) : IAppDialogs
{