From 43b092bd5dbbd1f72731aa5e539ab04e82551718 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 3 Nov 2026 11:19:21 +0100 Subject: [PATCH] fix(workspace): newer-format editor stays usable; media learn the home's photo names A pull onto a newer Chronos's settings made the editor throw: ProjectHistory.Replace rebased every undo and redo snapshot through ProjectMerge, which refuses to merge a newer format when both sides changed, so any non-empty undo stack broke the reload after a sync that had succeeded. Replace now drops the steps instead when either side (or a step) is of a newer format: the project is shown read-only and undo never brings back values from before the newer settings. The media learnt the home's hashes and conversion aliases only inside a replay, so a status or Save version before that compared a SHA-named base with photo-named media and read a false Modified or saved a version that only re-keyed photos. Now: - ProjectContent.SameChoices also compares the texts as placed on the frames, hashed or not (Bound), so status and commit without a home agree with the base; - a status asked of the home teaches the media its names (written under the lease, or when the lease is free), and so does a checkout of a project already here; - WorkspaceStatus.MediaOutdated reports frames moved at the home, or names the media could not learn yet, and the project menu offers Update media for it (tooltip text updated in en and it). Co-Authored-By: Claude Opus 5.5 --- i18n/en/Tooltips.resx | 2 +- i18n/it/Tooltips.it.resx | 2 +- src/Chronos.App/Editor/ProjectHistory.cs | 13 ++- .../Workspace/ProjectMenuViewModel.cs | 3 +- src/Chronos.Core/Project/ProjectContent.cs | 33 +++++-- src/Chronos.Data/Workspaces/WorkspaceSync.cs | 86 +++++++++++++++-- .../Editor/ProjectHistoryTests.cs | 33 +++++++ .../Workspace/WorkspaceNewerFormatTests.cs | 49 ++++++++++ .../Project/ProjectContentTests.cs | 23 +++++ .../Workspaces/WorkspaceMergeTests.cs | 96 +++++++++++++++++++ 10 files changed, 321 insertions(+), 19 deletions(-) create mode 100644 tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index b48b5abb..0189e145 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -327,7 +327,7 @@ The settings that differ: your value, then the library's Keep your values of these settings; they are sent to the library Decide later and keep editing; Sync asks again - Photos were added to or removed from this sequence in the library after the workspace copied it + The library added, removed, converted or verified photos of this sequence after the workspace copied it Open project {0}, which holds your versionslong Keep the library's values in this project, and send yours to a new project “{0}”{0} the new project's name Versions saved here that wait to be sent to the library: {0}. Sync sends them{0} number of versions diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index d3b216a5..46054e19 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -326,7 +326,7 @@ Le impostazioni diverse: il tuo valore, poi quello della libreria Tieni i tuoi valori di queste impostazioni; vengono inviati alla libreria Decidi più tardi e continua a modificare; Sincronizza lo chiede di nuovo - Sono state aggiunte o tolte foto a questa sequenza nella libreria dopo che lo spazio di lavoro l'ha copiata + La libreria ha aggiunto, tolto, convertito o verificato foto di questa sequenza dopo che lo spazio di lavoro l'ha copiata Apri il progetto {0}, che contiene le tue versioni Tieni i valori della libreria in questo progetto e invia i tuoi a un nuovo progetto «{0}» Versioni salvate qui in attesa di essere inviate alla libreria: {0}. Sincronizza le invia diff --git a/src/Chronos.App/Editor/ProjectHistory.cs b/src/Chronos.App/Editor/ProjectHistory.cs index fc396f9f..bb909cae 100644 --- a/src/Chronos.App/Editor/ProjectHistory.cs +++ b/src/Chronos.App/Editor/ProjectHistory.cs @@ -69,12 +69,23 @@ public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200, /// /// Adopts a project changed outside the editor (analysis advice, another client's edit merged on save) without an /// undo step. Every undo and redo snapshot takes the same outside change, so undo reverts only the user's own steps - /// and never brings back a value that predates the adopted change. + /// and never brings back a value that predates the adopted change. Settings of a newer Chronos on either side (a pull + /// took them: the project is shown read-only) are never merged with this one's (), so no step + /// can take that change: the undo and redo steps go instead, and undo never brings back values from before it. /// public void Replace(ProjectSettings current) { ArgumentNullException.ThrowIfNull(current); if (ProjectMerge.SameValues(current, Current)) return; + if (current.IsNewerFormat || Current.IsNewerFormat || _undo.Any(s => s.IsNewerFormat) || _redo.Any(s => s.IsNewerFormat)) + { + _undo.Clear(); + _redo.Clear(); + _runKey = null; + Current = current; + Changed?.Invoke(); + return; + } var (basis, theirs) = (Current, current); Func rebase = merge is null ? new ProjectMerge.Rebase(basis, theirs).Apply : step => merge(basis, step, theirs); Rebase(_undo, rebase); diff --git a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs index f6a49add..4c44b3d6 100644 --- a/src/Chronos.App/Workspace/ProjectMenuViewModel.cs +++ b/src/Chronos.App/Workspace/ProjectMenuViewModel.cs @@ -170,7 +170,8 @@ public sealed class ProjectMenuViewModel : LocalizedViewModel var status = await _host.StatusAsync(ProjectId); var moved = await _source.HomeFramesChangedAsync(CancellationToken.None); if (_disposed) return; - _homeFramesChanged = moved; + // Also photos the library named otherwise since the copy (hashed, converted) while the media could not learn it. + _homeFramesChanged = moved || status.MediaOutdated; Apply(status); } catch (Exception ex) when (ex is not OutOfMemoryException) diff --git a/src/Chronos.Core/Project/ProjectContent.cs b/src/Chronos.Core/Project/ProjectContent.cs index 41fbfff5..3269106a 100644 --- a/src/Chronos.Core/Project/ProjectContent.cs +++ b/src/Chronos.Core/Project/ProjectContent.cs @@ -69,6 +69,21 @@ public static class ProjectContent { ArgumentNullException.ThrowIfNull(portableJson); ArgumentNullException.ThrowIfNull(frames); + return Renamed(portableJson, frames, hashedOnly: true); + } + + /// + /// The portable text with each pending frame whose photo hold named as the frame holding it is, + /// hashed or not, which copy of it included: what the text places on these frames, read so to compare two texts only + /// (). Unlike , a SHA-256 the frames do not know yet (the photo hashed where + /// the text was saved, not when the frames were copied) gives way to the frame's size and capture time, so a text saved + /// on hashed frames and one saved on frames not hashed yet read alike. Always canonical. + /// + private static string Bound(string portableJson, FramePhotos frames) => Canonical(Renamed(portableJson, frames, hashedOnly: false)); + + /// (: only onto frames that are hashed), else 's renaming. + private static string Renamed(string portableJson, FramePhotos frames, bool hashedOnly) + { if (frames.Count == 0 || !portableJson.Contains("pendingFrames", StringComparison.OrdinalIgnoreCase)) return portableJson; if (FormatOf(portableJson) > ProjectSettings.CurrentVersion) return portableJson; if (JsonNode.Parse(portableJson, new JsonNodeOptions { PropertyNameCaseInsensitive = true }) is not JsonObject project @@ -81,15 +96,17 @@ public static class ProjectContent DateTime? captured = entry["capturedAt"] is JsonValue t && t.TryGetValue(out var time) ? time : null; if (string.IsNullOrEmpty(sha) && (captured is null || size < 0)) continue; var occurrence = entry["occurrence"] is JsonValue o && o.TryGetValue(out var n) && n > 0 ? n : 0; - // Only a frame that is hashed names a photo better than the entry does. - if (frames.IndexOf(new FramePhoto(sha, size, captured), occurrence) is not { } at || frames[at] is not { IsHashed: true } held) continue; + // Only a frame that is hashed names a photo better than the entry does (to keep; to compare, any frame does). + if (frames.IndexOf(new FramePhoto(sha, size, captured), occurrence) is not { } at || frames[at] is not { } held || (hashedOnly && !held.IsHashed)) continue; // The copy a placement looks for under the new name: among the frames holding that SHA-256, not those of that size and time. var copy = frames.Occurrence(at); var sameTime = held.CapturedAt is { } heldAt ? captured is { } entryAt && FramePhoto.Millisecond(heldAt) == FramePhoto.Millisecond(entryAt) : captured is null; - if (string.Equals(held.Sha256, sha, StringComparison.OrdinalIgnoreCase) && held.Size == size && sameTime && copy == occurrence) continue; - entry["sha256"] = held.Sha256!.ToLowerInvariant(); + if (string.Equals(held.Sha256 ?? string.Empty, sha ?? string.Empty, StringComparison.OrdinalIgnoreCase) && held.Size == size && sameTime + && copy == occurrence) continue; + if (held.IsHashed) entry["sha256"] = held.Sha256!.ToLowerInvariant(); + else entry.Remove("sha256"); entry["size"] = held.Size; if (held.CapturedAt is { } heldTime) entry["capturedAt"] = heldTime; else entry.Remove("capturedAt"); @@ -169,7 +186,9 @@ public static class ProjectContent /// /// Whether two portable texts hold the same choices on the frames of : the same text, or the - /// same once their pending frames are named as the frames hold their photos now (). + /// same once their pending frames are named as the frames hold their photos now (), or as the frame + /// each lands on is named, hashed or not (): a version saved where a photo was hashed after these + /// frames were copied holds what a working state saved on them does, so it reads neither as a change nor as one to save. /// /// A text is not a project object. public static bool SameChoices(string portable, string other, FramePhotos frames) @@ -177,7 +196,9 @@ public static class ProjectContent ArgumentNullException.ThrowIfNull(portable); ArgumentNullException.ThrowIfNull(other); ArgumentNullException.ThrowIfNull(frames); - return portable == other || (frames.Count > 0 && Rebind(portable, frames) == Rebind(other, frames)); + if (portable == other) return true; + if (frames.Count == 0) return false; + return Rebind(portable, frames) == Rebind(other, frames) || (frames.HasUnhashed && Bound(portable, frames) == Bound(other, frames)); } /// diff --git a/src/Chronos.Data/Workspaces/WorkspaceSync.cs b/src/Chronos.Data/Workspaces/WorkspaceSync.cs index 8a76265d..1bcbf590 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceSync.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceSync.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text.Json; +using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; using Chronos.Core.Model; using Chronos.Core.Project; @@ -46,7 +47,16 @@ public enum WorkspaceState /// The home's version the project was last in step with. /// The home's newest version, when it was asked. public sealed record WorkspaceStatus(WorkspaceState State, bool Modified, int Ahead, int Behind, bool Offline, bool MediaRemoved, bool ReadOnly, - WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead); + WorkspaceConflict? Conflict, BundleBase? Base, ProjectVersion? HomeHead) +{ + /// + /// The media are behind the home's frames, as the home was asked: frames added, removed or converted there since the copy + /// (Update media copies them again), or photos the home names otherwise now (hashed, or joined to another encoding, + /// there since) whose names the media could not learn yet because another operation held the project. Every sync + /// teaches the media the home's names; false without a home asked. + /// + public bool MediaOutdated { get; init; } +} /// What a push, pull or resolve did: the versions it stored at the home and those it took from there, and where it left the project. /// After : the new project at the home holding this workspace's versions. @@ -134,7 +144,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) /// The project of brought into the workspace: its folder, the home's /// head as the base and the working state (positions waiting for the media, which a /// job copies: ). A project already here is left as - /// it is. + /// it is, but for its media's names of the photos (). /// /// The home has no such project. /// A project of that id from another home is in the workspace. @@ -150,6 +160,15 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) var existing = project.ReadBundle(); if (existing.Workspace!.Home.SequenceId != sequence.Home.SequenceId) throw new InvalidOperationException($"Project {projectId} in the workspace belongs to another sequence."); + // Opened again: its media learn how the home names its photos now, as a sync's do (damaged ones are copied again). + try + { + await MediaNamedAsAtHomeAsync(project, home, cancellationToken).ConfigureAwait(false); + } + catch (InvalidDataException ex) + { + Log.Warning("workspace", $"The media index of workspace project {projectId} cannot be read", ex); + } return project; } var listed = (await home.ListAsync(cancellationToken).ConfigureAwait(false)).FirstOrDefault(p => p.Id == projectId) @@ -378,11 +397,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) } } - /// Where the project stands; with a , against the home's head too (offline when it cannot be reached). + /// + /// Where the project stands; with a , against the home's head too (offline when it cannot be + /// reached), the media naming the photos as the home does now (written when the project's lease is free). + /// public async Task StatusAsync(Guid projectId, IProjectHome? home = null, CancellationToken cancellationToken = default) { var project = Existing(projectId); - return await StatusLockedAsync(project, home, cancellationToken).ConfigureAwait(false); + return await StatusLockedAsync(project, home, cancellationToken, leased: false).ConfigureAwait(false); } /// The versions this workspace saved and has not pushed yet, oldest first. @@ -767,7 +789,14 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) return version; } - private async Task StatusLockedAsync(WorkspaceProject project, IProjectHome? home, CancellationToken cancellationToken) + /// + /// Where the project stands. With a , the media first learn how it names its photos now (a photo + /// hashed or converted there since the copy, ), so a version the home made since + /// and the working state name each photo alike: written at once while the project's lease is held + /// (), else when it can be taken without waiting ( + /// when it cannot). + /// + private async Task StatusLockedAsync(WorkspaceProject project, IProjectHome? home, CancellationToken cancellationToken, bool leased = true) { var bundle = project.ReadBundle(); var workspace = bundle.Workspace!; @@ -782,22 +811,32 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) } var conflict = project.ReadSync().Conflict; var locals = Unpushed(project, bundle); - var tipHash = locals.Count > 0 ? locals[^1].ContentHash : workspace.Base?.ContentHash; - var modified = !bundle.IsReadOnly && (Portable(bundle.Project, media) is not { } portable - || (ProjectContent.Hash(portable) != tipHash && !SameAsTip(project, bundle, locals, portable, media))); ProjectVersion? head = null; + HomeFrames? frames = null; var offline = false; if (home is not null) { try { head = await home.HeadAsync(project.ProjectId, cancellationToken).ConfigureAwait(false); + if (media is not null) frames = await home.FramesAsync(cancellationToken).ConfigureAwait(false); } catch (HomeUnavailableException) { offline = true; } } + var outdated = false; + if (media is not null && frames is not null) + { + var named = media.NamedAsAt(frames); + if (!ReferenceEquals(named, media)) outdated = !await LearnNamesAsync(project, frames, leased, cancellationToken).ConfigureAwait(false); + outdated |= frames.FramesVersion != media.FramesVersion; + media = named; + } + var tipHash = locals.Count > 0 ? locals[^1].ContentHash : workspace.Base?.ContentHash; + var modified = !bundle.IsReadOnly && (Portable(bundle.Project, media) is not { } portable + || (ProjectContent.Hash(portable) != tipHash && !SameAsTip(project, bundle, locals, portable, media))); var behind = head is not null && head.Id != workspace.Base?.VersionId ? Math.Max(1, head.Number - (workspace.Base?.Number ?? 0)) : 0; // A local commit the home stored although its answer was lost reads as behind by the commits it holds: they are ours. if (head is not null && locals.Any(v => v.Id == head.Id)) behind = 0; @@ -808,7 +847,36 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) : locals.Count > 0 ? WorkspaceState.Ahead : modified ? WorkspaceState.Modified : WorkspaceState.InSync; - return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head); + return new WorkspaceStatus(state, modified, locals.Count, behind, offline, media is null, bundle.IsReadOnly, conflict, workspace.Base, head) + { + MediaOutdated = outdated, + }; + } + + /// + /// Writes the media with the photos named as name them (read again under the lease: a copy + /// may have written new media meanwhile); without , only when the lease is free now. Whether + /// the media know the home's names. + /// + private async Task LearnNamesAsync(WorkspaceProject project, HomeFrames frames, bool leased, CancellationToken cancellationToken) + { + IDisposable? lease = null; + try + { + if (!leased) lease = await project.LockAsync(TimeSpan.Zero, cancellationToken).ConfigureAwait(false); + if (project.ReadMedia() is not { } media) return false; + var named = media.NamedAsAt(frames); + if (!ReferenceEquals(named, media)) project.WriteMedia(named); + return true; + } + catch (Exception ex) when (ex is LeaseUnavailableException or InvalidDataException) + { + return false; + } + finally + { + lease?.Dispose(); + } } /// diff --git a/tests/Chronos.App.Tests/Editor/ProjectHistoryTests.cs b/tests/Chronos.App.Tests/Editor/ProjectHistoryTests.cs index 33ad5a47..f7e8505a 100644 --- a/tests/Chronos.App.Tests/Editor/ProjectHistoryTests.cs +++ b/tests/Chronos.App.Tests/Editor/ProjectHistoryTests.cs @@ -1,5 +1,6 @@ using Chronos.App.Editor; using Chronos.Core.Project; +using Chronos.Data.Projects; using Chronos.Testing; namespace Chronos.App.Tests.Editor; @@ -113,6 +114,38 @@ public sealed class ProjectHistoryTests Assert.Null(history.Current.HeroFrame, "the user's step reverts the value it set"); } + [Test] + public void SettingsOfANewerChronosAdoptedDropTheStepsInsteadOfMergingThem() + { + var newer = ProjectSettings.FromJson("""{ "version": 2, "exposure": { "exposureOffsetEv": 1.5 }, "grade": { "look": "film" } }""", allowNewer: true); + // The workspace's merge throws as ProjectMerge does where both sides changed and one is a newer Chronos's. + foreach (var merge in new Func?[] + { null, (basis, ours, theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs).Merged }) + { + var history = new ProjectHistory(new ProjectSettings(), merge: merge); + history.Apply(WithOffset(history.Current, 0.3)); + history.Apply(history.Current with { HeroFrame = 2 }); + history.Undo(); + Assert.True(history.CanUndo && history.CanRedo); + var changes = 0; + history.Changed += () => changes++; + + // A pull took the newer settings (nothing of the editor's waited): shown as they are, read-only. + history.Replace(newer); + Assert.True(history.Current.IsNewerFormat); + Assert.Equal(1.5, history.Current.Exposure.ExposureOffsetEv); + Assert.False(history.CanUndo, "no step brings back this Chronos's values over a newer one's"); + Assert.False(history.CanRedo); + Assert.False(history.Undo()); + Assert.Equal(1, changes); + + // Back to this Chronos's format (a Save both took another project): nothing is merged into the newer settings either. + history.Replace(WithOffset(new ProjectSettings(), 0.6)); + Assert.Equal(0.6, history.Current.Exposure.ExposureOffsetEv); + Assert.False(history.CanUndo); + } + } + [Test] public void EndingARunMakesTheNextEditANewStep() { diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs new file mode 100644 index 00000000..21775e98 --- /dev/null +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs @@ -0,0 +1,49 @@ +using Chronos.Core.Project; +using Chronos.Testing; + +namespace Chronos.App.Tests.Workspace; + +/// +/// The editor of a workspace project whose home moved to settings of a newer Chronos (owner review 2, R8): shown read-only, +/// never merged with this Chronos's, the editor usable whatever its undo steps hold. +/// +[Category("workspace")] +public sealed class WorkspaceNewerFormatTests(TestContext context) +{ + private static ProjectSettings Exposure(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } }; + + [Test] + public async Task AnEditorWithUndoStepsTakesANewerChronossSettingsReadOnly() + { + await using var bed = await WorkspaceTestBed.CreateAsync(context); + var host = bed.Host(); + var projectId = await bed.CheckoutAsync(host); + var (_, session) = await bed.OpenAsync(host, projectId); + await using (session) + { + // Edited, saved and kept as a version: every edit is stored, the undo steps stay. + Assert.True(session.Edit(p => Exposure(p, 0.4))); + Assert.True(session.Edit(p => p with { ExcludedFrames = [2] })); + Assert.True(await session.FlushAsync()); + Assert.NotNull(await host.CommitAsync(projectId, bed.Ct)); + Assert.True(session.History.CanUndo); + + // A pull with nothing of this PC's waiting moved the working state onto a newer Chronos's settings. + var folder = host.Store.Find(projectId)!; + var stored = folder.ReadBundle(); + folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } }); + await session.ReloadAsync(); + + Assert.True(session.IsReadOnly); + Assert.True(session.Project.IsNewerFormat); + Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv); + Assert.False(session.History.CanUndo, "no step brings this Chronos's values back over the newer ones"); + Assert.False(session.Undo()); + Assert.False(session.Edit(p => Exposure(p, 0.2))); + Assert.False(session.HasPendingSave); + // Read again (another analysis, another pull): the editor stays as it is. + await session.ReloadAsync(); + Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv); + } + } +} diff --git a/tests/Chronos.Core.Tests/Project/ProjectContentTests.cs b/tests/Chronos.Core.Tests/Project/ProjectContentTests.cs index 44e9db62..ef1de52d 100644 --- a/tests/Chronos.Core.Tests/Project/ProjectContentTests.cs +++ b/tests/Chronos.Core.Tests/Project/ProjectContentTests.cs @@ -135,6 +135,29 @@ public sealed class ProjectContentTests Assert.Equal(newer, ProjectContent.Rebind(newer, now)); } + [Test] + public void ChoicesSavedWhereAPhotoWasHashedReadAsTheSameOnFramesCopiedBeforeIt() + { + // A workspace copied photo 1 before its home hashed it; a version the home made since names it by its SHA-256. + var copied = Frames(Photo(1, hashed: false), Photo(2), Photo(3)); + var home = Frames(Photo(1), Photo(2), Photo(3)); + var choices = new ProjectSettings { ExcludedFrames = [0], Camera = new CameraSettings { Keyframes = [new CameraKey(0, 0.3, 0.5, 1.2, 0)] } }; + var atHome = ProjectContent.ToPortable(choices, home); + var here = ProjectContent.ToPortable(choices, copied); + Assert.NotEqual(atHome, here); + + // The same choices on the frames held here: no change to show or to save as a version. + Assert.True(ProjectContent.SameChoices(atHome, here, copied)); + Assert.True(ProjectContent.SameChoices(here, atHome, copied)); + // What is kept keeps the hash the frames do not know yet; a choice of its own still differs. + Assert.Equal(atHome, ProjectContent.Rebind(atHome, copied)); + Assert.False(ProjectContent.SameChoices(atHome, ProjectContent.ToPortable(new ProjectSettings { ExcludedFrames = [1] }, copied), copied)); + Assert.False(ProjectContent.SameChoices(atHome, ProjectContent.ToPortable(choices with { ExcludedFrames = [] }, copied), copied)); + // A photo none of the frames holds is compared as it is named. + var gone = ProjectContent.ToPortable(choices, Frames(Photo(4))); + Assert.False(ProjectContent.SameChoices(gone, ProjectContent.ToPortable(choices, Frames(Photo(4, hashed: false))), copied)); + } + [Test] public void APhotoOfABurstToldApartByItsOrderKeepsItsPositionOnceHashed() { diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceMergeTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceMergeTests.cs index d36d43ce..ed8518d3 100644 --- a/tests/Chronos.Data.Tests/Workspaces/WorkspaceMergeTests.cs +++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceMergeTests.cs @@ -118,6 +118,102 @@ public abstract class WorkspaceMergeTests(TestContext context) : DatabaseTest(co Assert.Null(await sync.CommitAsync(id, cancellationToken: fx.Ct)); } + [Test] + public async Task ABaseNamingAPhotoByItsHashReadsAsTheWorkingStateOnMediaThatHaveNotLearntIt() + { + var fx = await FixtureAsync(); + await UnhashAsync(fx, 2); + var (_, sync) = fx.Workspace(); + var project = await fx.CheckoutAsync(sync); + var id = project.ProjectId; + var copied = project.ReadMedia()!; + await EditAsync(sync, id, s => s with { ExcludedFrames = [2] }, fx.Ct); + await sync.CommitAsync(id, cancellationToken: fx.Ct); + await sync.PushAsync(id, fx.Home, fx.Ct); + await VerifyAsync(fx); + await WriteAtHomeAsync(fx, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.7 } }); + Assert.Equal(WorkspaceState.InSync, (await sync.PullAsync(id, fx.Home, fx.Ct)).Status.State); + var hashed = (await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id))[2].Sha256!; + Assert.Contains(hashed, (await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson); + + // Media that have not learnt the hash (copied so, the home out of reach since): the base still holds the working state. + project.WriteMedia(copied); + var status = await sync.StatusAsync(id, cancellationToken: fx.Ct); + Assert.Equal((WorkspaceState.InSync, false), (status.State, status.Modified)); + Assert.Null(await sync.CommitAsync(id, cancellationToken: fx.Ct)); + Assert.Empty(sync.Unpushed(id)); + + // A change of the user's own still reads as one, and its version keeps the exclusion. + await EditAsync(sync, id, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.9 } }, fx.Ct); + Assert.True((await sync.StatusAsync(id, cancellationToken: fx.Ct)).Modified); + var saved = Assert.NotNull(await sync.CommitAsync(id, cancellationToken: fx.Ct)); + Assert.SequenceEqual([2], ProjectSettings.FromJson(ProjectContent.Place(saved.SettingsJson, copied.Photos)).ExcludedFrames); + Assert.Equal(WorkspaceState.InSync, (await sync.PushAsync(id, fx.Home, fx.Ct)).Status.State); + var settings = await SequenceSettingsAsync(fx); + Assert.Equal((0.9, 2), (settings.Exposure.ExposureOffsetEv, settings.ExcludedFrames.Single())); + } + + [Test] + public async Task APhotoHashedAtTheHomeIsOutdatedMediaUntilTheMediaLearnItsHash() + { + var fx = await FixtureAsync(); + await UnhashAsync(fx, 2); + var (_, sync) = fx.Workspace(); + var project = await fx.CheckoutAsync(sync); + var id = project.ProjectId; + await EditAsync(sync, id, s => s with { ExcludedFrames = [2] }, fx.Ct); + await sync.CommitAsync(id, cancellationToken: fx.Ct); + await sync.PushAsync(id, fx.Home, fx.Ct); + Assert.False((await sync.StatusAsync(id, fx.Home, fx.Ct)).MediaOutdated); + await VerifyAsync(fx); + await WriteAtHomeAsync(fx, s => s with { Exposure = s.Exposure with { ExposureOffsetEv = 0.7 } }); + var hashed = (await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id))[2].Sha256!; + + // Asked while another operation holds the project: outdated, the media as they were, nothing to save here. + WorkspaceStatus busy; + using (await project.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), fx.Ct)) + busy = await sync.StatusAsync(id, fx.Home, fx.Ct); + Assert.True(busy.MediaOutdated); + Assert.Equal((WorkspaceState.Behind, false), (busy.State, busy.Modified)); + Assert.Null(project.ReadMedia()!.Frames[2].Sha256); + Assert.False((await sync.StatusAsync(id, cancellationToken: fx.Ct)).MediaOutdated, "without a home nothing is known of it"); + + // Asked again with the project free: the media learn the hash, the frames and their files as copied. + var learnt = await sync.StatusAsync(id, fx.Home, fx.Ct); + Assert.False(learnt.MediaOutdated); + Assert.Equal((WorkspaceState.Behind, false), (learnt.State, learnt.Modified)); + Assert.Equal(hashed, project.ReadMedia()!.Frames[2].Sha256); + var pulled = await sync.PullAsync(id, fx.Home, fx.Ct); + Assert.Equal((WorkspaceState.InSync, false), (pulled.Status.State, pulled.Status.MediaOutdated)); + Assert.SequenceEqual([2], (await sync.OpenAsync(id, fx.Ct)).Working.ExcludedFrames); + } + + [Test] + public async Task APhotoConvertedAtTheHomeIsOutdatedMediaAndTheMediaLearnItsEncodings() + { + var fx = await FixtureAsync(4); + var (store, sync) = fx.Workspace(); + var project = await fx.CheckoutAsync(sync); + var id = project.ProjectId; + var copied = project.ReadMedia()!; + Assert.Null(copied.Aliases); + await ProjectServiceTests.ConvertAsync(fx.Archive, fx.Sequence.Id, [1], 700); + var converted = (await fx.Db.Frames.ListBySequenceAsync(fx.Sequence.Id))[1].Sha256!; + + // Opened again: the media learn the encodings the conversion joined, but still hold the photo as copied. + await sync.CheckoutAsync(fx.Home, id, cancellationToken: fx.Ct); + var link = Assert.NotNull(project.ReadMedia()!.Aliases).Single(); + Assert.Equal((copied.Frames[1].Sha256!.ToLowerInvariant(), converted.ToLowerInvariant()), (link.Sha256.ToLowerInvariant(), link.Replacement.ToLowerInvariant())); + Assert.Equal(copied.Frames[1].Sha256, project.ReadMedia()!.Frames[1].Sha256); + var status = await sync.StatusAsync(id, fx.Home, fx.Ct); + Assert.True(status.MediaOutdated, "the file is not the library's any more: Update media copies it again"); + Assert.False(status.Modified); + + await fx.CopyAsync(store, id); + Assert.False((await sync.StatusAsync(id, fx.Home, fx.Ct)).MediaOutdated); + Assert.Equal(converted, project.ReadMedia()!.Frames[1].Sha256); + } + [Test] public async Task AVersionSavedBeforeAnotherWorkspaceNamedThePhotoByItsHashKeepsItsEdit() {