Files
Chronos/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs
T
Claude d25ecca64e feat(app): taskbar progress, Windows notifications, job toasts, rail badges and section shortcuts
UI-05: the main window's TaskbarItemInfo mirrors the job bar (progress, sliding while
the total is unknown) and turns red while a failure waits on the Jobs screen.

UI-06: the Uploader's tray icon moves to Titano.Ui (Interop/TrayIcon, with a balloon
click callback and error balloons) and the Uploader keeps using it. While the main
window is minimised, hidden or behind another program, every toast (card inserted,
auto-import, job ended, server messages) also becomes a Windows notification; clicking
it restores the window and runs the toast's action. The icon exists only while such a
notification can be clicked. Settings › General gains Notifications (on by default)
and Startup: Start with Windows writes the HKCU Run value "Titano" with --minimized,
and the window then waits minimised on the taskbar.

UI-07: Ctrl+1…6 and Ctrl+, navigate from anywhere in the window, as the rail tooltips
say (not behind the first-run dialog). The editor's 1:1 view moves to Ctrl+Shift+1;
its tooltip key is renamed so no translation keeps the old shortcut.

UI-08: the Jobs screen raises one toast when a long operation ends (render, deep
analysis, verify, rebuild, maintenance, upload: Open; failures: Retry, or Import for a
failed import), whichever screen started it. Background work and scans end silently,
and a finished render of the sequence open in the editor is left to the editor's own
toast with its output file.

UI-10: the Jobs badge adds failures not seen on the Jobs screen yet; the Server badge
counts settings conflicts waiting for a choice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 09:32:39 +00:00

266 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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.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);
// 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.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();
});
[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" };
Assert.Equal("SD 128 GB" + Environment.NewLine + "Import", OsNotifications.BalloonText(card));
Assert.Equal("Job finished", OsNotifications.BalloonText(new Toast { Title = "Job finished" }));
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 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);
});
/// <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");
}
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,
};
}