fix(reorganize): Apply on the first click, one offer per toast, no open dialog replaced

Review of owner review 2, phase 4a (R7): the Reorganize dialogs of the desktop and the web panel.

Desktop
- Clicking Apply first takes the focus from the template field, which committed it and started
  a dry run identical to the one on screen: Apply turned off under the click. A commit now plans
  only when the templates differ from the shown plan (or the last dry run failed).
- The Settings toast's Reorganize… disposed whatever dialog the Archive screen had open, so a
  running Delete stopped without being asked. An open dialog now stays and its archive is not
  switched; Reorganize says it waits and opens once that dialog closes, with the archive's
  templates read again and every part the toasts offered meanwhile.
- Each Settings toast takes its own archive's offer (one pending offer per archive), and a toast
  gone early (dismissed, pushed out) lets the next change of that archive raise its own toast:
  Toast.Closed now says when a toast leaves the screen.

Web panel
- The Library sends the selected ids up to a thousand. all:true is used only above that, when
  the selection is exactly what Select all fetched without a filter and the archive has not grown
  since, so a sequence unticked or added later is never reorganized; otherwise the toast asks to
  select again.
- The preview's "before" of an untitled sequence is its old name, not the new title twice.
- A dry run of the same request answering during the confirmation no longer drops the confirmed
  apply; a plan that really changed is shown and said (Admin.Reorganize.PlanChanged).
- Enter in a template plans at once (the form never submitted on Enter).
- The confirm tooltip and the module header no longer say the moves are verified: moves and
  renames are not hashed.

Strings in en and it; the reworded key exists in no other culture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit bed718fb5af2ef69943fd348690c689259872a34)
This commit is contained in:
Alby96 committed 2026-10-27 16:30:01 +01:00
1 parent 9ae773aa5a
commit 59ee982e4d
14 files changed
+301 -49

No files matched your search

@@ -3,7 +3,12 @@ using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.App.Archiving;
using Chronos.App.DesignTime;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Tests.Import;
using Chronos.App.Tests.Uploader;
using Chronos.App.Tests.Windows;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
@@ -12,6 +17,7 @@ using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Archiving;
@@ -110,16 +116,73 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.True(offer.Add(main, ReorganizeParts.Folders, now), "the first change raises the toast");
var saved = main with { FileTemplate = "{date}_{n:000}" };
Assert.False(offer.Add(saved, ReorganizeParts.Files, now.AddSeconds(5)), "a change while it is up joins it");
Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(), "both templates, the archive as saved last");
Assert.Null(offer.Take(), "a second toast of the same offer finds it taken");
Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(main.Id), "both templates, the archive as saved last");
Assert.Null(offer.Take(main.Id), "a second toast of the same offer finds it taken");
Assert.True(offer.Add(main, ReorganizeParts.Folders, now.AddSeconds(6)), "once taken, the next change raises a toast again");
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(7)), "another archive has its own toast");
Assert.Equal((other, ReorganizeParts.Files), offer.Take());
Assert.Equal((other, ReorganizeParts.Files), offer.Take(other.Id));
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(8)));
Assert.True(offer.Add(other, ReorganizeParts.Folders, now.AddSeconds(17)), "the toast is gone: a new one");
// Each toast takes its own archive's offer: the older toast of Main opens Main, not the Other changed since.
Assert.Equal((main, ReorganizeParts.Folders), offer.Take(main.Id));
Assert.Equal((other, ReorganizeParts.Files | ReorganizeParts.Folders), offer.Take(other.Id), "Other's offer stayed for its own toast");
Assert.Null(offer.Take(main.Id));
}
[Test]
public void AToastGoneEarlyLetsTheNextChangeRaiseItsOwn()
{
var main = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive" };
var offer = new ReorganizeOffer(TimeSpan.FromSeconds(8));
var now = new DateTime(2026, 10, 27, 9, 0, 0, DateTimeKind.Utc);
Assert.True(offer.Add(main, ReorganizeParts.Folders, now));
offer.Closed(main.Id, now);
Assert.True(offer.Add(main, ReorganizeParts.Files, now.AddSeconds(2)), "dismissed after a second: the next change has a toast of its own");
Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(3)), "and joins it while it is up");
offer.Closed(main.Id, now);
Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(4)), "an older toast leaving changes nothing for the one up");
Assert.Equal((main, ReorganizeParts.Folders | ReorganizeParts.Files | ReorganizeParts.Titles), offer.Take(main.Id),
"the toast up offers every change since the last one taken");
offer.Closed(main.Id, now.AddSeconds(2));
Assert.Null(offer.Take(main.Id), "the toast closing after its action finds nothing to keep");
}
/// <summary>
/// The toasts' host says when a toast leaves the screen, as Settings › Archive needs to know whether its offer is still
/// up: dismissed, pushed out by three newer ones, timed out or closed by its action, once each.
/// </summary>
[Test]
[WindowsOnly]
public void AToastLeavingTheScreenSaysSoOnce() => WpfApplication.Dispatcher.Invoke(() =>
{
var host = new ToastHost();
var closed = new List<string>();
Toast Show(string title)
{
var toast = new Toast { Title = title };
toast.Closed += (_, _) => closed.Add(title);
host.Show(toast);
return toast;
}
var first = Show("first");
var second = Show("second");
host.Dismiss(second);
host.Dismiss(second);
Assert.SequenceEqual(["second"], closed, "dismissed, once");
Show("third");
Show("fourth");
Assert.Empty(closed.Skip(1), "three on screen");
Show("fifth");
Assert.SequenceEqual(["second", "first"], closed, "the oldest pushed out by a fourth");
host.Dismiss(first);
Assert.Count(2, closed, "a toast gone already says nothing");
foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
});
[Test]
public async Task SwitchesChooseTheTemplatesAndApplyQueuesExactlyThatPlan()
{
@@ -182,14 +245,24 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.Null(plan.FileTemplate);
Assert.True(dialog.ApplyCommand.CanExecute(null));
// Typing again: Apply waits for the dry run of what is on screen.
// Typing again: Apply waits for the dry run of what is on screen; Enter plans it at once.
dialog.Folders.Field.Text = "{year}/{date} {title}";
Assert.Null(dialog.Plan);
Assert.False(dialog.ApplyCommand.CanExecute(null));
Assert.True(dialog.Folders.Field.Commit());
Assert.Equal(Loc.L("Archive.Reorganize.Planning"), dialog.BusyText, "a template changed since its dry run plans without waiting for the typing to pause");
dialog.Folders.Field.Text = "{year}/{date}";
await dialog.PlanAsync();
plan = Assert.NotNull(dialog.Plan);
// A click on Apply takes the focus from the field first, which commits it: the dry run on screen is of that text
// already, so no other one starts and Apply stays on under the click.
Assert.True(dialog.Folders.Field.IsDirty, "typed, not committed");
Assert.True(dialog.Folders.Field.Commit());
Assert.Same(plan, dialog.Plan);
Assert.Null(dialog.BusyText);
Assert.True(dialog.ApplyCommand.CanExecute(null));
dialog.ApplyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
await UntilAsync(() => closed);
@@ -218,6 +291,76 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.True(Directory.Exists(Path.Combine(archive.RootPath, "2026", "2026-09-28")));
}
/// <summary>
/// The Settings toast's Reorganize… is reached from another screen while the Archive screen may have a dialog open (a
/// Delete moving sequences, the trash): that dialog is neither replaced nor stopped. Reorganize says it waits, and
/// opens once that dialog closes, on every sequence with every part the toasts offered meanwhile.
/// </summary>
[Test]
[WindowsOnly]
public void TheToastsReorganizeWaitsForTheDialogOpenOnTheArchiveScreen()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var environment = AppEnvironment.ForCapture();
try
{
SingleThreadedContext.Run(async () =>
{
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
await sample.OpenEmptyAsync();
await sample.FillAsync();
var shell = new ShellViewModel(services);
try
{
var toasts = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
var screen = shell.Archive;
await screen.LoadAsync();
var archive = Assert.NotNull(screen.SelectedArchive);
await screen.OpenTrashAsync();
var trash = Assert.NotNull(screen.Dialog as TrashDialogViewModel);
await screen.OpenReorganizeAllAsync(archive with { FileTemplate = "{date}_{n:0000}" }, ReorganizeParts.Files);
await screen.OpenReorganizeAllAsync(archive, ReorganizeParts.Folders);
Assert.Same(trash, screen.Dialog);
Assert.Equal(Loc.L("Archive.Reorganize.Waiting"), toasts[^1].Title);
trash.CloseCommand.Execute(null);
await UntilAsync(() => screen.Dialog is ReorganizeDialogViewModel);
var reorganize = (ReorganizeDialogViewModel)screen.Dialog!;
await UntilAsync(() => reorganize.BusyText is null);
Assert.Null(reorganize.ErrorText);
Assert.Equal(Loc.L("Archive.Reorganize.HeadingAll", archive.Name), reorganize.Heading);
Assert.True(reorganize.Folders.IsEnabled, "the parts of both toasts");
Assert.True(reorganize.Files.IsEnabled);
Assert.False(reorganize.Titles.IsEnabled);
Assert.Equal(archive.FileTemplate, reorganize.Files.Field.Text, "the archive's templates as the index holds them when it opens");
reorganize.CloseCommand.Execute(null);
Assert.Null(screen.Dialog);
}
finally
{
shell.Dispose();
await services.DisposeAsync();
}
});
}
finally
{
environment.DeleteCaptureData();
}
}
/// <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>Uploads two photos ten seconds apart into a new sequence filed with the archive's templates; returns its id.</summary>
private async Task<Guid> UploadAsync(ArchiveService archives, Core.Model.Archive archive, string key, DateTime start, int seed)
{
@@ -32,9 +32,12 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.Contains(@"from ""../reorganize.js""", library);
Assert.Contains(@"data-mass=""reorganize"" data-i18n=""Admin.Reorganize.Action"" data-i18n-title=""Admin.Reorganize.Action.Tip""", library);
Assert.Contains(@"if (action === ""reorganize"") return reorganize();", library);
// The selection: every sequence after Select all without a filter, else the ids (one request takes a thousand).
Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }", library);
Assert.Contains("selection.size > BULK_LIMIT", library);
// The selection: its ids up to a thousand (one request); beyond, every sequence only while the selection is exactly
// what Select all fetched without a filter, the archive no larger since; a sequence unticked or added is never in it.
Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }", library);
Assert.Contains("const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&", library);
Assert.Contains("ids.length === matching.length && matching.every((s) => selection.has(s.id));", library);
Assert.Contains("if (!everything && ids.length > BULK_LIMIT) {", library);
var archive = await server.Client.GetStringAsync("/admin/pages/archive.js");
Assert.Contains(@"from ""../reorganize.js""", archive);
Assert.Contains("target: { all: true }", archive);
@@ -56,6 +59,16 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.Contains("api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint })", dialog);
Assert.Contains("#/jobs?job=", dialog);
Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler");
// Enter in a template plans at once: a form of three fields and no submit button never submits on Enter.
Assert.Contains(@"form.addEventListener(""keydown"", (e) => {", dialog);
Assert.Contains(@"if (e.key !== ""Enter"" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === ""checkbox"") return;", dialog);
// An untitled sequence that gets a title reads by its old name before, never by the new title twice.
Assert.Contains("const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);", dialog);
Assert.Contains(@"change(before, toTitle ?? before, ""auto"")", dialog);
// A dry run answering during the confirmation: the same plan is applied, a different one is shown and said.
Assert.Contains("if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {", dialog);
Assert.Contains(@"showError(t(""Admin.Reorganize.PlanChanged""))", dialog);
Assert.True(!dialog.Contains("plan !== chosen) return;", StringComparison.Ordinal), "a confirmed apply is dropped when the same plan is answered again");
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
@@ -65,6 +78,10 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
}
Assert.Equal("Riorganizza…", it["Admin.Reorganize.Action"]);
// The job renames and moves; nothing in it hashes a file again, so nothing says it verifies them.
Assert.False(en["Admin.Reorganize.Confirm.Tip"].Contains("verif", StringComparison.OrdinalIgnoreCase), en["Admin.Reorganize.Confirm.Tip"]);
Assert.False(it["Admin.Reorganize.Confirm.Tip"].Contains("verific", StringComparison.OrdinalIgnoreCase), it["Admin.Reorganize.Confirm.Tip"]);
Assert.False(Regex.IsMatch(dialog, @"^//.*\bverified\b", RegexOptions.Multiline), "the header says the moves are verified");
}
[Test]