diff --git a/src/Titano.App/Server/ConnectFlow.cs b/src/Titano.App/Server/ConnectFlow.cs
index d024edfa..2dcfb9fb 100644
--- a/src/Titano.App/Server/ConnectFlow.cs
+++ b/src/Titano.App/Server/ConnectFlow.cs
@@ -131,23 +131,28 @@ public sealed class ConnectFlow(IServerApiFactory factory, ITrustStore trust) :
return await IdentifyAsync(ct);
}
- /// Sends the credentials; only possible once the server is identified and trusted.
+ ///
+ /// Sends the credentials; only possible once the server is identified and trusted. An answer that arrives after the
+ /// flow moved on (disconnected, or connecting elsewhere) changes nothing.
+ ///
public async Task SignInAsync(string username, string password, CancellationToken ct = default)
{
- if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is null) return Step;
+ if (Step is not (ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) || _api is not { } api) return Step;
if (string.IsNullOrWhiteSpace(username)) return Retry(ConnectError.BadCredentials);
Set(ConnectStep.SigningIn, ConnectError.None);
try
{
- var login = await _api.LoginAsync(username.Trim(), password, ct);
+ var login = await api.LoginAsync(username.Trim(), password, ct);
+ if (!ReferenceEquals(api, _api)) return Step;
if (login.Token is null) return Retry(ConnectError.BadCredentials);
// TitanoClient keeps the token itself; set it explicitly so every IServerApi behaves the same.
- _api.Token = login.Token;
+ api.Token = login.Token;
User = login.User;
return Set(ConnectStep.Connected, ConnectError.None);
}
catch (Exception ex) when (Classify(ex, ct) is { } error)
{
+ if (!ReferenceEquals(api, _api)) return Step;
return error is ConnectError.BadCredentials ? Retry(error) : Fail(error);
}
}
diff --git a/src/Titano.App/Server/ServerSession.cs b/src/Titano.App/Server/ServerSession.cs
index 9f944024..7f588642 100644
--- a/src/Titano.App/Server/ServerSession.cs
+++ b/src/Titano.App/Server/ServerSession.cs
@@ -144,17 +144,23 @@ public sealed class ServerSession : ObservableObject, ITrustStore, IDisposable
if (step != ConnectStep.AwaitingCredentials) return false;
}
+ // The form may be cancelled while the server is still answering: that answer must not sign this PC in.
+ using var attempt = CancellationTokenSource.CreateLinkedTokenSource(ct);
var signedIn = dialogs.SignIn(display, _settings.ServerUsername, async (user, password) =>
{
- var result = await _flow.SignInAsync(user, password, ct);
- return result == ConnectStep.Connected ? null : ErrorText(_flow.Error);
+ var result = await _flow.SignInAsync(user, password, attempt.Token);
+ // An answer the flow dropped (the form was cancelled meanwhile) carries no error of its own.
+ return result == ConnectStep.Connected ? null : ErrorText(_flow.Error is ConnectError.None ? ConnectError.Failed : _flow.Error);
});
if (signedIn && IsConnected)
{
Remember();
return true;
}
- if (!IsConnected && _flow.Step == ConnectStep.AwaitingCredentials) _flow.Disconnect();
+ await attempt.CancelAsync();
+ // Signed in just before the cancel was handled: the session the user turned down ends on the server too.
+ if (IsConnected) await _flow.SignOutAsync();
+ else if (_flow.Step is ConnectStep.AwaitingCredentials or ConnectStep.SigningIn) _flow.Disconnect();
return false;
}
finally
diff --git a/src/Titano.App/Server/SyncHost.cs b/src/Titano.App/Server/SyncHost.cs
index 13a0fbb5..abfaedcb 100644
--- a/src/Titano.App/Server/SyncHost.cs
+++ b/src/Titano.App/Server/SyncHost.cs
@@ -29,7 +29,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
private Task _switch = Task.CompletedTask;
private Credentials? _credentials;
- private (SyncAgent Agent, ISyncRemote Remote, Credentials Credentials)? _running;
+ private Running? _running;
private JobEngine? _renders;
/// Connections over ; screenshots substitute a fake server.
@@ -44,10 +44,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
public SyncService? Service { get; private set; }
/// The background comparison of the signed-in server; null while signed out.
- public SyncAgent? Agent => _running?.Agent;
+ public SyncAgent? Agent => Volatile.Read(ref _running)?.Agent;
/// The agent's connection, for the table's own calls (conflict resolution); null while signed out.
- public ISyncRemote? Remote => _running?.Remote;
+ public ISyncRemote? Remote => Volatile.Read(ref _running)?.Remote;
/// Key of the signed-in server (); null while signed out.
public string? Server => Volatile.Read(ref _credentials) is { } c ? SyncService.ServerKey(c.Address) : null;
@@ -103,8 +103,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// Compares now, once the session switch in progress settled; null while signed out.
public async Task RefreshAsync(CancellationToken ct = default)
{
- await _switch;
- return Agent is { } agent ? await agent.RefreshAsync(ct) : null;
+ await _switch.ConfigureAwait(false);
+ return Agent is { } agent ? await agent.RefreshAsync(ct).ConfigureAwait(false) : null;
}
/// Compares again soon (an option changed, an edit on this PC).
@@ -135,13 +135,17 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
return RemoteFactory(c.Address, c.Token, c.Fingerprints);
}
+ ///
+ /// Stops the agent once the session switch in progress settled. The app's exit waits for this on the UI thread, so
+ /// nothing here, in the switch or in the stop continues on it.
+ ///
public async ValueTask DisposeAsync()
{
Volatile.Write(ref _credentials, null);
Uploads.Dispose();
if (_renders is not null) _renders.JobChanged -= OnJobChanged;
- await _switch;
- await StopAsync();
+ await _switch.ConfigureAwait(false);
+ await StopAsync().ConfigureAwait(false);
}
private bool Allows(Permissions permission) => services.Server.User is { } user && (user.Permissions & (long)permission) != 0;
@@ -183,11 +187,16 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
}
}
+ ///
+ /// Switches are chained (each waits for the previous one) and continue on the thread pool: a switch still stopping
+ /// the old agent when the app exits must not need the UI thread its exit blocks.
+ ///
private async Task SwitchAsync(Task previous, Credentials? wanted)
{
- await previous;
- if (_running is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return;
- await StopAsync();
+ await previous.ConfigureAwait(false);
+ if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token)
+ return;
+ await StopAsync().ConfigureAwait(false);
if (wanted is not { } start || Service is not { } service)
{
Changed?.Invoke();
@@ -197,19 +206,21 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.Start();
- _running = (agent, remote, start);
+ Volatile.Write(ref _running, new Running(agent, remote, start));
Log.Info("sync", $"Comparing with {remote.Server}");
Changed?.Invoke();
}
private async Task StopAsync()
{
- if (_running is not { } running) return;
- _running = null;
- await running.Agent.DisposeAsync();
+ if (Interlocked.Exchange(ref _running, null) is not { } running) return;
+ await running.Agent.DisposeAsync().ConfigureAwait(false);
running.Remote.Dispose();
Changed?.Invoke();
}
private sealed record Credentials(Uri Address, string Token, IReadOnlyCollection Fingerprints);
+
+ /// The agent of the signed-in session: one reference, so the UI thread never reads half of a switch.
+ private sealed record Running(SyncAgent Agent, ISyncRemote Remote, Credentials Credentials);
}
diff --git a/src/Titano.App/Shell/LoginDialog.xaml.cs b/src/Titano.App/Shell/LoginDialog.xaml.cs
index b0adb296..6e374890 100644
--- a/src/Titano.App/Shell/LoginDialog.xaml.cs
+++ b/src/Titano.App/Shell/LoginDialog.xaml.cs
@@ -1,6 +1,7 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
+using Titano.Core.Diagnostics;
using Titano.Ui.Controls;
namespace Titano.App.Shell;
@@ -9,16 +10,20 @@ namespace Titano.App.Shell;
/// The login form (BRIEF ยง12.7). It calls back the connection with the credentials and stays open with the
/// error sentence until the sign-in succeeds or the user cancels. The password never leaves the PasswordBox
/// except for that call. A failed sign-in is announced to screen readers and marks the password box (error border,
-/// sentence as its help text) until the next attempt.
+/// sentence as its help text) until the next attempt. Cancel stays available while the server answers: the form
+/// closes at once and the connection drops the answer.
///
public sealed partial class LoginDialog : TitanoWindow
{
private readonly Func> _signIn;
+ private bool _pending;
+ private bool _closed;
private LoginDialog(string server, string? username, Func> signIn)
{
_signIn = signIn;
InitializeComponent();
+ Closed += (_, _) => _closed = true;
ServerText.Text = server;
User.Text = username ?? string.Empty;
Loaded += (_, _) =>
@@ -41,28 +46,41 @@ public sealed partial class LoginDialog : TitanoWindow
private async void OnSignIn(object sender, RoutedEventArgs e)
{
+ if (_pending) return;
+ _pending = true;
SignIn.IsEnabled = false;
Error.Visibility = Visibility.Collapsed;
Field.SetError(Password, null);
+ string? error;
try
{
- var error = await _signIn(User.Text, Password.Password);
- if (error is null)
- {
- DialogResult = true;
- return;
- }
- Error.Text = error;
- Error.Visibility = Visibility.Visible;
- Field.SetError(Password, error);
- Password.Clear();
- Password.Focus();
- UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent(
- AutomationNotificationKind.ActionCompleted, AutomationNotificationProcessing.ImportantMostRecent, error, "Titano.SignIn");
+ error = await _signIn(User.Text, Password.Password);
+ }
+ catch (Exception ex) when (ex is not OutOfMemoryException)
+ {
+ // Cancel ended the request: nobody waits for this answer any more.
+ if (_closed && ex is OperationCanceledException) return;
+ Log.Warning("server", "Sign-in failed", ex);
+ error = ErrorText.For(ex);
}
finally
{
+ _pending = false;
SignIn.IsEnabled = true;
}
+ // The form was cancelled or closed while the server answered: a result can no longer be set on it.
+ if (_closed) return;
+ if (error is null)
+ {
+ DialogResult = true;
+ return;
+ }
+ Error.Text = error;
+ Error.Visibility = Visibility.Visible;
+ Field.SetError(Password, error);
+ Password.Clear();
+ Password.Focus();
+ UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent(
+ AutomationNotificationKind.ActionCompleted, AutomationNotificationProcessing.ImportantMostRecent, error, "Titano.SignIn");
}
}
diff --git a/src/Titano.App/Shell/ShellViewModel.cs b/src/Titano.App/Shell/ShellViewModel.cs
index 9e9df006..5ea0e3fd 100644
--- a/src/Titano.App/Shell/ShellViewModel.cs
+++ b/src/Titano.App/Shell/ShellViewModel.cs
@@ -292,6 +292,8 @@ public sealed class ShellViewModel : LocalizedViewModel
public override void Dispose()
{
+ // The editor first: it stops its runners and closes its source before the engine and the index under it go.
+ Sequence.Dispose();
Jobs.Dispose();
Library.Dispose();
Import.Dispose();
diff --git a/tests/Titano.App.Tests/Server/ServerSessionSignInTests.cs b/tests/Titano.App.Tests/Server/ServerSessionSignInTests.cs
new file mode 100644
index 00000000..ad3c4fe1
--- /dev/null
+++ b/tests/Titano.App.Tests/Server/ServerSessionSignInTests.cs
@@ -0,0 +1,154 @@
+using System.Net;
+using Titano.App.Infrastructure;
+using Titano.App.Server;
+using Titano.Protocol;
+using Titano.Protocol.Client;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Server;
+
+/// The login form cancelled while the server is still answering (DESK-8): nothing signs this PC in afterwards.
+public sealed class ServerSessionSignInTests
+{
+ [Test]
+ public async Task CancelEndsTheSignInStillWaitingForTheServer()
+ {
+ var server = new GatedServer { HonoursCancellation = true };
+ var settings = new AppSettings();
+ using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
+ Task? pending = null;
+ var dialogs = new Dialogs((_, _, signIn) =>
+ {
+ pending = signIn("alberto", "secret");
+ return false;
+ });
+
+ Assert.False(await session.ConnectAsync("nas.local:8443", dialogs));
+ // The request the form left behind was cancelled, and the session dropped the connection it belonged to.
+ await Assert.ThrowsAsync(() => pending!);
+ Assert.False(session.IsConnected);
+ Assert.Equal(ConnectStep.Idle, session.Flow.Step);
+ Assert.Null(settings.ProtectedToken);
+ }
+
+ [Test]
+ public async Task AnAnswerArrivingAfterCancelSignsNothingIn()
+ {
+ var server = new GatedServer { HonoursCancellation = false };
+ var settings = new AppSettings();
+ using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
+ Task? pending = null;
+ var dialogs = new Dialogs((_, _, signIn) =>
+ {
+ pending = signIn("alberto", "secret");
+ return false;
+ });
+
+ Assert.False(await session.ConnectAsync("nas.local:8443", dialogs));
+ // The server accepts the password only now: the answer belongs to a connection that is gone.
+ server.Answer();
+ Assert.NotNull(await pending!);
+ Assert.False(session.IsConnected);
+ Assert.Equal(ConnectStep.Idle, session.Flow.Step);
+ Assert.Null(session.Flow.Token);
+ Assert.Null(settings.ProtectedToken);
+ Assert.Null(settings.ServerUrl);
+ }
+
+ [Test]
+ public async Task SignedInJustBeforeTheCancelSignsOutAgain()
+ {
+ var server = new GatedServer { HonoursCancellation = false };
+ server.Answer();
+ var settings = new AppSettings();
+ using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
+ var dialogs = new Dialogs((_, _, signIn) =>
+ {
+ // The server's answer was handled first, then the click on Cancel closed the form.
+ Assert.Null(signIn("alberto", "secret").GetAwaiter().GetResult());
+ return false;
+ });
+
+ Assert.False(await session.ConnectAsync("nas.local:8443", dialogs));
+ Assert.False(session.IsConnected);
+ Assert.Equal(1, server.Logouts);
+ Assert.Null(settings.ProtectedToken);
+ }
+
+ [Test]
+ public async Task ASignInTheFormConfirmsIsRemembered()
+ {
+ var server = new GatedServer { HonoursCancellation = true };
+ server.Answer();
+ var settings = new AppSettings();
+ using var session = new ServerSession(settings, () => { }, server, new PlainProtector());
+ var dialogs = new Dialogs((_, _, signIn) => signIn("alberto", "secret").GetAwaiter().GetResult() is null);
+
+ Assert.True(await session.ConnectAsync("nas.local:8443", dialogs));
+ Assert.True(session.IsConnected);
+ Assert.Equal("token-1", settings.ProtectedToken);
+ Assert.Equal(0, server.Logouts);
+ }
+
+ private sealed class Dialogs(Func>, bool> signIn) : IAppDialogs
+ {
+ public string? PickFolder(string title, string? initialFolder = null) => null;
+ public string? PickJsonFile(string title) => null;
+ public bool Confirm(ConfirmRequest request) => true;
+ public bool SignIn(string server, string? username, Func> callback) => signIn(server, username, callback);
+ }
+
+ private sealed class PlainProtector : ITokenProtector
+ {
+ public string Protect(string token) => token;
+ public string? Unprotect(string protectedToken) => protectedToken;
+ }
+
+ /// A server whose login answers only when the test says so.
+ private sealed class GatedServer : IServerApiFactory
+ {
+ private readonly TaskCompletionSource _answer = new();
+
+ /// The request ends when its token is cancelled (as over HTTP); otherwise the answer is already on its way.
+ public bool HonoursCancellation { get; init; }
+
+ public int Logins { get; private set; }
+ public int Logouts { get; private set; }
+
+ public void Answer() => _answer.TrySetResult();
+
+ public IServerApi Create(Uri baseAddress, IReadOnlyCollection trustedFingerprints) => new Client(this, baseAddress);
+
+ private sealed class Client(GatedServer server, Uri baseAddress) : IServerApi
+ {
+ public Uri BaseAddress { get; } = baseAddress;
+ public string? Token { get; set; }
+
+ public Task GetInfoAsync(CancellationToken ct) =>
+ Task.FromResult(new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0)));
+
+ public async Task LoginAsync(string username, string password, CancellationToken ct)
+ {
+ server.Logins++;
+ await (server.HonoursCancellation ? server._answer.Task.WaitAsync(ct) : server._answer.Task);
+ if (password != "secret") throw new TitanoApiException(HttpStatusCode.Unauthorized, new ApiError("bad_credentials", "Wrong"));
+ return new LoginResponse("token-" + server.Logins, User(username), false, DateTimeOffset.UtcNow.AddDays(1));
+ }
+
+ public Task MeAsync(CancellationToken ct) => Task.FromResult(User("alberto"));
+
+ public Task LogoutAsync(CancellationToken ct)
+ {
+ server.Logouts++;
+ return Task.CompletedTask;
+ }
+
+ public void Dispose()
+ {
+ }
+
+ private static UserDto User(string name) =>
+ new(Guid.Empty, name, null, "editor", 0, 5_000_000_000_000, 0, false, false, DateTimeOffset.UtcNow, null);
+ }
+ }
+}
diff --git a/tests/Titano.App.Tests/Server/SyncHostTests.cs b/tests/Titano.App.Tests/Server/SyncHostTests.cs
new file mode 100644
index 00000000..bcaca983
--- /dev/null
+++ b/tests/Titano.App.Tests/Server/SyncHostTests.cs
@@ -0,0 +1,61 @@
+using System.Diagnostics;
+using Titano.App.DesignTime;
+using Titano.App.Infrastructure;
+using Titano.App.Tests.Uploader;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Server;
+
+public sealed class SyncHostTests
+{
+ /// Dialogs that answer like a user who cancels everything.
+ private sealed class NoDialogs : IAppDialogs
+ {
+ public string? PickFolder(string title, string? initialFolder = null) => null;
+ public string? PickJsonFile(string title) => null;
+ public bool Confirm(ConfirmRequest request) => false;
+ public bool SignIn(string server, string? username, Func> signIn) => false;
+ }
+
+ ///
+ /// DESK-1: a signed-in user whose archive is not polled (no archive, or offline at start) exits. Nothing before the
+ /// sync agent's stop leaves the UI thread, and the agent stops asynchronously: its continuation must not need the UI
+ /// thread that App.OnExit blocks, or the exit waits 10 s and never closes the engine and the index.
+ ///
+ [Test]
+ [WindowsOnly]
+ public void ExitWithASignedInSessionAndNoPollingDoesNotWaitForTheUiThread()
+ {
+ var environment = AppEnvironment.ForCapture();
+ try
+ {
+ SingleThreadedContext.Run(async () =>
+ {
+ var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs());
+ var sample = SampleData.Configure(services);
+ // An index without the archive poller (OpenAsync never ran) and a saved session, as for a server-only user.
+ await sample.OpenEmptyAsync();
+ await sample.FillAsync();
+ services.Settings.RenderNodeOptIn = false;
+ await services.Server.RestoreAsync();
+ Assert.True(services.Server.IsConnected, "session restored");
+ var until = DateTime.UtcNow + TimeSpan.FromSeconds(10);
+ while (services.Sync.Agent is null)
+ {
+ Assert.True(DateTime.UtcNow < until, "sync agent not started");
+ await Task.Delay(20);
+ }
+
+ // App.OnExit blocks the UI thread until the services stop.
+ var clock = Stopwatch.StartNew();
+ Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped");
+ Assert.Less(clock.Elapsed.TotalSeconds, 5, "the exit waited for the UI thread");
+ Assert.Null(services.Sync.Agent);
+ });
+ }
+ finally
+ {
+ environment.DeleteCaptureData();
+ }
+ }
+}
diff --git a/tests/Titano.App.Tests/Windows/ShellLifetimeTests.cs b/tests/Titano.App.Tests/Windows/ShellLifetimeTests.cs
new file mode 100644
index 00000000..925b1b81
--- /dev/null
+++ b/tests/Titano.App.Tests/Windows/ShellLifetimeTests.cs
@@ -0,0 +1,53 @@
+using Titano.App.DesignTime;
+using Titano.App.Infrastructure;
+using Titano.App.Shell;
+using Titano.Testing;
+using Titano.Ui.Theming;
+
+namespace Titano.App.Tests.Windows;
+
+/// What the shell stops when the app exits (App.OnExit disposes it before the services).
+[WindowsOnly]
+[Serial]
+[Timeout(120_000)]
+public sealed class ShellLifetimeTests
+{
+ private sealed class NoDialogs : IAppDialogs
+ {
+ public string? PickFolder(string title, string? initialFolder = null) => null;
+ public string? PickJsonFile(string title) => null;
+ public bool Confirm(ConfirmRequest request) => false;
+ public bool SignIn(string server, string? username, Func> signIn) => false;
+ }
+
+ /// DESK-7: the open editor goes with the shell, before the engine and the index under it.
+ [Test]
+ public Task DisposingTheShellClosesTheOpenEditor() => ScreenHost.RunAsync(async () =>
+ {
+ var environment = AppEnvironment.ForCapture();
+ UiLanguage.Apply("en");
+ ThemeManager.Apply(AppTheme.Dark);
+ var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
+ try
+ {
+ var sample = SampleData.Configure(services);
+ var shell = new ShellViewModel(services);
+ await sample.OpenEmptyAsync();
+ await shell.StartAsync();
+ var id = await sample.FillEditorAsync();
+ shell.OpenSequence(id);
+ await shell.Sequence.OpenAsync(id);
+ var editor = Assert.NotNull(shell.Sequence.Editor);
+ editor.PlayCommand.Execute(null);
+ Assert.True(editor.IsPlaying, "the editor plays");
+
+ shell.Dispose();
+ Assert.False(editor.IsPlaying, "the editor's player stopped with the shell");
+ }
+ finally
+ {
+ await services.DisposeAsync();
+ environment.DeleteCaptureData();
+ }
+ });
+}