fix(copies): close the owner review 6 second verification findings

Upload again now deletes the gone pair row once the new sequence is linked, so
the pair stops reading "deleted on server" or "kept here". A linked upload the
server refuses into its sequence (403 for an account without Edit that does not
own it) falls back to ordinary uploads instead of failing; an Integrate that
would add photos to such a sequence is blocked in its plan (NoAddRight).
Automatic photo transfers pause on a metered connection whatever the option
says. Integrate trashes server photos only against the manifest version that
checked the winner, and a merge is blocked while the other sequence holds a
damaged photo nothing else holds (DamagedPhotos), so nothing unverified reaches
the trash.

The plan and the confirmations now say what really happens: replaced versions
are no longer counted as kept, a merge lists the kept sequence's replaced
photos, plan lines use the text colour, an integrated pair that left photos out
says new photos move by hand, and a merging pair reads "merging" with its
progress. The Compare dialog gets per-side tooltips, class sizes for both
sides, policy-aware class tooltips, column headings and readable file names;
the sync table shows "deleted there" with Review and warns on skipped rows; the
Edit picker names the server, the Library card shows the match status second,
a deleted server sequence is named instead of "0 photos", and the match
tooltips stop calling a sequence a copy. The capture scenes use the server
name, the link names and consistent sample sizes.

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 16:08:49 +01:00
1 parent b34b6b6fe0
commit 9657c1711d
44 files changed
+802 -128

No files matched your search

@@ -111,7 +111,7 @@ public sealed class CopyScreenSmokeTests
// 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 = CopyDialogViewModel.ReplaceRequest(Assert.NotNull(dialog.Plan));
var replace = dialog.ReplaceRequest(Assert.NotNull(dialog.Plan));
Assert.True(replace.IsDestructive);
Assert.Equal(Loc.L("Server.Copies.Confirm.Replace.Title"), replace.Heading);
@@ -180,7 +180,8 @@ public sealed class CopyScreenSmokeTests
await LibraryScenes.ShowCopiesAsync(shell, CopyScenes.Alps);
var item = Assert.Contains(shell.Library.Items, i => i.HasMatch && i.Title == CopyScenes.Alps);
Assert.NotNull(item.MatchStatus);
Assert.Contains(item.Statuses, s => s == 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();
+126 -3
View File
@@ -1,4 +1,6 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Server;
using Chronos.App.Server.Copies;
using Chronos.Core.Localization;
@@ -127,7 +129,11 @@ public sealed class CopyTextTests
foreach (var c in Enum.GetValues<PhotoClass>())
{
Assert.False(string.IsNullOrWhiteSpace(CopyText.Class(c)), $"{culture}: {c}");
Assert.False(string.IsNullOrWhiteSpace(CopyText.ClassToolTip(c)), $"{culture}: {c} has a tooltip");
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}");
@@ -176,9 +182,9 @@ public sealed class CopyTextTests
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.
// 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.Offline, Loc.L("Server.Sync.State.Skipped")), (skipped.Kind, skipped.Text));
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 };
@@ -196,6 +202,8 @@ public sealed class CopyTextTests
// 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));
@@ -247,6 +255,121 @@ public sealed class CopyTextTests
], lines);
}
[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));
}
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()
@@ -57,6 +57,23 @@ public sealed class UploadHoldTests
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));
}
[Test]
public void TransfersWithThisPcsLibraryAndOtherJobsAreNot()
{
@@ -472,6 +472,31 @@ public abstract class SequenceMergerTests(TestContext context) : DatabaseTest(co
Assert.Null(await fx.Db.Sequences.GetAsync(drop.Id));
}
[Test]
public async Task AChangedPhotoOfTheOtherNothingElseHoldsBlocksTheMerge()
{
var fx = await FixtureAsync();
var keep = await SequenceAsync(fx, "keep", [(1, 0, "IMG_0001.JPG")]);
var drop = await SequenceAsync(fx, "drop", [(1, 0, "IMG_0001.JPG"), (2, 10_000, "IMG_0002.JPG")]);
// A photo of the other edited after import: a verify flags it Corrupt (changed), its file holds the only copy.
var edited = (await fx.Db.Frames.ListBySequenceAsync(drop.Id)).First(f => f.Sha256 == Sha(2, 10_000));
var file = fx.Paths.FromRelative(edited.RelativePath);
File.WriteAllBytes(file, Photos.Jpeg(Start.AddMilliseconds(10_000), 88));
await fx.Db.Frames.UpdateFlagsAsync([edited.Id], FrameFlags.Corrupt, FrameFlags.None, Ct);
var copy = await PairAsync(fx, keep.Id, drop.Id);
var merger = Merger(fx);
var choices = await ChoicesAsync(fx, keep.Id, drop.Id, CopyPhotoPolicy.Union);
var plan = await merger.PlanAsync(copy.Id, keep.Id, drop.Id, choices, NoContext, Ct);
Assert.Contains(CopyBlock.DamagedPhotos, plan.Blocks);
Assert.False(plan.CanApply);
Assert.Equal(Chronos.Core.Localization.Loc.L("Errors.Copies.DamagedPhotos", "Drop"), SequenceMerger.BlockText(plan, CopyBlock.DamagedPhotos, "Keep", "Drop"));
// Another sequence of this index holds that content too: nothing would be lost, the merge may go on.
await SequenceAsync(fx, "elsewhere", [(88, 10_000, "IMG_0002.JPG")]);
Assert.DoesNotContain(CopyBlock.DamagedPhotos, (await merger.PlanAsync(copy.Id, keep.Id, drop.Id, choices, NoContext, Ct)).Blocks);
}
[Test]
public async Task APhotoAddedToTheOtherOrDeletedFromTheKeptOneMeanwhileKeepsTheOtherOutOfTheTrash()
{
@@ -353,11 +353,13 @@ public sealed class CopyEngineTests(TestContext context)
];
using var engine = new CopyEngine(f.Sync, f.Archive.Service, new IntegratePlanner(f.Sync, sides, f.Archive.Service.Projects),
new SequenceMerger(f.Db, f.Archive.Service, sides), new CopyReviewBuilder(f.Db, f.Archive.Service.Projects, sides), _ => Context,
workspaceProjects: _ => Task.FromResult(projects));
serverNames: key => key == f.Server ? "Studio NAS" : null, workspaceProjects: _ => Task.FromResult(projects));
var twin = (await engine.TwinsAsync(f.Ct)).Single();
Assert.Equal((pair.Id, linked.Id, "Grade", linkedRemote.Id, "Grade NAS"), (twin.CopyId, twin.LocalId, twin.LocalProject, twin.RemoteId, twin.ServerProject));
Assert.Equal(f.Server, twin.Server);
// The Edit picker shows the server by its name, never by its key.
Assert.Equal("Studio NAS", twin.ServerName);
}
}
@@ -199,6 +199,35 @@ public abstract class FoundCopyStoreTests(TestContext context) : RepositoryTest(
Assert.Count(4, await store.ListAsync(Ct));
}
[Test]
public async Task UploadAgainDeletesTheGoneRowLinkedOrKeptHere()
{
var (db, _, s) = await SetupAsync(2);
var store = new FoundCopyStore(db);
foreach (var (sequence, keptHere) in new[] { (s[0], false), (s[1], true) })
{
var (gone, fresh) = (Guid.CreateVersion7(), Guid.CreateVersion7());
var linked = await store.EnsureLinkedAsync(Nas, gone, sequence.Id, Ct);
// A refresh's 404 forgets the link (hit 1); the recheck counts the second.
await store.MarkRemoteGoneAsync(Nas, gone, sequence.Id, Guid.NewGuid(), TestData.Now, Ct);
await store.MarkRemoteGoneAsync(Nas, gone, sequence.Id, Guid.NewGuid(), TestData.Now.AddHours(1), Ct);
if (keptHere) Assert.True(await store.SetStateAsync(linked.Id, null, CopyState.KeptApart, Answer(), Ct));
Assert.True((await store.GetAsync(linked.Id, Ct))!.RemoteGone);
// Upload again: the first original creates a new server sequence and the link points at it.
var uploaded = await store.EnsureLinkedAsync(Nas, fresh, sequence.Id, Ct);
Assert.Null(await store.GetAsync(linked.Id, Ct));
var left = await store.ListByLocalAsync(sequence.Id, Ct);
Assert.Equal((uploaded.Id, CopyState.Linked, (Guid?)fresh, 0), (left.Single().Id, left.Single().State, left.Single().RemoteId, left.Single().RemoteGoneHits));
// Upload all local no longer reads it as deleted on the server.
var entry = new SyncEntry(sequence, null, SyncStatus.LocalOnly);
var (upload, skipped) = UploadAllRule.Select([entry], left, new HashSet<Guid>(), new HashSet<Guid>());
Assert.Empty(skipped);
Assert.Count(1, upload);
}
}
[Test]
public async Task A404CountsOncePerRefreshAndDeletesTheCandidatesOfThatRemote()
{
@@ -221,6 +221,14 @@ public sealed class IntegrateTests(TestContext context)
plan = await planner.PlanAsync(f.Remote, pair, choices, PlanContext(canUpload: false, canFetch: false), f.Ct);
Assert.Contains(CopyBlock.NoUploadRight, plan.Blocks);
Assert.Contains(CopyBlock.NoFetchRight, plan.Blocks);
// Photos sent into a server sequence the account neither owns nor may edit: the server would refuse them (403).
var readUpload = PlanContext(canDelete: false) with { CanEdit = false, UserId = Guid.NewGuid() };
Assert.Contains(CopyBlock.NoAddRight, (await planner.PlanAsync(f.Remote, pair, choices, readUpload, f.Ct)).Blocks);
Assert.Equal(Loc.L("Errors.Copies.NoAddRight"), IntegratePlanner.BlockText(plan, CopyBlock.NoAddRight, "Comet", "NAS"));
remote.OwnerUserId = readUpload.UserId;
Assert.DoesNotContain(CopyBlock.NoAddRight, (await planner.PlanAsync(f.Remote, pair, choices, readUpload, f.Ct)).Blocks);
Assert.DoesNotContain(CopyBlock.NoAddRight, (await planner.PlanAsync(f.Remote, pair, choices, PlanContext(canDelete: false), f.Ct)).Blocks);
remote.OwnerUserId = null;
// A detail without a side.
plan = await planner.PlanAsync(f.Remote, pair, choices with { Details = new Dictionary<string, CopySide>() }, PlanContext(), f.Ct);
@@ -433,6 +441,26 @@ public sealed class IntegrateTests(TestContext context)
Assert.DoesNotContain(Sha(5, 30_250), await LocalHashesAsync(f, local.Id));
}
[Test]
public async Task AServerSequenceChangedAfterTheWinnerCheckKeepsItsLoser()
{
await using var f = await FixtureAsync(context);
var (engine, _) = Engine(f);
await using var _ = engine;
await engine.StartAsync(f.Ct);
var (local, remote, pair) = await ScenarioAsync(f);
var plan = await Planner(f).PlanAsync(f.Remote, pair, await ChoicesAsync(f, local.Id, remote.Id, CopyPhotoPolicy.ThisPcWins), PlanContext(), f.Ct);
// Another client changes the server sequence after the job read the manifest that showed the winner in place.
f.Remote.OnceBeforeDelete = () => remote.FramesVersion++;
var job = await CopyJobs.EnqueueIntegrateAsync(engine, f.Sync.Copies, plan, local.DisplayTitle, f.Ct);
var failed = await f.Archive.WaitForAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.Plural("Errors.Copies.Kept", 1), failed.Error);
Assert.Empty(f.Remote.Trashed);
Assert.Contains(Sha(5, 30_250), RemoteHashes(remote));
}
[Test]
public async Task AServerRefusalKeepsItsLoserAndTheRestIsDone()
{
@@ -79,6 +79,17 @@ internal sealed class FakeSyncRemote : ISyncRemote
public int CopiedInto { get; private set; }
/// <summary>
/// Uploads into a target refused with 403, as for an account with Read and Upload but not Edit that does not own the
/// target; <see cref="RefusedInto"/> counts them.
/// </summary>
public bool ForbidInto { get; set; }
public int RefusedInto { get; private set; }
/// <summary>Runs once, before the next frame deletion is answered (the server sequence changing meanwhile).</summary>
public Action? OnceBeforeDelete { get; set; }
/// <summary>Frame deletions refused with 403, as for an account that is neither the owner nor an admin.</summary>
public bool ForbidFrameDeletes { get; set; }
@@ -139,6 +150,11 @@ internal sealed class FakeSyncRemote : ISyncRemote
bool capable;
lock (_gate) capable = Capabilities.Contains(ServerCapabilities.UploadInto);
if (!capable) return await UploadFileAsync(path, sequenceId, null, sha256, capturedAt, cancellationToken);
if (ForbidInto)
{
lock (_gate) RefusedInto++;
throw new ChronosApiException(HttpStatusCode.Forbidden, new ApiError("forbidden", "into"));
}
var bytes = await File.ReadAllBytesAsync(path, cancellationToken);
if (Convert.ToHexStringLower(SHA256.HashData(bytes)) != sha256)
throw new ChronosApiException(HttpStatusCode.BadRequest, new ApiError("hash_mismatch", "hash"));
@@ -162,6 +178,11 @@ internal sealed class FakeSyncRemote : ISyncRemote
/// </summary>
public Task<FrameDeleteResultDto> DeleteFramesAsync(Guid sequenceId, FrameDeleteRequest request, CancellationToken cancellationToken)
{
if (OnceBeforeDelete is { } before)
{
OnceBeforeDelete = null;
before();
}
lock (_gate)
{
var sequence = Find(sequenceId);
@@ -492,7 +513,10 @@ internal sealed class FakeSequence
}
public SequenceDto Dto() => new(Id, Title, Title ?? "Untitled", "2026/" + Id.ToString("N"), "Canon", CameraModel, null, FirstCapture, null, Frames.Count, 10,
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, null, UpdatedAt);
Frames.Sum(f => (long)f.Bytes.Length), (long)Status, Renders.Count, null, Tags, Rating, Notes, SettingsVersion, FramesVersion, 0, OwnerUserId, UpdatedAt);
/// <summary>The server account that owns the sequence (none by default).</summary>
public Guid? OwnerUserId { get; set; }
public SequenceManifest Manifest(Func<Guid, bool> proxySent) => new(Id, FramesVersion, SettingsVersion, SettingsJson, Tags,
[.. Frames.Select((f, i) => new ManifestFrame(f.Id, i, f.FileName, f.Bytes.Length, Unhashed ? string.Empty : f.Sha256,
@@ -224,4 +224,25 @@ public sealed class SyncTransferCopyTests(TestContext context)
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.Equal((1, 1), (f.Remote.IntoUploads, f.Remote.CopiedInto));
}
[Test]
public async Task ALinkedUploadTheServerRefusesIntoItsTargetStillFilesEveryOriginal()
{
await using var f = Capable(await SyncFixture.CreateAsync(context));
// An account with Read and Upload but not Edit, whose local sequence is linked to another account's: 403 for "into".
f.Remote.ForbidInto = true;
var photos = f.NewPhotos(4);
var local = await f.LocalAsync("Comet", photos);
var remote = f.Remote.Add("Comet", [photos[0]]);
await f.Sync.LinkAsync(f.Server, remote.Id, local.Id, f.Ct);
var engine = await f.StartEngineAsync();
var job = await f.Sync.EnqueueUploadAsync(engine, f.Server, local);
await f.Archive.WaitForAsync(job.Id, JobState.Done);
// The refusal falls back to the upload as before the server could file into a target: every original is there.
Assert.True(remote.Frames.Select(fr => fr.Sha256).ToHashSet().SetEquals(photos.Select(Sha)));
Assert.True(f.Remote.RefusedInto >= 1);
Assert.Equal(0, f.Remote.IntoUploads);
}
}