feat(copies): matches between this PC and the server, Integrate and merge (owner review 6, v1.2.0) (#74)
CI / Build and test (push) Successful in 13m44s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 16s
Release / Build, test and publish (push) Successful in 26m34s
CI / PostgreSQL 16 integration (push) Failing after 17m36s
CI / PostgreSQL 17 integration (push) Failing after 15m36s
CI / Docker image (push) Successful in 1m12s
Release / Server image (push) Failing after 15s

The same time-lapse on a server and on this PC under different ids, or twice on this PC, is recognised,
compared and settled as the owner asked in owner review 6.

Matches are found after each sync refresh, through the server's new photo lookup, and after the jobs that
change photos. The default is to ask every time. Server › Matches offers:
- Keep apart, which is remembered;
- Link only and Unlink;
- the Compare dialog: photos, details line by line, projects and the plan.

Integrate completes both sides. Photos default to Union, projects are copied across, and a losing version
goes to the trash only after a hash check. Afterwards new photos move by themselves, and deletions wait for
the user.

A merge of two local sequences verifies every photo before the other sequence goes to its archive's trash.
Upload all local skips suspected matches and flags them.

Migration 0012 adds the found_copies and copy_probes tables. Jobs 25 (Integrate) and 26 (MergeSequences) are
new, and so are the server capabilities photo-lookup and upload-into.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #74.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-18 15:20:29 +01:00
1 parent 43719bb5c5
commit f33bcac32e
586 files changed
+41546 -280

No files matched your search

@@ -0,0 +1,619 @@
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Media;
using Chronos.App.DesignTime;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Sections;
using Chronos.App.Server;
using Chronos.App.Server.Copies;
using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Server;
/// <summary>
/// Server › Matches on the capture sample pairs (owner review 6, #73): the list and its chip, the Compare dialog in the
/// window, its plan and blocks, the confirmations, the Library's match cards and the Settings rows.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class CopyScreenSmokeTests
{
[Test]
public Task TheMatchesListOrdersThePairsAndEveryActionSaysWhatItDoes() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var table = shell.Server.Sync;
var list = table.Copies;
await CopyScenes.ShowAsync(shell, "server-copies");
Assert.True(table.IsMatches);
Assert.True(table.ShowCopyList, "the Matches list replaces the sync table");
Assert.GreaterOrEqual(list.Count, 5);
Assert.Equal(list.Count, table.Chips.Single(c => c.Filter == SyncFilter.FoundCopies).Count);
Assert.True(list.AttentionCount > 0);
// Pairs that ask for a choice come first.
Assert.True(list.Rows[0].IsConflict);
Assert.True(list.Rows.SkipWhile(r => r.IsConflict).All(r => !r.IsConflict), "attention first, then the rest");
foreach (var row in list.Rows)
{
Assert.False(string.IsNullOrWhiteSpace(row.StateToolTip), $"{row.Title}: the state has a tooltip");
foreach (var action in row.Actions)
{
Assert.False(string.IsNullOrWhiteSpace(action.ToolTip), $"{row.Title}: {action.Text} has a tooltip");
Assert.LessOrEqual(action.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"\"{action.Text}\" is at most three words");
}
}
var lighthouse = list.Rows.Single(r => r.Title == CopyScenes.Lighthouse);
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Integrate, CopyAction.KeepApart], lighthouse.Actions.Select(a => a.Action));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Merge, CopyAction.KeepApart],
list.Rows.Single(r => r.Title == CopyScenes.Alps).Actions.Select(a => a.Action));
await app.ExpectAsync<ServerView>("server-copies");
// The search narrows the pairs, by either title.
table.SearchText = "Alps";
Assert.Count(1, list.Rows);
table.SearchText = string.Empty;
// The sync table marks the sequence of an unanswered pair and offers Compare… first.
table.ShowFilter(SyncFilter.All);
var marked = table.Rows.First(r => r.Title == CopyScenes.Lighthouse);
Assert.Equal(Loc.L("Server.Sync.State.CopyFound"), marked.StateText);
Assert.Equal(SyncAction.Compare, marked.Actions[0].Action);
// A match the server deleted: the local row offers what the Matches row does (design §6.3), each with a tooltip.
await CopyScenes.ShowAsync(shell, "server-copies-gone");
var gone = table.Rows.Single(r => r.Title == "Garden 2026");
Assert.SequenceEqual([SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash], gone.Actions.Select(a => a.Action));
foreach (var action in gone.Actions)
{
Assert.False(string.IsNullOrWhiteSpace(action.ToolTip), $"{action.Text} has a tooltip");
Assert.Equal(Loc.L("Server.Copies.Action." + action.Action), action.Text);
}
CopyScenes.Reset(shell);
});
[Test]
public Task TheCompareDialogWaitsForTheDetailsAndConfirmsWhatItReplaces() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var server = shell.Server;
var list = server.Sync.Copies;
await CopyScenes.ShowAsync(shell, "server-copies");
// Integrate… opens on the details while one waits for a choice.
var pair = list.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
var dialog = Assert.NotNull(list.Open(pair, CopyDialogPart.Plan, integrate: true));
await dialog.LoadAsync();
Assert.True(server.IsDialogOpen);
Assert.False(server.IsContentEnabled, "the screen behind the dialog takes no input");
Assert.Equal(CopyDialogPart.Details, dialog.Part);
Assert.Equal(3, dialog.Unchosen);
await app.ExpectAsync<ServerView>("server-copies-details");
// The footer: one primary action, Cancel answers Esc; both say what they do.
var cancel = app.FindAll<Button>().Single(b => b.IsVisible && b.IsCancel);
Assert.Equal(Loc.L("Tooltips.Server.Copies.Cancel"), cancel.ToolTip);
Assert.Contains(app.FindAll<Button>(), b => b.IsVisible && b.Content as string == dialog.ApplyText && b.ToolTip is not null);
// The plan is blocked until every detail is chosen; the block line offers Choose.
dialog.Part = CopyDialogPart.Plan;
await dialog.PlanNowAsync();
var block = Assert.Contains(dialog.Blocks, b => b.Block == CopyBlock.DetailsUnchosen);
Assert.True(block.HasChoose);
Assert.False(dialog.ApplyCommand.CanExecute(null));
Assert.Equal(block.Text, dialog.ApplyToolTip);
dialog.AllHereCommand.Execute(null);
Assert.Equal(0, dialog.Unchosen);
await dialog.PlanNowAsync();
Assert.False(dialog.Blocks.Any(b => b.Block == CopyBlock.DetailsUnchosen), "every detail chosen");
Assert.True(dialog.ApplyCommand.CanExecute(null));
Assert.NotEmpty(dialog.HereLines);
await app.ExpectAsync<ServerView>("server-copies-plan");
// This PC's version wins: the server's versions go to its trash, so the confirmation is destructive.
dialog.Policy = dialog.Policies.First(o => o.Value == CopyPhotoPolicy.ThisPcWins);
await dialog.PlanNowAsync();
var replace = dialog.ReplaceRequest(Assert.NotNull(dialog.Plan));
Assert.True(replace.IsDestructive);
Assert.Equal(Loc.L("Server.Copies.Confirm.Replace.Title"), replace.Heading);
// Cancel closes the dialog and gives the screen back.
dialog.CloseCommand.Execute(null);
Assert.False(server.IsDialogOpen);
Assert.True(server.IsContentEnabled);
// A local pair merges into the kept copy, preselected; the confirmation asks for the dropped photo count.
var merge = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-merge"));
Assert.True(merge.IsMerge);
Assert.Count(2, merge.KeepOptions);
Assert.Count(1, merge.KeepOptions.Where(o => o.IsChecked));
merge.AllHereCommand.Execute(null);
await merge.PlanNowAsync();
var plan = Assert.NotNull(merge.MergePlan);
var request = merge.MergeRequest(plan);
Assert.True(request.IsDestructive);
var dropped = list.Pairs.Single(p => p.Here.Title == CopyScenes.Alps) is var alps && plan.KeepId == alps.Copy.LocalId ? alps.There : alps.Here;
Assert.Equal(dropped.Photos.ToString(System.Globalization.CultureInfo.InvariantCulture), request.TypedConfirmation);
Assert.Contains(request.TypedConfirmation!, request.TypedPrompt!);
// Its first line is the dropped sequence's fact, not a photo held elsewhere.
Assert.False(request.Detail!.StartsWith(Loc.L("Server.Copies.Confirm.Elsewhere", string.Empty).Trim(), StringComparison.Ordinal),
"a merge's facts carry no Held elsewhere prefix");
await app.ExpectAsync<ServerView>("server-copies-merge");
// Choose on "choose the sequence to keep" takes the keyboard to the first Kept radio of the Plan part.
merge.Part = CopyDialogPart.Plan;
var view = app.FindAll<ServerView>().First(v => v.IsVisible);
for (var i = 0; i < 80 && ServerView.FirstKeepOption(view) is null; i++)
{
view.UpdateLayout();
await Task.Delay(25);
}
Assert.NotNull(ServerView.FirstKeepOption(view), "the Kept sequence radios are on the Plan part");
CopyScenes.Reset(shell);
Assert.False(server.IsDialogOpen);
});
[Test]
public Task AMergeKeepingThePairsOtherCopyShowsItFirstAndKeepsItsValues() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var merge = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-merge"));
Assert.Equal(Loc.L("Server.Copies.Detail.AllKept"), merge.AllHereText);
Assert.Equal(Loc.L("Server.Copies.Detail.AllOther"), merge.AllThereText);
Assert.True(merge.Details.Count > 0, "the Alps pair has details that differ");
// Kept: the pair's other sequence. Its values move to the first column, and "kept" stays the kept one's.
merge.KeepOptions.Single(o => o.SequenceId == merge.Copy.OtherId).IsChecked = true;
var detail = merge.Details[0];
Assert.Equal(detail.Line.There ?? Loc.L("Server.Sync.None"), detail.HereToolTip);
Assert.Equal(detail.Line.Here ?? Loc.L("Server.Sync.None"), detail.ThereToolTip);
// The segments say what choosing them does, with the worded value each takes, not the raw value.
Assert.Equal(Loc.L("Tooltips.Server.Copies.Detail.UseKept", detail.HereText), detail.HereChoiceToolTip);
Assert.Equal(Loc.L("Tooltips.Server.Copies.Detail.UseOther", detail.ThereText), detail.ThereChoiceToolTip);
detail.ChoiceIndex = 0;
await merge.PlanNowAsync();
var plan = Assert.NotNull(merge.MergePlan);
Assert.Equal(CopySide.ThisPc, plan.Choices.Details[detail.Path]);
CopyScenes.Reset(shell);
});
[Test]
public Task EditsPickerMarksAProjectWhoseTimeLapseHasATwin() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
// A workspace project of this PC: the sample reads it as a linked pair's, with a project on the server.
var id = await app.Sample.FillEditorAsync();
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
Assert.Contains(CopyScenes.Views, v => v == "edit-picker-twins");
await CopyScenes.ShowAsync(shell, "edit-picker-twins");
var twin = Assert.Contains(shell.Sequence.Picker.WorkspaceItems, i => i.HasTwin);
Assert.False(string.IsNullOrWhiteSpace(twin.TwinToolTip), "the Twin chip says where the other project is");
await app.ExpectAsync<SequenceView>("edit-picker-twins", waitForThumbnails: true);
CopyScenes.Reset(shell);
});
[Test]
public Task ManyProjectsScrollInsideTheDialog() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var dialog = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-projects-many"));
Assert.True(dialog.IsProjects);
Assert.Equal((CopyScenes.ManyProjects, CopyScenes.ManyProjects), (dialog.HereProjects.Count, dialog.ThereProjects.Count));
await app.ExpectAsync<ServerView>("server-copies-projects-many");
// Both lists sit in one scroll viewer that holds more than it shows: the dialog's footer stays in view.
var scroll = Assert.Contains(app.FindAll<ScrollViewer>(), s => s.IsVisible && s.ScrollableHeight > 0
&& s.Content is Grid grid && grid.Children.OfType<ItemsControl>().Count() == 2);
Assert.True(scroll.ViewportHeight > 0);
// Each heading shares its list's column, so the scroll bar never moves a list off its heading.
var lists = ((Grid)scroll.Content).Children.OfType<ItemsControl>().ToList();
var headings = ((Grid)scroll.Content).Children.OfType<TextBlock>().ToList();
Assert.Count(2, headings);
for (var i = 0; i < 2; i++)
{
var window = Window.GetWindow(scroll);
Assert.Approximately(lists[i].TranslatePoint(new Point(0, 0), window).X, headings[i].TranslatePoint(new Point(0, 0), window).X, 0.5,
$"heading {i} starts where its list does");
}
// The sample pair has its own projects back for the other scenes.
var lighthouse = shell.Server.Sync.Copies.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
Assert.Equal(2, (await shell.Services.Sync.Copies!.CompareAsync(lighthouse.Copy.Id, null, CancellationToken.None)).Projects.Here.Count);
CopyScenes.Reset(shell);
});
[Test]
public Task TheLibraryAndSettingsShowTheMatches() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
// A card in a pair that asks for a choice carries the match status and offers Compare….
await LibraryScenes.ShowCopiesAsync(shell, CopyScenes.Alps);
var item = Assert.Contains(shell.Library.Items, i => i.HasMatch && i.Title == CopyScenes.Alps);
Assert.NotNull(item.MatchStatus);
// Second, right after the analysis status, so a narrow card cuts the others first.
Assert.Equal(item.MatchStatus, item.Statuses[1]);
Assert.True(shell.Library.CompareItemCommand.CanExecute(item));
// A refresh builds new cards: the match status stays on them.
await shell.Library.RefreshAsync();
item = Assert.Contains(shell.Library.Items, i => i.HasMatch && i.Title == CopyScenes.Alps);
Assert.NotNull(item.MatchStatus);
await app.ExpectAsync<LibraryView>("library-copies", waitForThumbnails: true);
// Two versions… lists the photos the sequence keeps in two versions (a Union merge's), here none, and says so.
Assert.True(shell.Library.VersionsItemCommand.CanExecute(item));
await shell.Library.ShowVersionsAsync(item.Id);
var versions = Assert.NotNull(shell.Library.Dialog as VersionsDialogViewModel);
Assert.True(versions.IsEmpty && !versions.HasRows);
Assert.Contains(CopyScenes.Alps, versions.Heading);
versions.CloseCommand.Execute(null);
Assert.Null(shell.Library.Dialog);
shell.Library.CompareItemCommand.Execute(item);
Assert.Equal(SectionKey.Server, shell.Current.Key);
Assert.True(shell.Server.Sync.IsMatches);
Assert.Equal(CopyScenes.Alps, shell.Server.Sync.SearchText);
CopyScenes.Reset(shell);
// Settings › Server: three rows, every option with its tooltip, each choice saved at once.
var rows = shell.Settings.CopyRows;
foreach (var option in rows.LinkingOptions.Cast<object>().Concat(rows.PhotoOptions).Concat(rows.ProjectOptions))
{
var (label, tip) = option switch
{
SettingsOption<CopyLinking> o => (o.Label, o.ToolTip),
SettingsOption<CopyPhotoPolicy> o => (o.Label, o.ToolTip),
SettingsOption<CopyProjects> o => (o.Label, o.ToolTip),
_ => (string.Empty, null),
};
Assert.False(string.IsNullOrWhiteSpace(tip), $"{label} has a tooltip");
Assert.LessOrEqual(label.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"\"{label}\" is at most three words");
}
rows.Linking = rows.LinkingOptions.First(o => o.Value == CopyLinking.WhenIdentical);
Assert.Equal(CopyLinking.WhenIdentical, shell.Services.Settings.CopyLinking);
shell.Navigate(SectionKey.Settings);
shell.Settings.Page = SettingsPage.Server;
await app.ExpectAsync<SettingsView>("settings-server");
Assert.Contains(app.FindAll<ComboBox>(), c => c.IsVisible && Equals(c.SelectedItem, rows.Linking) && c.ToolTip is not null);
});
[Test]
public Task TheDialogStartsFromTheSettingsAndChooseEachPreselectsNothing() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var settings = shell.Services.Settings;
var list = shell.Server.Sync.Copies;
var pair = list.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
var (photos, projects) = (settings.CopyPhotos, settings.CopyProjects);
try
{
// Owner review 6 (#73): the dialog opens on Settings › Server's choices, whatever they are.
settings.CopyPhotos = CopyPhotoPolicy.ThisPcWins;
settings.CopyProjects = CopyProjects.Leave;
var dialog = Assert.NotNull(list.Open(pair, CopyDialogPart.Photos));
await dialog.LoadAsync();
Assert.Equal((CopyPhotoPolicy.ThisPcWins, 1), (dialog.Policy.Value, dialog.ProjectsIndex));
dialog.CloseCommand.Execute(null);
settings.CopyPhotos = CopyPhotoPolicy.Union;
settings.CopyProjects = CopyProjects.CopyAcross;
dialog = Assert.NotNull(list.Open(pair, CopyDialogPart.Photos));
await dialog.LoadAsync();
Assert.Equal((CopyPhotoPolicy.Union, 0), (dialog.Policy.Value, dialog.ProjectsIndex));
// Choose each: every photo row of every class starts unticked and without a version chosen.
dialog.Policy = dialog.Policies.First(o => o.Value == CopyPhotoPolicy.ChoosePerPhoto);
Assert.True(dialog.IsChoosing);
var offered = 0;
foreach (var cls in dialog.Classes)
{
dialog.SelectedClass = cls;
foreach (var row in dialog.Photos)
{
if (row.CanBring || row.CanChoose) offered++;
Assert.Null(row.Chosen);
Assert.False(row.Bring, $"{row.Name} is not ticked");
Assert.Null(row.Choice);
}
}
Assert.True(offered > 0, "the Lighthouse pair has photos to choose");
dialog.CloseCommand.Execute(null);
}
finally
{
(settings.CopyPhotos, settings.CopyProjects) = (photos, projects);
CopyScenes.Reset(shell);
}
});
[Test]
public Task MatchesFoundInTheBackgroundAndPhotosNotSentAreTold() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var table = shell.Server.Sync;
var raised = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => raised.AddRange(e.NewItems?.OfType<Toast>() ?? []);
var pair = table.Copies.Pairs.Single(p => p.Here.Title == CopyScenes.Lighthouse);
shell.Navigate(SectionKey.Library);
// A detection that ran by itself (after a refresh, a scan, an import): "1 match found" · Review (design §8.4).
var engine = Assert.NotNull(shell.Services.Sync.Copies as Chronos.App.DesignTime.SampleCopyEngine);
engine.RaiseFound(new CopyFindResult([pair.Copy], [], []));
var found = await ToastAsync(raised, Loc.Plural("Server.Copies.Found", 1));
Assert.Equal(Loc.L("Server.Copies.Action.Review"), found.ActionText);
Assert.False(string.IsNullOrWhiteSpace(found.ActionToolTip));
Assert.True(found.RunsFromNotification, "a click on the Windows notification opens the matches");
found.ActionCommand!.Execute(null);
Assert.Equal(SectionKey.Server, shell.Current.Key);
Assert.True(table.IsMatches);
// A detection that found nothing tells nothing.
shell.Navigate(SectionKey.Library);
raised.Clear();
engine.RaiseFound(CopyFindResult.Empty);
await Task.Delay(200);
Assert.Empty(raised.Where(t => t.Title == Loc.Plural("Server.Copies.Found", 1)));
// Automatic photos of an integrated pair failed three times: "{title}: photos not sent" · Show, an error (design §6.1).
shell.Services.Sync.TellPhotosNotSent("server", pair.Copy.LocalId, new AutoPhotoFailure(SyncAgent.NotSentAfter, "Quota reached"));
var notSent = await ToastAsync(raised, Loc.L("Server.Sync.NotSentToast", CopyScenes.Lighthouse));
Assert.True(notSent.IsError);
Assert.Equal((Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.ShowNotSent")), (notSent.ActionText, notSent.ActionToolTip));
Assert.True(notSent.RunsFromNotification);
notSent.ActionCommand!.Execute(null);
Assert.Equal(SectionKey.Server, shell.Current.Key);
Assert.False(table.IsMatches);
Assert.Equal(CopyScenes.Lighthouse, table.SearchText);
Assert.Contains(table.Rows, r => r.Title == CopyScenes.Lighthouse);
CopyScenes.Reset(shell);
});
[Test]
public Task ASwappedMergeOffersToTrashOnDeletedInOtherFromTheKeptSequenceOnly() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var engine = (SampleCopyEngine)shell.Services.Sync.Copies!;
var list = shell.Server.Sync.Copies;
await CopyScenes.ShowAsync(shell, "server-copies");
var alps = list.Pairs.Single(p => p.Here.Title == CopyScenes.Alps);
var start = new DateTime(2025, 7, 14, 5, 30, 0);
// The pair's first deleted 3 photos its other still holds (Deleted here), and the other deleted 2 the first holds.
var restore = engine.With(alps.Copy.Id, p => p with
{
Photos = [.. p.Photos, .. SampleCopies.Photos(PhotoClass.DeletedHere, 3, start, 950, here: false, there: true),
.. SampleCopies.Photos(PhotoClass.DeletedThere, 2, start, 960, here: true, there: false)],
});
try
{
var dialog = Assert.NotNull(list.Open(alps, CopyDialogPart.Photos, PhotoClass.DeletedHere));
await dialog.LoadAsync();
Assert.Equal(alps.Copy.OtherId, dialog.KeepOptions.Single(o => o.IsChecked).SequenceId);
// Kept: the pair's other. Its "Deleted in other" (the first deleted them) offers To trash…, from the kept one.
var deletedInOther = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedHere);
Assert.Equal(CopyText.Class(PhotoClass.DeletedThere, merge: true), deletedInOther.Text);
dialog.SelectedClass = deletedInOther;
Assert.True(dialog.CanTrashHere);
var plan = await dialog.PlanTrashHereAsync([dialog.Photos[0].Key]);
Assert.Equal(alps.Copy.OtherId, plan.Plan.Sequence.Id);
// "Deleted in kept": its frames are the dropped sequence's, which go with the merge; no To trash….
var deletedInKept = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedThere);
Assert.Equal(CopyText.Class(PhotoClass.DeletedHere, merge: true), deletedInKept.Text);
dialog.SelectedClass = deletedInKept;
Assert.False(dialog.CanTrashHere);
// Kept: the pair's first. Now Deleted there reads "Deleted in other" and trashes from the first.
dialog.KeepOptions.Single(o => o.SequenceId == alps.Copy.LocalId).IsChecked = true;
dialog.SelectedClass = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedThere);
Assert.True(dialog.CanTrashHere);
Assert.Equal(alps.Copy.LocalId, (await dialog.PlanTrashHereAsync([dialog.Photos[0].Key])).Plan.Sequence.Id);
dialog.SelectedClass = dialog.Classes.Single(c => c.Class == PhotoClass.DeletedHere);
Assert.False(dialog.CanTrashHere);
}
finally
{
restore();
CopyScenes.Reset(shell);
}
});
[Test]
public Task InMainMarksTheVersionTheKeptSequencesMainUses() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var dialog = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-versions"));
var alps = shell.Server.Sync.Copies.Pairs.Single(p => p.Here.Title == CopyScenes.Alps);
var review = await shell.Services.Sync.Copies!.CompareAsync(alps.Copy.Id, null, CancellationToken.None);
Assert.Equal(alps.Copy.OtherId, dialog.KeepOptions.Single(o => o.IsChecked).SequenceId);
// The two Mains use different versions: the kept sequence's (the pair's other) is marked.
Assert.Count(1, dialog.Photos.Where(p => p.InMain));
foreach (var marked in dialog.Photos.Where(x => x.InMain)) Assert.DoesNotContain(marked.Key, review.ExcludedThere);
await app.ExpectAsync<ServerView>("server-copies-versions");
// Both sides hold both versions: the side reads whole beside "In Main", and Drop… keeps its gap.
var view = app.FindAll<ServerView>().First(v => v.IsVisible);
foreach (var row in app.FindAll<ListBoxItem>().Where(i => i is { DataContext: CopyPhotoRow, IsVisible: true }))
{
var photo = (CopyPhotoRow)row.DataContext;
var side = Descendants<TextBlock>(row).Single(t => t.Text == photo.SideText);
// Layout rounding may take under a pixel; a trimmed text loses a whole character to the ellipsis.
Assert.True(Needed(side, side.Text) <= side.ActualWidth + 1.0, $"'{side.Text}' needs {Needed(side, side.Text):0.0} px, has {side.ActualWidth:0.0}");
var drop = Descendants<Button>(row).Single(b => b.IsVisible);
Assert.True(drop.Margin.Left >= 10, "Drop… keeps a gap from the side cell");
}
Assert.NotNull(view);
// Kept: the pair's first. The marker follows its Main.
dialog.KeepOptions.Single(o => o.SequenceId == alps.Copy.LocalId).IsChecked = true;
Assert.Count(1, dialog.Photos.Where(p => p.InMain));
foreach (var marked in dialog.Photos.Where(x => x.InMain)) Assert.DoesNotContain(marked.Key, review.ExcludedHere);
CopyScenes.Reset(shell);
});
[Test]
public Task ATwinNeedsItsSiblingAtTheOtherHome() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var engine = (SampleCopyEngine)shell.Services.Sync.Copies!;
// The integrated pair: Main and Vertical on this PC, only Main on the server.
var bridge = engine.Pairs.Single(p => p.Copy is { Kind: CopyKind.LocalServer, State: CopyState.Integrated });
Assert.SequenceEqual(["Main", "Vertical"], bridge.Projects.Here.Select(p => p.Name));
Assert.SequenceEqual(["Main"], bridge.Projects.There.Select(p => p.Name));
await CopyScenes.ShowAsync(shell, "edit-picker-twins");
var picker = shell.Sequence.Picker;
var home = Chronos.App.Workspace.WorkspaceHost.ArchiveHome(bridge.Copy.LocalId);
IReadOnlyList<Chronos.App.Workspace.WorkspaceEntry> entries =
[
new(Guid.CreateVersion7(), bridge.Copy.LocalId, "Main", true, home, bridge.Here.Title, HasMedia: true, SampleData.Now),
new(Guid.CreateVersion7(), bridge.Copy.LocalId, "Vertical", false, home, bridge.Here.Title, HasMedia: true, SampleData.Now),
];
await picker.ShowSampleWorkspaceAsync(entries, new Chronos.Data.Workspaces.WorkspaceStatus(Chronos.Data.Workspaces.WorkspaceState.InSync, false, 0, 0,
false, false, false, null, null, null));
var main = picker.WorkspaceItems.Single(i => i.Entry.Name == "Main");
var vertical = picker.WorkspaceItems.Single(i => i.Entry.Name == "Vertical");
Assert.True(main.HasTwin, "Main has its sibling on the server");
Assert.Contains(main.Name, main.TwinToolTip!);
Assert.False(vertical.HasTwin, "Vertical is only on this PC");
CopyScenes.Reset(shell);
});
[Test]
public Task TheDialogsPolicyAndVersionChoicesFitTheirBoxesInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var dialog = Assert.NotNull(await CopyScenes.ShowAsync(shell, "server-copies-choose"));
await app.ExpectAsync<ServerView>("server-copies-choose");
var policy = app.FindAll<ComboBox>().Single(c => c.IsVisible && AutomationProperties.GetName(c) == Loc.L("Server.Copies.Policy.Label"));
var version = app.FindAll<ComboBox>().First(c => c.IsVisible && c.DataContext is CopyPhotoRow);
List<string> misses = [];
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
app.Window.UpdateLayout();
await app.Window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
foreach (var merge in new[] { false, true })
{
Fits(misses, language, policy, CopyDialogViewModel.PolicyOptions(merge).Select(o => o.Label));
Fits(misses, language, version, CopyDialogViewModel.VersionChoices(merge).Select(o => o.Label));
}
}
}
finally
{
UiLanguage.Apply("en");
}
Assert.True(misses.Count == 0, string.Join(Environment.NewLine, misses));
Assert.NotNull(dialog);
CopyScenes.Reset(shell);
});
[Test]
public Task TheMatchesSettingsFitTheirBoxesInEveryLanguage() => ScreenHost.RunAsync(async () =>
{
await using var app = await StartAsync();
var shell = app.Shell;
var settings = shell.Settings;
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Server;
await app.ExpectAsync<Chronos.App.Sections.SettingsView>("settings-server");
string[] names = ["Settings.Server.CopyLinking", "Settings.Server.CopyPhotos", "Settings.Server.CopyProjects"];
List<string> misses = [];
try
{
foreach (var language in Languages.Shipped)
{
UiLanguage.Apply(language);
settings.CopyRows.Refresh();
app.Window.UpdateLayout();
await app.Window.Dispatcher.InvokeAsync(() => { }, System.Windows.Threading.DispatcherPriority.ApplicationIdle);
foreach (var name in names)
{
var box = app.FindAll<ComboBox>().Single(c => c.IsVisible && AutomationProperties.GetName(c) == Loc.L(name));
var labels = box.ItemsSource.Cast<object>().Select(o => (string)o.GetType().GetProperty("Label")!.GetValue(o)!);
Fits(misses, language, box, labels);
}
}
}
finally
{
UiLanguage.Apply("en");
settings.CopyRows.Refresh();
}
Assert.True(misses.Count == 0, string.Join(Environment.NewLine, misses));
});
/// <summary>
/// Adds to <paramref name="misses"/> each label that does not show whole in <paramref name="box"/>'s selection box (its
/// content site, inside the margins).
/// </summary>
private static void Fits(List<string> misses, string language, ComboBox box, IEnumerable<string> labels)
{
box.ApplyTemplate();
var site = (FrameworkElement)box.Template.FindName("ContentSite", box);
var room = box.ActualWidth - site.Margin.Left - site.Margin.Right - box.BorderThickness.Left - box.BorderThickness.Right;
var probe = new TextBlock { FontFamily = box.FontFamily, FontSize = box.FontSize, FontWeight = box.FontWeight, FlowDirection = box.FlowDirection };
foreach (var label in labels.Where(l => Needed(probe, l) > room + 0.5))
misses.Add($"{language}: '{label}' needs {Needed(probe, label):0.0} px, its box has {room:0.0}");
}
/// <summary>The width <paramref name="text"/> takes in <paramref name="cell"/>'s font.</summary>
private static double Needed(TextBlock cell, string text) => new FormattedText(text, System.Globalization.CultureInfo.CurrentUICulture, cell.FlowDirection,
new Typeface(cell.FontFamily, cell.FontStyle, cell.FontWeight, cell.FontStretch), cell.FontSize, Brushes.Black, 1.0).WidthIncludingTrailingWhitespace;
private static IEnumerable<T> Descendants<T>(DependencyObject node)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(node); i++)
{
var child = VisualTreeHelper.GetChild(node, i);
if (child is T match) yield return match;
foreach (var inner in Descendants<T>(child)) yield return inner;
}
}
private static async Task<Toast> ToastAsync(List<Toast> raised, string title)
{
for (var i = 0; i < 250 && !raised.Any(t => t.Title == title); i++) await Task.Delay(20);
return Assert.Contains(raised, t => t.Title == title);
}
private static async Task<ScreenSmokeTests.SampleApp> StartAsync()
{
var app = await ScreenSmokeTests.SampleApp.StartAsync();
var shell = app.Shell;
await app.Sample.FillAsync();
await shell.Services.Server.RestoreAsync();
Assert.NotNull(await shell.Services.Sync.RefreshAsync());
await app.Sample.FillCopiesAsync();
await shell.Library.RefreshAsync();
await shell.Server.Sync.ReloadAsync();
return app;
}
}
@@ -0,0 +1,545 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Server.Copies;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Server;
/// <summary>Words, glyphs and actions of a match (owner review 6, #73, design §8.1), and the sync rows a match marks.</summary>
[Serial]
public sealed class CopyTextTests
{
private const string Nas = "https://nas.local:8443";
private static readonly CopyRights SignedIn = new(Nas, "Studio NAS", CanIntegrate: true, CanUpload: true);
private static readonly Sequence Local = new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = "Lighthouse 2026-08-13",
Folder = "2026/lighthouse",
FrameCount = 1_204,
TotalBytes = 18_200_000_000,
Status = SequenceStatus.ProxiesBuilt,
};
private static readonly SyncLink Link = new()
{
Server = Nas,
RemoteId = Guid.CreateVersion7(),
Title = "Lighthouse 2026-08-13",
TotalBytes = 18_200_000_000,
RemoteStatus = SequenceStatus.ProxiesBuilt,
};
[Test]
public void EachStateOffersTheActionsOfTheTable()
{
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Integrate, CopyAction.KeepApart], CopyText.Actions(Copy(CopyState.Candidate)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Merge, CopyAction.KeepApart], CopyText.Actions(Copy(CopyState.Candidate, CopyKind.LocalLocal)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.AskAgain], CopyText.Actions(Copy(CopyState.KeptApart)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Integrate, CopyAction.Unlink], CopyText.Actions(Copy(CopyState.Linked)));
// Three buttons at most: a linked pair with photos deleted there reaches Integrate through Compare… or Review.
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Unlink, CopyAction.Review], CopyText.Actions(Copy(CopyState.Linked, deletedThere: 3)));
foreach (var state in Enum.GetValues<CopyState>())
{
foreach (var copy in new[] { Copy(state), Copy(state, deletedThere: 3), Copy(state, gone: true), Copy(state, CopyKind.LocalLocal, deletedThere: 3) })
Assert.LessOrEqual(CopyText.Actions(copy).Count, 3, $"{state}: at most three row buttons");
}
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Unlink], CopyText.Actions(Copy(CopyState.Integrated)));
Assert.SequenceEqual([CopyAction.Compare, CopyAction.Unlink, CopyAction.Review], CopyText.Actions(Copy(CopyState.Integrated, deletedThere: 3)));
Assert.SequenceEqual([CopyAction.Pause], CopyText.Actions(Copy(CopyState.Integrating), JobState.Running));
Assert.SequenceEqual([CopyAction.Resume], CopyText.Actions(Copy(CopyState.Integrating), JobState.Paused));
// The server deleted its copy: keep it here, send it again or move it to the trash; once kept, only send again.
Assert.SequenceEqual([CopyAction.KeepHere, CopyAction.UploadAgain, CopyAction.ToTrash], CopyText.Actions(Copy(CopyState.Linked, gone: true)));
Assert.SequenceEqual([CopyAction.UploadAgain], CopyText.Actions(Copy(CopyState.KeptApart, gone: true)));
}
[Test]
public void TheStateGlyphFollowsWhatThePairAsksFor()
{
Assert.Equal(StatusKind.Warning, CopyText.State(Copy(CopyState.Candidate)).Kind);
Assert.Equal(StatusKind.Offline, CopyText.State(Copy(CopyState.KeptApart)).Kind);
Assert.Equal(StatusKind.Synced, CopyText.State(Copy(CopyState.Linked)).Kind);
Assert.Equal(StatusKind.Running, CopyText.State(Copy(CopyState.Integrating), progress: (3, 10)).Kind);
Assert.Equal(StatusKind.Done, CopyText.State(Copy(CopyState.Integrated)).Kind);
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.DeletedThere", "3")),
Head(CopyText.State(Copy(CopyState.Integrated, deletedThere: 3))));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.DeletedOther", "3")),
Head(CopyText.State(Copy(CopyState.Integrated, CopyKind.LocalLocal, deletedThere: 3))));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.RemoteGone")), Head(CopyText.State(Copy(CopyState.Linked, gone: true))));
Assert.Equal((StatusKind.Offline, Loc.L("Server.Copies.State.KeptHere")), Head(CopyText.State(Copy(CopyState.KeptApart, gone: true))));
// The candidate's tooltip says how much the two share.
Assert.Contains("98", CopyText.State(Copy(CopyState.Candidate)).ToolTip);
}
[Test]
public void AnActionThatCannotRunSaysWhy()
{
var candidate = Copy(CopyState.Candidate);
Assert.Null(CopyText.Blocked(candidate, CopyAction.Integrate, SignedIn));
// A pair of another server needs that server signed in; the answers that move nothing never do.
var signedOut = new CopyRights(null, null, false, false);
Assert.Equal(Loc.L("Tooltips.Server.Copies.SignIn", Nas), CopyText.Blocked(candidate, CopyAction.Compare, signedOut));
Assert.Null(CopyText.Blocked(candidate, CopyAction.KeepApart, signedOut));
Assert.Equal(Loc.L("Tooltips.Server.Copies.NeedsNewerServer"), CopyText.Blocked(candidate, CopyAction.Integrate, SignedIn with { CanIntegrate = false }));
Assert.Equal(Loc.L("Errors.Copies.Busy"), CopyText.Blocked(candidate, CopyAction.Integrate, SignedIn with { Busy = true }));
Assert.Null(CopyText.Blocked(candidate, CopyAction.Compare, SignedIn with { Busy = true }));
var gone = Copy(CopyState.Linked, gone: true);
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NoRight"), CopyText.Blocked(gone, CopyAction.UploadAgain, SignedIn with { CanUpload = false }));
// A local pair needs no server.
Assert.Null(CopyText.Blocked(Copy(CopyState.Candidate, CopyKind.LocalLocal), CopyAction.Merge, signedOut));
// The tooltip of a disabled button is its reason.
Assert.Equal(Loc.L("Errors.Copies.Busy"), CopyText.ToolTip(candidate, CopyAction.Integrate, SignedIn with { Busy = true }));
}
[Test]
public void AttentionComesFirstThenTheStrongerHints()
{
var kept = View(Copy(CopyState.KeptApart) with { Score = Score(hints: 900) }, "Aurora");
var weak = View(Copy(CopyState.Candidate) with { Score = Score(hints: 100) }, "Bridge");
var strong = View(Copy(CopyState.Candidate) with { Score = Score(hints: 800) }, "Comet");
Assert.SequenceEqual(["Comet", "Bridge", "Aurora"], CopyText.Sorted([kept, weak, strong]).Select(p => p.Here.Title));
Assert.True(CopyText.Matches(strong, "com"));
Assert.True(CopyText.Matches(strong, "Comet (nas)"));
Assert.False(CopyText.Matches(strong, "Aurora"));
}
[Test]
public void EveryWordResolvesInEnglishAndItalianAndLabelsStayShort()
{
var missing = new List<string>();
void OnMissing(string key) => missing.Add(key);
Loc.MissingKey += OnMissing;
try
{
foreach (var culture in new[] { "en", "it" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
var gone = Copy(CopyState.Linked, gone: true);
foreach (var action in Enum.GetValues<CopyAction>())
{
var label = CopyText.Label(action);
Assert.LessOrEqual(label.Split(' ', StringSplitOptions.RemoveEmptyEntries).Length, 3, $"{culture}: \"{label}\" is at most three words");
Assert.False(string.IsNullOrWhiteSpace(CopyText.ToolTip(gone, action, SignedIn)), $"{culture}: {action} has a tooltip");
}
foreach (var c in Enum.GetValues<PhotoClass>())
{
Assert.False(string.IsNullOrWhiteSpace(CopyText.Class(c)), $"{culture}: {c}");
foreach (var policy in Enum.GetValues<CopyPhotoPolicy>())
{
foreach (var merge in new[] { false, true })
Assert.False(string.IsNullOrWhiteSpace(CopyText.ClassToolTip(c, policy, merge)), $"{culture}: {c} has a tooltip under {policy}");
}
}
foreach (var block in Enum.GetValues<CopyBlock>())
Assert.False(string.IsNullOrWhiteSpace(CopyText.Block(block, "Lighthouse", "Studio NAS", "2 GB", 2)), $"{culture}: {block}");
foreach (var state in Enum.GetValues<CopyState>())
{
foreach (var copy in new[] { Copy(state), Copy(state, deletedThere: 2), Copy(state, gone: true), Copy(state, CopyKind.LocalLocal, deletedThere: 2) })
{
var (_, text, tip) = CopyText.State(copy, "Studio NAS", (1, 4));
Assert.False(string.IsNullOrWhiteSpace(text) || string.IsNullOrWhiteSpace(tip), $"{culture}: {state}");
}
}
foreach (var why in Enum.GetValues<UploadSkip>())
Assert.False(string.IsNullOrWhiteSpace(SyncText.State(Entry(SyncStatus.LocalOnly, link: null), new SyncMark(null, why)).ToolTip), $"{culture}: {why}");
Assert.False(string.IsNullOrWhiteSpace(SyncText.ToolTip(Entry(SyncStatus.InSync), SyncAction.Compare)), $"{culture}: Compare has a tooltip");
Assert.Equal(Loc.L("Server.Copies.Detail.OtherSetting"), SyncText.DetailLabel("nothing.known"));
}
}
finally
{
Loc.MissingKey -= OnMissing;
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
Assert.Empty(missing);
}
[Test]
public void ASyncRowInAMatchSaysSoAndOffersCompare()
{
var entry = Entry(SyncStatus.LocalOnly, link: null);
// The Matches chip lists pairs, never sync rows.
Assert.False(SyncText.Matches(entry, SyncFilter.FoundCopies, string.Empty));
var editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
var candidate = new SyncMark(Copy(CopyState.Candidate), null, "Studio NAS");
var (kind, text, tip) = SyncText.State(entry, candidate);
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.CopyFound")), (kind, text));
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.CopyFound", "Studio NAS"), tip);
Assert.SequenceEqual([SyncAction.Compare, SyncAction.Upload], SyncText.Actions(entry, editor, candidate));
// A linked row offers Compare last; one without a pair, nothing more.
var linked = Entry(SyncStatus.InSync);
Assert.SequenceEqual([SyncAction.Compare], SyncText.Actions(linked, editor, new SyncMark(Copy(CopyState.Linked), null)));
Assert.Empty(SyncText.Actions(linked, editor, default));
// Deleted on the server, or kept here after that.
Assert.Equal(Loc.L("Server.Sync.State.RemoteGone"), SyncText.State(linked, new SyncMark(Copy(CopyState.Linked, gone: true), null)).Text);
Assert.Equal(Loc.L("Server.Sync.State.KeptHere"), SyncText.State(linked, new SyncMark(Copy(CopyState.KeptApart, gone: true), null)).Text);
// Upload all local left it out: "skipped", with the reason, under the Warning glyph (design §6.4).
var skipped = SyncText.State(entry, new SyncMark(null, UploadSkip.KeptApart));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.Skipped")), (skipped.Kind, skipped.Text));
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.Skipped", Loc.L("Tooltips.Server.Sync.Skip.KeptApart")), skipped.ToolTip);
// A transfer still shows first.
var upload = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.UploadCommit, State = JobState.Running };
Assert.Equal(SyncText.State(entry with { Transfer = upload }), SyncText.State(entry with { Transfer = upload }, candidate));
}
[Test]
public void ASkipForASuspectedMatchNamesWhereTheMatchLies()
{
var mark = new SyncMark(null, UploadSkip.SuspectedCopy, "Studio NAS");
// A match on another server than the signed-in one is named by that server.
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopy", "Lab NAS"),
SyncText.SkipReason(UploadSkip.SuspectedCopy, mark with { SkippedMatch = new SkippedMatch("Lab NAS", false) }));
// One in another archive of this PC says "in", not "on".
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopyLocal", "Old archive"),
SyncText.SkipReason(UploadSkip.SuspectedCopy, mark with { SkippedMatch = new SkippedMatch("Old archive", true) }));
// Unknown: the signed-in server.
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopy", "Studio NAS"), SyncText.SkipReason(UploadSkip.SuspectedCopy, mark));
// A job on it may integrate or merge it: the words say neither alone.
Assert.Equal(Loc.L("Tooltips.Server.Sync.Skip.Busy"), SyncText.SkipReason(UploadSkip.Busy, mark));
}
[Test]
public void ARowWhoseMatchTheServerDeletedOffersWhatTheMatchesRowDoes()
{
var entry = Entry(SyncStatus.LocalOnly, link: null);
var editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
var gone = new SyncMark(Copy(CopyState.Linked, gone: true), null, "Studio NAS");
Assert.SequenceEqual([SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash], SyncText.Actions(entry, editor, gone));
// Kept here: only Upload again.
Assert.SequenceEqual([SyncAction.UploadAgain], SyncText.Actions(entry, editor, new SyncMark(Copy(CopyState.KeptApart, gone: true), null)));
foreach (var action in new[] { SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash })
{
var row = new SyncRowAction(action, () => Task.CompletedTask);
Assert.Equal(Loc.L("Server.Copies.Action." + action), row.Text);
Assert.False(string.IsNullOrWhiteSpace(SyncText.ToolTip(entry, action, editor, gone)), $"{action} has a tooltip");
}
Assert.Equal(Loc.L("Tooltips.Server.Copies.UploadAgain", "Studio NAS"), SyncText.ToolTip(entry, SyncAction.UploadAgain, editor, gone));
// Without the upload right, Upload again is offered disabled with the reason.
var reader = SyncRights.Of((long)RolePermissions.Default(UserRole.Viewer));
Assert.False(SyncText.IsEnabled(SyncAction.UploadAgain, reader));
Assert.Equal(Loc.L("Tooltips.Server.Sync.UploadAll.NoRight"), SyncText.ToolTip(entry, SyncAction.UploadAgain, reader, gone));
}
[Test]
public void TheOwnerReview6TextsFitTheirPlaces()
{
// Integrating: the share in the cell, "x of y" in the tooltip.
var (_, text, tip) = CopyText.State(Copy(CopyState.Integrating), progress: (1_234, 2_400));
Assert.Equal(Loc.L("Server.Copies.State.Integrating", "51"), text);
Assert.Contains(Loc.L("Server.Copies.State.Progress", "1,234", "2,400"), tip);
Assert.Equal(Loc.L("Server.Copies.State.Integrating", "0"), CopyText.State(Copy(CopyState.Integrating)).Text);
// The count comes first, so a trimmed cell keeps what tells two pairs apart.
Assert.True(CopyText.Where(Facts("Lighthouse", "Main archive", 1_204), isServer: false).StartsWith("1,204", StringComparison.Ordinal));
// A server that deleted its sequence is named alone, never "0 photos".
Assert.Equal("Studio NAS", CopyText.Where(Facts(string.Empty, "Studio NAS", 0), isServer: true, gone: true));
// The frame positions read as the setting they are, with the count of photos they place.
Assert.Equal(Loc.L("Server.Copies.Detail.Positions"), SyncText.DetailLabel(CopyPayload.PendingFramesPath));
Assert.Equal(Loc.Plural("Shell.Status.Photos", 2), SyncText.DetailValue(CopyPayload.PendingFramesPath, "{\"a\":{},\"b\":{}}"));
Assert.Equal("Lighthouse", SyncText.DetailValue("sequence.title", "Lighthouse"));
Assert.Equal("41", SyncText.DetailValue("exposure.deflickerWindow.manual", "41"));
Assert.Equal(Loc.L("Server.Copies.Detail.Changed"), SyncText.DetailValue("exposure.curve", "{\"points\":[[0,0],[1,1]]}"));
// The members of one setting are one row and one choice.
Assert.Equal(SyncText.DetailSetting("exposure.deflickerWindow.isAuto"), SyncText.DetailSetting("exposure.deflickerWindow.manual"));
var row = new CopyDetailRow([new DetailLine("exposure.deflickerWindow.isAuto", "true", "false"), new DetailLine("exposure.deflickerWindow.manual", "41", "33")],
isMerge: false, () => { });
Assert.SequenceEqual(["exposure.deflickerWindow.isAuto", "exposure.deflickerWindow.manual"], row.Paths);
Assert.Equal(string.Join(Loc.Separator, Loc.L("Server.Setting.Auto"), "41"), row.HereText);
// A match between this PC's archives names the other archive, not the server.
var local = new SyncMark(Copy(CopyState.Candidate, CopyKind.LocalLocal), null, "Studio NAS", OtherWhere: "Old archive");
Assert.Equal(Loc.L("Tooltips.Library.Status.CopyFoundLocal", "Old archive"), SyncText.State(Entry(SyncStatus.LocalOnly, link: null), local).ToolTip);
// The Library card of a sequence whose server copy was deleted says so.
var gone = View(Copy(CopyState.Linked, gone: true), "Lighthouse");
var status = CopyListViewModel.LibraryStatus(gone, Local.Id);
Assert.Equal(Loc.L("Library.Status.RemoteGone"), status.Text);
// A plan line is what will happen (queued), a warning leads.
Assert.Equal(StatusKind.Queued, new CopyPlanLine("Receives 2 photos").Kind);
Assert.Equal(StatusKind.Warning, new CopyPlanLine("Only copy", IsWarning: true).Kind);
}
[Test]
public void TheReplaceConfirmationListsEachSidesLosersUnderItsHeading()
{
var trashed = new List<PhotoStep>
{
new("a", PhotoAction.TrashHere, Guid.NewGuid(), "IMG_0001.JPG", 10, "a"),
new("b", PhotoAction.TrashHere, Guid.NewGuid(), "IMG_0002.JPG", 10, "b"),
new("c", PhotoAction.TrashThere, Guid.NewGuid(), "IMG_0003.JPG", 10, "c"),
};
var lasts = new List<LastCopy> { new("b", CopySide.ThisPc, "IMG_0002.JPG", 10) };
var lines = CopyDialogViewModel.ReplaceLines(lasts, trashed, "Studio NAS").Split(Environment.NewLine);
Assert.SequenceEqual(
[
Loc.L("Server.Copies.Plan.OnThisPc"),
" " + Loc.L("Server.Copies.Confirm.LastCopy", "IMG_0002.JPG"),
// A replaced version under an "Only copy:" line carries its own prefix (owner review 6, verification round 5).
" " + Loc.L("Server.Copies.Confirm.Replaced", "IMG_0001.JPG"),
Loc.L("Server.Copies.Plan.OnServer", "Studio NAS"),
" " + Loc.L("Server.Copies.Confirm.Replaced", "IMG_0003.JPG"),
], lines);
// To trash… and Delete on server…: the only copies first, the photos held elsewhere each with their prefix, once.
var trash = CopyDialogViewModel.Lines(lasts, ["IMG_0002.JPG", "IMG_0001.JPG", "IMG_0001.JPG"]).Split(Environment.NewLine);
Assert.SequenceEqual(
[
Loc.L("Server.Copies.Confirm.LastCopy", "IMG_0002.JPG"),
Loc.L("Server.Copies.Confirm.Elsewhere", "IMG_0001.JPG"),
], trash);
// A merge's facts are not photos held elsewhere: they carry no prefix, after the only copies.
var facts = CopyDialogViewModel.Lines(lasts, ["1 render moved"], elsewhere: false).Split(Environment.NewLine);
Assert.SequenceEqual(
[
Loc.L("Server.Copies.Confirm.LastCopy", "IMG_0002.JPG"),
"1 render moved",
], facts);
}
[Test]
public void AMergeNamesItsSidesByRoleAndAsksForAVersionOfEachDifferentPhoto()
{
// Class words: by role once a sequence is kept, oriented from the kept one; by place before.
var onlyHere = new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyHere, 38, 570_000_000, 0), CopyPhotoPolicy.Union, isMerge: true);
Assert.Equal(Loc.L("Server.Copies.Class.OnlyKept"), onlyHere.Text);
var raised = new List<string?>();
onlyHere.PropertyChanged += (_, e) => raised.Add(e.PropertyName);
onlyHere.Swapped = true;
Assert.Equal(Loc.L("Server.Copies.Class.OnlyOther"), onlyHere.Text);
Assert.Contains(nameof(CopyClassRow.Text), raised);
raised.Clear();
onlyHere.Places = ("Main archive", "Studio archive");
Assert.Equal(Loc.L("Server.Copies.Class.OnlyHere"), onlyHere.Text);
Assert.Contains(nameof(CopyClassRow.Text), raised);
Assert.Equal(Loc.L("Server.Copies.Class.DeletedOther"), CopyText.Class(PhotoClass.DeletedThere, merge: true));
Assert.Equal(Loc.L("Server.Copies.Class.Differs"), CopyText.Class(PhotoClass.Differs, merge: true));
Assert.Equal(Loc.L("Server.Copies.Class.OnlyHere"), new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyHere, 1, 1, 0)).Text);
// Choose each in a merge: its own tooltip, no Leave, and the unchosen block leads to the photos.
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.ChooseMerge"),
CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ChoosePerPhoto, isMerge: true));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.Choose"), CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ChoosePerPhoto));
Assert.SequenceEqual([PhotoChoice.KeepBoth, PhotoChoice.TakeHere, PhotoChoice.TakeThere],
CopyDialogViewModel.VersionChoices(merge: true).Select(o => o.Value));
Assert.Contains(PhotoChoice.Leave, CopyDialogViewModel.VersionChoices(merge: false).Select(o => o.Value));
Assert.True(CopyText.HasChoose(CopyBlock.PhotosUnchosen));
// A version choice not made yet is read out as such, not as Leave.
var photo = new ComparedPhoto(PhotoClass.Differs, "k",
new CopyPhotoInput(Guid.NewGuid(), 0, "IMG_0004.JPG", "a", 10, null, false), new CopyPhotoInput(Guid.NewGuid(), 0, "IMG_0004.JPG", "b", 12, null, false),
1, 1, 10);
var row = new CopyPhotoRow(photo, isMerge: true, canBring: false, canChoose: true, CopyDialogViewModel.VersionChoices(true), null, () => { }, null);
Assert.Equal(Loc.L("Server.Copies.ControlFor", "IMG_0004.JPG", Loc.L("Server.Copies.Version.None")), row.ChoiceAccessibleName);
Assert.False(row.InMain);
}
[Test]
public void ThePairWordsFollowWhatTheRunReallyDoes()
{
// An Integrate that left photos out moves new photos only by hand; one that left nothing out, by itself.
Assert.Equal(Loc.L("Tooltips.Server.Copies.State.IntegratedByHand"), CopyText.State(Copy(CopyState.Integrated)).ToolTip);
Assert.Equal(Loc.L("Tooltips.Server.Copies.State.Integrated"), CopyText.State(Copy(CopyState.Integrated) with { AutoPhotos = true }).ToolTip);
// A pair of this PC's archives is merged, with the same "x of y".
var (_, text, tip) = CopyText.State(Copy(CopyState.Integrating, CopyKind.LocalLocal), progress: (1, 4));
Assert.Equal(Loc.L("Server.Copies.State.Merging", "25"), text);
Assert.Equal(string.Join(Environment.NewLine, Loc.L("Tooltips.Server.Copies.State.Merging"), Loc.L("Server.Copies.State.Progress", "1", "4")), tip);
// The row follows a merge's progress as it follows an Integrate's.
Assert.True(CopyListViewModel.Follows(JobKind.MergeSequences));
Assert.True(CopyListViewModel.Follows(JobKind.Integrate));
Assert.False(CopyListViewModel.Follows(JobKind.UploadCommit));
// A class says what the chosen policy does with it, and a merge says it its own way.
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs"), CopyText.ClassToolTip(PhotoClass.Differs));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.ThisPcWins"), CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ThisPcWins));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.KeptWins"), CopyText.ClassToolTip(PhotoClass.Differs, CopyPhotoPolicy.ThisPcWins, isMerge: true));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.OnlyHere.Choose"), CopyText.ClassToolTip(PhotoClass.OnlyHere, CopyPhotoPolicy.ChoosePerPhoto));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.OnlyThere.Merge"), CopyText.ClassToolTip(PhotoClass.OnlyThere, CopyPhotoPolicy.ChoosePerPhoto, isMerge: true));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.SameUnhashed.Integrate"), CopyText.ClassToolTip(PhotoClass.SameUnhashed));
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.SameUnhashed"), CopyText.ClassToolTip(PhotoClass.SameUnhashed, isMerge: true));
// The class row follows the dialog's policy, and a merge keeping the other sequence reads its classes from the kept side.
var differs = new CopyClassRow(new PhotoClassTotal(PhotoClass.Differs, 2, 51_400_000, 51_800_000));
differs.Policy = CopyPhotoPolicy.OtherWins;
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.Differs.OtherWins"), differs.ToolTip);
var onlyHere = new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyHere, 38, 570_000_000, 0), CopyPhotoPolicy.Union, isMerge: true) { Swapped = true };
Assert.Equal(Loc.L("Tooltips.Server.Copies.Class.OnlyThere.Merge"), onlyHere.ToolTip);
// The size cell shows the bytes of the side that holds them; both sides in the tooltip when both do.
var onlyThere = new CopyClassRow(new PhotoClassTotal(PhotoClass.OnlyThere, 3, 0, 45_000_000));
Assert.Equal(Formatting.Bytes(45_000_000), onlyThere.BytesText);
Assert.Equal(Loc.L("Server.Copies.Detail.Server") + " " + Formatting.Bytes(45_000_000), onlyThere.BytesToolTip);
Assert.Equal(Formatting.Bytes(51_400_000), differs.BytesText);
Assert.Equal(string.Join(Loc.Separator, Loc.L("Server.Copies.Detail.ThisPc") + " " + Formatting.Bytes(51_400_000),
Loc.L("Server.Copies.Detail.Server") + " " + Formatting.Bytes(51_800_000)), differs.BytesToolTip);
}
[Test]
public void ASyncRowOfAPairWhoseMatchDeletedPhotosSaysSoAndOffersReview()
{
var entry = Entry(SyncStatus.InSync);
var editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
foreach (var state in new[] { CopyState.Linked, CopyState.Integrated })
{
var mark = new SyncMark(Copy(state, deletedThere: 3), null);
Assert.Equal((StatusKind.Warning, Loc.L("Server.Copies.State.DeletedThere", "3"), Loc.Plural("Tooltips.Server.Copies.State.DeletedThere", 3)),
SyncText.State(entry, mark));
Assert.SequenceEqual([SyncAction.Compare, SyncAction.Review], SyncText.Actions(entry, editor, mark).TakeLast(2));
Assert.False(string.IsNullOrWhiteSpace(SyncText.ToolTip(entry, SyncAction.Review)));
}
// Nothing deleted: the ordinary sync state, Compare last.
Assert.Equal(SyncText.State(entry), SyncText.State(entry, new SyncMark(Copy(CopyState.Linked), null)));
Assert.Equal(SyncAction.Compare, SyncText.Actions(entry, editor, new SyncMark(Copy(CopyState.Linked), null))[^1]);
}
[Test]
public void TheMatchStatusComesRightAfterTheAnalysisStatus()
{
var analysed = new Chronos.Ui.Visuals.CardStatus(StatusKind.Analysed, "Analysed");
var proxies = new Chronos.Ui.Visuals.CardStatus(StatusKind.Done, "Proxies");
var synced = new Chronos.Ui.Visuals.CardStatus(StatusKind.Synced, "Synced");
var match = new Chronos.Ui.Visuals.CardStatus(StatusKind.Warning, "Also elsewhere");
Assert.SequenceEqual([analysed, match, proxies, synced], Chronos.App.Library.SequenceItem.WithMatch([analysed, proxies, synced], match));
Assert.SequenceEqual([analysed, proxies], Chronos.App.Library.SequenceItem.WithMatch([analysed, proxies], null));
}
[Test]
public void TheMatchWordsNeverUseTheNounCopy()
{
// Design §1.1: the duplicates report owns "copy/copie"; a match is a sequence twice. The photo-level "last copy"
// and the verb "copy" stay.
string[] areas = ["Server.Copies.", "Server.Sync.Skip.", "Server.Sync.State.", "Library.Status.", "Settings.Copy", "Errors.Copies."];
string[] allowed =
[
"Server.Copies.Projects.CopyAcross", "Server.Copies.Plan.LastCopies.one", "Server.Copies.Plan.LastCopies.other",
"Server.Copies.Confirm.LastCopy", "Tooltips.Server.Copies.ToTrashSequence", "Tooltips.Server.Copies.Bring",
];
var noun = new System.Text.RegularExpressions.Regex(@"\b(copy|copie)\b", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var found = new List<string>();
foreach (var culture in new[] { "en", "it" })
{
foreach (var file in Directory.EnumerateFiles(Path.Combine(TestContext.RepositoryRoot, "i18n", culture), "*.resx"))
{
foreach (var data in System.Xml.Linq.XDocument.Load(file).Root!.Elements("data"))
{
var name = (string)data.Attribute("name")!;
var bare = name.StartsWith("Tooltips.", StringComparison.Ordinal) ? name["Tooltips.".Length..] : name;
if (!areas.Any(a => bare.StartsWith(a, StringComparison.Ordinal)) || allowed.Contains(name)) continue;
if (noun.IsMatch((string?)data.Element("value") ?? string.Empty)) found.Add($"{culture}: {name}");
}
}
}
Assert.Empty(found);
}
[Test]
public void APlanCountsAsSecondVersionsOnlyThoseKeptBesideTheirPair()
{
// Union keeps "a" beside its pair; This PC wins replaces "b" (its loser goes to the trash on the same side).
var steps = new List<PhotoStep>
{
new("a", PhotoAction.SendVersion, Guid.NewGuid(), "IMG_0001.JPG", 10, "a"),
new("b", PhotoAction.SendVersion, Guid.NewGuid(), "IMG_0002.JPG", 10, "b"),
new("b", PhotoAction.TrashThere, Guid.NewGuid(), "IMG_0002.JPG", 10, "b2"),
new("c", PhotoAction.FetchVersion, Guid.NewGuid(), "IMG_0003.JPG", 10, "c"),
new("c", PhotoAction.TrashHere, Guid.NewGuid(), "IMG_0003.JPG", 10, "c2"),
};
Assert.Equal(1, CopyDialogViewModel.KeptVersions(steps, PhotoAction.SendVersion, PhotoAction.TrashThere));
Assert.Equal(0, CopyDialogViewModel.KeptVersions(steps, PhotoAction.FetchVersion, PhotoAction.TrashHere));
}
[Test]
public void TheMergesTypedConfirmationIsTheCountWithoutSeparatorsAndThePromptNamesIt()
{
// 1,204 photos: what to type has no group separator in any language ("1.204" in Italian), and the prompt says it.
foreach (var culture in new[] { "en", "it", "de", "hu" })
{
Loc.SetCulture(CultureInfo.GetCultureInfo(culture));
try
{
Assert.Equal("1204", CopyDialogViewModel.MergeTyped(1_204));
var prompt = CopyDialogViewModel.MergeTypedPrompt(1_204, "Alps 2026");
Assert.Contains("1204", prompt);
Assert.Contains("Alps 2026", prompt);
}
finally
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
}
}
}
[Test]
public void TheSessionKeysTooltipNamesTheKeysThatStayOnlyWhenThereAreAny()
{
Assert.Equal(Loc.L("Tooltips.Server.Copies.Plan.SessionKeys"), CopyDialogViewModel.SessionKeysToolTip([]));
var kept = CopyDialogViewModel.SessionKeysToolTip(["card:A1", "folder:B2"]);
Assert.False(kept.Contains("{0}", StringComparison.Ordinal), "no placeholder is left in the text");
Assert.Contains("card:A1", kept);
Assert.Contains("folder:B2", kept);
}
[Test]
public void AMatchRowTrimsALongArchiveNameInItsMiddleAndItsTooltipSaysItWhole()
{
Assert.Equal("Main archive", CopyText.MiddleTrim("Main archive", CopyText.RowNameLength));
var name = "ChronosArchive-Photos-2026-Studio NAS backup";
var trimmed = CopyText.MiddleTrim(name, CopyText.RowNameLength);
Assert.LessOrEqual(trimmed.Length, CopyText.RowNameLength);
Assert.True(trimmed.StartsWith("ChronosArch", StringComparison.Ordinal) && trimmed.EndsWith("NAS backup", StringComparison.Ordinal), trimmed);
Assert.Contains("…", trimmed);
var facts = Facts("Lighthouse", name, 1_204);
Assert.Contains(trimmed, CopyText.Where(facts, isServer: false, maxName: CopyText.RowNameLength));
Assert.Contains(name, CopyText.Where(facts, isServer: false));
}
private static (StatusKind, string) Head((StatusKind Kind, string Text, string ToolTip) state) => (state.Kind, state.Text);
private static FoundCopy Copy(CopyState state, CopyKind kind = CopyKind.LocalServer, int deletedThere = 0, bool gone = false) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
LocalId = Local.Id,
Server = kind == CopyKind.LocalServer ? Nas : null,
RemoteId = kind == CopyKind.LocalServer ? Link.RemoteId : null,
OtherId = kind == CopyKind.LocalLocal ? Guid.CreateVersion7() : null,
Evidence = CopyEvidence.Hashes,
State = state,
Score = Score(deletedThere: deletedThere),
Fingerprint = "f",
RemoteGoneHits = gone ? 2 : 0,
UpdatedAt = new DateTimeOffset(2026, 11, 16, 9, 0, 0, TimeSpan.Zero),
};
private static CopyScore Score(int deletedThere = 0, int hints = 500) =>
new(1_178, 0, 0, 24, 0, 2, 0, deletedThere, 0, 1_204, 1_180, 980, 960, hints);
private static FoundCopyView View(FoundCopy copy, string title) =>
new(copy, Facts(title, "Main archive", 1_204), Facts(title + " (nas)", "Studio NAS", 1_180));
private static CopyFacts Facts(string title, string where, int photos) =>
new(title, where, null, photos, photos * 15_000_000L, null, null, null, photos, null, [], false);
private static SyncEntry Entry(SyncStatus status, SyncLink? link = null) =>
new(Local, status == SyncStatus.LocalOnly ? link : link ?? Link, status, null);
}
@@ -0,0 +1,100 @@
using Chronos.App.Server;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.App.Tests.Server;
/// <summary>
/// The local detection that runs by itself (owner review 6, #73; design §3.4): once after the index opened, after a job that
/// changes photos ended, one at a time, and the requests that arrive meanwhile coalesce into one more.
/// </summary>
public sealed class CopyWatchTests
{
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(30);
private static readonly CopyWatchOptions Quick = new() { StartDelay = TimeSpan.FromMilliseconds(20), AfterJobDelay = TimeSpan.FromMilliseconds(50) };
private static Job Ended(JobKind kind, JobState state = JobState.Done) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
State = state,
Created = DateTimeOffset.UtcNow,
};
private static async Task WaitAsync(Func<bool> condition, string what)
{
var until = DateTime.UtcNow + Deadline;
while (!condition())
{
if (DateTime.UtcNow > until) Assert.Fail($"timed out waiting for {what}");
await Task.Delay(10);
}
}
[Test]
public async Task ItLooksOnceAfterStartAndAfterAJobThatChangesPhotos()
{
var runs = 0;
await using var watch = new CopyWatch(_ =>
{
Interlocked.Increment(ref runs);
return Task.CompletedTask;
}, Quick);
watch.Start(null);
await WaitAsync(() => watch.Runs == 1, "the first detection");
watch.OnJobChanged(Ended(JobKind.Render));
watch.OnJobChanged(Ended(JobKind.Scan, JobState.Running));
await Task.Delay(200);
Assert.Equal(1, watch.Runs, "a render, or a scan still running, asks for none");
watch.OnJobChanged(Ended(JobKind.Scan));
watch.OnJobChanged(Ended(JobKind.Import, JobState.Failed));
watch.OnJobChanged(Ended(JobKind.MergeSequences, JobState.Cancelled));
await WaitAsync(() => watch.Runs == 2, "the detection after the jobs");
await Task.Delay(200);
Assert.Equal(2, Volatile.Read(ref runs), "jobs that end close together ask for one detection");
}
[Test]
public async Task RequestsWhileOneRunsGiveExactlyOneMore()
{
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var running = 0;
var overlapped = false;
await using var watch = new CopyWatch(async _ =>
{
if (Interlocked.Increment(ref running) > 1) overlapped = true;
await release.Task;
Interlocked.Decrement(ref running);
}, Quick with { StartDelay = TimeSpan.Zero, AfterJobDelay = TimeSpan.Zero });
watch.Start(null);
await WaitAsync(() => Volatile.Read(ref running) == 1, "the first detection to start");
foreach (var kind in CopyWatch.Triggers) watch.OnJobChanged(Ended(kind));
await Task.Delay(100);
release.TrySetResult();
await WaitAsync(() => watch.Runs == 2, "the one more detection");
await Task.Delay(200);
Assert.Equal(2, watch.Runs);
Assert.False(overlapped, "never two at once");
}
[Test]
public async Task AFailedDetectionDoesNotStopTheWatch()
{
var calls = 0;
await using var watch = new CopyWatch(_ => Interlocked.Increment(ref calls) == 1 ? throw new InvalidOperationException("index busy") : Task.CompletedTask,
Quick);
watch.Start(null);
await WaitAsync(() => watch.Runs == 1, "the failed detection");
watch.OnJobChanged(Ended(JobKind.Download));
await WaitAsync(() => watch.Runs == 2, "the next detection");
Assert.Equal(2, Volatile.Read(ref calls));
}
}
@@ -169,6 +169,21 @@ public sealed class SyncTextTests
Assert.Contains("403 forbidden", tip);
}
[Test]
public void PhotosThatFailedToMoveThreeTimesReadNotSentWithTheReason()
{
// Owner review 6 (#73), design §7.3: automatic photos of an integrated pair failed NotSentAfter times in a row.
var entry = Entry(SyncStatus.InSync);
var told = SyncText.State(entry, new SyncMark(null, null, NotSent: new AutoPhotoFailure(SyncAgent.NotSentAfter, "Quota reached")));
Assert.Equal((StatusKind.Warning, Loc.L("Server.Sync.State.NotSent")), (told.Kind, told.Text));
Assert.Equal(Loc.L("Tooltips.Server.Sync.State.NotSent", "Quota reached"), told.ToolTip);
// Fewer failures are still retried quietly; a transfer running now wins.
Assert.Equal(SyncText.State(entry), SyncText.State(entry, new SyncMark(null, null, NotSent: new AutoPhotoFailure(SyncAgent.NotSentAfter - 1, "Quota reached"))));
var moving = Entry(SyncStatus.Transferring, transfer: Upload(JobState.Running));
Assert.Equal(SyncText.State(moving), SyncText.State(moving, new SyncMark(null, null, NotSent: new AutoPhotoFailure(SyncAgent.NotSentAfter, "x"))));
}
[Test]
public void FiltersAndSearchSelectRows()
{
@@ -1,3 +1,4 @@
using System.IO;
using Chronos.App.Server;
using Chronos.Core.Model;
using Chronos.Data.Archiving.Jobs;
@@ -8,7 +9,7 @@ namespace Chronos.App.Tests.Server;
/// <summary>
/// Which jobs "Pause metered transfers" holds (Server.html, phase 5c): uploads, the sync's downloads, and the workspace's copies from and renders
/// sent to a server; never a copy from or a send to this PC's archive.
/// sent to a server, and the integrations of pairs with a server sequence; never a copy from or a send to this PC's archive, nor a merge.
/// </summary>
public sealed class UploadHoldTests
{
@@ -46,9 +47,104 @@ public sealed class UploadHoldTests
Assert.True(UploadHold.Holds(Of(JobKind.Download)));
Assert.True(UploadHold.Holds(Of(WorkspaceJobs.CopyFromServer(SequenceId, "Harbour", Server, Root, ProjectId))));
Assert.True(UploadHold.Holds(Of(WorkspaceJobs.Send(SequenceId, "Harbour", Root, ProjectId, [], Server))));
Assert.SequenceEqual([JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend], UploadHold.Kinds);
Assert.SequenceEqual([JobKind.UploadCommit, JobKind.Download, JobKind.WorkspaceCopy, JobKind.WorkspaceSend, JobKind.Integrate], UploadHold.Kinds);
}
[Test]
public void AnIntegrationIsHeldAMergeIsNot()
{
// An integration always moves photos with a server (owner review 6, #73); a merge of two local sequences never does.
Assert.True(UploadHold.Holds(Of(JobKind.Integrate)));
Assert.False(UploadHold.Holds(Of(JobKind.MergeSequences)));
}
[Test]
public void AnAutomaticTransferIsHeldOnAMeteredConnectionWithTheOptionOff()
{
// Owner review 6, Q6: new photos of an integrated pair move by themselves, "paused on metered connections".
var automatic = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals","automatic":true}""");
var manual = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals"}""");
Assert.True(Chronos.Data.Sync.SyncService.IsAutomaticTransfer(automatic));
Assert.False(Chronos.Data.Sync.SyncService.IsAutomaticTransfer(manual));
Assert.True(UploadHold.HeldNow(automatic, metered: true, optionOn: false));
Assert.False(UploadHold.HeldNow(manual, metered: true, optionOn: false));
Assert.True(UploadHold.HeldNow(manual, metered: true, optionOn: true));
Assert.False(UploadHold.HeldNow(automatic, metered: false, optionOn: true));
// An automatic upload too.
Assert.True(UploadHold.HeldNow(Of(JobKind.UploadCommit, $$"""{"server":"{{Server}}","automatic":true}"""), metered: true, optionOn: false));
}
/// <summary>A fresh index in a temporary folder and its job engine (not started).</summary>
private static async Task HoldScenarioAsync(Func<Chronos.Data.ChronosDatabase, Chronos.Data.Jobs.JobEngine, Task> body)
{
var folder = Path.Combine(Path.GetTempPath(), "chronos-hold-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(folder);
try
{
await using var db = await Chronos.Data.ChronosDatabase.OpenAsync(Chronos.Data.DatabaseOptions.Sqlite(Path.Combine(folder, "index.db")));
await using var engine = new Chronos.Data.Jobs.JobEngine(db, [], new Chronos.Data.Jobs.JobEngineOptions { Workers = 1, WorkerId = "test" });
await body(db, engine);
}
finally
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (IOException)
{
}
}
}
[Test]
public Task ATransferTheHoldPausedBeforeARestartResumesOnceTheConnectionIsNotMetered() => HoldScenarioAsync(async (db, engine) =>
{
var automatic = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals","automatic":true}""");
var userPaused = Of(JobKind.Download, $$"""{"server":"{{Server}}","mode":"Originals","automatic":true}""");
await db.Jobs.EnqueueAsync(automatic);
await db.Jobs.EnqueueAsync(userPaused);
// The user paused this one before the connection became metered: the hold never paused it.
await db.Jobs.SetStateAsync(userPaused.Id, JobState.Paused, null);
using (var before = new UploadHold(() => db, () => false, () => true))
{
before.Attach(engine);
await before.ApplyAsync();
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(automatic.Id))!.State);
}
// A new hold after a restart reads the record the first one kept in the index.
using var hold = new UploadHold(() => db, () => false, () => false);
hold.Attach(engine);
await hold.ApplyAsync();
Assert.Equal(JobState.Queued, (await db.Jobs.GetAsync(automatic.Id))!.State);
// An automatic transfer the user paused stays paused: the hold resumes only what it paused.
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(userPaused.Id))!.State);
Assert.Equal("[]", await db.Settings.GetJsonAsync(Chronos.Data.Repositories.SettingScope.App, null, UploadHold.RecordKey));
});
[Test]
public Task AJobTheUserPausesWhileHeldIsNeverResumedByTheHold() => HoldScenarioAsync(async (db, engine) =>
{
var automatic = Of(JobKind.UploadCommit, $$"""{"server":"{{Server}}","automatic":true}""");
await db.Jobs.EnqueueAsync(automatic);
var metered = true;
using var hold = new UploadHold(() => db, () => false, () => metered);
hold.Attach(engine);
await hold.ApplyAsync();
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(automatic.Id))!.State);
// The user pauses it from Jobs (the queue tells the hold), then the connection is no longer metered.
using var queue = new Chronos.App.Jobs.EngineJobQueue(db, engine, started: false, acted: id => hold.ForgetAsync(id).GetAwaiter().GetResult());
await queue.PauseAsync(automatic.Id);
metered = false;
await hold.ApplyAsync();
Assert.Equal(JobState.Paused, (await db.Jobs.GetAsync(automatic.Id))!.State);
});
[Test]
public void TransfersWithThisPcsLibraryAndOtherJobsAreNot()
{