From 6417e2b3c2aa13b234539568965d7f0760d1e129 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 10:35:19 +0000 Subject: [PATCH] fix(app): notification clicks run only what the toast names, batches speak once, warnings get badges - Toast.RunsFromNotification: a click on a Windows notification restores the window and runs the toast's action only when the toast opts in (card detected: Import; interrupted import: Resume; job finished: Open; navigation to Import or Jobs) and it is the only notification shown since the icon appeared. Cancel, Undo and Retry stay in the window, and the notification text no longer offers them. - Job endings are coalesced: finished jobs of one kind wait until no job of that kind the user waits for is queued or running, then one toast says how many finished ("12 jobs finished", action Jobs); failures of one update share one toast. Server > Upload all no longer raises one toast and one notification per sequence. - Every failure that is not upkeep (scan, thumbnails, proxies, light analysis) is announced, including move, adopt and user downloads; finished moves and adoptions are announced too. - Rail badges: Library counts the sequences with warnings (the Warnings filter), refreshed after analyses; Archive counts the index health lines that need attention. - Tests: the balloon click path, the --minimized restore to a saved maximised window, batch and failure coalescing, and the new badges. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/ARCHITECTURE.md | 6 +- i18n/en/Shell.resx | 4 + i18n/it/Shell.it.resx | 4 + src/Titano.App/Jobs/JobListModel.cs | 7 + src/Titano.App/Jobs/JobNotices.cs | 65 +++++++- src/Titano.App/Sections/ArchiveViewModel.cs | 2 + src/Titano.App/Sections/ImportViewModel.cs | 4 +- src/Titano.App/Sections/JobsViewModel.cs | 79 +++++++--- src/Titano.App/Sections/LibraryViewModel.cs | 12 ++ src/Titano.App/Shell/MainWindow.xaml.cs | 20 ++- src/Titano.App/Shell/OsNotifications.cs | 40 +++-- src/Titano.App/Shell/ShellViewModel.cs | 5 +- src/Titano.Ui/Controls/Toasts.cs | 7 + .../Titano.App.Tests/Jobs/JobNoticesTests.cs | 102 ++++++++++-- .../Windows/ShellNotificationTests.cs | 145 +++++++++++++++++- 15 files changed, 438 insertions(+), 64 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9936c0bf..9df8466c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -46,7 +46,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Model` | Domain entities and enums (§5) shared by Data, Server and clients | | `Packaging` | TPK1 installer payload writer/reader, staged install transaction | | `Diagnostics` | `Log`, file sink, synthetic sequences, `SecretScrubber`, `DiagnosticsArchive` (scrubbed diagnostics zip) | -| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, CRC-32/SHA helpers, brand mark geometry | +| `Localization`, `IO`, `Hashing`, `Branding` | `Loc`/plural rules, `AtomicFile`, `StartupCommand` (sign-in entries of the programs, removed by the uninstaller), CRC-32/SHA helpers, brand mark geometry | ### 2.2 Titano.Data @@ -71,8 +71,8 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) | | `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, mass rename and move, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`), `ArchiveFailures` | | `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` | -| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast); settings rows, encoder inventory, language catalog, naming preview; update check and download | -| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppEnvironment` (installed or portable), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), device monitor | +| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); settings rows, encoder inventory, language catalog, naming preview; update check and download | +| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppEnvironment` (installed or portable), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), device monitor | | `DesignTime` | `SampleData`: the archive, jobs and server the screenshots and smoke tests run on | ### 2.4 Titano.Ui and Titano.Server diff --git a/i18n/en/Shell.resx b/i18n/en/Shell.resx index 40ec77a9..478c846a 100644 --- a/i18n/en/Shell.resx +++ b/i18n/en/Shell.resx @@ -6,7 +6,11 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Titanoinvariant Job finished + {0} job finished + {0} jobs finished Job failed + {0} job failed + {0} jobs failed Ready Pause job Ready · {0} jobs queued diff --git a/i18n/it/Shell.it.resx b/i18n/it/Shell.it.resx index 676f7569..417f41f4 100644 --- a/i18n/it/Shell.it.resx +++ b/i18n/it/Shell.it.resx @@ -5,7 +5,11 @@ System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 Attività completata + {0} attività completata + {0} attività completate Attività non riuscita + {0} attività non riuscita + {0} attività non riuscite Pronto Pausa attività Pronto · {0} attività in coda diff --git a/src/Titano.App/Jobs/JobListModel.cs b/src/Titano.App/Jobs/JobListModel.cs index 4621ace1..364396fd 100644 --- a/src/Titano.App/Jobs/JobListModel.cs +++ b/src/Titano.App/Jobs/JobListModel.cs @@ -137,6 +137,13 @@ public sealed class JobListModel public int QueuedCount => _entries.Values.Count(e => e.State == JobState.Queued); + /// + /// A job of that the user waits for (not background work) is queued or running. Paused jobs + /// do not count: they wait for the user, or for an unmetered network, not for the queue. + /// + public bool IsBusy(JobKind kind) => + _entries.Values.Any(e => e.Job.Kind == kind && e.Job.Priority != JobPriority.Background && e.State is JobState.Queued or JobState.Running); + /// Same order as JobRepository.ClaimNextAsync: priority descending, then creation time and id. public static bool ClaimsBefore(Job a, Job b) => a.Priority != b.Priority ? a.Priority > b.Priority : a.Created != b.Created ? a.Created < b.Created : a.Id.CompareTo(b.Id) < 0; diff --git a/src/Titano.App/Jobs/JobNotices.cs b/src/Titano.App/Jobs/JobNotices.cs index 8d516776..71a7f036 100644 --- a/src/Titano.App/Jobs/JobNotices.cs +++ b/src/Titano.App/Jobs/JobNotices.cs @@ -14,7 +14,8 @@ public enum JobNotice /// Which job endings raise a toast (BRIEF §12.1 "toasts for job completion"): the long operations the user asked for /// end with one toast, whichever screen started them. Background work (thumbnails, proxies, light analysis, the /// analysis queued after an import) and scans (the archive is rescanned every 10 minutes) end silently; an import -/// has its own toast when it ends well, and the Import screen holds its retry. Cancelled jobs were stopped on purpose. +/// has its own toast when it ends well, and a download shows on its Library card and Server row. Every other failure +/// is said. Cancelled jobs were stopped on purpose. /// public static class JobNotices { @@ -29,11 +30,69 @@ public static class JobNotices return job.State switch { JobState.Done when Announces(job.Kind) => JobNotice.Done, - JobState.Failed when Announces(job.Kind) || job.Kind == JobKind.Import => JobNotice.Failed, + JobState.Failed when !IsUpkeep(job.Kind) => JobNotice.Failed, _ => JobNotice.None, }; } private static bool Announces(JobKind kind) => - kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit; + kind is JobKind.Render or JobKind.DeepAnalyse or JobKind.Verify or JobKind.Rebuild or JobKind.Maintenance or JobKind.UploadCommit + or JobKind.Move or JobKind.Adopt; + + /// Work that keeps the index and its previews current: the next run repeats it, the Archive screen shows what is missing. + private static bool IsUpkeep(JobKind kind) => + kind is JobKind.Scan or JobKind.Thumbs or JobKind.Proxies or JobKind.LightAnalyse; +} + +/// Endings said in one toast: one job, or several of a batch. +public sealed record JobEnding(JobNotice Notice, IReadOnlyList Jobs); + +/// +/// Job endings waiting for their toast, so that a batch speaks once (Server › Upload all queues one upload per +/// sequence): finished jobs of one kind wait until no job of that kind the user waits for is queued or running, then +/// one toast says how many finished; failures are said at the end of the update that brought them, together when +/// several failed at once. WPF-free; feed it on the UI thread. +/// +public sealed class JobEndings +{ + private readonly SortedDictionary> _done = []; + private readonly List _failed = []; + + /// Finished jobs still waiting for the rest of their kind (tests). + public int Waiting => _done.Values.Sum(l => l.Count); + + public void Add(JobNotice notice, Job job) + { + ArgumentNullException.ThrowIfNull(job); + if (notice == JobNotice.Failed) + { + _failed.Add(job); + } + else if (notice == JobNotice.Done) + { + if (!_done.TryGetValue(job.Kind, out var jobs)) _done[job.Kind] = jobs = []; + jobs.Add(job); + } + } + + /// + /// The toasts due now: the failures added since the last call, then each finished kind that + /// no longer reports as queued or running. What is returned is forgotten. + /// + public IReadOnlyList Take(Func busy) + { + ArgumentNullException.ThrowIfNull(busy); + var due = new List(); + if (_failed.Count > 0) + { + due.Add(new JobEnding(JobNotice.Failed, [.. _failed])); + _failed.Clear(); + } + foreach (var kind in _done.Keys.Where(k => !busy(k)).ToList()) + { + due.Add(new JobEnding(JobNotice.Done, _done[kind])); + _done.Remove(kind); + } + return due; + } } diff --git a/src/Titano.App/Sections/ArchiveViewModel.cs b/src/Titano.App/Sections/ArchiveViewModel.cs index a2d11016..6bc7ee4c 100644 --- a/src/Titano.App/Sections/ArchiveViewModel.cs +++ b/src/Titano.App/Sections/ArchiveViewModel.cs @@ -484,6 +484,8 @@ public sealed class ArchiveViewModel : SectionViewModel _ => null, })), ]; + // The rail badge counts the health lines that need attention (BRIEF §12.1 "badge counts (warnings, …)"). + Badge = Health.Count(h => !h.IsOk); } private static IReadOnlyList Bars(IReadOnlyList values) => diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs index 763091c5..f934a46e 100644 --- a/src/Titano.App/Sections/ImportViewModel.cs +++ b/src/Titano.App/Sections/ImportViewModel.cs @@ -1399,7 +1399,7 @@ public sealed class ImportViewModel : SectionViewModel if (_phase == ImportPhase.Failed && _jobId is not null && _jobSourceKey == device.Identity) { Shell.Notify(Loc.L("Import.Toast.Inserted", source.Title), Loc.L("Import.Toast.ResumeMessage"), Loc.L("Import.Toast.Resume"), - Loc.L("Tooltips.Import.Resume"), () => RetryCommand.Execute(null)); + Loc.L("Tooltips.Import.Resume"), () => RetryCommand.Execute(null), runsFromNotification: true); return; } if (_phase == ImportPhase.Running) return; @@ -1425,6 +1425,8 @@ public sealed class ImportViewModel : SectionViewModel SelectSource(device.Identity); Shell.Navigate(SectionKey.Import); }), + // BRIEF §12.4: the Windows notification "Card X detected — Import" opens the card on Import. + RunsFromNotification = true, }); } diff --git a/src/Titano.App/Sections/JobsViewModel.cs b/src/Titano.App/Sections/JobsViewModel.cs index e82b8f4c..fff2a7fb 100644 --- a/src/Titano.App/Sections/JobsViewModel.cs +++ b/src/Titano.App/Sections/JobsViewModel.cs @@ -62,6 +62,7 @@ public sealed class JobsViewModel : SectionViewModel private readonly JobUpdateBuffer _buffer = new(); private readonly Dictionary _rows = []; private readonly HashSet _unseenFailures = []; + private readonly JobEndings _endings = new(); private readonly JobActions _actions; private CoalescingThrottle? _throttle; private IJobQueue? _queue; @@ -227,6 +228,7 @@ public sealed class JobsViewModel : SectionViewModel Follow(before, job); } foreach (var p in progress) _model.Apply(p); + foreach (var ending in _endings.Take(_model.IsBusy)) Shell.ShowToast(ToastFor(ending)); SyncRows(); UpdateShell(); } @@ -241,43 +243,72 @@ public sealed class JobsViewModel : SectionViewModel /// /// A change the engine reported (these are live, never pages read again): a failure counts on the rail until this - /// screen is opened, and a long operation that ends says so in a toast with one action (BRIEF §12.1, §0.2 rule 6). + /// screen is opened, and a long operation that ends is announced at the end of the flush (). /// private void Follow(JobState? before, Job job) { if (job.State != JobState.Failed) _unseenFailures.Remove(job.Id); else if (before != JobState.Failed && !IsSelected) _unseenFailures.Add(job.Id); var notice = JobNotices.For(before, job); - if (notice == JobNotice.None || (notice == JobNotice.Done && EditorAnnounces(job))) return; - Shell.ShowToast(notice == JobNotice.Done - ? new Toast + if (notice == JobNotice.Done && EditorAnnounces(job)) return; + _endings.Add(notice, job); + } + + /// + /// The toast of a job that ended, with one action (BRIEF §12.1, §0.2 rule 6). Several endings at once (a batch + /// finished, or failed together) say how many and lead to this screen. Clicking the Windows notification of a + /// toast opens what it names; a retry waits until the user has seen why the job failed. + /// + private Toast ToastFor(JobEnding ending) + { + var job = ending.Jobs[0]; + var failed = ending.Notice == JobNotice.Failed; + if (ending.Jobs.Count > 1) + { + return new Toast + { + Title = Loc.Plural(failed ? "Shell.Job.FailedPlural" : "Shell.Job.DonePlural", ending.Jobs.Count), + Message = ending.Jobs.All(j => j.Kind == job.Kind) ? JobText.Kind(job.Kind) : null, + ActionText = Loc.L("Shell.Nav.Jobs"), + ActionToolTip = Loc.L("Tooltips.Nav.Jobs"), + ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Jobs)), + IsError = failed, + RunsFromNotification = true, + }; + } + if (!failed) + { + return new Toast { Title = Loc.L("Shell.Job.Done"), Message = JobText.Name(job), ActionText = Loc.L("Jobs.Action.Open"), ActionToolTip = Loc.L("Tooltips.Jobs.Open"), ActionCommand = new AsyncRelayCommand(() => OpenTargetAsync(job)), + RunsFromNotification = true, + }; + } + return job.Kind == JobKind.Import + // The Import screen resumes an import with its plan and card; it holds the retry. + ? new Toast + { + Title = Loc.L("Shell.Job.Failed"), + Message = JobText.Name(job), + ActionText = Loc.L("Shell.Nav.Import"), + ActionToolTip = Loc.L("Tooltips.Nav.Import"), + ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import)), + IsError = true, + RunsFromNotification = true, } - : job.Kind == JobKind.Import - // The Import screen resumes an import with its plan and card; it holds the retry. - ? new Toast - { - Title = Loc.L("Shell.Job.Failed"), - Message = JobText.Name(job), - ActionText = Loc.L("Shell.Nav.Import"), - ActionToolTip = Loc.L("Tooltips.Nav.Import"), - ActionCommand = new RelayCommand(() => Shell.Navigate(SectionKey.Import)), - IsError = true, - } - : new Toast - { - Title = Loc.L("Shell.Job.Failed"), - Message = JobText.Name(job), - ActionText = Loc.L("Jobs.Action.Retry"), - ActionToolTip = Loc.L("Tooltips.Jobs.Retry"), - ActionCommand = new AsyncRelayCommand(() => _queue?.ResumeAsync(job.Id) ?? Task.CompletedTask), - IsError = true, - }); + : new Toast + { + Title = Loc.L("Shell.Job.Failed"), + Message = JobText.Name(job), + ActionText = Loc.L("Jobs.Action.Retry"), + ActionToolTip = Loc.L("Tooltips.Jobs.Retry"), + ActionCommand = new AsyncRelayCommand(() => _queue?.ResumeAsync(job.Id) ?? Task.CompletedTask), + IsError = true, + }; } /// A finished render of the sequence open in the editor: the editor says it, with its output file. diff --git a/src/Titano.App/Sections/LibraryViewModel.cs b/src/Titano.App/Sections/LibraryViewModel.cs index 9b680bdc..5af04da3 100644 --- a/src/Titano.App/Sections/LibraryViewModel.cs +++ b/src/Titano.App/Sections/LibraryViewModel.cs @@ -700,6 +700,7 @@ public sealed class LibraryViewModel : SectionViewModel _hasArchive = (await _db.Archives.ListAsync()).Count > 0; Shell.SetLibraryTotals(stats.Sequences, stats.Photos, stats.Bytes); _localStats = stats; + await CountWarningsAsync(); _suppressReload = true; var tag = _tag.Value; @@ -1025,6 +1026,8 @@ public sealed class LibraryViewModel : SectionViewModel if (job.Kind is JobKind.Scan or JobKind.Rebuild or JobKind.Import or JobKind.Adopt or JobKind.Move or JobKind.UploadCommit || SyncService.TransferKind(job) is SyncTransferKind.DownloadOriginals or SyncTransferKind.GetExports) await RefreshAsync(); + else if (job.Kind is JobKind.LightAnalyse or JobKind.DeepAnalyse) + await CountWarningsAsync(); } catch (DatabaseException ex) { @@ -1032,6 +1035,15 @@ public sealed class LibraryViewModel : SectionViewModel } } + /// + /// The rail badge counts the sequences of this PC with warnings (BRIEF §12.1 "badge counts (warnings, …)"), the + /// ones the Warnings filter shows; analyses change it. + /// + private async Task CountWarningsAsync() + { + if (_db is not null) Badge = await _db.Sequences.CountAsync(new SequenceQuery { WithStatus = SequenceStatus.HasWarnings }); + } + /// Open: the editor for a sequence here; for a remote card, with proxies (fetched first when this PC has none). private async Task OpenAsync(SequenceItem item) { diff --git a/src/Titano.App/Shell/MainWindow.xaml.cs b/src/Titano.App/Shell/MainWindow.xaml.cs index 4dd67dac..d8d19c07 100644 --- a/src/Titano.App/Shell/MainWindow.xaml.cs +++ b/src/Titano.App/Shell/MainWindow.xaml.cs @@ -43,6 +43,17 @@ public partial class MainWindow : TitanoWindow internal static bool StartsMinimized(IReadOnlyList arguments) => arguments.Any(a => a.Equals(RunKeyStartWithWindows.MinimizedOption, StringComparison.OrdinalIgnoreCase)); + /// Minimised until the user opens it; that first restore brings back the saved state (maximised or not). + internal void WaitMinimized(bool maximized) + { + WindowState = WindowState.Minimized; + _restoreTo = maximized ? WindowState.Maximized : WindowState.Normal; + } + + /// The maximised flag to save: a window started minimised and never opened keeps the state it would come back to. + internal static bool SavesMaximized(WindowState state, WindowState? restoreTo) => + state == WindowState.Maximized || (state == WindowState.Minimized && restoreTo == WindowState.Maximized); + /// The first restore of a window started minimised brings back the saved maximised state. protected override void OnStateChanged(EventArgs e) { @@ -101,11 +112,7 @@ public partial class MainWindow : TitanoWindow if (_shell.Services.Environment.IsCapture) return; var p = _shell.Services.Settings.Window; var maximized = p?.Maximized == true; - if (StartsMinimized(Environment.GetCommandLineArgs())) - { - WindowState = WindowState.Minimized; - _restoreTo = maximized ? WindowState.Maximized : WindowState.Normal; - } + if (StartsMinimized(Environment.GetCommandLineArgs())) WaitMinimized(maximized); if (p is null || p.Width < MinWidth || p.Height < MinHeight) return; var virtualScreen = new Rect(SystemParameters.VirtualScreenLeft, SystemParameters.VirtualScreenTop, SystemParameters.VirtualScreenWidth, SystemParameters.VirtualScreenHeight); var rect = new Rect(p.Left, p.Top, p.Width, p.Height); @@ -128,8 +135,7 @@ public partial class MainWindow : TitanoWindow Top = b.Top, Width = b.Width, Height = b.Height, - // Started minimised and never opened: the saved state stays the one it would have been restored to. - Maximized = WindowState == WindowState.Maximized || (WindowState == WindowState.Minimized && _restoreTo == WindowState.Maximized), + Maximized = SavesMaximized(WindowState, _restoreTo), }; } } diff --git a/src/Titano.App/Shell/OsNotifications.cs b/src/Titano.App/Shell/OsNotifications.cs index 38c81783..906db231 100644 --- a/src/Titano.App/Shell/OsNotifications.cs +++ b/src/Titano.App/Shell/OsNotifications.cs @@ -9,8 +9,10 @@ namespace Titano.App.Shell; /// Windows notifications for the toasts nobody would see (BRIEF §12.1 "optional OS toast when minimised", §12.4 "Card /// X detected — Import"): while the main window is minimised, hidden or behind another program, every toast also goes /// to a tray balloon, which Windows 10/11 shows as a notification, when Settings › General allows it. Clicking it -/// brings the window back and runs the toast's action. The tray icon exists only while such a notification can be -/// clicked: it goes once a window of Titano is active again. Create, use and dispose it on the UI thread. +/// brings the window back; it also runs the toast's action when the toast allows it +/// () and it is the only notification shown, since Windows does not say which +/// of several was clicked. The tray icon exists only while such a notification can be clicked: it goes once a window +/// of Titano is active again. Create, use and dispose it on the UI thread. /// public sealed class OsNotifications : IDisposable { @@ -21,6 +23,7 @@ public sealed class OsNotifications : IDisposable private readonly Action _dismiss; private TrayIcon? _tray; private Toast? _latest; + private int _shown; private bool _disposed; /// The main window, restored by a click. @@ -44,6 +47,7 @@ public sealed class OsNotifications : IDisposable if (_disposed || !_enabled() || !IsUnseen(_window.WindowState, _window.IsVisible, AnyWindowActive())) return false; _tray ??= new TrayIcon(Loc.L("Shell.AppName"), Menu, OnMenu, Restore, OnBalloonClicked); _latest = toast; + _shown++; _tray.ShowBalloon(toast.Title, BalloonText(toast), toast.IsError); return true; } @@ -60,16 +64,31 @@ public sealed class OsNotifications : IDisposable state == WindowState.Minimized || !isVisible || !anyWindowActive; /// - /// The notification's text: the toast's message, then its action ("Import"), which a click on it runs; the title - /// alone when there is neither (Windows needs a text to show a notification at all). + /// The notification's text: the toast's message, then the action a click on it runs ("Import"); the title alone + /// when there is neither (Windows needs a text to show a notification at all). An action a click does not run + /// waits in the window and is not offered here. /// public static string BalloonText(Toast toast) { ArgumentNullException.ThrowIfNull(toast); - var lines = new[] { toast.Message, toast.ActionText }.Where(l => !string.IsNullOrWhiteSpace(l)); + var lines = new[] { toast.Message, toast.RunsFromNotification ? toast.ActionText : null }.Where(l => !string.IsNullOrWhiteSpace(l)); return string.Join(Environment.NewLine, lines) is { Length: > 0 } text ? text : toast.Title; } + /// + /// A notification was clicked: the window comes back, and the toast's action runs when the toast allows it and + /// no other notification was shown since the icon appeared (Windows does not say which one was clicked). + /// + internal void OnBalloonClicked() + { + var toast = _shown == 1 ? _latest : null; + _latest = null; + Restore(); + if (toast is not { RunsFromNotification: true, ActionCommand: { } command } || !command.CanExecute(null)) return; + command.Execute(null); + _dismiss(toast); + } + private static bool AnyWindowActive() => Application.Current?.Windows.OfType().Any(w => w.IsActive) ?? false; private IReadOnlyList Menu() => [new(MenuShow, Loc.L("Shell.Tray.Show"))]; @@ -87,16 +106,6 @@ public sealed class OsNotifications : IDisposable _window.Activate(); } - private void OnBalloonClicked() - { - var toast = _latest; - _latest = null; - Restore(); - if (toast?.ActionCommand is not { } command || !command.CanExecute(null)) return; - command.Execute(null); - _dismiss(toast); - } - /// /// Back in front: the notifications have done their job. The icon goes after the current message, since activation /// may come from a click the icon's own window is still handling, unless the window went to the background again. @@ -113,6 +122,7 @@ public sealed class OsNotifications : IDisposable private void RemoveIcon() { _latest = null; + _shown = 0; _tray?.Dispose(); _tray = null; } diff --git a/src/Titano.App/Shell/ShellViewModel.cs b/src/Titano.App/Shell/ShellViewModel.cs index e762d7f7..0cd51a77 100644 --- a/src/Titano.App/Shell/ShellViewModel.cs +++ b/src/Titano.App/Shell/ShellViewModel.cs @@ -291,8 +291,10 @@ public sealed class ShellViewModel : LocalizedViewModel /// /// A one-line notice with one action (job done, update available). marks something that /// did not happen or failed: screen readers then say it at once instead of after what they are reading. + /// : a click on its Windows notification also runs the action (). /// - public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) => + public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false, + bool runsFromNotification = false) => ShowToast(new Toast { Title = title, @@ -301,6 +303,7 @@ public sealed class ShellViewModel : LocalizedViewModel ActionToolTip = actionToolTip, ActionCommand = action is null ? null : new RelayCommand(action), IsError = isError, + RunsFromNotification = runsFromNotification, }); /// Errors are one sentence saying what happened plus one action (BRIEF §0.2 rule 6); the details go to the log. diff --git a/src/Titano.Ui/Controls/Toasts.cs b/src/Titano.Ui/Controls/Toasts.cs index 16f8c33c..f4538890 100644 --- a/src/Titano.Ui/Controls/Toasts.cs +++ b/src/Titano.Ui/Controls/Toasts.cs @@ -22,6 +22,13 @@ public sealed class Toast : ObservableObject /// Something failed: screen readers say it at once, ahead of other notices (assertive, not polite). public bool IsError { get; init; } + + /// + /// A click on the toast's Windows notification also runs its action (it opens what the toast names). Off by + /// default: people click a notification to bring the window back, so a Cancel, Undo or Retry there would act + /// before they have read why. + /// + public bool RunsFromNotification { get; init; } } /// diff --git a/tests/Titano.App.Tests/Jobs/JobNoticesTests.cs b/tests/Titano.App.Tests/Jobs/JobNoticesTests.cs index 69136c59..797ebb88 100644 --- a/tests/Titano.App.Tests/Jobs/JobNoticesTests.cs +++ b/tests/Titano.App.Tests/Jobs/JobNoticesTests.cs @@ -4,7 +4,7 @@ using Titano.Testing; namespace Titano.App.Tests.Jobs; -/// UI-08: which job endings raise the shell's toast, whichever screen started the job. +/// UI-08: which job endings raise the shell's toast, whichever screen started the job, and how a batch speaks once. public sealed class JobNoticesTests { [Theory] @@ -14,6 +14,8 @@ public sealed class JobNoticesTests [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))); @@ -28,26 +30,30 @@ public sealed class JobNoticesTests [Case(JobKind.LightAnalyse)] [Case(JobKind.Thumbs)] [Case(JobKind.Proxies)] - [Case(JobKind.Download)] - public void BackgroundWorkAndScansEndSilently(JobKind kind) + 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))); } - [Test] - public void AnImportSaysOnlyThatItFailed() + [Theory] + [Case(JobKind.Import)] + [Case(JobKind.Download)] + [Case(JobKind.Duplicates)] + [Case(JobKind.Orphans)] + public void EveryOtherFailureIsSaid(JobKind kind) { - // The Import screen announces a finished import with its result. - Assert.Equal(JobNotice.None, JobNotices.For(JobState.Running, Job(JobKind.Import, JobState.Done))); - Assert.Equal(JobNotice.Failed, JobNotices.For(JobState.Running, Job(JobKind.Import, JobState.Failed))); + // 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 runs in the background. + // 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))); @@ -56,6 +62,84 @@ public sealed class JobNoticesTests 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(), diff --git a/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs b/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs index 03771f37..11b19f09 100644 --- a/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs +++ b/tests/Titano.App.Tests/Windows/ShellNotificationTests.cs @@ -8,6 +8,7 @@ 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; @@ -110,6 +111,7 @@ public sealed class ShellNotificationTests 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(); @@ -124,6 +126,7 @@ public sealed class ShellNotificationTests 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); @@ -150,6 +153,37 @@ public sealed class ShellNotificationTests 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] @@ -161,9 +195,12 @@ public sealed class ShellNotificationTests 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" }; + 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"])); @@ -184,6 +221,80 @@ public sealed class ShellNotificationTests 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 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 () => { @@ -244,6 +355,31 @@ public sealed class ShellNotificationTests 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); + }); + /// The Jobs screen read its first page (it would set the job bar and the badge again). private static async Task JobsLoadedAsync(ShellViewModel shell) { @@ -251,6 +387,13 @@ public sealed class ShellNotificationTests Assert.True(shell.Jobs.IsEmpty || shell.Jobs.HasRows, "the job list loaded"); } + /// The window reached (a restore from a notification is a posted system command). + 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(),