Merge branch 'fix/shell-notify': taskbar progress, OS notifications, shortcuts, job notices, badges, General settings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 11:13:04 +00:00
commit 979a27e3d3
117 files changed
+1807 -190

No files matched your search

@@ -0,0 +1,45 @@
using Titano.App.Infrastructure;
using Titano.Core.IO;
using Titano.Testing;
namespace Titano.App.Tests.Infrastructure;
/// <summary>Settings › General › Startup: one sign-in entry shared by every copy of Titano, which no copy takes over by starting.</summary>
public sealed class StartWithWindowsTests
{
private const string Installed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.exe";
[Test]
public void AStartFollowsOnlyAnEntryAnUpdateLeftBehindInItsOwnFolder()
{
static bool Gone(string path) => false;
static bool Present(string path) => true;
var installed = StartupCommand.Format(Installed, RunKeyStartWithWindows.MinimizedOption);
// The entry already starts this copy: nothing to write.
Assert.False(RunKeyStartWithWindows.Follows(installed, Installed, Gone));
// An update renamed the program in its folder: the entry follows it.
Assert.True(RunKeyStartWithWindows.Follows(StartupCommand.Format(@"C:\Users\ada\AppData\Local\Programs\Titano\Titano.old.exe", "--minimized"),
Installed, Gone));
// The installed copy is still there: a portable copy, a second install or a development build that starts leaves it alone.
Assert.False(RunKeyStartWithWindows.Follows(installed, @"E:\Titano\Titano.exe", Present));
Assert.False(RunKeyStartWithWindows.Follows(installed, @"C:\src\Titano\bin\Debug\Titano.exe", Present));
// Gone from another folder (a USB stick that is not plugged in): still not this copy's entry.
Assert.False(RunKeyStartWithWindows.Follows(installed, @"E:\Titano\Titano.exe", Gone));
// No entry, or no executable path: nothing to follow.
Assert.False(RunKeyStartWithWindows.Follows(null, Installed, Gone));
Assert.False(RunKeyStartWithWindows.Follows(installed, null, Gone));
}
[Test]
public void ScreenshotsAndPortableCopiesKeepTheChoiceInMemory()
{
var startup = new MemoryStartWithWindows();
Assert.False(startup.IsEnabled);
startup.SetEnabled(true);
startup.Refresh();
Assert.True(startup.IsEnabled);
startup.SetEnabled(false);
Assert.False(startup.IsEnabled);
}
}
@@ -0,0 +1,152 @@
using Titano.App.Jobs;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.App.Tests.Jobs;
/// <summary>UI-08: which job endings raise the shell's toast, whichever screen started the job, and how a batch speaks once.</summary>
public sealed class JobNoticesTests
{
[Theory]
[Case(JobKind.Render)]
[Case(JobKind.DeepAnalyse)]
[Case(JobKind.Verify)]
[Case(JobKind.Rebuild)]
[Case(JobKind.Maintenance)]
[Case(JobKind.UploadCommit)]
[Case(JobKind.Move)]
[Case(JobKind.Adopt)]
public void ALongOperationThatEndsSaysSo(JobKind kind)
{
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, Job(kind, JobState.Failed)));
// Queued and finished between two flushes of the Jobs screen: still one notice.
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Queued, Job(kind, JobState.Done)));
Assert.Equal(JobNotice.Done, JobNotices.For(null, Job(kind, JobState.Done)));
}
[Theory]
[Case(JobKind.Scan)]
[Case(JobKind.LightAnalyse)]
[Case(JobKind.Thumbs)]
[Case(JobKind.Proxies)]
public void UpkeepAndScansEndSilently(JobKind kind)
{
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Failed)));
}
[Theory]
[Case(JobKind.Import)]
[Case(JobKind.Download)]
[Case(JobKind.Duplicates)]
[Case(JobKind.Orphans)]
public void EveryOtherFailureIsSaid(JobKind kind)
{
// An import announces its result on the Import screen, a download on its Library card and Server row.
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(kind, JobState.Done)));
Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, Job(kind, JobState.Failed)));
}
[Test]
public void BackgroundPriorityCancelledAndRepeatedEndingsSayNothing()
{
// The deep analysis queued after an import, and the proxies sync fetches, run in the background.
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(JobKind.DeepAnalyse, JobState.Done, JobPriority.Background)));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(JobKind.Download, JobState.Failed, JobPriority.Background)));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(JobKind.Render, JobState.Cancelled)));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Done, Job(JobKind.Render, JobState.Done)));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Failed, Job(JobKind.Render, JobState.Failed)));
Assert.Equal(JobNotice.None, JobNotices.For(JobState.Queued, Job(JobKind.Render, JobState.Running)));
// "Add to queue" renders have Normal priority: they are announced too.
Assert.Equal(JobNotice.Done, JobNotices.For(JobState.Running, Job(JobKind.Render, JobState.Done, JobPriority.Normal)));
}
[Test]
public void ABatchOfOneKindSpeaksOnceWhenItsLastJobEnds()
{
// Server › Upload all: 100 uploads queued; each one that ends waits for the rest.
var endings = new JobEndings();
var model = new JobListModel();
var uploads = Enumerable.Range(0, 100).Select(_ => Job(JobKind.UploadCommit, JobState.Queued)).ToList();
foreach (var upload in uploads) model.Apply(upload);
for (var i = 0; i < 99; i++)
{
var done = uploads[i] with { State = JobState.Done };
model.Apply(done);
endings.Add(JobNotices.For(JobState.Running, done), done);
Assert.Empty(endings.Take(model.IsBusy));
}
Assert.Equal(99, endings.Waiting);
// A render of the same flush is its own kind: it is said at once.
var render = Job(JobKind.Render, JobState.Done);
model.Apply(render);
endings.Add(JobNotice.Done, render);
var due = endings.Take(model.IsBusy);
Assert.Count(1, due);
Assert.Equal(JobNotice.Done, due[0].Notice);
Assert.SequenceEqual([render.Id], due[0].Jobs.Select(j => j.Id));
var last = uploads[99] with { State = JobState.Done };
model.Apply(last);
endings.Add(JobNotice.Done, last);
due = endings.Take(model.IsBusy);
Assert.Count(1, due);
Assert.SequenceEqual(uploads.Select(u => u.Id), due[0].Jobs.Select(j => j.Id));
Assert.Equal(0, endings.Waiting);
Assert.Empty(endings.Take(model.IsBusy));
}
[Test]
public void PausedAndBackgroundJobsDoNotHoldABatch()
{
var endings = new JobEndings();
var model = new JobListModel();
// An upload paused on a metered network, and the proxies sync fetches in the background, wait for something else.
model.Apply(Job(JobKind.UploadCommit, JobState.Paused));
model.Apply(Job(JobKind.Download, JobState.Running, JobPriority.Background));
var upload = Job(JobKind.UploadCommit, JobState.Done);
model.Apply(upload);
endings.Add(JobNotice.Done, upload);
Assert.Count(1, endings.Take(model.IsBusy));
Assert.False(model.IsBusy(JobKind.UploadCommit));
Assert.False(model.IsBusy(JobKind.Download));
}
[Test]
public void FailuresAreSaidAtTheEndOfTheirFlushTogether()
{
var endings = new JobEndings();
var model = new JobListModel();
// More uploads still run: failures do not wait for them.
model.Apply(Job(JobKind.UploadCommit, JobState.Running));
var first = Job(JobKind.UploadCommit, JobState.Failed);
var second = Job(JobKind.Verify, JobState.Failed);
endings.Add(JobNotice.Failed, first);
endings.Add(JobNotice.Failed, second);
endings.Add(JobNotice.None, Job(JobKind.Scan, JobState.Done));
var due = endings.Take(model.IsBusy);
Assert.Count(1, due);
Assert.Equal(JobNotice.Failed, due[0].Notice);
Assert.SequenceEqual([first.Id, second.Id], due[0].Jobs.Select(j => j.Id));
// The next flush starts again.
var third = Job(JobKind.UploadCommit, JobState.Failed);
endings.Add(JobNotice.Failed, third);
due = endings.Take(model.IsBusy);
Assert.Count(1, due);
Assert.SequenceEqual([third.Id], due[0].Jobs.Select(j => j.Id));
Assert.Empty(endings.Take(model.IsBusy));
}
private static Job Job(JobKind kind, JobState state, JobPriority priority = JobPriority.User) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
State = state,
Priority = priority,
TargetLabel = "Harbour sunset",
Created = DateTimeOffset.UtcNow,
};
}
@@ -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;
/// <summary>The login form cancelled while the server is still answering (DESK-8): nothing signs this PC in afterwards.</summary>
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<string?>? 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<OperationCanceledException>(() => 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<string?>? 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<string, string?, Func<string, string, Task<string?>>, 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<string, string, Task<string?>> callback) => signIn(server, username, callback);
}
private sealed class PlainProtector : ITokenProtector
{
public string Protect(string token) => token;
public string? Unprotect(string protectedToken) => protectedToken;
}
/// <summary>A server whose login answers only when the test says so.</summary>
private sealed class GatedServer : IServerApiFactory
{
private readonly TaskCompletionSource _answer = new();
/// <summary>The request ends when its token is cancelled (as over HTTP); otherwise the answer is already on its way.</summary>
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<string> 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<ServerInfo> GetInfoAsync(CancellationToken ct) =>
Task.FromResult(new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0)));
public async Task<LoginResponse> 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<UserDto> 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);
}
}
}
@@ -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
{
/// <summary>Dialogs that answer like a user who cancels everything.</summary>
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<string, string, Task<string?>> signIn) => false;
}
/// <summary>
/// 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.
/// </summary>
[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();
}
}
}
@@ -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;
/// <summary>What the shell stops when the app exits (App.OnExit disposes it before the services).</summary>
[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<string, string, Task<string?>> signIn) => false;
}
/// <summary>DESK-7: the open editor goes with the shell, before the engine and the index under it.</summary>
[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();
}
});
}
@@ -0,0 +1,408 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Shell;
using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Data.Repositories;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
using Titano.Ui.Visuals;
namespace Titano.App.Tests.Windows;
/// <summary>
/// The shell's ways of telling what happens outside the screen in front: the taskbar button (UI-05), Windows
/// notifications (UI-06), section shortcuts (UI-07), job toasts (UI-08), rail badges (UI-10), and the General settings
/// that drive them; the usage counts consent stays hidden in builds without monetization (RF-3).
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class ShellNotificationTests
{
[Test]
public Task TheTaskbarButtonMirrorsTheJobBar() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await JobsLoadedAsync(shell);
var taskbar = Assert.NotNull(app.Window.TaskbarItemInfo);
shell.SetJob("Render · Harbour sunset", 0.25, name: "Render: Harbour sunset");
Assert.Equal(TaskbarItemProgressState.Normal, taskbar.ProgressState);
Assert.Approximately(0.25, taskbar.ProgressValue, 1e-9);
shell.SetJob("Scan · Archive", 0, indeterminate: true);
Assert.Equal(TaskbarItemProgressState.Indeterminate, taskbar.ProgressState);
shell.SetJob(null, 0);
Assert.Equal(TaskbarItemProgressState.None, taskbar.ProgressState);
// A failure nobody has seen on the Jobs screen turns the idle button red.
shell.SetUnseenFailures(1);
Assert.Equal(TaskbarItemProgressState.Error, taskbar.ProgressState);
Assert.Approximately(1, taskbar.ProgressValue, 1e-9);
shell.SetJob("Render · Harbour sunset", 0.5);
Assert.Equal(TaskbarItemProgressState.Normal, taskbar.ProgressState, "a running job comes first");
shell.SetUnseenFailures(0);
shell.SetJob(null, 0);
Assert.Equal(TaskbarItemProgressState.None, taskbar.ProgressState);
});
[Test]
public Task TheRailShortcutsOfTheTooltipsNavigate() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(firstRun: true);
var shell = app.Shell;
var bindings = app.Window.InputBindings.OfType<KeyBinding>().ToList();
var expected = new (Key Key, SectionKey Section)[]
{
(Key.D1, SectionKey.Library), (Key.D2, SectionKey.Import), (Key.D3, SectionKey.Sequence), (Key.D4, SectionKey.Archive),
(Key.D5, SectionKey.Jobs), (Key.D6, SectionKey.Server), (Key.OemComma, SectionKey.Settings),
};
// The first-run dialog keeps the shell behind it: no shortcut moves it.
var library = bindings.Single(b => b.Key == Key.D1 && b.Modifiers == ModifierKeys.Control);
Assert.False(library.Command.CanExecute(library.CommandParameter), "no navigation behind the first-run dialog");
shell.CompleteWelcome();
foreach (var (key, section) in expected)
{
var binding = bindings.Single(b => b.Key == key && b.Modifiers == ModifierKeys.Control);
Assert.True(binding.Command.CanExecute(binding.CommandParameter), $"Ctrl+{key}");
binding.Command.Execute(binding.CommandParameter);
Assert.Equal(section, shell.Current.Key, $"Ctrl+{key}");
// The rail tooltip lists the shortcut it answers to.
var shortcut = key == Key.OemComma ? "Ctrl+," : "Ctrl+" + (char)('1' + (key - Key.D1));
Assert.True(shell.Current.ToolTip.EndsWith(shortcut, StringComparison.Ordinal), $"{section} tooltip ends with {shortcut}");
}
// The editor's 1:1 view no longer takes Ctrl+1 from the Library.
var gestures = PreviewViewport.ActualSizeCommand.InputGestures.OfType<KeyGesture>().ToList();
Assert.True(gestures.All(g => g is not { Key: Key.D1, Modifiers: ModifierKeys.Control }), "the preview keeps away from Ctrl+1");
Assert.Contains(gestures, g => g is { Key: Key.D1, Modifiers: ModifierKeys.Control | ModifierKeys.Shift });
Assert.Contains("Ctrl+Shift+1", Loc.L("Tooltips.Editor.Preview.OneToOne"));
});
[Test]
public Task JobsThatEndRaiseOneToastAndFailuresCountUntilSeen() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
shell.CompleteWelcome();
await JobsLoadedAsync(shell);
var jobs = shell.Jobs;
var raised = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.Cast<Toast>() ?? []);
var badge = jobs.Badge;
// A deep analysis started from the Library ends: one toast whose action opens what it worked on.
var analysis = Job(JobKind.DeepAnalyse, JobState.Running, Guid.CreateVersion7());
jobs.OnJobChanged(analysis);
jobs.Flush();
jobs.OnJobChanged(analysis with { State = JobState.Done });
jobs.Flush();
var done = raised.Single(t => t.Title == Loc.L("Shell.Job.Done"));
Assert.Equal(Loc.L("Jobs.Action.Open"), done.ActionText);
Assert.False(done.IsError);
Assert.True(done.RunsFromNotification, "a click on the Windows notification opens what the job worked on");
// The same ending reported again says nothing more.
jobs.OnJobChanged(analysis with { State = JobState.Done });
jobs.Flush();
Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Shell.Job.Done")));
// A failed verify: an error toast with Retry, a badge on the rail and a red taskbar button until Jobs is opened.
var verify = Job(JobKind.Verify, JobState.Running, Guid.CreateVersion7());
jobs.OnJobChanged(verify);
jobs.Flush();
jobs.OnJobChanged(verify with { State = JobState.Failed, Error = "Disk read error" });
jobs.Flush();
var failed = raised.Single(t => t.Title == Loc.L("Shell.Job.Failed"));
Assert.True(failed.IsError);
Assert.Equal(Loc.L("Jobs.Action.Retry"), failed.ActionText);
Assert.False(failed.RunsFromNotification, "a click on the Windows notification does not retry before the user sees why");
Assert.Equal(badge + 1, jobs.Badge);
Assert.Equal(TaskbarItemProgressState.Error, shell.TaskbarState);
shell.Navigate(SectionKey.Jobs);
Assert.Equal(badge, jobs.Badge);
Assert.NotEqual(TaskbarItemProgressState.Error, shell.TaskbarState);
// The editor announces the renders of its own sequence, with their output: the shell says nothing then.
var id = await app.Sample.FillEditorAsync();
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
Assert.NotNull(shell.Sequence.Editor);
raised.Clear();
var render = Job(JobKind.Render, JobState.Running, id);
jobs.OnJobChanged(render);
jobs.Flush();
jobs.OnJobChanged(render with { State = JobState.Done });
jobs.Flush();
Assert.False(raised.Any(t => t.Title == Loc.L("Shell.Job.Done")), "the editor's own render toast is not doubled");
// A render of another sequence is the shell's to announce.
var other = Job(JobKind.Render, JobState.Running, Guid.CreateVersion7());
jobs.OnJobChanged(other);
jobs.Flush();
jobs.OnJobChanged(other with { State = JobState.Done });
jobs.Flush();
Assert.Equal(1, raised.Count(t => t.Title == Loc.L("Shell.Job.Done")));
await shell.Sequence.CloseAsync();
// Server › Upload all: the batch speaks once, when its last upload ends.
raised.Clear();
var uploads = Enumerable.Range(0, 3).Select(_ => Job(JobKind.UploadCommit, JobState.Queued, Guid.CreateVersion7())).ToList();
foreach (var upload in uploads) jobs.OnJobChanged(upload);
jobs.Flush();
foreach (var upload in uploads)
{
Assert.Empty(raised);
jobs.OnJobChanged(upload with { State = JobState.Done });
jobs.Flush();
}
var batch = raised.Single();
Assert.Equal(Loc.Plural("Shell.Job.DonePlural", 3), batch.Title);
Assert.Equal(Loc.L("Jobs.Kind.UploadCommit"), batch.Message);
Assert.Equal(Loc.L("Shell.Nav.Jobs"), batch.ActionText);
shell.Navigate(SectionKey.Library);
batch.ActionCommand!.Execute(null);
Assert.Equal(SectionKey.Jobs, shell.Current.Key);
// Two failures of one update: one error toast that leads to the Jobs screen.
raised.Clear();
var broken = new[] { Job(JobKind.Move, JobState.Running, Guid.CreateVersion7()), Job(JobKind.Adopt, JobState.Running, Guid.CreateVersion7()) };
foreach (var job in broken) jobs.OnJobChanged(job);
jobs.Flush();
foreach (var job in broken) jobs.OnJobChanged(job with { State = JobState.Failed });
jobs.Flush();
var failures = raised.Single();
Assert.True(failures.IsError);
Assert.Equal(Loc.Plural("Shell.Job.FailedPlural", 2), failures.Title);
Assert.Null(failures.Message);
});
[Test]
public Task ToastsBecomeWindowsNotificationsOnlyWhileNobodySeesTheWindow() => ScreenHost.RunAsync(async () =>
{
Assert.True(OsNotifications.IsUnseen(WindowState.Minimized, isVisible: true, anyWindowActive: true));
Assert.True(OsNotifications.IsUnseen(WindowState.Normal, isVisible: true, anyWindowActive: false));
Assert.True(OsNotifications.IsUnseen(WindowState.Maximized, isVisible: false, anyWindowActive: true));
Assert.False(OsNotifications.IsUnseen(WindowState.Maximized, isVisible: true, anyWindowActive: true));
// The card prompt of BRIEF §12.4 reads "Card X detected", then its action, which a click runs.
var card = new Toast { Title = "EOS R5 card A inserted", Message = "SD 128 GB", ActionText = "Import", RunsFromNotification = true };
Assert.Equal("SD 128 GB" + Environment.NewLine + "Import", OsNotifications.BalloonText(card));
Assert.Equal("Job finished", OsNotifications.BalloonText(new Toast { Title = "Job finished" }));
// An action a click does not run (the auto-import's Cancel) waits in the window.
var auto = new Toast { Title = "EOS R5 card A inserted", Message = "Importing into the archive", ActionText = "Cancel" };
Assert.Equal("Importing into the archive", OsNotifications.BalloonText(auto));
Assert.True(MainWindow.StartsMinimized(["Titano.exe", "--minimized"]));
Assert.False(MainWindow.StartsMinimized(["Titano.exe"]));
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Shell.CompleteWelcome();
// Minimised: nobody sees the window.
app.Window.WindowState = WindowState.Minimized;
var enabled = false;
using var notifications = new OsNotifications(app.Window, () => enabled, _ => { });
Assert.False(notifications.Show(card), "Settings › General › Notifications is off");
Assert.False(notifications.HasTrayIcon);
enabled = true;
Assert.True(notifications.Show(new Toast { Title = "Job finished", Message = "Render · Harbour sunset", ActionCommand = new RelayCommand(() => { }) }));
Assert.True(notifications.HasTrayIcon, "the notification area holds the icon while a notification can be clicked");
notifications.Dispose();
Assert.False(notifications.HasTrayIcon);
app.Window.WindowState = WindowState.Normal;
});
[Test]
public Task AClickOnANotificationBringsTheWindowBackAndRunsOnlyWhatItNames() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Shell.CompleteWelcome();
var window = app.Window;
var imported = 0;
var cancelled = 0;
var dismissed = new List<Toast>();
Toast Import() => new() { Title = "EOS R5 card A inserted", ActionText = "Import", ActionCommand = new RelayCommand(() => imported++), RunsFromNotification = true };
// "Card X detected — Import": the click restores the window, opens the card and closes the in-window toast.
using (var notifications = new OsNotifications(window, () => true, dismissed.Add))
{
window.WindowState = WindowState.Minimized;
var card = Import();
Assert.True(notifications.Show(card));
notifications.OnBalloonClicked();
await StateAsync(window, WindowState.Normal);
Assert.Equal(1, imported);
Assert.SequenceEqual([card], dismissed);
}
// The auto-import's toast offers Cancel: the click only brings the window back.
using (var notifications = new OsNotifications(window, () => true, dismissed.Add))
{
window.WindowState = WindowState.Minimized;
Assert.True(notifications.Show(new Toast { Title = "EOS R5 card A inserted", ActionText = "Cancel", ActionCommand = new RelayCommand(() => cancelled++) }));
notifications.OnBalloonClicked();
await StateAsync(window, WindowState.Normal);
Assert.Equal(0, cancelled);
Assert.Count(1, dismissed);
}
// Two notifications: Windows does not say which one was clicked, so neither action runs.
using (var notifications = new OsNotifications(window, () => true, dismissed.Add))
{
window.WindowState = WindowState.Minimized;
Assert.True(notifications.Show(Import()));
Assert.True(notifications.Show(Import()));
notifications.OnBalloonClicked();
await StateAsync(window, WindowState.Normal);
Assert.Equal(1, imported);
Assert.Count(1, dismissed);
}
});
[Test]
public Task AWindowStartedMinimisedComesBackAsItWasSaved() => ScreenHost.RunAsync(async () =>
{
// Closed while still minimised from the start: the saved state stays the one it would have come back to.
Assert.True(MainWindow.SavesMaximized(WindowState.Maximized, restoreTo: null));
Assert.True(MainWindow.SavesMaximized(WindowState.Minimized, WindowState.Maximized));
Assert.False(MainWindow.SavesMaximized(WindowState.Minimized, WindowState.Normal));
Assert.False(MainWindow.SavesMaximized(WindowState.Normal, restoreTo: null));
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
app.Shell.CompleteWelcome();
var window = app.Window;
// Started at sign-in with the window saved maximised: it waits on the taskbar.
window.WaitMinimized(maximized: true);
Assert.Equal(WindowState.Minimized, window.WindowState);
// The user opens it from the taskbar: it comes back maximised.
window.WindowState = WindowState.Normal;
await StateAsync(window, WindowState.Maximized);
// Only that first restore: later ones are the user's.
window.WindowState = WindowState.Normal;
window.WindowState = WindowState.Minimized;
window.WindowState = WindowState.Normal;
await StateAsync(window, WindowState.Normal);
await Task.Delay(100);
Assert.Equal(WindowState.Normal, window.WindowState);
});
[Test]
public Task GeneralSettingsHoldStartupAndNotificationsButNoConsent() => ScreenHost.RunAsync(async () =>
{
// Monetization (BRIEF §21) ships disabled: the default build offers no usage counts consent.
Assert.False(ProductFeatures.AdsEnabled);
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(firstRun: true);
var shell = app.Shell;
await app.ExpectAsync<WelcomeView>("welcome");
Assert.False(app.FindAll<CheckBox>().Any(c => c.IsVisible && Equals(c.Content, Loc.L("Settings.General.UsageCounts"))), "no consent on the first-run dialog");
shell.CompleteWelcome();
var settings = shell.Settings;
var startup = new MemoryStartWithWindows();
settings.Startup = startup;
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.General;
await app.ExpectAsync<SettingsView>("settings-general");
var boxes = app.FindAll<CheckBox>().Where(c => c.IsVisible).ToList();
Assert.False(boxes.Any(c => Equals(c.Content, Loc.L("Settings.General.UsageCounts"))), "no consent in Settings");
var start = boxes.Single(c => Equals(c.Content, Loc.L("Settings.General.StartWithWindows")));
Assert.Equal(Loc.L("Tooltips.Settings.StartWithWindows"), start.ToolTip);
var notify = boxes.Single(c => Equals(c.Content, Loc.L("Settings.General.OsNotifications")));
Assert.Equal(Loc.L("Tooltips.Settings.OsNotifications"), notify.ToolTip);
Assert.True(notify.IsChecked == true, "Windows notifications are on by default");
settings.StartWithWindows = true;
Assert.True(startup.IsEnabled);
settings.OsNotifications = false;
Assert.False(shell.Services.Settings.OsNotifications);
settings.ResetSectionCommand.Execute(null);
Assert.False(startup.IsEnabled, "Reset section turns Start with Windows off");
Assert.True(shell.Services.Settings.OsNotifications, "Reset section turns notifications back on");
// Reset section also returned the language to the system's.
UiLanguage.Apply("en");
// The search finds General by its new rows, not by the hidden consent.
settings.SearchText = Loc.L("Settings.General.Startup");
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.General);
settings.SearchText = Loc.L("Settings.General.Usage");
Assert.False(settings.VisiblePages.Any(p => p.Page == SettingsPage.General), "the hidden consent does not match");
settings.SearchText = string.Empty;
});
[Test]
public Task TheServerBadgeCountsConflicts() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
shell.CompleteWelcome();
Assert.Equal(0, shell.Server.Badge);
await app.Sample.FillAsync();
await shell.Services.Server.RestoreAsync();
Assert.NotNull(await shell.Services.Sync.RefreshAsync());
await shell.Server.Sync.ReloadAsync();
// The sample server holds one sequence whose settings changed on both sides.
Assert.Equal(1, shell.Server.Sync.Chips.Single(c => c.Filter == Titano.App.Server.SyncFilter.Conflicts).Count);
Assert.Equal(1, shell.Server.Badge);
});
[Test]
public Task TheLibraryAndArchiveBadgesCountWarnings() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
shell.CompleteWelcome();
await app.Sample.FillAsync();
var db = Assert.NotNull(shell.Services.Database);
// Library: the sequences the Warnings filter shows; an analysis that finds warnings adds one.
await shell.Library.RefreshAsync();
var warned = await db.Sequences.CountAsync(new SequenceQuery { WithStatus = SequenceStatus.HasWarnings });
Assert.Equal(warned, shell.Library.Badge);
var clean = (await db.Sequences.ListAsync(new SequenceQuery { WithoutStatus = SequenceStatus.HasWarnings, Limit = 1 })).Items[0];
await db.Sequences.RecordAnalysisAsync(clean.Id, SequenceStatus.AnalyzedLight | SequenceStatus.HasWarnings, SequenceStatus.None, 2, null);
await shell.Library.RefreshAsync();
Assert.Equal(warned + 1, shell.Library.Badge);
// Archive: the index health lines that need attention (the sample has unverified sequences).
shell.Navigate(SectionKey.Archive);
await shell.Archive.LoadAsync();
Assert.Greater(shell.Archive.Badge, 0);
Assert.Equal(shell.Archive.Health.Count(h => !h.IsOk), shell.Archive.Badge);
});
/// <summary>The Jobs screen read its first page (it would set the job bar and the badge again).</summary>
private static async Task JobsLoadedAsync(ShellViewModel shell)
{
for (var i = 0; i < 200 && !shell.Jobs.IsEmpty && !shell.Jobs.HasRows; i++) await Task.Delay(20);
Assert.True(shell.Jobs.IsEmpty || shell.Jobs.HasRows, "the job list loaded");
}
/// <summary>The window reached <paramref name="state"/> (a restore from a notification is a posted system command).</summary>
private static async Task StateAsync(Window window, WindowState state)
{
for (var i = 0; i < 250 && window.WindowState != state; i++) await Task.Delay(20);
Assert.Equal(state, window.WindowState);
}
private static Job Job(JobKind kind, JobState state, Guid target) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
State = state,
Priority = JobPriority.User,
TargetIds = [target],
TargetLabel = "Harbour sunset",
Created = DateTimeOffset.UtcNow,
Started = DateTimeOffset.UtcNow,
};
}