fix(copies): close the owner review 6 gaps with tests

Photos not sent: automatic photos of an integrated pair that failed three
times in a row are now told with an error toast that shows the row, and the
row reads "not sent" with the last reason. The matches-found and linked toasts
of background detections run from their Windows notification too.

Maintenance now clears a merge's or an integration's journal whose job is done,
cancelled, or deleted without a cancel and untouched for the history's days.

Tests pin the matches jobs in the priority queue, the owner's defaults (ask
always, union, copy across), the dialog starting from the settings, Choose
each preselecting nothing, no automatic photos for a pair whose server copy
is gone, the repair of a corrupt local frame by an Integrate, and the owner's
whole scenario end to end against a real in-process server.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 14:03:23 +01:00
1 parent fe752a0a21
commit d10577b175
18 files changed
+804 -11

No files matched your search

+6
View File
@@ -23,6 +23,12 @@ commits follow Conventional Commits (release notes are generated from them by `C
- Drop… on Two versions trashes one version on both sides, after re-checking the other one.
- A merge that keeps the pair's other sequence shows it in the first column and applies the choices to it.
- Upload all reads every pair, not only the ones listed.
- New photos of an integrated pair that failed to move three times in a row are told ("photos not sent" · Show) and
their row reads "not sent" with the reason.
- The "matches found" and "sequences linked" toasts of a detection that ran by itself open the matches from their
Windows notification too.
- The maintenance pass clears the journal of a merge or an integration that ended without deleting it, or whose job
was deleted without a cancel and nothing wrote for as long as the job history keeps jobs.
## [1.1.1] — 2026-11-16
+3
View File
@@ -907,3 +907,6 @@ One line per decision: date · decision · alternative · reason.
| 2026-11-17 | A local copy's probe stores the server's newest update time it saw (`copy_probes.server_newest`, in migration 0012); a server sequence is due only when the server shows a newer one (to the microsecond) | Compare with this PC's clock | A server whose clock is behind would hide its new sequences |
| 2026-11-17 | The photo lookup's sample also carries the hashed sample photos by size and capture time; the hit threshold counts each sampled photo once | Hashes only | A server that has not hashed its copy yet (adopted, not verified) lists no hash |
| 2026-11-17 | In a merge keeping the pair's other sequence the dialog swaps its columns; detail index 0 stays "kept" and Different photos are re-keyed to the kept one's version | Keep the pair's order | The merge reads ThisPc and TakeHere as the kept side |
| 2026-11-17 | The maintenance pass clears a merge's or an integration's journal (`merge-<job>.json`, `integrate-<job>.json`) once its job is done or cancelled, or once the index no longer knows the job and nothing wrote the file for the job history's days; a failed or paused job's journal stays for its retry (#73) | Clear it with the job's deletion only | A job deleted without a cancel (or another host's) never deletes its journal itself |
| 2026-11-17 | Automatic photos that failed `SyncAgent.NotSentAfter` (3) times in a row are told once with an error toast "{title}: photos not sent" · Show, which runs from its Windows notification too and shows the row; the row reads "not sent", the last reason in its tooltip, until a transfer succeeds (#73) | A toast at every failure; a badge only | Design §6.1/§7.3: retried quietly with backoff, told when it keeps failing; a toast that only navigates may run from the notification, as the jobs' Open does |
| 2026-11-17 | A Corrupt or Missing frame on this PC whose photo the server holds is repaired by an Integrate through the ordinary fetch: the plan lists it as a Fetch (the comparison leaves unusable frames out), and the ingest replaces the damaged holder in place, the old file moved aside as `.damaged-<time>` (#73) | A repair step of its own | Design §5c says unusable photos are fetched or sent as a repair; the ingest already repairs a damaged holder of the same SHA-256, so no new code was needed, only a test |
+1
View File
@@ -1146,6 +1146,7 @@
<data name="Tooltips.Server.Sync.Filter.FoundCopies" xml:space="preserve"><value>Sequences that seem to be the same here and on the server, or twice on this PC.</value></data>
<data name="Tooltips.Server.Sync.Show" xml:space="preserve"><value>Show this list.</value></data>
<data name="Tooltips.Server.Sync.ShowSkipped" xml:space="preserve"><value>Show the sequences Upload all local left out, first in Local only.</value></data>
<data name="Tooltips.Server.Sync.ShowNotSent" xml:space="preserve"><value>Show the sequence whose new photos were not sent.</value></data>
<data name="Tooltips.Server.Sync.State.CopyFound" xml:space="preserve"><value>This sequence may also be on {0}. Compare to decide.</value></data>
<data name="Tooltips.Server.Sync.State.Skipped" xml:space="preserve"><value>Upload all local left this out: {0}.</value></data>
<data name="Tooltips.Server.Sync.State.NotSent" xml:space="preserve"><value>Photos did not move by themselves: {0}.</value></data>
+1
View File
@@ -1144,6 +1144,7 @@
<data name="Tooltips.Server.Sync.Filter.FoundCopies" xml:space="preserve"><value>Sequenze che sembrano le stesse qui e sul server, o due volte su questo PC.</value></data>
<data name="Tooltips.Server.Sync.Show" xml:space="preserve"><value>Mostra questo elenco.</value></data>
<data name="Tooltips.Server.Sync.ShowSkipped" xml:space="preserve"><value>Mostra per prime in Solo locali le sequenze che Carica le locali ha saltato.</value></data>
<data name="Tooltips.Server.Sync.ShowNotSent" xml:space="preserve"><value>Mostra la sequenza le cui foto nuove non sono state inviate.</value></data>
<data name="Tooltips.Server.Sync.State.CopyFound" xml:space="preserve"><value>Questa sequenza potrebbe essere anche su {0}. Confronta per decidere.</value></data>
<data name="Tooltips.Server.Sync.State.Skipped" xml:space="preserve"><value>Carica le locali l'ha saltata: {0}.</value></data>
<data name="Tooltips.Server.Sync.State.NotSent" xml:space="preserve"><value>Le foto non sono passate da sole: {0}.</value></data>
@@ -1277,7 +1277,7 @@ public sealed class SettingsViewModel : SectionViewModel
private string? ValidateParallelism(string text) => ValidateInt(text, 1, Math.Max(1, LogicalCores * 2));
/// <summary>The kinds the priority queue lists, in the order of the Jobs screen's kinds the user starts most.</summary>
private static readonly JobKind[] PriorityKinds =
internal static readonly JobKind[] PriorityKinds =
[
JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse,
JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move,
@@ -285,14 +285,24 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
await ReloadAsync();
}
/// <summary>"2 matches found" · Review, and "3 sequences linked" · Show (design §8.4).</summary>
/// <summary>
/// "2 matches found" · Review, and "3 sequences linked" · Show (design §8.4), for Find matches and for the detections
/// that run by themselves (after a refresh, a scan, an import): both only navigate, so a click on their Windows
/// notification runs them too.
/// </summary>
internal void Announce(CopyFindResult found)
{
var asking = found.New.Count + found.AskedAgain.Count;
if (asking > 0)
_shell.Notify(Loc.Plural("Server.Copies.Found", asking), null, Loc.L("Server.Copies.Action.Review"), Loc.L("Tooltips.Server.Copies.ReviewFound"), ShowMatches);
{
_shell.Notify(Loc.Plural("Server.Copies.Found", asking), null, Loc.L("Server.Copies.Action.Review"), Loc.L("Tooltips.Server.Copies.ReviewFound"),
ShowMatches, runsFromNotification: true);
}
if (found.AutoLinked.Count > 0)
_shell.Notify(Loc.Plural("Server.Copies.Linked", found.AutoLinked.Count), null, Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.Show"), ShowMatches);
{
_shell.Notify(Loc.Plural("Server.Copies.Linked", found.AutoLinked.Count), null, Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.Show"),
ShowMatches, runsFromNotification: true);
}
}
private void ShowMatches()
+19
View File
@@ -181,6 +181,24 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
/// <summary>Pauses uploads while the connection is metered and the option is on.</summary>
public UploadHold Uploads { get; } = new(services);
/// <summary>
/// The automatic photo transfers of the signed-in server's integrated pairs that failed in a row, by local sequence
/// (owner review 6, #73; design §6.1): a row reads "not sent" from <see cref="SyncAgent.NotSentAfter"/> on. Empty while
/// signed out.
/// </summary>
public IReadOnlyDictionary<Guid, AutoPhotoFailure> PhotoFailures => Agent?.PhotoFailures ?? NoFailures;
/// <summary>
/// The automatic photo transfers of a local sequence failed <see cref="SyncAgent.NotSentAfter"/> times in a row (the
/// server's key, the local sequence, the last failure; any thread): "{title}: photos not sent" · Show.
/// </summary>
public event Action<string, Guid, AutoPhotoFailure>? PhotosNotSent;
/// <summary>Tells <see cref="PhotosNotSent"/> (the agent, and tests).</summary>
internal void TellPhotosNotSent(string server, Guid localId, AutoPhotoFailure failure) => PhotosNotSent?.Invoke(server, localId, failure);
private static readonly IReadOnlyDictionary<Guid, AutoPhotoFailure> NoFailures = new Dictionary<Guid, AutoPhotoFailure>();
/// <summary>The agent started, stopped or compared, or the table of the signed-in server changed (any thread).</summary>
public event Action? Changed;
@@ -510,6 +528,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo
var agent = new SyncAgent(service, remote, () => Policy, services.Engine);
agent.Changed += () => Changed?.Invoke();
agent.ProjectChanged += e => ProjectChanged?.Invoke(remote.Server, e);
agent.PhotosNotSent += (localId, failure) => TellPhotosNotSent(remote.Server, localId, failure);
agent.Start();
Volatile.Write(ref _running, new Running(agent, remote, start));
Log.Info("sync", $"Comparing with {remote.Server}");
+34 -1
View File
@@ -226,6 +226,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
if (_attached) return;
_attached = true;
Host.Changed += OnChanged;
Host.PhotosNotSent += OnPhotosNotSent;
Loc.CultureChanged += OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
@@ -271,6 +272,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
if (!_attached) return;
_attached = false;
Host.Changed -= OnChanged;
Host.PhotosNotSent -= OnPhotosNotSent;
Loc.CultureChanged -= OnCultureChanged;
if (_shell.Services.Jobs is { } jobs)
{
@@ -337,7 +339,8 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
/// <summary>What the Matches list adds to the row of <paramref name="entry"/>: its pair and why Upload all left it out.</summary>
private SyncMark Mark(SyncEntry entry) => entry.Local is { } local
? new SyncMark(Copies.PairOf(local.Id), _skipped.TryGetValue(local.Id, out var why) ? why : null, _shell.Services.Server.Flow.Info?.Name)
? new SyncMark(Copies.PairOf(local.Id), _skipped.TryGetValue(local.Id, out var why) ? why : null, _shell.Services.Server.Flow.Info?.Name,
Host.PhotoFailures.TryGetValue(local.Id, out var failure) && failure.Count >= SyncAgent.NotSentAfter ? failure : null)
: new SyncMark(Copies.PairOf(entry.Id), null, _shell.Services.Server.Flow.Info?.Name);
/// <summary>The rule of Upload all local (design §6.4): what it sends, and what it leaves out and why.</summary>
@@ -550,6 +553,36 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private void OnChanged() => Dispatch(() => _ = ReloadAsync());
private void OnPhotosNotSent(string server, Guid localId, AutoPhotoFailure failure) => Dispatch(() => _ = TellNotSentAsync(localId));
/// <summary>
/// The new photos of an integrated pair failed to move by themselves three times in a row (design §6.1): "{title}: photos
/// not sent" · Show, which shows the sequence's row (it reads "not sent", the reason in its tooltip).
/// </summary>
internal async Task TellNotSentAsync(Guid localId)
{
var title = _entries.FirstOrDefault(e => e.Local?.Id == localId)?.Title;
if (title is null && _shell.Services.Database is { } db)
{
try
{
title = (await db.Sequences.GetAsync(localId))?.DisplayTitle;
}
catch (Data.DatabaseException ex)
{
Log.Warning("sync", "The sequence whose photos were not sent could not be read", ex);
}
}
if (title is null) return;
var shown = title;
_shell.Notify(Loc.L("Server.Sync.NotSentToast", title), null, Loc.L("Server.Sync.Show"), Loc.L("Tooltips.Server.Sync.ShowNotSent"), () =>
{
_shell.Navigate(SectionKey.Server);
ShowFilter(SyncFilter.All, shown);
}, isError: true, runsFromNotification: true);
await ReloadAsync();
}
private void OnCultureChanged(object? sender, EventArgs e) => Dispatch(() =>
{
foreach (var chip in _chips) chip.Relabel();
+9 -5
View File
@@ -49,10 +49,11 @@ public enum SyncAction
}
/// <summary>
/// What the Matches list adds to a sync row (owner review 6, #73): the pair the row's sequence is in, and why Upload all
/// local left it out.
/// What the Matches list adds to a sync row (owner review 6, #73): the pair the row's sequence is in, why Upload all
/// local left it out, and the automatic photo transfers of an integrated pair that failed too often in a row.
/// </summary>
public readonly record struct SyncMark(Data.Copies.FoundCopy? Copy, Data.Copies.UploadSkip? Skipped, string? ServerName = null)
public readonly record struct SyncMark(Data.Copies.FoundCopy? Copy, Data.Copies.UploadSkip? Skipped, string? ServerName = null,
AutoPhotoFailure? NotSent = null)
{
/// <summary>The row's sequence is in a pair nobody answered yet.</summary>
public bool IsCandidate => Copy is { State: Data.Copies.CopyState.Candidate, RemoteGone: false };
@@ -181,8 +182,9 @@ public static class SyncText
/// <summary>
/// The State column with what the Matches list knows (owner review 6, #73): a transfer still shows first; then a sequence
/// in an unanswered pair reads "match found", one whose server copy was deleted "deleted on server" or "kept here", and
/// one Upload all local left out "skipped" with the reason.
/// in an unanswered pair reads "match found", one whose server copy was deleted "deleted on server" or "kept here", one
/// whose new photos failed to move by themselves <see cref="SyncAgent.NotSentAfter"/> times in a row "not sent" with the
/// last reason, and one Upload all local left out "skipped" with the reason.
/// </summary>
public static (StatusKind Kind, string Text, string ToolTip) State(SyncEntry entry, SyncMark mark)
{
@@ -193,6 +195,8 @@ public static class SyncText
? (StatusKind.Offline, Loc.L("Server.Sync.State.KeptHere"), Loc.L("Tooltips.Server.Copies.State.KeptHere"))
: (StatusKind.Warning, Loc.L("Server.Sync.State.RemoteGone"), Loc.L("Tooltips.Server.Copies.State.RemoteGone"));
}
if (mark.NotSent is { Count: >= SyncAgent.NotSentAfter } failure)
return (StatusKind.Warning, Loc.L("Server.Sync.State.NotSent"), Loc.L("Tooltips.Server.Sync.State.NotSent", failure.Reason));
if (mark.IsCandidate)
return (StatusKind.Warning, Loc.L("Server.Sync.State.CopyFound"), Loc.L("Tooltips.Server.Sync.State.CopyFound", mark.ServerName ?? mark.Copy!.Server ?? string.Empty));
if (mark.Skipped is { } why && entry.Status == SyncStatus.LocalOnly)
@@ -201,7 +201,8 @@ public sealed class ArchiveMaintenance
/// stays while a retry can use it, and goes once the job is done. A job this index does not know (another host's on a
/// shared archive, or one its history forgot) may still be resumed where it is known: its journal and staged conversions
/// stay together while any of them was written within as long as the job history keeps jobs, then go together (staged
/// conversions without a journal, which no resume can use, once idle for a day).
/// conversions without a journal, which no resume can use, once idle for a day). The journal of a merge or an integration
/// goes once its job is done or cancelled, or once this index does not know the job and nothing wrote it for as long.
/// </summary>
private async Task<List<string>> PurgeTemporaryFilesAsync(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun,
CancellationToken cancellationToken)
@@ -270,6 +271,16 @@ public sealed class ArchiveMaintenance
var state = await StateAsync(job).ConfigureAwait(false);
if (state == JobState.Done || state is null && Expired(job)) found.Add(file);
}
// A merge's or an integration's journal (owner review 6, #73): its job deletes it when it ends or is cancelled, and
// keeps it after a failure for a retry. One whose job ended anyway (a crash before the delete), or that this index
// no longer knows (a job deleted without a cancel, forgotten by the history, or another host's) and that nothing
// wrote for as long as the history keeps jobs, has no retry left to serve.
foreach (var file in Directory.EnumerateFiles(paths.JournalDirectory, "*.json"))
{
if (CopyJournalJob(Path.GetFileName(file)) is not { } job) continue;
var state = await StateAsync(job).ConfigureAwait(false);
if (state is JobState.Done or JobState.Cancelled || state is null && Old(file, JournalAge)) found.Add(file);
}
}
Collect(paths.MetaDirectory, ".*.tmp", TempAge, recursive: false);
foreach (var location in locations)
@@ -296,6 +307,20 @@ public sealed class ArchiveMaintenance
return found.ConvertAll(paths.ToRelative);
}
/// <summary>The journal prefixes of the matches' jobs (<see cref="MergeJournal"/>, <c>IntegrateJournal</c>): "&lt;prefix&gt;&lt;job:N&gt;.json".</summary>
private static readonly string[] CopyJournalPrefixes = ["merge-", "integrate-"];
/// <summary>The job a merge's or an integration's journal belongs to; null for any other file.</summary>
internal static Guid? CopyJournalJob(string name)
{
if (!name.EndsWith(".json", StringComparison.Ordinal)) return null;
foreach (var prefix in CopyJournalPrefixes)
{
if (name.StartsWith(prefix, StringComparison.Ordinal) && Guid.TryParseExact(name[prefix.Length..^".json".Length], "N", out var job)) return job;
}
return null;
}
private async Task<List<string>> CompactPacksAsync(ArchivePaths paths, IReadOnlyList<SequenceLocation> locations, bool dryRun, CancellationToken cancellationToken)
{
var compacted = new List<string>();
@@ -201,6 +201,105 @@ public sealed class CopyScreenSmokeTests
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);
});
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();
@@ -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()
{
@@ -327,6 +327,36 @@ public sealed class SettingsLogicTests
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: false, active: true));
}
[Test]
public void ThePriorityQueueListsTheMatchesJobsUnderTheirOwnNames()
{
// Owner review 6 (#73): integrating with the server and merging two local copies are jobs the user may rank too.
var kinds = Chronos.App.Sections.SettingsViewModel.PriorityKinds;
Assert.Contains(Chronos.Core.Model.JobKind.Integrate, kinds);
Assert.Contains(Chronos.Core.Model.JobKind.MergeSequences, kinds);
Assert.Equal(kinds.Length, kinds.Distinct().Count());
foreach (var row in kinds.Select(k => new JobPriorityRow(k, _ => default, (_, _) => { }))
.Where(r => r.Kind is Chronos.Core.Model.JobKind.Integrate or Chronos.Core.Model.JobKind.MergeSequences))
{
Assert.False(string.IsNullOrWhiteSpace(row.Label) || row.Label.StartsWith("Jobs.Kind.", StringComparison.Ordinal), row.Label);
Assert.True(row.ToolTip.Contains(row.Label, StringComparison.Ordinal), row.ToolTip);
Assert.True(Loc.GetArea("Jobs", CultureInfo.GetCultureInfo("it")).ContainsKey("Jobs.Kind." + row.Kind), $"Italian name of {row.Kind}");
}
}
[Test]
public void TheMatchesStartFromTheOwnersDefaults()
{
// Owner review 6 (#73): ask before linking, keep every photo of both sides, copy the projects across.
var settings = new AppSettings();
Assert.Equal((Chronos.Data.Copies.CopyLinking.AskAlways, Chronos.Data.Copies.CopyPhotoPolicy.Union, Chronos.Data.Copies.CopyProjects.CopyAcross),
(settings.CopyLinking, settings.CopyPhotos, settings.CopyProjects));
var loaded = AppSettings.Parse("{}")!;
Assert.Equal((Chronos.Data.Copies.CopyLinking.AskAlways, Chronos.Data.Copies.CopyPhotoPolicy.Union, Chronos.Data.Copies.CopyProjects.CopyAcross),
(loaded.CopyLinking, loaded.CopyPhotos, loaded.CopyProjects));
Assert.Equal(Chronos.Data.Copies.CopyLinking.AskAlways, new Chronos.Data.Sync.SyncPolicy().Linking);
}
[Test]
public void FormatsShowTheirTierAndWhatToInstall()
{
@@ -0,0 +1,76 @@
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Tests.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Copies;
/// <summary>
/// What a merge or an integration leaves in the archive's journal folder (owner review 6, #73): the maintenance pass keeps
/// the journal a retry can use and clears the one no job will read again, as it does for conversions.
/// </summary>
[Category("archive")]
public sealed class CopyJournalMaintenanceTests(TestContext context)
{
[Test]
public async Task MaintenanceClearsTheJournalOfAMergeOrIntegrateNoJobWillReadAgain()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var failed = Guid.CreateVersion7();
var done = Guid.CreateVersion7();
var cancelled = Guid.CreateVersion7();
var paused = Guid.CreateVersion7();
foreach (var (id, kind, state) in new[]
{
(failed, JobKind.MergeSequences, JobState.Failed), (done, JobKind.Integrate, JobState.Done),
(cancelled, JobKind.MergeSequences, JobState.Cancelled), (paused, JobKind.Integrate, JobState.Paused),
})
await fx.Db.Jobs.EnqueueAsync(new Job { Id = id, Kind = kind, State = state, Created = DateTimeOffset.UtcNow }, fx.Ct);
// Deleted without a cancel: the index no longer knows the job.
var deleted = Guid.CreateVersion7();
var recent = Guid.CreateVersion7();
const int Old = Housekeeping.CleanupSteps.DefaultHistoryDays + 1;
string Write(string path, int daysOld)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
File.WriteAllText(path, "{}");
File.SetLastWriteTimeUtc(path, DateTime.UtcNow.AddDays(-daysOld));
return path;
}
var failedJournal = Write(MergeJournal.PathFor(fx.Paths, failed), Old);
var doneJournal = Write(IntegrateJournal.PathFor(fx.Paths, done), 0);
var cancelledJournal = Write(MergeJournal.PathFor(fx.Paths, cancelled), 0);
var pausedJournal = Write(IntegrateJournal.PathFor(fx.Paths, paused), Old);
var deletedJournal = Write(MergeJournal.PathFor(fx.Paths, deleted), Old);
var recentJournal = Write(IntegrateJournal.PathFor(fx.Paths, recent), 1);
var other = Write(Path.Combine(fx.Paths.JournalDirectory, "merge-notes.json"), Old);
var dry = await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: true, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.SequenceEqual(new[] { doneJournal, cancelledJournal, deletedJournal }.Select(fx.Paths.ToRelative).Order(), dry.TemporaryFiles.Order());
Assert.FileExists(deletedJournal);
await fx.Service.Maintenance.RunAsync(fx.Archive, dryRun: false, 0, _ => ValueTask.CompletedTask, fx.Ct);
Assert.FileMissing(doneJournal);
Assert.FileMissing(cancelledJournal);
Assert.FileMissing(deletedJournal);
// A retry still reads these: the failed and the paused job's, and one another host may still be writing.
Assert.FileExists(failedJournal);
Assert.FileExists(pausedJournal);
Assert.FileExists(recentJournal);
Assert.FileExists(other);
}
[Test]
public void OnlyTheJournalsOfMergesAndIntegrationsAreRecognised()
{
var job = Guid.CreateVersion7();
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json"));
Assert.Equal(job, ArchiveMaintenance.CopyJournalJob($"integrate-{job:N}.json"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"convert-{job:N}.json"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:N}.json.tmp"));
Assert.Null(ArchiveMaintenance.CopyJournalJob($"merge-{job:D}.json"));
}
}
@@ -280,6 +280,46 @@ public sealed class IntegrateTests(TestContext context)
Assert.False(File.Exists(IntegrateJournal.PathFor(f.Archive.Paths, job.Id)));
}
[Test]
public async Task ACorruptPhotoOnThisPcIsRepairedFromTheServersCopy()
{
await using var f = await FixtureAsync(context);
var local = await LocalAsync(f, "Comet", [(1, 0, "IMG_0001.JPG"), (2, 10_000, "IMG_0002.JPG")]);
var names = await NamesAsync(f, local.Id);
var remote = Remote(f, "Comet", [(1, 0, names[0]), (2, 10_000, names[1])]);
var pair = await PairAsync(f, local.Id, remote.Id);
// A verify finds the second photo damaged on this PC (design §5c: an unusable photo the other side holds is a repair).
var damaged = (await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct)).Single(fr => fr.Sha256 == Sha(2, 10_000));
var file = f.Archive.Paths.FromRelative(damaged.RelativePath);
var bytes = await File.ReadAllBytesAsync(file, f.Ct);
bytes[^10] ^= 0xFF;
await File.WriteAllBytesAsync(file, bytes, f.Ct);
await f.Archive.Service.Verifier.VerifyAsync(f.Archive.Archive, [local.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: f.Ct);
Assert.Equal(FrameFlags.Corrupt, (await f.Db.Frames.GetAsync(damaged.Id, f.Ct))!.Flags);
var (engine, _) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
var plan = await Planner(f).PlanAsync(f.Remote, pair, await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.Union), PlanContext(), f.Ct);
Assert.SequenceEqual([(PhotoAction.Fetch, Sha(2, 10_000))], plan.Photos.Select(p => (p.Action, p.Sha256!)));
Assert.Equal(0, plan.LeftOut);
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
var frames = await f.Db.Frames.ListBySequenceAsync(local.Id, cancellationToken: f.Ct);
Assert.Count(2, frames);
var repaired = frames.Single(fr => fr.Sha256 == Sha(2, 10_000));
Assert.Equal(FrameFlags.None, repaired.Flags & (FrameFlags.Corrupt | FrameFlags.Missing));
var repairedFile = f.Archive.Paths.FromRelative(repaired.RelativePath);
Assert.Equal(Sha(2, 10_000), Sha(await File.ReadAllBytesAsync(repairedFile, f.Ct)));
// The damaged file is kept beside it, never deleted.
var aside = Directory.EnumerateFiles(Path.GetDirectoryName(repairedFile)!, Path.GetFileName(repairedFile) + ".damaged-*").ToList();
Assert.Count(1, aside);
Assert.True((await File.ReadAllBytesAsync(aside[0], f.Ct)).AsSpan().SequenceEqual(bytes), "the damaged file moved aside");
Assert.Equal(0, f.Remote.IntoUploads);
Assert.Equal(CopyState.Integrated, (await f.Sync.Copies.GetAsync(pair.Id, f.Ct))!.State);
}
[Test]
public async Task AJobWhosePlanMovedRefusesAndSetsThePairBack()
{
@@ -197,6 +197,12 @@ internal sealed class FakeSyncRemote : ISyncRemote
return sequence;
}
/// <summary>Someone deletes the sequence on the server: every later call for it answers 404.</summary>
public void Drop(Guid id)
{
lock (_gate) Sequences.Remove(id);
}
/// <summary>Someone else edits the settings on the server.</summary>
public void EditSettings(Guid id, string settingsJson)
{
@@ -1,3 +1,4 @@
using Chronos.Core.IO;
using Chronos.Core.Model;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
@@ -76,6 +77,37 @@ public sealed class SyncAgentCopyTests(TestContext context)
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
}
[Test]
public async Task APairWhoseServerCopyIsGoneQueuesNoAutomaticPhotos()
{
await using var f = await SyncFixture.CreateAsync(context);
// A server keyed by its id, so a 404 counts against the pair (design §7.5).
var nas = new FakeSyncRemote { Server = HomeFolders.IdKey(Guid.NewGuid()) };
var photos = f.NewPhotos(3);
var local = await f.LocalAsync("Comet", photos);
var remote = nas.Add("Comet NAS", photos.Take(2));
await f.Sync.LinkAsync(nas.Server, remote.Id, local.Id, f.Ct);
var row = await f.Sync.Copies.EnsureLinkedAsync(nas.Server, remote.Id, local.Id, f.Ct);
Assert.True(await f.Sync.Copies.SetStateAsync(row.Id, null, CopyState.Integrated,
new CopyAnswer(null, null, null, true, DateTimeOffset.UtcNow), f.Ct));
nas.Drop(remote.Id);
await using var engine = new JobEngine(f.Db, [.. f.Sync.CreateJobHandlers(new SyncFixture.Connector(nas))],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50) });
await using var agent = new SyncAgent(f.Sync, nas, () => new SyncPolicy(), engine, Quick);
await agent.RefreshAsync(f.Ct);
await using (var session = await f.Db.Database.OpenAsync(f.Ct))
await session.ExecuteAsync("UPDATE found_copies SET remote_gone_at = $1 WHERE id = $2", [DateTimeOffset.UtcNow.AddMinutes(-11), row.Id], f.Ct);
await agent.RefreshAsync(f.Ct);
var pair = (await f.Sync.Copies.GetAsync(row.Id, f.Ct))!;
Assert.True(pair.RemoteGoneHits > 0);
Assert.Equal((CopyState.Integrated, true), (pair.State, pair.AutoPhotos));
Assert.Count(0, await QueuedAsync(f, JobKind.UploadCommit));
Assert.Count(0, await QueuedAsync(f, JobKind.Download));
Assert.Count(0, agent.PhotoFailures);
}
[Test]
public async Task FailedTransfersCountWaitForTheirBackoffAndThreeInARowAreTold()
{
@@ -0,0 +1,393 @@
using System.Security.Cryptography;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Copies;
using Chronos.Data.Jobs;
using Chronos.Data.Projects;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol.Client;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Sync;
/// <summary>
/// The owner's scenario of review 6 (#73) end to end, against a real in-process server: a time-lapse uploaded from this PC,
/// an old copy of it found again on a disk adopted as an archive, compared, kept apart, integrated (Union) both ways with
/// the details settled line by line and the projects copied across, its new photos moving by themselves unless the
/// connection is metered, Upload all local leaving a suspected copy out, and two copies on this PC merged into one.
/// </summary>
[Category("server")]
[Timeout(300_000)]
public sealed class CopyScenarioTests(TestContext context)
{
private const string PcName = "STUDIO";
private const string ServerName = "Test server";
private static readonly DateTime Start = new(2026, 9, 28, 18, 0, 0);
private static readonly TimeSpan Deadline = TimeSpan.FromSeconds(60);
private CancellationToken Ct => context.Cancellation;
[Test]
public async Task AnOldCopyFoundOnAnAdoptedDiskIsIntegratedWithTheServerAndMergedOnThisPc()
{
await using var server = await TestServer.StartAsync(context, o => o.ChunkSizeBytes = 64 * 1024, ArchiveModule.Register);
var (_, _, token) = await server.UserAsync("alberto", "editor");
await using var pc = await Pc.StartAsync(context, server, token);
// 1. A time-lapse of eight photos, rated 4, uploaded from this PC.
// Photo 3 carries the camera's sub-second time: two versions of it at that instant under one name are one photo that differs.
static DateTime Captured(int i) => Start.AddSeconds(10 * i).AddMilliseconds(i == 3 ? 250 : 0);
var photos = Enumerable.Range(1, 8).Select(i => Jpeg(Captured(i), i)).ToList();
var original = await pc.LocalAsync(pc.Main, "Comet over the ridge", photos.Select((p, i) => (p, Captured(i + 1))).ToList());
original = (await pc.Db.Sequences.EditAsync(original.Id, new SequenceEdit { Rating = 4 }, null, Ct)).Sequence!;
await pc.WaitAsync((await pc.Sync.EnqueueUploadAsync(pc.Jobs, pc.Server, original, Ct)).Id);
var remoteId = (await pc.Sync.LinkOfAsync(pc.Server, original.Id, Ct))!.RemoteId;
var onServer = Assert.NotNull(await server.Database.Sequences.GetAsync(remoteId));
Assert.True((await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
await ServerIdleAsync(server);
// Freed on this PC since: the server holds it.
await pc.Archives.DeleteAsync(await pc.Archives.PlanDeleteAsync([original.Id], cancellationToken: Ct), "alberto", cancellationToken: Ct);
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, original.Id, Ct));
// 2. An old disk adopted as an archive: photos 1-6 (photo 3 in another version), two more of its own, another title and rating.
var manifest = await pc.Remote.GetManifestAsync(remoteId, Ct);
var names = manifest.Frames.OrderBy(f => f.Index).Select(f => f.FileName).ToList();
var diskRoot = context.CreateTempDirectory("old-disk");
var folder = Path.Combine(diskRoot, "2026-09-28 comet");
Directory.CreateDirectory(folder);
var differing = Jpeg(Captured(3), 103);
var extras = new[] { Jpeg(Start.AddSeconds(5), 201), Jpeg(Start.AddSeconds(75), 202) };
for (var i = 0; i < 6; i++) await File.WriteAllBytesAsync(Path.Combine(folder, names[i]), i == 2 ? differing : photos[i], Ct);
await File.WriteAllBytesAsync(Path.Combine(folder, "IMG_9001.JPG"), extras[0], Ct);
await File.WriteAllBytesAsync(Path.Combine(folder, "IMG_9002.JPG"), extras[1], Ct);
var disk = await pc.Archives.AdoptAsync(diskRoot, "Old disk", Ct);
await pc.Archives.Indexer.ScanAsync(disk, ScanMode.Full, null, _ => ValueTask.CompletedTask, Ct);
var old = Assert.NotNull((await pc.Db.Sequences.ListAsync(new SequenceQuery { ArchiveId = disk.Id }, Ct)).Items.SingleOrDefault());
old = (await pc.Db.Sequences.EditAsync(old.Id, new SequenceEdit { Title = "Old disk comet", Rating = 2 }, null, Ct)).Sequence!;
Assert.Equal(8, old.FrameCount);
// 3. Detection with Ask always (a refresh in the background): the match is listed, told, and not linked.
var told = new List<CopyFindResult>();
pc.Copies.Found += told.Add;
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
var pair = Assert.Contains(await pc.Copies.ListAsync(Ct), v => v.Copy.LocalId == old.Id).Copy;
Assert.Equal((CopyKind.LocalServer, CopyState.Candidate, (Guid?)remoteId), (pair.Kind, pair.State, pair.RemoteId));
Assert.Contains(told.SelectMany(r => r.New), c => c.Id == pair.Id);
Assert.Empty(told.SelectMany(r => r.AutoLinked));
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct));
// 4. Verified (an adopted folder holds no hashes until then), the comparison shows each class of photo.
await pc.Archives.Verifier.VerifyAsync(disk, [old.Id], default, (_, _, _) => ValueTask.CompletedTask, cancellationToken: Ct);
var review = await pc.Copies.CompareAsync(pair.Id, pc.Remote, Ct);
int Count(PhotoClass c) => review.Photos.Photos.Count(p => p.Class == c);
Assert.Equal((5, 2, 2, 1), (Count(PhotoClass.Same), Count(PhotoClass.OnlyHere), Count(PhotoClass.OnlyThere), Count(PhotoClass.Differs)));
Assert.True(review.Photos.Photos.Where(p => p.Class == PhotoClass.OnlyThere).Select(p => p.There!.Sha256).ToHashSet().SetEquals([Sha(photos[6]), Sha(photos[7])]));
Assert.True(review.Photos.Photos.Where(p => p.Class == PhotoClass.OnlyHere).Select(p => p.Here!.Sha256).ToHashSet().SetEquals(extras.Select(Sha)));
var differs = review.Photos.Photos.Single(p => p.Class == PhotoClass.Differs);
Assert.Equal((Sha(differing), Sha(photos[2])), (differs.Here!.Sha256, differs.There!.Sha256));
Assert.Contains(review.Details, d => d.Path == "sequence.title" && d.Here == "Old disk comet" && d.There == onServer.Title);
Assert.Contains(review.Details, d => d.Path == "sequence.rating" && d.Here == "2" && d.There == onServer.Rating.ToString(System.Globalization.CultureInfo.InvariantCulture));
// 5. Keep apart is remembered across refreshes; Ask again brings it back.
await pc.Copies.KeepApartAsync(pair.Id, Ct);
for (var i = 0; i < 2; i++)
{
await pc.Sync.Finder.ResetProbesAsync(pc.Server, Ct);
await pc.Sync.RefreshAsync(pc.Remote, Policy, Ct);
}
Assert.Equal(CopyState.KeptApart, (await pc.Sync.Copies.GetAsync(pair.Id, Ct))!.State);
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct));
await pc.Copies.AskAgainAsync(pair.Id, Ct);
// 6. A project other than Main on each side, under one name, each edited its own way.
await ProjectAsync(new ArchiveProjectHome(pc.Db, pc.Archives.Projects, old.Id), "Vertical", 41);
await ProjectAsync(pc.ServerHome(remoteId), "Vertical", 33);
// 7. Integrate with Union: the server's title, this PC's rating, the rest the server's; the projects copied across.
review = await pc.Copies.CompareAsync(pair.Id, pc.Remote, Ct);
var details = review.Details.Select(d => d.Path).Distinct()
.ToDictionary(p => p, p => p == "sequence.rating" ? CopySide.ThisPc : CopySide.Other);
var plan = await pc.Copies.PlanIntegrateAsync(pair.Id, pc.Remote,
new IntegrateChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), details, CopyProjects.CopyAcross), Ct);
Assert.True(plan.CanApply, string.Join(", ", plan.Blocks));
Assert.Equal((0, true, false), (plan.LeftOut, plan.AutoPhotos, plan.Destructive));
Assert.SequenceEqual(["Other:Vertical (Test server)", "ThisPc:Vertical (STUDIO)"],
plan.Projects.Select(p => $"{p.From}:{p.TargetName}").Order(StringComparer.Ordinal));
await pc.WaitAsync((await pc.Copies.EnqueueIntegrateAsync(pc.Jobs, plan, Ct)).Id);
var union = photos.Select(Sha).Concat(extras.Select(Sha)).Append(Sha(differing)).ToHashSet(StringComparer.Ordinal);
Assert.True((await LocalHashesAsync(pc, old.Id)).SetEquals(union), "this PC holds every photo of both, both versions of photo 3");
Assert.True((await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256!).ToHashSet().SetEquals(union), "and so does the server");
var here = (await pc.Db.Sequences.GetAsync(old.Id, Ct))!;
var there = (await server.Database.Sequences.GetAsync(remoteId))!;
Assert.Equal((onServer.Title, 2), (here.Title, here.Rating));
Assert.Equal((onServer.Title, 2), (there.Title, there.Rating));
static List<string> Names(IEnumerable<SequenceProject> list) => [.. list.Where(p => !p.IsMain).Select(p => p.Name).Order(StringComparer.Ordinal)];
Assert.SequenceEqual(["Vertical", "Vertical (Test server)"], Names(await pc.Archives.Projects.ListAsync(old.Id, Ct)));
Assert.SequenceEqual(["Vertical", "Vertical (STUDIO)"], Names(await pc.ServerHome(remoteId).ListAsync(Ct)));
var integrated = (await pc.Sync.Copies.GetAsync(pair.Id, Ct))!;
Assert.Equal((CopyState.Integrated, true), (integrated.State, integrated.AutoPhotos));
Assert.Equal(remoteId, (await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct))?.RemoteId);
await ServerIdleAsync(server);
// 8. A new photo on this PC moves to the server by itself, but not while the connection is metered.
var later = Jpeg(Start.AddSeconds(200), 301);
await pc.AddPhotoAsync(disk, old.Id, later, Start.AddSeconds(200));
var held = await pc.StopJobsAsync();
await using (var agent = new SyncAgent(pc.Sync, pc.Remote, () => Policy, held, new SyncAgentOptions
{
RefreshInterval = TimeSpan.FromHours(1),
EventDelay = TimeSpan.FromMilliseconds(20),
MinBackoff = TimeSpan.FromMilliseconds(20),
MaxBackoff = TimeSpan.FromMilliseconds(200),
}))
{
await agent.RefreshAsync(Ct);
var automatic = (await pc.Db.Jobs.ListAsync(JobState.Queued, JobKind.UploadCommit, 10, cancellationToken: Ct)).Items.Single();
Assert.Equal((old.Id, JobPriority.Background), (automatic.TargetIds.Single(), automatic.Priority));
// Metered: the hold pauses the transfers with the server (UploadHold, the desktop's, does this on Windows).
await held.PauseAsync(automatic.Id, Ct);
await held.StartAsync(Ct);
await Task.Delay(TimeSpan.FromSeconds(1), Ct);
Assert.Equal(JobState.Paused, (await pc.Db.Jobs.GetAsync(automatic.Id, Ct))!.State);
Assert.DoesNotContain(Sha(later), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256));
// No longer metered: it goes on.
await held.ResumeAsync(automatic.Id, Ct);
await pc.WaitAsync(automatic.Id);
Assert.Contains(Sha(later), (await server.Database.Frames.ListBySequenceAsync(remoteId)).Select(f => f.Sha256));
}
// 9. Upload all local: a copy filed again from the card is a suspected duplicate, skipped and flagged; the rest goes.
var card = await pc.LocalAsync(pc.Main, "Comet from the card", [(photos[0], Start.AddSeconds(10)), (photos[1], Start.AddSeconds(20)),
(Jpeg(Start.AddSeconds(210), 401), Start.AddSeconds(210))]);
var other = await pc.LocalAsync(pc.Main, "Harbour", [(Jpeg(Start.AddDays(1), 501), Start.AddDays(1)), (Jpeg(Start.AddDays(1).AddSeconds(10), 502), Start.AddDays(1).AddSeconds(10))]);
await pc.Copies.FindAsync(pc.Remote, Ct);
var local = Assert.Contains(await pc.Copies.ListAsync(Ct), v => v.Copy.Kind == CopyKind.LocalLocal).Copy;
Assert.True(new[] { local.LocalId, local.OtherId!.Value }.ToHashSet().SetEquals([old.Id, card.Id]));
Assert.Equal(CopyState.Candidate, local.State);
var entries = (await pc.Sync.ListAsync(pc.Server, Ct)).Where(e => e.Status == SyncStatus.LocalOnly);
var (upload, skipped) = UploadAllRule.Select(entries, await pc.Copies.ListAllPairsAsync(Ct), new HashSet<Guid>(), new HashSet<Guid>());
Assert.Equal((card.Id, UploadSkip.SuspectedCopy), (skipped.Single().Entry.Local!.Id, skipped.Single().Why));
Assert.Equal(other.Id, upload.Single().Local!.Id);
await pc.WaitAsync((await pc.Sync.EnqueueUploadAsync(held, pc.Server, upload.Single().Local!, Ct)).Id);
Assert.NotNull(await pc.Sync.LinkOfAsync(pc.Server, other.Id, Ct));
Assert.Null(await pc.Sync.LinkOfAsync(pc.Server, card.Id, Ct));
// 10. The two copies on this PC merge into the linked one; the other goes to the archive trash once every photo is verified there.
review = await pc.Copies.CompareAsync(local.Id, null, Ct);
var merge = await pc.Copies.PlanMergeAsync(local.Id, old.Id,
new MergeChoices(CopyPhotoPolicy.Union, new Dictionary<string, PhotoChoice>(), review.Details.Select(d => d.Path).Distinct().ToDictionary(p => p, _ => CopySide.ThisPc)), Ct);
Assert.True(merge.CanApply, string.Join(", ", merge.Blocks));
Assert.Equal((old.Id, card.Id), (merge.KeepId, merge.DropId));
await pc.WaitAsync((await pc.Copies.EnqueueMergeAsync(held, merge, Ct)).Id);
Assert.Null(await pc.Db.Sequences.GetAsync(card.Id, Ct));
var kept = await pc.Db.Frames.ListBySequenceAsync(old.Id, cancellationToken: Ct);
Assert.Contains(Sha(Jpeg(Start.AddSeconds(210), 401)), kept.Select(f => f.Sha256));
foreach (var frame in kept) Assert.Equal(frame.Sha256, Sha(await File.ReadAllBytesAsync(Path.Combine(disk.RootPath, frame.RelativePath), Ct)));
Assert.Contains(await pc.Archives.ListTrashAsync(pc.Main.Id, Ct), t => t.SequenceId == card.Id);
Assert.Equal(remoteId, (await pc.Sync.LinkOfAsync(pc.Server, old.Id, Ct))?.RemoteId);
}
private static readonly SyncPolicy Policy = new(Linking: CopyLinking.AskAlways);
private static string Sha(byte[] bytes) => Convert.ToHexStringLower(SHA256.HashData(bytes));
/// <summary>A project named <paramref name="name"/> at <paramref name="home"/> with one version of its own (a deflicker window).</summary>
private async Task ProjectAsync(IProjectHome home, string name, int window)
{
var project = await home.CreateAsync(name, null, "alberto", Ct);
var head = await home.HeadAsync(project.Id, Ct);
var portable = ProjectContent.ToPortable(ProjectSettings.FromJson("""{"exposure":{"deflickerWindow":{"isAuto":false,"manual":""" + window + "}}}"), new FramePhotos([]));
var pushed = await home.PushAsync(project.Id, new ProjectVersion
{
Id = Guid.CreateVersion7(),
ProjectId = project.Id,
ParentId = head.Id,
Number = head.Number + 1,
Kind = ProjectVersionKind.Commit,
Author = "alberto",
ClientName = PcName,
SettingsJson = portable,
ContentHash = ProjectContent.Hash(portable),
FramesVersion = head.FramesVersion,
CreatedAt = DateTimeOffset.UtcNow,
}, Ct);
Assert.NotNull(pushed.Version);
}
/// <summary>A small real JPEG with Exif (camera and capture time); each seed gives distinct bytes.</summary>
private static byte[] Jpeg(DateTime captured, int seed)
{
using var image = new ImageBuffer(48, 32);
var random = new Random(seed);
for (var c = 0; c < 3; c++)
{
var plane = image.Plane(c);
var level = (float)random.NextDouble();
for (var i = 0; i < plane.Length; i++) plane[i] = level * (0.5f + 0.5f * (i % 48) / 48f);
}
var exif = ExifWriter.BuildJpegApp1(new FrameMetadata { Make = "Canon", Model = "Canon EOS R5", BodySerial = "0431", CapturedAt = captured, Iso = 100 });
return JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 85, App1Segments = [exif[4..]] });
}
private static async Task<HashSet<string>> LocalHashesAsync(Pc pc, Guid id) =>
(await pc.Db.Frames.ListBySequenceAsync(id, cancellationToken: pc.Ct)).Select(f => f.Sha256!).ToHashSet(StringComparer.Ordinal);
private Task ServerIdleAsync(TestServer server) =>
UntilAsync(async () => await server.Database.Jobs.CountAsync(DateTimeOffset.UtcNow) is { Queued: 0, Running: 0 }, "the server's jobs");
private async Task UntilAsync(Func<Task<bool>> condition, string what)
{
var until = DateTime.UtcNow + Deadline;
while (!await condition())
{
if (DateTime.UtcNow > until) Assert.Fail("Timed out waiting for " + what);
await Task.Delay(50, Ct);
}
}
/// <summary>
/// This PC as the desktop composes it (AppServices): its index and archive, the sync engine, the matches engine with its
/// planners and the server's project homes, and a job engine with the archive, sync, Integrate and Merge handlers.
/// </summary>
private sealed class Pc : IAsyncDisposable
{
private readonly TestContext _context;
private readonly ChronosClient _client;
private readonly Connector _connector;
private Pc(TestContext context, ChronosDatabase db, ArchiveService archives, Archive main, SyncService sync, ChronosClient client)
{
_context = context;
Db = db;
Archives = archives;
Main = main;
Sync = sync;
_client = client;
Remote = new ChronosSyncRemote(client, ownsClient: false);
_connector = new Connector(client);
var sides = new CopySides(db);
var homes = CopyJobs.ServerHomes(_connector);
Copies = new CopyEngine(sync, archives, new IntegratePlanner(sync, sides, archives.Projects, homes), new SequenceMerger(db, archives, sides),
new CopyReviewBuilder(db, archives.Projects, sides, homes), remote => new CopyPlanContext(PcName, remote is null ? null : ServerName,
true, true, true, false, false, remote is not null, null, new HashSet<Guid>(), new HashSet<Guid>()),
serverNames: _ => ServerName);
Jobs = NewJobs();
}
public ChronosDatabase Db { get; }
public ArchiveService Archives { get; }
public Archive Main { get; }
public SyncService Sync { get; }
public ChronosSyncRemote Remote { get; }
public CopyEngine Copies { get; }
public JobEngine Jobs { get; private set; }
public string Server => Remote.Server;
public CancellationToken Ct => _context.Cancellation;
public static async Task<Pc> StartAsync(TestContext context, TestServer server, string token)
{
var ct = context.Cancellation;
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("studio-db"), "chronos.db")), ct);
var options = new ArchiveServiceOptions { Owner = PcName, LeaseWait = TimeSpan.FromSeconds(20) };
var archives = new ArchiveService(db, options);
var main = await archives.CreateAsync(context.CreateTempDirectory("studio-archive"), "Main", cancellationToken: ct);
var sync = new SyncService(db, archives, new SyncOptions { Archive = options, ProxyCacheDirectory = context.CreateTempDirectory("studio-proxies") });
var client = new ChronosClient(server.HttpBase, new CertificatePinning([]), PcName) { Token = token };
var pc = new Pc(context, db, archives, main, sync, client);
await pc.Jobs.StartAsync(ct);
return pc;
}
/// <summary>A job engine over this index with every handler the desktop registers for these jobs (not started).</summary>
public JobEngine NewJobs() => new(Db,
[
.. Archives.CreateJobHandlers(), .. Sync.CreateJobHandlers(_connector),
CopyJobs.CreateIntegrateHandler(Sync, Archives, _connector, Sync.Copies),
SequenceMerger.CreateHandler(Db, new SequenceMerger(Db, Archives, new CopySides(Db)), Archives, new ProjectTransplant(), new NoWorkspace()),
],
new JobEngineOptions { Workers = 2, WorkerId = PcName, PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
/// <summary>Stops the engine that runs jobs as they come and puts one not started in its place: the next jobs wait for it.</summary>
public async Task<JobEngine> StopJobsAsync()
{
await Jobs.DisposeAsync();
return Jobs = NewJobs();
}
public IProjectHome ServerHome(Guid remoteId) => new ServerProjectHome(_client, remoteId, ServerName, null, Server);
/// <summary>A local sequence filed photo by photo through the archive ingest.</summary>
public async Task<Sequence> LocalAsync(Archive archive, string title, IReadOnlyList<(byte[] Bytes, DateTime Captured)> photos)
{
Guid? id = null;
for (var i = 0; i < photos.Count; i++)
{
var result = await IngestAsync(archive, id, id is null ? title : null, photos[i].Bytes, $"IMG_{photos[i].Captured:HHmmss}.JPG", photos[i].Captured);
id = result.SequenceId;
}
return (await Db.Sequences.GetAsync(id!.Value, Ct))!;
}
public Task<IngestResult> AddPhotoAsync(Archive archive, Guid sequenceId, byte[] photo, DateTime captured) =>
IngestAsync(archive, sequenceId, null, photo, $"IMG_{captured:HHmmss}.JPG", captured);
private async Task<IngestResult> IngestAsync(Archive archive, Guid? sequenceId, string? title, byte[] photo, string name, DateTime captured)
{
var staging = Path.Combine(archive.RootPath, ".chronos", "staging", "test");
Directory.CreateDirectory(staging);
var path = Path.Combine(staging, $"{Guid.NewGuid():N}.part");
await File.WriteAllBytesAsync(path, photo, Ct);
return await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, sequenceId, title, null, path, name, photo.Length, Sha(photo), captured, null), Ct);
}
public async Task<Job> WaitAsync(Guid jobId)
{
var until = DateTime.UtcNow.AddSeconds(TestTiming.Budget(60));
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, Ct);
if (job?.State == JobState.Done) return job;
if (job?.State is JobState.Failed or JobState.Cancelled) Assert.Fail($"Job {job.Kind} {job.State}: {job.Error}\n{job.LogTail}");
if (DateTime.UtcNow > until) Assert.Fail($"Job {jobId} did not finish (now {job?.State})");
await Task.Delay(25, Ct);
}
}
public async ValueTask DisposeAsync()
{
await Jobs.DisposeAsync();
Copies.Dispose();
Remote.Dispose();
_client.Dispose();
await Db.DisposeAsync();
}
/// <summary>No workspace here: no sequence has workspace work not sent home.</summary>
private sealed class NoWorkspace : IWorkspaceGuard
{
public Task<bool> HasUnsentAsync(Guid sequenceId, CancellationToken ct) => Task.FromResult(false);
}
/// <summary>The signed-in session: a remote per job and the server's project homes (Settings › Server's server keeps projects).</summary>
private sealed class Connector(ChronosClient client) : ISyncConnector
{
public ValueTask<ISyncRemote?> ConnectAsync(string server, CancellationToken cancellationToken)
{
ISyncRemote remote = new ChronosSyncRemote(client, ownsClient: false);
return ValueTask.FromResult<ISyncRemote?>(remote.Server == server ? remote : null);
}
public IProjectHome? ProjectHome(BundleHome home) =>
home.IsArchive ? null : new ServerProjectHome(client, home.SequenceId, ServerName, null, home.Server);
}
}
}