Files
Chronos/tests/Chronos.App.Tests/Archive/ReorganizeDialogTests.cs
T
Alby96 59ee982e4d 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)
2026-10-27 16:30:01 +01:00

406 lines
22 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.Globalization;
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;
using Chronos.Data;
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;
/// <summary>
/// Reorganize… (owner review 2, R7): each template with its switch, the dry run listed sequence by sequence, and Apply
/// queuing the job of exactly the plan on screen, which the job then applies.
/// </summary>
public sealed class ReorganizeDialogTests(TestContext context)
{
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
[Test]
public void EachTemplateIsCheckedAsItsPartIsNamed()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Folders, "{year}/{date} {title}"));
Assert.NotNull(ReorganizePlans.Validate(ReorganizeParts.Folders, "{nope}"));
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Files, "{date}_{n:000}"));
Assert.Equal(Loc.L("Errors.Template.FileSeparator"), ReorganizePlans.Validate(ReorganizeParts.Files, "{year}/{n}"), "a file name has no folder");
Assert.Equal(Loc.L("Errors.Template.NotUnique"), ReorganizePlans.Validate(ReorganizeParts.Files, "{date}"), "file names tell the photos apart");
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Titles, "{title} · {camera}"));
Assert.Null(ReorganizePlans.Validate(ReorganizeParts.Titles, "{date}"), "every photo of a sequence shares its title");
Assert.NotNull(ReorganizePlans.Validate(ReorganizeParts.Titles, "{title"));
foreach (var part in new[] { ReorganizeParts.Folders, ReorganizeParts.Files, ReorganizeParts.Titles })
Assert.Equal(Loc.L("Errors.Template.Empty", string.Empty, 1), ReorganizePlans.Validate(part, " "), part.ToString());
}
[Test]
public void TheDryRunIsListedSequenceBySequence()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var moved = new RenameStep(Guid.CreateVersion7(), "2026/Harbour", "2026/2026-09-28 Harbour", "Harbour", "Harbour sunset")
{
FramesVersion = 3,
FileChanges = 120,
FileSamples =
[
new FileRename(Guid.CreateVersion7(), "originals/IMG_0001.JPG", "originals/Harbour sunset_001.JPG"),
new FileRename(Guid.CreateVersion7(), "originals/IMG_0002.JPG", "originals/Harbour sunset_002.JPG"),
],
Blocked = [new RenameBlocked(RenameBlock.Unhashed, 12)],
};
var carried = new RenameStep(Guid.CreateVersion7(), "2026/Harbour/Night", "2026/2026-09-28 Harbour/Night", null, null, Carried: true);
var kept = new RenameStep(Guid.CreateVersion7(), "2025/Comet", "2025/Comet", "Comet", "Comet") { Blocked = [new RenameBlocked(RenameBlock.Unreadable, 0)] };
var plan = new RenamePlan(Guid.CreateVersion7(), Guid.CreateVersion7(), [moved, kept, carried])
{
FileTemplate = "{title}_{n:000}",
Subjects = [moved.SequenceId, kept.SequenceId],
};
var rows = ReorganizePlans.Rows(plan);
Assert.Count(3, rows);
var first = rows[0];
Assert.Equal("Harbour sunset", first.Name);
Assert.False(first.IsNamePath, "a title reads in the language's direction");
Assert.Equal(Loc.Plural("Archive.Reorganize.Renamed", 120), first.Note);
Assert.SequenceEqual(
[
$"{Loc.L("Archive.Reorganize.Folder")}|2026/Harbour|2026/2026-09-28 Harbour|True",
$"{Loc.L("Archive.Reorganize.Title")}|Harbour|Harbour sunset|False",
$"{Loc.L("Archive.Reorganize.File")}|originals/IMG_0001.JPG|originals/Harbour sunset_001.JPG|True",
$"{Loc.L("Archive.Reorganize.File")}|originals/IMG_0002.JPG|originals/Harbour sunset_002.JPG|True",
],
first.Lines.Select(l => $"{l.Label}|{l.From}|{l.To}|{l.IsPath}"));
Assert.SequenceEqual([Loc.L("Archive.Reorganize.Blocked.Unhashed") + Loc.Separator + Loc.Plural("Shell.Status.Photos", 12)], first.Kept);
Assert.Contains(Loc.L("Archive.Reorganize.Change", Loc.L("Archive.Reorganize.Folder"), "2026/Harbour", "2026/2026-09-28 Harbour"), first.Description);
Assert.Contains(first.Kept[0], first.Description);
var comet = rows[1];
Assert.Empty(comet.Lines, "nothing of it changes");
Assert.SequenceEqual([Loc.L("Archive.Reorganize.Blocked.Unreadable")], comet.Kept, "an unreadable sidecar has no photo count");
Assert.False(comet.HasNote);
var night = rows[2];
Assert.Equal("2026/2026-09-28 Harbour/Night", night.Name, "without a title, the row is named by its folder");
Assert.True(night.IsNamePath);
Assert.Equal(Loc.L("Archive.Reorganize.Carried"), night.Note);
// A sequence carried along is listed, not counted; the names kept are the photos', not the sequences'.
Assert.Equal(1, ReorganizePlans.Changed(plan));
Assert.Equal(string.Join(Loc.Separator, Loc.Plural("Archive.Rename.Summary", 1, 2), Loc.Plural("Archive.Reorganize.Renamed", 120),
Loc.Plural("Archive.Reorganize.Kept", 12)), ReorganizePlans.Summary(plan, 2));
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 1, 2), ReorganizePlans.Summary(plan with { FileTemplate = null, Steps = [moved with { Blocked = [] }] }, 2),
"no file template, no file count; nothing kept, nothing said");
}
[Test]
public void TemplatesChangedWhileTheToastIsUpJoinItsOffer()
{
var main = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive" };
var other = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Other", RootPath = "/other" };
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), "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(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(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()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var directory = context.CreateTempDirectory("reorganize-dialog");
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")), context.Cancellation);
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Main", cancellationToken: context.Cancellation);
var harbour = await UploadAsync(archives, archive, "harbour", Start, 1);
var comet = await UploadAsync(archives, archive, "comet", Start.AddDays(1), 11);
var (before, title) = (await db.Sequences.GetAsync(harbour)) is { } filed ? (filed.Folder, filed.Title ?? string.Empty) : default;
var queued = new TaskCompletionSource<ArchiveJobRequest>(TaskCreationOptions.RunContinuationsAsynchronously);
var closed = false;
using var dialog = new ReorganizeDialogViewModel(archives, archive, [harbour, comet], ReorganizePlans.Layout, request =>
{
queued.TrySetResult(request);
return Task.CompletedTask;
}, _ => closed = true);
// From the mass bar: the archive's layout, folders and file names, prefilled from its settings.
Assert.True(dialog.Folders.IsEnabled);
Assert.True(dialog.Files.IsEnabled);
Assert.False(dialog.Titles.IsEnabled);
Assert.Equal(new RenameTemplates(archive.FolderTemplate, archive.FileTemplate), dialog.Current());
Assert.Equal(Loc.Plural("Archive.Reorganize.Heading", 2), dialog.Heading);
await dialog.PlanAsync();
Assert.Empty(dialog.Rows, "photos filed with the archive's templates already follow them");
Assert.Equal(Loc.L("Archive.Blocked.NoChanges"), dialog.ApplyToolTip);
Assert.False(dialog.ApplyCommand.CanExecute(null));
// A template switched off neither counts nor blocks with its errors; switched on, its error does.
dialog.Titles.Field.Text = "{title";
Assert.Null(dialog.Titles.Error);
Assert.Null(dialog.Current()!.Title);
dialog.Titles.IsEnabled = true;
Assert.NotNull(dialog.Titles.Error);
Assert.Null(dialog.Current());
Assert.Equal(dialog.Titles.Error, dialog.ApplyToolTip);
dialog.Titles.IsEnabled = false;
dialog.Folders.IsEnabled = false;
dialog.Files.IsEnabled = false;
Assert.Null(dialog.Current());
Assert.Equal(Loc.L("Archive.Blocked.NoTemplate"), dialog.ApplyToolTip);
Assert.False(dialog.ApplyCommand.CanExecute(null));
dialog.Folders.IsEnabled = true;
dialog.Folders.Field.Text = "{year}/{date}";
dialog.Titles.Field.Text = "Shoot {date}";
dialog.Titles.IsEnabled = true;
Assert.Equal(Loc.L("Archive.Blocked.Planning"), dialog.ApplyToolTip, "the dry run on screen is not the one of the templates typed");
await dialog.PlanAsync();
var plan = Assert.NotNull(dialog.Plan);
Assert.Count(2, dialog.Rows);
var row = dialog.Rows.Single(r => r.SequenceId == harbour);
Assert.Equal("Shoot 2026-09-28", row.Name);
Assert.SequenceEqual([$"{before}>2026/2026-09-28", $"{title}>Shoot 2026-09-28"], row.Lines.Select(l => $"{l.From}>{l.To}"), "folders and titles, no file names");
Assert.Equal(Loc.Plural("Archive.Rename.Summary", 2, 2), dialog.SummaryText);
Assert.Null(plan.FileTemplate);
Assert.True(dialog.ApplyCommand.CanExecute(null));
// 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);
Assert.Equal(JobKind.Move, request.Kind);
Assert.SequenceEqual([archive.Id], request.Targets);
Assert.Equal(archive.Name, request.Label);
Assert.Equal(JobPriority.User, request.Priority);
using (var parameters = JsonDocument.Parse(request.ParametersJson!))
{
var json = parameters.RootElement;
Assert.Equal("{year}/{date}", json.GetProperty("folderTemplate").GetString());
Assert.Equal("Shoot {date}", json.GetProperty("titleTemplate").GetString());
Assert.False(json.TryGetProperty("fileTemplate", out var file) && file.ValueKind != JsonValueKind.Null, "the file names were switched off");
Assert.Equal(plan.Fingerprint(), json.GetProperty("fingerprint").GetString());
}
Assert.Equal(before, (await db.Sequences.GetAsync(harbour))!.Folder, "the job reorganizes, not the dialog");
// The job applies the plan the dialog showed.
await using var engine = new JobEngine(db, archives.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(request, cancellationToken: context.Cancellation);
await WaitForAsync(db, job.Id);
var after = (await db.Sequences.GetAsync(harbour))!;
Assert.Equal(("2026/2026-09-28", "Shoot 2026-09-28"), (after.Folder, after.Title));
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)
{
Guid id = default;
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
Directory.CreateDirectory(staging);
for (var i = 0; i < 2; i++)
{
var bytes = ImportTestData.Jpeg(start.AddSeconds(10 * i), seed + i);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, bytes, context.Cancellation);
var request = new IngestRequest(archive.Id, null, null, key, path, $"IMG_{seed + i:0000}.JPG", bytes.Length, Convert.ToHexStringLower(SHA256.HashData(bytes)),
null, null);
id = (await archives.Ingest.CommitAsync(request, context.Cancellation)).SequenceId;
}
return id;
}
private async Task WaitForAsync(ChronosDatabase db, Guid jobId)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(30));
Job? job = null;
while (DateTime.UtcNow < until)
{
job = await db.Jobs.GetAsync(jobId, context.Cancellation);
if (job?.State == JobState.Done) return;
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"The reorganize job ended {job.State}: {job.Error}\n{job.LogTail}");
await Task.Delay(20, context.Cancellation);
}
Assert.Fail($"The reorganize job did not finish (now {job?.State}).");
}
private static async Task UntilAsync(Func<bool> condition)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (!condition())
{
Assert.True(DateTime.UtcNow < until, "timed out");
await Task.Delay(20);
}
}
}