From e8ea8580219c6d36a189984b457b99ff40000f9b Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Tue, 3 Nov 2026 12:55:13 +0100 Subject: [PATCH] fix: phase 5a fix round 3, desktop: newer copies, readable discard, working-state conflicts, edits kept aside Owner review 2, R8. Round 2's checkers left five desktop problems: - A workspace copy whose project.chronos a newer Chronos wrote (a format this one does not know) was listed as damaged and offered for Discard. It is now listed as "Newer Chronos" with its own tooltip, named from what of its file still reads. It never opens, is never checked out over, and Remove local copy refuses it with a sentence that says why. - Discard of any copy moved only the files Chronos knows. It now moves every file and folder of the copy aside (only the media are deleted) and removes the folder only when nothing else came into it. - Discarding a damaged copy asked to type its folder's GUID. It now asks for the name the copy is still known by (its file, else the library's index; the project's name, else the sequence's title), else for the number of its files. The heading never shows the id. - A conflict at a path where the working state had gone back to the base value listed the local version's value. The conflict now lists the working state's value in every case. Where the working state already holds the library's value there is nothing to ask: that path takes the library's value in the replayed versions too, so they agree. - EditorSession.ReloadAsync, ResolveConflict and TakeOverAsync threw NewerSettingsException on every reload when an edit was not stored yet and the stored project became a newer Chronos's. The edit is now kept in versions/.replaced (outside the chain, never sent), a toast says so, the pending save is dropped and the newer settings are shown read-only. When the edit cannot be kept aside, the editor stays as it is and nothing is dropped. The SequenceViewModel wiring now has a view-model test: the copy's facts in Open in workspace, the refused-folder toast and its Choose folder action, and the picker for a newer copy and a damaged one. Co-Authored-By: Claude Opus 5.5 --- i18n/en/Editor.resx | 6 + i18n/en/Errors.resx | 1 + i18n/en/Tooltips.resx | 1 + i18n/it/Editor.it.resx | 6 + i18n/it/Errors.it.resx | 1 + i18n/it/Tooltips.it.resx | 1 + src/Chronos.App/Editor/EditorSession.cs | 81 +++++++- src/Chronos.App/Editor/EditorViewModel.cs | 12 ++ src/Chronos.App/Editor/ISequenceSource.cs | 7 + src/Chronos.App/Editor/ProjectSaver.cs | 30 ++- .../Editor/WorkspaceSequenceSource.cs | 37 ++++ .../Sections/SequencePickerViewModel.cs | 4 +- src/Chronos.App/Sections/SequenceViewModel.cs | 13 +- src/Chronos.App/Workspace/WorkspaceDialogs.cs | 32 +++- src/Chronos.App/Workspace/WorkspaceHost.cs | 181 +++++++++++++++--- .../Workspace/WorkspaceProjectItem.cs | 18 +- src/Chronos.Data/Workspaces/WorkspaceSync.cs | 40 +++- .../Workspace/WorkspaceFallbackTests.cs | 66 +++++++ .../Workspace/WorkspaceNewerFormatTests.cs | 49 +++++ .../Workspace/WorkspaceSectionTests.cs | 104 ++++++++++ .../Workspaces/WorkspaceConflictTests.cs | 60 ++++++ 21 files changed, 696 insertions(+), 54 deletions(-) diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index b1a3f4ab..4caa9f14 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -271,6 +271,8 @@ {0} · proxies outdated {0} · read-only Unsaved changes + Discard a damaged copy? + Remove a damaged copy Discard changes The versions not sent and the unsaved changes go to the workspace's trash folder; Chronos does not bring them back.long Discard the changes of {0}? @@ -281,6 +283,7 @@ Send first Size Remove local copy of {0}{0} project name + Type the number of files, {0}, to confirmlong; {0} number of files Type the project name to confirmlong Versions not sent Yes @@ -389,6 +392,8 @@ Project not deleted Project {0} deleted{0} project name {0} {1} here, {2} in the librarylong; {0} setting name, {1} value in this workspace, {2} value in the library + Edit kept aside + A newer Chronos saved this project before your last edit was stored: that edit is kept aside in the project's folder, and the newer settings show read-only.long {0} changed in the library while your edit waited to be saved. The settings below differ: keep your values, or take the library's.long Project in sync Library photos changed @@ -413,6 +418,7 @@ In sync No media Changedthe project has changes not saved as a version + Newer Chronosa newer Chronos saved this workspace copy; this one cannot open it Offline Checkingthe project's state is being read from the library Syncing diff --git a/i18n/en/Errors.resx b/i18n/en/Errors.resx index a078d2ea..d3800727 100644 --- a/i18n/en/Errors.resx +++ b/i18n/en/Errors.resx @@ -67,6 +67,7 @@ The workspace's photos of this project changed; the editor reads them again. The workspace holds no photos of this project; open it again to copy them. Another project of this sequence has that name. + A newer Chronos saved this copy in the workspace; update Chronos to open it or remove it. The drive of the workspace folder lacks room for this copy and the 0.5 GB the copy keeps free. The project is no longer in the workspace. The library cannot be reached now; your work stays in the workspace and can be sent once it is back. diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 4fe333a8..5be87407 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -344,6 +344,7 @@ Every version of this project is in the library, and nothing changed since the last one The workspace holds no photos of this project: opening it copies them again Changes not saved as a version yet: Save version (Ctrl+S) keeps them in the history + A newer Chronos saved this copy, so this one cannot open it; update Chronos: nothing in it is changed or removed herelong The library cannot be reached now: your work stays here and is sent once it is back The library cannot be reached now. Versions waiting to be sent once it is back: {0}{0} number of versions Asking the library where this project stands diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index 38bc3bcb..8fa0c5f2 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -260,6 +260,8 @@ {0} · proxy superati {0} · sola lettura Modifiche non salvate + Scartare una copia danneggiata? + Rimuovi una copia danneggiata Scarta modifiche Le versioni non inviate e le modifiche non salvate vanno nella cartella cestino dello spazio di lavoro; Chronos non le riporta indietro. Scartare le modifiche di {0}? @@ -270,6 +272,7 @@ Prima invia Dimensione Rimuovi copia locale di {0} + Scrivi il numero di file, {0}, per confermare Scrivi il nome del progetto per confermare Versioni non inviate Sì @@ -364,6 +367,8 @@ Progetto non eliminato Progetto {0} eliminato {0} {1} qui, {2} nella libreria + Modifica da parte + Un Chronos più recente ha salvato questo progetto prima che la tua ultima modifica fosse memorizzata: quella modifica è tenuta da parte nella cartella del progetto, e le impostazioni più recenti si vedono in sola lettura. {0} è cambiato nella libreria mentre la tua modifica attendeva il salvataggio. Le impostazioni qui sotto sono diverse: tieni i tuoi valori o prendi quelli della libreria. Progetto sincronizzato Foto della libreria cambiate @@ -388,6 +393,7 @@ Sincronizzato Senza media Modificato + Chronos più recente Non in linea Verifica Sincronizzazione diff --git a/i18n/it/Errors.it.resx b/i18n/it/Errors.it.resx index 103430e4..0fc124eb 100644 --- a/i18n/it/Errors.it.resx +++ b/i18n/it/Errors.it.resx @@ -67,6 +67,7 @@ Le foto di questo progetto nello spazio di lavoro sono cambiate; l'editor le rilegge. Lo spazio di lavoro non ha foto di questo progetto; riaprilo per copiarle. Un altro progetto di questa sequenza ha già quel nome. + Un Chronos più recente ha salvato questa copia nello spazio di lavoro; aggiorna Chronos per aprirla o rimuoverla. All'unità della cartella dello spazio di lavoro manca lo spazio per questa copia e per gli 0,5 GB che la copia lascia liberi. Il progetto non è più nello spazio di lavoro. La libreria ora non è raggiungibile; il tuo lavoro resta nello spazio di lavoro e potrà essere inviato quando torna. diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index d130493c..603428e1 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -343,6 +343,7 @@ Ogni versione di questo progetto è nella libreria e nulla è cambiato dall'ultima Lo spazio di lavoro non ha foto di questo progetto: aprirlo le copia di nuovo Modifiche non ancora salvate come versione: Salva versione (Ctrl+S) le tiene nella cronologia + Un Chronos più recente ha salvato questa copia, quindi questo non può aprirla; aggiorna Chronos: qui nulla viene cambiato o rimosso La libreria ora non è raggiungibile: il tuo lavoro resta qui e viene inviato quando torna La libreria ora non è raggiungibile. Versioni in attesa di essere inviate quando torna: {0} Chiede alla libreria lo stato di questo progetto diff --git a/src/Chronos.App/Editor/EditorSession.cs b/src/Chronos.App/Editor/EditorSession.cs index c23dbd7b..39eeb8c6 100644 --- a/src/Chronos.App/Editor/EditorSession.cs +++ b/src/Chronos.App/Editor/EditorSession.cs @@ -69,6 +69,12 @@ public sealed class EditorSession : IAsyncDisposable /// A save met settings changed on the server too ( was null): the user picks a side. public event Action? ConflictFound; + /// + /// An edit not stored yet met a newer Chronos's settings stored meanwhile, which this one never merges with: the edit + /// was kept aside at the path given () and the newer settings shown read-only. + /// + public event Action? EditSetAside; + public ISequenceSource Source { get; } /// A server sequence edited with proxies: saved, analysed and rendered on the server. @@ -204,8 +210,17 @@ public sealed class EditorSession : IAsyncDisposable Conflict = null; var basis = _basis; _basis = theirs; - History.Replace(Source.Merge(basis, Project, theirs).Merged); - if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged); + try + { + History.Replace(Source.Merge(basis, Project, theirs).Merged); + if (!keepMine) History.Apply(Source.Merge(basis, theirs, Project).Merged); + } + catch (NewerSettingsException ex) + { + // Never merged with a newer Chronos's settings: the edit is kept aside, those settings shown read-only. + _ = TakeNewerAsync(theirs, ex, CancellationToken.None); + return true; + } // The change waiting for its retry goes now, on top of the server's settings. _ = _saver.FlushAsync(); return true; @@ -237,7 +252,9 @@ public sealed class EditorSession : IAsyncDisposable /// /// Reads the sequence again (an analysis finished): new reports and advice, the frames with the project's positions /// following them (), the stored project merged into the open one. Saves wait until it is taken, - /// and a read waits for the one under way, so each follows the frames the one before it took. + /// and a read waits for the one under way, so each follows the frames the one before it took. A stored project of a + /// newer Chronos met with an edit not stored yet is never merged: the edit is kept aside and the newer settings shown + /// read-only (). /// public async Task ReloadAsync(CancellationToken cancellationToken = default) { @@ -249,7 +266,15 @@ public sealed class EditorSession : IAsyncDisposable Follow(content); // Settings a server or a sync stored that conflict with the editor's waiting change are not merged over it: that // change's retry meets them and asks (Conflict). - var merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null; + ProjectMergeResult? merge = null; + try + { + merge = Conflict is null ? Source.Merge(_basis, Project, content.Project) : null; + } + catch (NewerSettingsException ex) + { + await TakeNewerAsync(content.Project, ex, cancellationToken); + } if (merge is not null && (!Source.AsksConflicts || !merge.HasConflicts)) { _basis = content.Project; @@ -283,9 +308,17 @@ public sealed class EditorSession : IAsyncDisposable Follow(content); var basis = _basis; _basis = content.Project; - History.Replace(Source.Merge(basis, Project, kept).Merged); - var before = Project; - if (!IsReadOnly && History.Apply(Source.Merge(kept, Project, content.Project).Merged)) step = new ProjectRestore(this, before, Project); + try + { + History.Replace(Source.Merge(basis, Project, kept).Merged); + var before = Project; + if (!IsReadOnly && History.Apply(Source.Merge(kept, Project, content.Project).Merged)) step = new ProjectRestore(this, before, Project); + } + catch (NewerSettingsException ex) + { + _basis = basis; + await TakeNewerAsync(content.Project, ex, cancellationToken); + } } finally { @@ -343,6 +376,40 @@ public sealed class EditorSession : IAsyncDisposable NamesFrames(project) && ProjectSettings.FollowFrames(project.ToJson(), before, after) is { } moved ? ProjectSettings.FromJson(moved) : project; } + /// + /// The stored project is a newer Chronos's () while the editor holds an edit not stored yet, + /// which this Chronos can neither merge with it nor store over it (): the edit is + /// kept aside by the source (, said by ), never + /// dropped silently, and only then are the newer settings taken, read-only, the pending save dropped with it. A source + /// that keeps nothing aside, or a set-aside that fails, leaves the editor as it is (logged): the next read tries again. + /// Never throws. + /// + private async Task TakeNewerAsync(ProjectSettings newer, NewerSettingsException cause, CancellationToken cancellationToken) + { + var unsaved = Project; + string? kept; + try + { + kept = await Source.SetAsideAsync(unsaved, cancellationToken); + } + catch (Exception ex) when (ex is not OutOfMemoryException) + { + Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet could not be kept aside; it stays in the editor", ex); + return; + } + if (kept is null) + { + Log.Warning("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet meets newer settings and stays in the editor: {cause.Message}"); + return; + } + Log.Info("editor", $"The edit of {Content.Sequence.DisplayTitle} not stored yet was kept in {kept}: the stored project is a newer Chronos's ({cause.Message})"); + _saver.Drop(); + Conflict = null; + _basis = newer; + History.Replace(newer); + EditSetAside?.Invoke(kept); + } + /// /// Waits for the read under way (two jobs that end together read the sequence one after the other), then marks a new /// one under way until the returned source is completed. diff --git a/src/Chronos.App/Editor/EditorViewModel.cs b/src/Chronos.App/Editor/EditorViewModel.cs index e92d6b23..5e8fa221 100644 --- a/src/Chronos.App/Editor/EditorViewModel.cs +++ b/src/Chronos.App/Editor/EditorViewModel.cs @@ -149,6 +149,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable session.ContentChanged += OnContentChanged; session.SaveFailed += OnSaveFailed; session.ConflictFound += OnConflictFound; + session.EditSetAside += OnEditSetAside; session.Source.JobChanged += OnJobChanged; session.Source.ReadOnlyChanged += OnReadOnlyChanged; shell.Services.Sync.Changed += OnSyncChanged; @@ -725,6 +726,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable Session.ContentChanged -= OnContentChanged; Session.SaveFailed -= OnSaveFailed; Session.ConflictFound -= OnConflictFound; + Session.EditSetAside -= OnEditSetAside; Session.Source.JobChanged -= OnJobChanged; Session.Source.ReadOnlyChanged -= OnReadOnlyChanged; Shell.Services.Sync.Changed -= OnSyncChanged; @@ -1053,6 +1055,16 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()), }); + /// + /// An edit not stored yet met a newer Chronos's settings a sync took (owner review 2, R8): it was kept aside in the + /// project's folder, never dropped, and the toast says so; the newer settings show read-only. + /// + private void OnEditSetAside(string path) => _dispatcher.BeginInvoke(() => + { + if (_disposed) return; + Shell.ShowToast(new Toast { Title = Loc.L("Editor.Workspace.EditSetAside"), Message = Loc.L("Editor.Workspace.EditSetAsideMessage") }); + }); + /// /// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"), or, for /// a workspace project, that a sync took from the library while the edit waited (owner review 2, R8): the dialog lists diff --git a/src/Chronos.App/Editor/ISequenceSource.cs b/src/Chronos.App/Editor/ISequenceSource.cs index a1709a2d..eba0dee0 100644 --- a/src/Chronos.App/Editor/ISequenceSource.cs +++ b/src/Chronos.App/Editor/ISequenceSource.cs @@ -81,6 +81,13 @@ public interface ISequenceSource : IAsyncDisposable /// ProjectMergeResult Merge(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) => ProjectMerge.MergeWithConflicts(basis, ours, theirs); + /// + /// Keeps , an edit that can no longer be stored (the stored project became a newer Chronos's, + /// which this one never merges with), where the user finds it and nothing sends it; returns where, or null when this + /// source keeps nothing aside (the edit then stays in the editor as it is). + /// + Task SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken) => Task.FromResult(null); + /// Queues an analysis or render job for the sequence; returns the job id. Task SubmitAsync(ArchiveJobRequest request, CancellationToken cancellationToken); diff --git a/src/Chronos.App/Editor/ProjectSaver.cs b/src/Chronos.App/Editor/ProjectSaver.cs index 5a52759a..01447e71 100644 --- a/src/Chronos.App/Editor/ProjectSaver.cs +++ b/src/Chronos.App/Editor/ProjectSaver.cs @@ -21,6 +21,9 @@ public sealed class ProjectSaver(Func save, TimeSpan dela private bool _flushRequested; private bool _stopped; private int _failures; + + /// Changes dropped (): a write that fails after one is not retried. + private int _drops; private CancellationTokenSource? _wait; /// No write starts until (or ): the user is being asked about the pending change. @@ -103,6 +106,22 @@ public sealed class ProjectSaver(Func save, TimeSpan dela lock (_gate) ReleaseHold(); } + /// + /// Drops what is pending, a write under way included should it fail, and keeps saving what is scheduled from now on: the + /// change was kept elsewhere (set aside when the stored project became a newer Chronos's, where it can never be stored). + /// + public void Drop() + { + lock (_gate) + { + _pending = null; + _drops++; + _failures = 0; + LastError = null; + _wait?.Cancel(); + } + } + /// Drops what is pending and stops retrying (the editor closed and the user chose to discard the change). public void Stop() { @@ -153,8 +172,10 @@ public sealed class ProjectSaver(Func save, TimeSpan dela continue; } ProjectSettings next; + int drops; lock (_gate) { + drops = _drops; _flushRequested = false; if (_pending is null) { @@ -184,9 +205,16 @@ public sealed class ProjectSaver(Func save, TimeSpan dela } catch (Exception ex) { - LastError = ex; lock (_gate) { + if (_drops != drops) + { + // Dropped while it was written (kept elsewhere): not retried, and no failure to report. + EndWrite(); + wait = TimeSpan.Zero; + continue; + } + LastError = ex; // A newer change contains this one (projects are whole snapshots); otherwise this one waits for the retry. if (!_stopped) _pending ??= next; failures = ++_failures; diff --git a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs index 6549ce15..477bc522 100644 --- a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs +++ b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs @@ -252,6 +252,43 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders ProjectSettings.FromJson(ProjectContent.ToPortable(settings, photos), allowNewer: true); } + /// + /// Keeps an edit the working state can no longer take (a sync brought a newer Chronos's settings) as a version file in + /// versions/.replaced, where a take of the library's values keeps the working state it replaces: outside the chain + /// of versions, so it is never sent, and never lost. Written under the project's lease, its positions parked by photo. + /// + /// Another writer kept the project for longer than the sync waits. + public Task SetAsideAsync(ProjectSettings unsaved, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(unsaved); + var folder = Project; + var (photos, framesVersion, basis) = (Photos, MediaFramesVersion, Workspace?.Base); + return Task.Run(async () => + { + using (await folder.LockAsync(_sync.LockWait, cancellationToken)) + { + var portable = ProjectContent.ToPortable(unsaved, photos); + var version = new ProjectVersion + { + Id = Guid.CreateVersion7(), + ProjectId = ProjectId, + ParentId = basis?.VersionId, + Number = (basis?.Number ?? 0) + 1, + Kind = ProjectVersionKind.Commit, + ClientName = Environment.MachineName, + SettingsJson = portable, + ContentHash = ProjectContent.Hash(portable), + SettingsFormat = ProjectContent.FormatOf(portable), + FramesVersion = Math.Max(0, framesVersion), + CreatedAt = DateTimeOffset.UtcNow, + }; + var path = Path.Combine(folder.VersionsDirectory, WorkspaceProject.ReplacedFolder, Path.GetFileName(folder.VersionPath(version))); + ProjectSidecars.WriteVersion(path, version); + return path; + } + }, cancellationToken); + } + /// A merge path of a frame position (an exclusion, the hero, a camera keyframe, a frame waiting for its photo). private static bool NamesPosition(string path) => path is "excludedFrames" or "heroFrame" || path.StartsWith("camera.keyframes", StringComparison.Ordinal) || path.StartsWith("pendingFrames", StringComparison.Ordinal); diff --git a/src/Chronos.App/Sections/SequencePickerViewModel.cs b/src/Chronos.App/Sections/SequencePickerViewModel.cs index b9a53cfa..fcddba86 100644 --- a/src/Chronos.App/Sections/SequencePickerViewModel.cs +++ b/src/Chronos.App/Sections/SequencePickerViewModel.cs @@ -285,8 +285,8 @@ public sealed class SequencePickerViewModel : LocalizedViewModel foreach (var item in items) { if (generation != _generation) return; - // Its working state cannot be read: there is no state to ask for. - if (item.IsDamaged) continue; + // This Chronos cannot read its working state: there is no state to ask for. + if (!item.IsReadable) continue; try { item.Status = await Shell.Services.Workspace.StatusAsync(item.ProjectId); diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs index 0fe5e8a7..18c62c45 100644 --- a/src/Chronos.App/Sections/SequenceViewModel.cs +++ b/src/Chronos.App/Sections/SequenceViewModel.cs @@ -232,6 +232,12 @@ public sealed class SequenceViewModel : SectionViewModel KeepOpenSequence(); return; } + // A copy a newer Chronos wrote neither opens nor goes from here: the toast says so, nothing is offered over it. + if (item.IsNewer) + { + Shell.Notify(Loc.L("Editor.Workspace.OpenFailed"), Loc.L("Errors.Workspace.NewerCopy"), isError: true); + return; + } // A copy whose working state cannot be read cannot open: its removal plan is what it offers. if (item.IsDamaged) { @@ -441,7 +447,8 @@ public sealed class SequenceViewModel : SectionViewModel { await workspace.SendAllAsync(projectId); await RemoveCopyAsync(projectId, name, discard: false); - }, () => RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name), d => CloseDialog(d))); + }, () => plan.Damaged ? RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, plan) : RemoveCopyDialogViewModel.ConfirmDiscard(_workspaceUi, name), + d => CloseDialog(d))); } catch (Exception ex) when (ex is not OutOfMemoryException) { @@ -595,8 +602,8 @@ public sealed class SequenceViewModel : SectionViewModel { Main: true } => (await workspace.ProjectsOfAsync(row.Id)).FirstOrDefault(p => p.IsMain), _ => await workspace.LastUsedAsync(row.Id), }; - // Its working state cannot be read: nothing is checked out over it (the picker offers Remove local copy). - if (entry is { Damaged: true }) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged")); + // This Chronos cannot read its working state (damaged, or a newer Chronos's): nothing is checked out over it. + if (entry is { IsReadable: false } unreadable) throw WorkspaceHost.Unreadable(unreadable); if (entry is { HasMedia: true }) { workspace.Remember(row.Id, entry.ProjectId); diff --git a/src/Chronos.App/Workspace/WorkspaceDialogs.cs b/src/Chronos.App/Workspace/WorkspaceDialogs.cs index ae1d1e70..37ca4e06 100644 --- a/src/Chronos.App/Workspace/WorkspaceDialogs.cs +++ b/src/Chronos.App/Workspace/WorkspaceDialogs.cs @@ -503,7 +503,10 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel public WorkspaceRemovalPlan Plan { get; } - public string Heading => Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false)); + /// "Remove local copy of Main"; a damaged copy by the name it is still known by, else as a damaged copy (never by its folder's id). + public string Heading => !Plan.Damaged ? Loc.L("Editor.RemoveCopy.Title", WorkspaceText.ProjectName(Plan.Name, false)) + : Plan.KnownName is { Length: > 0 } known ? Loc.L("Editor.RemoveCopy.Title", known) + : Loc.L("Editor.RemoveCopy.DamagedTitle"); public IReadOnlyList Facts { get; } @@ -547,13 +550,38 @@ public sealed class RemoveCopyDialogViewModel : ArchiveDialogViewModel TypedPrompt = Loc.L("Editor.RemoveCopy.TypeName"), }; - /// Asks through : true when the user typed the name and confirmed. + /// + /// The typed confirmation of discarding a damaged copy (): the name it is still + /// known by (), never its folder's id; with no name known, the number of its + /// files, as the plan shows it. + /// + public static ConfirmRequest DiscardRequest(WorkspaceRemovalPlan plan) + { + ArgumentNullException.ThrowIfNull(plan); + if (plan.KnownName is { Length: > 0 } known) return DiscardRequest(known); + var files = Formatting.Count(plan.Files); + return DiscardRequest(string.Empty) with + { + Heading = Loc.L("Editor.RemoveCopy.DamagedDiscard"), + TypedConfirmation = files, + TypedPrompt = Loc.L("Editor.RemoveCopy.TypeFiles", files), + }; + } + + /// Asks through : true when the user typed the name and confirmed. public static bool ConfirmDiscard(IWorkspaceUi ui, string projectName) { ArgumentNullException.ThrowIfNull(ui); return ui.Confirm(DiscardRequest(projectName)); } + /// Asks through : true when the user typed what it asks and confirmed. + public static bool ConfirmDiscard(IWorkspaceUi ui, WorkspaceRemovalPlan plan) + { + ArgumentNullException.ThrowIfNull(ui); + return ui.Confirm(DiscardRequest(plan)); + } + private async Task DiscardAsync() { if (!_confirmDiscard()) return; diff --git a/src/Chronos.App/Workspace/WorkspaceHost.cs b/src/Chronos.App/Workspace/WorkspaceHost.cs index 6c6b236d..492462d0 100644 --- a/src/Chronos.App/Workspace/WorkspaceHost.cs +++ b/src/Chronos.App/Workspace/WorkspaceHost.cs @@ -1,4 +1,5 @@ using System.IO; +using System.Text.Json; using Chronos.App.Infrastructure; using Chronos.Core.Archiving; using Chronos.Core.Diagnostics; @@ -25,11 +26,32 @@ public sealed class WorkspaceException(string message, Exception? inner = null) /// The workspace holds the project's media (a copy that ended); without them it cannot open. /// When its working state was last written. /// -/// Its working state (project.chronos) cannot be read: listed by its folder, it cannot open, and Remove local copy -/// can only keep its files aside in the workspace's trash (Discard). +/// Its working state (project.chronos) cannot be read: listed by the name it is still known by (else its folder), it +/// cannot open, and Remove local copy can only keep its files aside in the workspace's trash (Discard). /// +/// +/// A copy this Chronos cannot read is no project of its sequence here ( is empty): nothing opens, +/// checks out or is copied over it. +/// public sealed record WorkspaceEntry(Guid ProjectId, Guid SequenceId, string Name, bool IsMain, BundleHome Home, string SequenceTitle, bool HasMedia, - DateTimeOffset Saved, bool Damaged = false); + DateTimeOffset Saved, bool Damaged = false) +{ + /// + /// Its working state was written by a newer Chronos (a project file format this one does not know): listed as such, + /// it neither opens nor goes from here, and nothing in it is changed; a newer Chronos opens it. + /// + public bool Newer { get; init; } + + /// + /// A copy this Chronos cannot read ( or ): the name it is still known by (its + /// project's, else its sequence's), from what of its project file can be read or from the library's index; null when + /// neither knows it. + /// + public string? KnownName { get; init; } + + /// This Chronos reads its working state: it can open. + public bool IsReadable => !Damaged && !Newer; +} /// What changing the workspace folder to does: Edit lists its projects from then on; nothing is moved. /// The folder in use, whose projects stay where they are (listed again once it is chosen back). @@ -73,6 +95,12 @@ public sealed record WorkspaceHistory(IReadOnlyList Versions, IR public sealed record WorkspaceRemovalPlan(Guid ProjectId, string Name, int Files, long Bytes, int Unsent, bool Modified, bool Conflict, bool Offline, bool Gone = false, bool Damaged = false) { + /// + /// A damaged copy: the name Discard asks to type (); null when no name is known, + /// and the number of its files is typed instead. + /// + public string? KnownName { get; init; } + /// Everything the copy holds is at the home: it can go without discarding anything. public bool IsSafe => Unsent == 0 && !Modified && !Conflict && !Damaged; } @@ -176,25 +204,35 @@ public sealed class WorkspaceHost /// /// The projects of the workspace; one whose working state cannot be read is listed as damaged (), - /// never hidden, and logged. A workspace folder not made yet that lies inside a library is not made by listing it: it lists nothing. + /// one a newer Chronos wrote as such (), never hidden, and logged. A workspace folder not + /// made yet that lies inside a library is not made by listing it: it lists nothing. /// public Task> ListAsync(CancellationToken cancellationToken = default) => Task.Run(async () => { if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return []; - return (IReadOnlyList)[.. Store.List().Select(EntryOrDamaged)]; + var entries = new List(); + foreach (var project in Store.List()) entries.Add(await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false)); + return (IReadOnlyList)entries; }, cancellationToken); /// The workspace projects of one sequence. public async Task> ProjectsOfAsync(Guid sequenceId, CancellationToken cancellationToken = default) => [.. (await ListAsync(cancellationToken).ConfigureAwait(false)).Where(e => e.SequenceId == sequenceId)]; - /// A workspace project by id (damaged when its working state cannot be read); null when the workspace has none. + /// A workspace project by id (damaged or newer when this Chronos cannot read its working state); null when the workspace has none. public Task FindAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () => { if (!Directory.Exists(Root) && await InsideALibraryAsync(cancellationToken).ConfigureAwait(false)) return null; - return Store.Find(projectId) is { } project ? EntryOrDamaged(project) : null; + return Store.Find(projectId) is { } project ? await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false) : null; }, cancellationToken); + /// Why a copy this Chronos cannot read neither opens nor is checked out over: a newer Chronos wrote it, or it is damaged. + public static WorkspaceException Unreadable(WorkspaceEntry entry) + { + ArgumentNullException.ThrowIfNull(entry); + return new WorkspaceException(Loc.L(entry.Newer ? "Errors.Workspace.NewerCopy" : "Errors.Workspace.Damaged")); + } + /// /// What changing the workspace folder to would do (Settings › Workspace › Change, and the /// refusal of a folder inside a library): the projects the folder in use keeps where they are, those the new one holds @@ -310,6 +348,9 @@ public sealed class WorkspaceHost ? listed.FirstOrDefault(p => p.Id == id) ?? throw new ProjectException(ProjectError.NotFound, $"The home has no project {id}.") : listed.First(p => p.IsMain); } + // A copy here this Chronos cannot read (damaged, or a newer Chronos's): nothing is checked out or copied over it. + if (Store.Find(project.Id) is { } here && await EntryOrUnreadableAsync(here, cancellationToken).ConfigureAwait(false) is { IsReadable: false } unreadable) + throw Unreadable(unreadable); await Sync.CheckoutAsync(home, project.Id, media, cancellationToken).ConfigureAwait(false); Log.Info("workspace", $"Project {project.Id} ('{project.Name}') of sequence {sequenceId} checked out into {Store.Root}"); return new WorkspaceCheckout(project, await QueueCopyCoreAsync(sequenceId, project.Id, media, cancellationToken).ConfigureAwait(false)); @@ -585,15 +626,18 @@ public sealed class WorkspaceHost } /// The plan of "Remove local copy": the folder's files and size, and what would not be at the home after it. + /// A newer Chronos wrote the copy: it goes from there, never from here. public Task PlanRemovalAsync(Guid projectId, CancellationToken cancellationToken = default) => Task.Run(async () => { var project = Existing(projectId); - if (EntryOrDamaged(project) is { Damaged: true } damaged) + var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false); + if (entry.Newer) throw Unreadable(entry); + if (entry.Damaged) { // What it holds is not known: every version file not marked sent, or not readable, counts as unsent work, kept aside by Discard. var (count, size) = Measure(project.Folder); var unsent = project.Versions().Count(v => v.StoredAt is null) + project.UnreadableVersions().Count; - return new WorkspaceRemovalPlan(projectId, damaged.Name, count, size, unsent, true, false, false, Damaged: true); + return new WorkspaceRemovalPlan(projectId, entry.Name, count, size, unsent, true, false, false, Damaged: true) { KnownName = entry.KnownName }; } var name = project.ReadBundle().Workspace!.Name; var status = await StatusAsync(projectId, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -605,16 +649,21 @@ public sealed class WorkspaceHost /// /// Removes a project's local copy. Without it is refused while anything is not at the home, /// and the home's head and the base this copy was made from are read back and checked against their hashes first. - /// With (the user's explicit word) the versions not sent and the working state are moved to - /// <workspace>/.trash rather than erased. The media (copies the home can make again) are deleted. + /// With (the user's explicit word) every file of the folder but the media (the versions not + /// sent, the working state, whatever else it holds) is moved to <workspace>/.trash rather than erased. The + /// media (copies the home can make again) are deleted. /// - /// Something is not at the home yet, or the home's copy does not check out. + /// + /// Something is not at the home yet, the home's copy does not check out, or a newer Chronos wrote the copy (it goes from there). + /// public async Task RemoveLocalCopyAsync(Guid projectId, bool discard, CancellationToken cancellationToken = default) { var sequenceId = await Task.Run(async () => { var project = Existing(projectId); - if (EntryOrDamaged(project) is { Damaged: true }) + var entry = await EntryOrUnreadableAsync(project, cancellationToken).ConfigureAwait(false); + if (entry.Newer) throw Unreadable(entry); + if (entry.Damaged) { // Its working state cannot be read: only Discard, which keeps every file of it aside, takes it out. if (!discard) throw new WorkspaceException(Loc.L("Errors.Workspace.Damaged")); @@ -715,9 +764,10 @@ public sealed class WorkspaceHost } /// - /// The project's folder taken out of the workspace under its lease: the working state, the versions, the sync state and - /// the exports moved to .trash/<id>-<time> (kept: nothing a user made is erased), the media deleted; the - /// emptied folder goes once the lease is released. + /// The project's folder taken out of the workspace under its lease: every file and folder in it but the media and the + /// lease (the working state, the versions, the sync state, the exports, and whatever else a Chronos keeps there) moved + /// to .trash/<id>-<time> as it is (kept: nothing a user made is erased), the media deleted; the emptied + /// folder goes once the lease is released, only when nothing else came into it meanwhile. /// private async Task RemoveFolderAsync(WorkspaceProject project, CancellationToken cancellationToken) { @@ -733,20 +783,27 @@ public sealed class WorkspaceHost Directory.CreateDirectory(aside); // The working state first: without it the folder is no project any more, whatever happens after. File.Move(project.BundlePath, Path.Combine(aside, WorkspaceProject.BundleFile)); - if (File.Exists(project.SyncPath)) File.Move(project.SyncPath, Path.Combine(aside, WorkspaceProject.SyncFile)); - if (Directory.Exists(project.VersionsDirectory)) Directory.Move(project.VersionsDirectory, Path.Combine(aside, WorkspaceProject.VersionsFolder)); - if (Directory.Exists(project.ExportsDirectory) && Directory.EnumerateFileSystemEntries(project.ExportsDirectory).Any()) - Directory.Move(project.ExportsDirectory, Path.Combine(aside, WorkspaceProject.ExportsFolder)); + foreach (var entry in Directory.EnumerateFileSystemEntries(project.Folder).ToList()) + { + var name = Path.GetFileName(entry); + if (IsLease(name) || string.Equals(name, WorkspaceProject.MediaFolder, StringComparison.OrdinalIgnoreCase)) continue; + if (Directory.Exists(entry)) Directory.Move(entry, Path.Combine(aside, name)); + else File.Move(entry, Path.Combine(aside, name)); + } if (Directory.Exists(project.MediaDirectory)) Directory.Delete(project.MediaDirectory, recursive: true); } try { - Directory.Delete(project.Folder, recursive: true); + // Only the lease's leftovers may be left: anything else is kept where it is. + if (Directory.EnumerateFileSystemEntries(project.Folder).All(e => IsLease(Path.GetFileName(e)))) Directory.Delete(project.Folder, recursive: true); + else Log.Info("workspace", $"The folder {project.Folder} stays: files came into it while its copy was removed"); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { Log.Info("workspace", $"The emptied folder {project.Folder} stays: {ex.Message}"); } + + static bool IsLease(string name) => name.StartsWith(".lock.lease", StringComparison.OrdinalIgnoreCase); } /// A version can be saved: no conflict waits, the settings are this Chronos's, the media are here. @@ -817,8 +874,12 @@ public sealed class WorkspaceHost bundle.Sequence.Title is { Length: > 0 } title ? title : bundle.Sequence.Folder, File.Exists(project.MediaIndexPath), bundle.Saved); } - /// The project's entry; a damaged one, named by its folder, when its working state cannot be read (logged). - private static WorkspaceEntry EntryOrDamaged(WorkspaceProject project) + /// + /// The project's entry; when its working state cannot be read (logged), one written by a newer Chronos + /// () or a damaged one (), named as it is still + /// known (what of its project file reads, else the library's index), else by its folder. + /// + private async Task EntryOrUnreadableAsync(WorkspaceProject project, CancellationToken cancellationToken) { try { @@ -826,10 +887,78 @@ public sealed class WorkspaceHost } catch (Exception ex) when (ex is IOException or InvalidDataException or UnauthorizedAccessException) { - Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex); + var peek = BundlePeek.Of(project); + if (peek.Newer) Log.Info("workspace", $"The project in {project.Folder} was saved by a newer Chronos (project file format {peek.Format}): it is left as it is"); + else Log.Warning("workspace", $"The project in {project.Folder} cannot be read", ex); + var (name, isMain, title) = (peek.Name, peek.IsMain, peek.Title); + if ((name is null || title is null) && _db() is { } db) + { + try + { + if (await db.Projects.GetAsync(project.ProjectId, cancellationToken).ConfigureAwait(false) is { } known) + { + if (name is null) (name, isMain) = (known.Name, known.IsMain); + title ??= (await db.Sequences.GetAsync(known.SequenceId, cancellationToken).ConfigureAwait(false))?.DisplayTitle; + } + } + catch (DatabaseException dbx) + { + Log.Info("workspace", $"The index could not name the project in {project.Folder}: {dbx.Message}"); + } + } var saved = File.Exists(project.BundlePath) ? new DateTimeOffset(File.GetLastWriteTimeUtc(project.BundlePath), TimeSpan.Zero) : DateTimeOffset.MinValue; - return new WorkspaceEntry(project.ProjectId, Guid.Empty, Path.GetFileName(project.Folder), false, new BundleHome(BundleHome.ArchiveKind, Guid.Empty), - project.Folder, false, saved, Damaged: true); + var shown = name is null ? null : WorkspaceText.ProjectName(name, isMain); + return new WorkspaceEntry(project.ProjectId, Guid.Empty, name ?? Path.GetFileName(project.Folder), isMain && name is not null, + new BundleHome(BundleHome.ArchiveKind, Guid.Empty), title ?? project.Folder, false, peek.Saved ?? saved, Damaged: !peek.Newer) + { + Newer = peek.Newer, + KnownName = shown ?? title, + }; + } + } + + /// + /// What a working state this Chronos cannot read still says, read as loosely as its JSON allows: whether a newer + /// Chronos wrote it (a format newer than ), and the project's name, + /// its sequence's title and when it was saved, each when it is there. + /// + private sealed record BundlePeek(bool Newer, int Format, string? Name, bool IsMain, string? Title, DateTimeOffset? Saved) + { + private static readonly BundlePeek Nothing = new(false, 0, null, false, null, null); + + public static BundlePeek Of(WorkspaceProject project) + { + try + { + var info = new FileInfo(project.BundlePath); + if (!info.Exists || info.Length > ProjectBundle.MaxBytes) return Nothing; + using var document = JsonDocument.Parse(File.ReadAllBytes(info.FullName), new JsonDocumentOptions { MaxDepth = 64 }); + var root = document.RootElement; + if (root.ValueKind != JsonValueKind.Object || Text(root, "format") != ProjectBundle.FormatName) return Nothing; + var format = root.TryGetProperty("formatVersion", out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out var n) ? n : 0; + string? name = null; + var isMain = false; + if (root.TryGetProperty("workspace", out var workspace) && workspace.ValueKind == JsonValueKind.Object + && Text(workspace, "projectId") is { } id && Guid.TryParse(id, out var projectId) && projectId == project.ProjectId) + { + name = Text(workspace, "name") is { Length: > 0 } named ? named : null; + isMain = workspace.TryGetProperty("isMain", out var main) && main.ValueKind == JsonValueKind.True; + } + var title = root.TryGetProperty("sequence", out var sequence) && sequence.ValueKind == JsonValueKind.Object + ? Text(sequence, "title") is { Length: > 0 } t ? t : Text(sequence, "folder") is { Length: > 0 } f ? f : null + : null; + DateTimeOffset? saved = root.TryGetProperty("saved", out var s) && s.ValueKind == JsonValueKind.String && s.TryGetDateTimeOffset(out var when) + ? when + : null; + return new BundlePeek(format > ProjectBundle.CurrentFormatVersion, format, name, isMain, title, saved); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or JsonException) + { + return Nothing; + } + + static string? Text(JsonElement element, string property) => + element.TryGetProperty(property, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null; } } diff --git a/src/Chronos.App/Workspace/WorkspaceProjectItem.cs b/src/Chronos.App/Workspace/WorkspaceProjectItem.cs index 532c8bcd..83913538 100644 --- a/src/Chronos.App/Workspace/WorkspaceProjectItem.cs +++ b/src/Chronos.App/Workspace/WorkspaceProjectItem.cs @@ -9,7 +9,7 @@ namespace Chronos.App.Workspace; /// /// A project of the workspace in Edit's picker (owner review 2, R8): its name, its sequence (title and thumbnail) and /// where it stands, a chip read from its home after the list shows. A copy whose working state cannot be read is listed -/// as damaged, by its folder. +/// as damaged, one a newer Chronos wrote as such, by the name each is still known by. /// public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? sequence) : ObservableObject { @@ -45,12 +45,22 @@ public sealed class WorkspaceProjectItem(WorkspaceEntry entry, SequenceItem? seq /// Its working state cannot be read: it cannot open, and Remove local copy keeps its files aside. public bool IsDamaged => Entry.Damaged; - public string StateText => Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged") + /// A newer Chronos wrote its working state: it neither opens nor goes from here, and stays as it is. + public bool IsNewer => Entry.Newer; + + /// This Chronos reads its working state: it opens, and its state is asked of its home. + public bool IsReadable => Entry.IsReadable; + + public string StateText => Entry.Newer ? Loc.L("Editor.Workspace.State.NewerCopy") + : Entry.Damaged ? Loc.L("Editor.Workspace.State.Damaged") : Entry.HasMedia || _status is not null ? WorkspaceText.State(_status) : Loc.L("Editor.Workspace.State.MediaRemoved"); - public StatusKind StateKind => Entry.Damaged ? StatusKind.Error : Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies; + public StatusKind StateKind => Entry.Newer ? StatusKind.Warning + : Entry.Damaged ? StatusKind.Error + : Entry.HasMedia || _status is not null ? WorkspaceText.Kind(_status) : StatusKind.NoProxies; - public string StateToolTip => Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy") + public string StateToolTip => Entry.Newer ? Loc.L("Tooltips.Editor.Workspace.State.NewerCopy") + : Entry.Damaged ? Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy") : Entry.HasMedia || _status is not null ? WorkspaceText.StateToolTip(_status) : Loc.L("Tooltips.Editor.Workspace.State.MediaRemoved"); /// "Vertical social · Harbour sunset · In sync": what screen readers hear for the row. diff --git a/src/Chronos.Data/Workspaces/WorkspaceSync.cs b/src/Chronos.Data/Workspaces/WorkspaceSync.cs index 228b0803..838af77d 100644 --- a/src/Chronos.Data/Workspaces/WorkspaceSync.cs +++ b/src/Chronos.Data/Workspaces/WorkspaceSync.cs @@ -446,7 +446,9 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) /// only when they are those lists (others are recorded and asked about first, as without a /// choice). Taking the server's everywhere tells the working state as keeping this side's values /// would have left it (placed), and the working state it replaces is kept aside (versions/.replaced), never in the - /// chain. A conflict recorded before stays when the home holds no version after the base (it lost them: nothing to + /// chain. A conflict lists this side's value as the working state holds it, the base value it went back to included; where + /// the working state holds the home's value already there is nothing to ask, and the replayed versions take that value + /// too. A conflict recorded before stays when the home holds no version after the base (it lost them: nothing to /// settle it against). /// Written in steps a cut can stop at any point (): the journal, the replayed versions, the /// base with the merged working state (the commit point), then the old versions set aside and the held ones adopted. @@ -500,6 +502,16 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) var choice = takeTheirs is EveryPath ? null : takeTheirs; List mine = [.. locals.Select(v => ProjectMerge.Read(ProjectContent.Rebind(v.SettingsJson, photos)))]; var replay = ProjectMerge.Replay(basisSettings, mine, headSettings, choice); + // Where the working state holds the home's value already, the user has nothing to choose: the home's value is taken + // there, in the replayed versions too, so they and the working state agree (never asked, never listed). + var workingSide = WorkingConflicts(tip, working, basisSettings, headSettings); + var silent = replay.Conflicts.Concat(ProjectMerge.Conflicts(tip, working, replay.Commits.Count > 0 ? replay.Commits[^1] : headSettings)) + .Select(d => d.Path).Where(p => !workingSide.Keys.Any(q => Overlaps(p, q))).ToHashSet(StringComparer.Ordinal); + if (silent.Count > 0) + { + choice = choice is null ? silent : new HashSet(choice.Concat(silent), StringComparer.Ordinal); + replay = ProjectMerge.Replay(basisSettings, mine, headSettings, choice); + } // This side's values wherever both changed: what taking the server's everywhere replaces (the editor's undo of it). var keptTip = replay.Commits.Count > 0 ? replay.Commits[^1] : headSettings; if (takeTheirs is EveryPath) replay = ProjectMerge.Replay(basisSettings, mine, headSettings, Paths(replay.Conflicts)); @@ -507,8 +519,7 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) var merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, choice); var keptMine = takeTheirs is EveryPath ? ProjectMerge.MergeWithConflicts(tip, working, keptTip).Merged : merge.Merged; if (takeTheirs is EveryPath) merge = ProjectMerge.MergeWithConflicts(tip, working, newTip, Paths(merge.Conflicts)); - var differences = AsInTheWorkingState(replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path), - ProjectMerge.Conflicts(basisSettings, working, headSettings)); + var differences = AsInTheWorkingState(replay.Conflicts.Concat(merge.Conflicts).DistinctBy(d => d.Path).Where(d => !silent.Contains(d.Path)), workingSide); if (differences.Count > 0 && (takeTheirs is null || (shown is not null && !SameDifferences(shown.Differences, differences)))) { var conflict = new WorkspaceConflict(head.Id, head.Number, basis?.Id ?? Guid.Empty, [.. locals.Select(v => v.Id)], differences, DateTimeOffset.UtcNow); @@ -1111,14 +1122,25 @@ public sealed class WorkspaceSync(WorkspaceStore store, string clientName) /// /// The conflicts found as the user sees them: where the working state holds a value of its own against the home's - /// (: edited since the last local version), that value is this side's, not the version's. + /// (, ), that value is this side's, not the version's. /// Keeping mine keeps it, and taking the server's replaces it, so one answer settles what was listed. /// - private static List AsInTheWorkingState(IEnumerable found, IReadOnlyList working) - { - var now = working.DistinctBy(d => d.Path).ToDictionary(d => d.Path, StringComparer.Ordinal); - return [.. found.Select(d => now.TryGetValue(d.Path, out var held) ? held : d)]; - } + private static List AsInTheWorkingState(IEnumerable found, IReadOnlyDictionary working) => + [.. found.Select(d => working.TryGetValue(d.Path, out var held) ? held : d)]; + + /// + /// The settings where the working state holds a value of its own against the home's head, by path: against the last + /// local version (: edited since it, the base value it went back to included), else against the + /// base (the version's value, unchanged since). A conflict at a path neither lists has the home's value in the working + /// state already. + /// + private static Dictionary WorkingConflicts(ProjectSettings tip, ProjectSettings working, ProjectSettings basis, ProjectSettings head) => + ProjectMerge.Conflicts(tip, working, head).Concat(ProjectMerge.Conflicts(basis, working, head)).DistinctBy(d => d.Path) + .ToDictionary(d => d.Path, StringComparer.Ordinal); + + /// Two merge paths name the same setting, or one lies inside the other ("camera" and "camera.aspect"). + private static bool Overlaps(string a, string b) => + a == b || a.StartsWith(b + ".", StringComparison.Ordinal) || b.StartsWith(a + ".", StringComparison.Ordinal); /// Whether two conflicts list the same settings with the same values on each side (in any order). private static bool SameDifferences(IReadOnlyList shown, IReadOnlyList found) => diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs index 93f6e9c2..0011a648 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceFallbackTests.cs @@ -6,6 +6,7 @@ using Chronos.App.Settings; using Chronos.App.Workspace; using Chronos.Core.Archiving; using Chronos.Core.Localization; +using Chronos.Core.Project; using Chronos.Data.Projects; using Chronos.Data.Sync; using Chronos.Data.Workspaces; @@ -156,6 +157,8 @@ public sealed class WorkspaceFallbackTests(TestContext context) var unsent = (await host.SaveVersionAsync(mainId, "Not sent")).Version!; var project = host.Store.Find(mainId)!; await File.WriteAllTextAsync(project.BundlePath, "{ this is not a project", bed.Ct); + // A file this Chronos does not know (a newer one's, the user's own): Discard keeps it too. + await File.WriteAllTextAsync(Path.Combine(project.Folder, "notes.txt"), "kept", bed.Ct); var all = await host.ListAsync(); Assert.Count(1, all); @@ -168,13 +171,27 @@ public sealed class WorkspaceFallbackTests(TestContext context) Assert.Equal((Loc.L("Editor.Workspace.State.Damaged"), StatusKind.Error, Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy")), (item.StateText, item.StateKind, item.StateToolTip)); + Assert.Equal(Loc.L("Editor.Project.Main"), listed.KnownName, "named as the library's index knows it, not by its folder's id"); var plan = await host.PlanRemovalAsync(mainId); Assert.True(plan is { Damaged: true, IsSafe: false, Unsent: 1 }); Assert.Greater(plan.Files, 0); + Assert.Equal(Loc.L("Editor.Project.Main"), plan.KnownName); + var typed = RemoveCopyDialogViewModel.DiscardRequest(plan); + Assert.Equal((Loc.L("Editor.RemoveCopy.DiscardTitle", Loc.L("Editor.Project.Main")), Loc.L("Editor.Project.Main")), (typed.Heading, typed.TypedConfirmation), + "a readable name is typed"); var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { }); Assert.False(dialog.RemoveCommand.CanExecute(null) || dialog.SendFirstCommand.CanExecute(null)); Assert.True(dialog.DiscardCommand.CanExecute(null)); Assert.Equal((Loc.L("Errors.Workspace.Damaged"), Loc.L("Errors.Workspace.Damaged")), (dialog.RemoveToolTip, dialog.SendFirstToolTip)); + Assert.Equal(Loc.L("Editor.RemoveCopy.Title", Loc.L("Editor.Project.Main")), dialog.Heading); + + // Known by no name at all: the number of its files is typed instead, and the heading names no id. + var unnamed = plan with { KnownName = null }; + var counted = RemoveCopyDialogViewModel.DiscardRequest(unnamed); + Assert.Equal((Loc.L("Editor.RemoveCopy.DamagedDiscard"), Formatting.Count(plan.Files), Loc.L("Editor.RemoveCopy.TypeFiles", Formatting.Count(plan.Files))), + (counted.Heading, counted.TypedConfirmation, counted.TypedPrompt)); + Assert.True(counted.IsDestructive); + Assert.Equal(Loc.L("Editor.RemoveCopy.DamagedTitle"), new RemoveCopyDialogViewModel(unnamed, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { }).Heading); var refused = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: false)); Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message); @@ -185,10 +202,59 @@ public sealed class WorkspaceFallbackTests(TestContext context) var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)), d => Path.GetFileName(d).StartsWith(mainId.ToString("N"), StringComparison.Ordinal)); Assert.Equal("{ this is not a project", await File.ReadAllTextAsync(Path.Combine(aside, WorkspaceProject.BundleFile), bed.Ct), "kept as it was"); + Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"), bed.Ct), "every file of the folder is kept, not only the known ones"); + Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the media, which the library makes again, are not kept"); + Assert.False(Directory.Exists(project.Folder)); Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase) || f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept"); } + [Test] + public async Task ACopyANewerChronosSavedIsListedAsSuchAndNeitherOpensNorGoes() + { + await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4); + var host = bed.Host(new AppSettings { WorkspaceAutoSync = false }); + var mainId = await bed.CheckoutAsync(host); + var project = host.Store.Find(mainId)!; + // A newer Chronos on this PC rewrote the working state in a format this one does not know (a downgrade since). + var json = System.Text.Json.Nodes.JsonNode.Parse(await File.ReadAllTextAsync(project.BundlePath, bed.Ct))!.AsObject(); + json["formatVersion"] = ProjectBundle.CurrentFormatVersion + 1; + json["somethingNew"] = "of a newer Chronos"; + var newer = json.ToJsonString(); + await File.WriteAllTextAsync(project.BundlePath, newer, bed.Ct); + await File.WriteAllTextAsync(Path.Combine(project.Folder, "newer.dat"), "a newer Chronos's", bed.Ct); + Assert.Throws(() => project.ReadBundle()); + + var listed = (await host.ListAsync()).Single(); + Assert.True(listed is { Newer: true, Damaged: false, IsReadable: false, HasMedia: false }); + Assert.Equal((mainId, ProjectService.MainName, true, Loc.L("Editor.Project.Main")), (listed.ProjectId, listed.Name, listed.IsMain, listed.KnownName), + "named from what of its file reads"); + Assert.Equal("Synthetic", listed.SequenceTitle); + Assert.True((await host.FindAsync(mainId))!.Newer); + Assert.Empty(await host.ProjectsOfAsync(bed.SequenceId), "never taken as the sequence's project to open"); + Assert.Null(await host.LastUsedAsync(bed.SequenceId)); + var item = new WorkspaceProjectItem(listed, null); + Assert.Equal((Loc.L("Editor.Workspace.State.NewerCopy"), StatusKind.Warning, Loc.L("Tooltips.Editor.Workspace.State.NewerCopy")), + (item.StateText, item.StateKind, item.StateToolTip)); + Assert.True(item is { IsNewer: true, IsDamaged: false, IsReadable: false }); + + // Not offered as damaged: no plan, no discard, and nothing checked out over it. + var planned = await Assert.ThrowsAsync(() => host.PlanRemovalAsync(mainId)); + Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), planned.Message); + var discarded = await Assert.ThrowsAsync(() => host.RemoveLocalCopyAsync(mainId, discard: true)); + Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), discarded.Message); + var checkedOut = await Assert.ThrowsAsync(() => host.CheckoutAsync(bed.SequenceId, mainId, null)); + Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), checkedOut.Message); + await Assert.ThrowsAsync(() => host.CheckoutAsync(bed.SequenceId, null, null)); + Assert.Equal(newer, await File.ReadAllTextAsync(project.BundlePath, bed.Ct), "left exactly as the newer Chronos wrote it"); + Assert.FileExists(Path.Combine(project.Folder, "newer.dat")); + Assert.True(Directory.Exists(project.MediaDirectory), "its media stay too"); + + // A damaged file is still damaged, not newer: a format number alone never makes one. + await File.WriteAllTextAsync(project.BundlePath, "{ \"format\": \"chronos-project\", \"formatVersion\": 9, ", bed.Ct); + Assert.True((await host.FindAsync(mainId)) is { Damaged: true, Newer: false }); + } + [Test] public async Task ACancelledFirstCopyLeavesNoHalfMedia() { diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs index 21775e98..f1d736a2 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceNewerFormatTests.cs @@ -1,4 +1,7 @@ +using System.IO; using Chronos.Core.Project; +using Chronos.Data.Projects; +using Chronos.Data.Workspaces; using Chronos.Testing; namespace Chronos.App.Tests.Workspace; @@ -46,4 +49,50 @@ public sealed class WorkspaceNewerFormatTests(TestContext context) Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv); } } + + [Test] + public async Task AnEditNotStoredYetIsKeptAsideWhenANewerChronossSettingsArrive() + { + await using var bed = await WorkspaceTestBed.CreateAsync(context); + var host = bed.Host(); + var projectId = await bed.CheckoutAsync(host); + var (source, session) = await bed.OpenAsync(host, projectId); + await using (session) + { + var kept = new List(); + session.EditSetAside += kept.Add; + Assert.True(session.Edit(p => Exposure(p, 0.4))); + Assert.True(await session.FlushAsync()); + Assert.NotNull(await host.CommitAsync(projectId, bed.Ct)); + var folder = host.Store.Find(projectId)!; + var stored = folder.ReadBundle(); + // A sync took a newer Chronos's settings while one more edit waited for its save (made during the sync). + folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } }); + Assert.True(session.Edit(p => p with { ExcludedFrames = [2] })); + Assert.False(await session.FlushAsync(), "the working state no longer takes it"); + + await session.ReloadAsync(); + + Assert.True(session.IsReadOnly); + Assert.True(session.Project.IsNewerFormat, "the newer settings are taken"); + Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv); + Assert.True(await session.FlushAsync(), "nothing retried that could never be stored"); + Assert.False(session.HasPendingSave); + Assert.Null(session.LastSaveError); + var path = Assert.NotNull(kept.SingleOrDefault(), "the edit is kept aside, and said"); + Assert.Equal(Path.Combine(folder.VersionsDirectory, WorkspaceProject.ReplacedFolder), Path.GetDirectoryName(path)); + var aside = ProjectSidecars.ReadVersion(path); + var placed = ProjectSettings.FromJson(ProjectContent.Place(aside.SettingsJson, source.Photos)); + Assert.Equal(0.4, placed.Exposure.ExposureOffsetEv); + Assert.SequenceEqual([2], placed.ExcludedFrames, "the edit as it was, by photo"); + Assert.False(folder.Versions().Any(v => v.Id == aside.Id), "outside the chain: never sent"); + Assert.Empty(host.Sync.Unpushed(projectId).Where(v => v.Id == aside.Id)); + + // Read again: no throw, nothing more kept aside, the editor as it is. + await session.ReloadAsync(); + Assert.Count(1, kept); + Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv); + Assert.True(await session.FlushAsync()); + } + } } diff --git a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs index f7fc49f4..720063a4 100644 --- a/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs +++ b/tests/Chronos.App.Tests/Workspace/WorkspaceSectionTests.cs @@ -15,6 +15,7 @@ using Chronos.Data; using Chronos.Data.Archiving; using Chronos.Data.Workspaces; using Chronos.Testing; +using Chronos.Ui.Controls; namespace Chronos.App.Tests.Workspace; @@ -115,6 +116,91 @@ public sealed class WorkspaceSectionTests(TestContext context) } }); + [Test] + public Task ARefusedFolderOffersAnotherFromItsToastAndCopiesThisChronosCannotReadAreNeverOpened() => ScreenHost.RunAsync(async () => + { + var directory = context.CreateTempDirectory("workspace-refused"); + var environment = AppEnvironment.From(AppPaths.Resolve(Directory.CreateDirectory(Path.Combine(directory, "app")).FullName, + Directory.CreateDirectory(Path.Combine(directory, "local")).FullName, [])); + UiLanguage.Apply("en"); + var settings = new AppSettings { Language = "en", FirstRunCompleted = true, CheckForUpdates = false }; + var outside = Path.Combine(directory, "outside"); + var dialogs = new ScriptedDialogs { Folder = outside }; + var services = new AppServices(environment, settings, () => { }, dialogs); + await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true); + var shell = new ShellViewModel(services); + var toasts = new List(); + shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []); + try + { + var library = Path.Combine(directory, "archive"); + var sequenceId = await SequenceAsync(services, library); + var inside = Path.Combine(library, "workspace"); + settings.WorkspaceFolder = inside; + var section = shell.Sequence; + + // Open in workspace shows what the copy writes and the room there is, then the folder is refused with a way on. + shell.OpenSequence(sequenceId); + await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time"); + var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!; + Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], ask.CopyFacts.Select(f => f.Label), "the copy's facts reach the dialog"); + ask.OpenCommand.Execute(null); + await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")), "the refusal is said"); + var refused = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.OpenFailed")); + Assert.True(refused is { IsError: true, ActionCommand: not null }, "an error with its action"); + Assert.Equal((Loc.L("Errors.Workspace.InsideLibraryEdit", Path.GetFullPath(inside)), Loc.L("Editor.Workspace.ChooseFolder"), Loc.L("Tooltips.Editor.Workspace.ChooseFolder")), + (refused.Message, refused.ActionText, refused.ActionToolTip)); + Assert.False(Directory.Exists(inside), "nothing was written inside the library"); + Assert.Null(section.Editor); + + // Its action picks another folder, shows the plan and uses it. + refused.ActionCommand!.Execute(null); + await WorkspaceTestBed.UntilAsync(() => string.Equals(services.Workspace.Root, Path.GetFullPath(outside), StringComparison.OrdinalIgnoreCase), "the folder chosen is used"); + Assert.Count(1, dialogs.Asked); + Assert.Equal(Loc.L("Settings.Workspace.ChangeTitle"), dialogs.Asked[0].Heading); + + // That workspace holds a copy a newer Chronos saved and a damaged one: listed, never opened. + var newerId = Guid.CreateVersion7(); + var newer = Directory.CreateDirectory(Path.Combine(outside, newerId.ToString("N"))).FullName; + await File.WriteAllTextAsync(Path.Combine(newer, WorkspaceProject.BundleFile), + $$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Harbour" }, "workspace": { "projectId": "{{newerId}}", "name": "Vertical" } }"""); + var damagedId = Guid.CreateVersion7(); + var damaged = Directory.CreateDirectory(Path.Combine(outside, damagedId.ToString("N"))).FullName; + await File.WriteAllTextAsync(Path.Combine(damaged, WorkspaceProject.BundleFile), "{ not a project"); + await File.WriteAllTextAsync(Path.Combine(damaged, "notes.txt"), "kept"); + await section.Picker.ReloadAsync(); + await section.Picker.WorkspaceLoadedAsync(); + var newerItem = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == newerId); + Assert.True(newerItem is { IsNewer: true, IsDamaged: false, IsReadable: false, Name: "Vertical", SequenceTitle: "Harbour" }); + Assert.Null(newerItem.Status, "no state is asked of it"); + await section.PickProjectAsync(newerItem); + Assert.Contains(toasts, t => t.Message == Loc.L("Errors.Workspace.NewerCopy") && t.IsError); + Assert.Null(section.Dialog, "nothing is offered over it"); + Assert.FileExists(Path.Combine(newer, WorkspaceProject.BundleFile)); + + // The damaged one offers its removal, named as a damaged copy; Discard asks its files' number and keeps every file aside. + var damagedItem = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == damagedId); + await section.PickProjectAsync(damagedItem); + var remove = Assert.NotNull(section.Dialog as RemoveCopyDialogViewModel); + Assert.Equal(Loc.L("Editor.RemoveCopy.DamagedTitle"), remove.Heading); + dialogs.Answer = true; + remove.DiscardCommand.Execute(null); + await WorkspaceTestBed.UntilAsync(() => !Directory.Exists(damaged), "the damaged copy goes"); + var discard = dialogs.Asked[^1]; + Assert.Equal((Loc.L("Editor.RemoveCopy.DamagedDiscard"), Formatting.Count(2), Loc.L("Editor.RemoveCopy.TypeFiles", Formatting.Count(2))), + (discard.Heading, discard.TypedConfirmation, discard.TypedPrompt)); + var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(outside, WorkspaceHost.TrashFolder)), + d => Path.GetFileName(d).StartsWith(damagedId.ToString("N"), StringComparison.Ordinal)); + Assert.Equal("kept", await File.ReadAllTextAsync(Path.Combine(aside, "notes.txt"))); + } + finally + { + await shell.Sequence.CloseAsync(); + shell.Dispose(); + await services.DisposeAsync(); + } + }); + /// An archive with one sequence of six synthetic photos, indexed. private async Task SequenceAsync(AppServices services, string root) { @@ -133,6 +219,24 @@ public sealed class WorkspaceSectionTests(TestContext context) return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id; } + /// Dialogs that pick and answer every confirmation with (yes first), recording what they were asked. + private sealed class ScriptedDialogs : IAppDialogs + { + public string? Folder { get; set; } + public bool Answer { get; set; } = true; + public List Asked { get; } = []; + public string? PickFolder(string title, string? initialFolder = null) => Folder; + public string? PickJsonFile(string title) => null; + + public bool Confirm(ConfirmRequest request) + { + Asked.Add(request); + return Answer; + } + + public bool SignIn(string server, string? username, Func> signIn) => false; + } + /// Dialogs that pick nothing and decline every confirmation. private sealed class DeclineDialogs : IAppDialogs { diff --git a/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs b/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs index 51b18b07..7ba32326 100644 --- a/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs +++ b/tests/Chronos.Data.Tests/Workspaces/WorkspaceConflictTests.cs @@ -150,6 +150,66 @@ public abstract class WorkspaceConflictTests(TestContext context) : DatabaseTest Assert.Equal(1.0, (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv, "the value listed as this side's is kept"); } + [Test] + public async Task AWorkingStateBackAtTheBaseValueIsListedAndKeptAsItIs() + { + var fx = await FixtureAsync(); + var (_, one) = fx.Workspace("one"); + var (_, two) = fx.Workspace("two"); + var id = (await fx.CheckoutAsync(one)).ProjectId; + await fx.CheckoutAsync(two, id); + var basis = (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv; + await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct); + await one.CommitAsync(id, cancellationToken: fx.Ct); + await one.PushAsync(id, fx.Home, fx.Ct); + // This side saved 0.8 as a version, then went back to the base value without saving. + await EditAsync(two, id, s => Offset(s, 0.8), fx.Ct); + await two.CommitAsync(id, "warmer", cancellationToken: fx.Ct); + await EditAsync(two, id, s => Offset(s, basis), fx.Ct); + + var shown = Assert.NotNull((await two.PullAsync(id, fx.Home, fx.Ct)).Status.Conflict); + var difference = shown.Differences.Single(); + Assert.Equal(("exposure.exposureOffsetEv", basis, 0.5), (difference.Path, Number(difference.Mine) ?? 0, Number(difference.Theirs)), + "this side's value is the working state's, not the version's 0.8"); + + var settled = await two.ResolveAsync(id, fx.Home, ConflictChoice.KeepMine, shown: shown, cancellationToken: fx.Ct); + Assert.Null(settled.Status.Conflict, "one answer settles what was shown"); + Assert.Equal(basis, (await two.OpenAsync(id, fx.Ct)).Working.Exposure.ExposureOffsetEv, "the value listed as this side's is the one kept"); + Assert.True(settled.Status.Modified, "the saved version keeps its own value; the working state's is not saved yet"); + Assert.Equal("warmer", two.Unpushed(id).Single().Note); + await two.CommitAsync(id, cancellationToken: fx.Ct); + await two.PushAsync(id, fx.Home, fx.Ct); + Assert.Equal(basis, ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson).Exposure.ExposureOffsetEv, "the library ends with the value kept"); + } + + [Test] + public async Task AWorkingStateHoldingTheLibrarysValueIsNoConflictAndItsVersionAgrees() + { + var fx = await FixtureAsync(); + var (_, one) = fx.Workspace("one"); + var (_, two) = fx.Workspace("two"); + var id = (await fx.CheckoutAsync(one)).ProjectId; + await fx.CheckoutAsync(two, id); + await EditAsync(one, id, s => Offset(s, 0.5), fx.Ct); + await one.CommitAsync(id, cancellationToken: fx.Ct); + await one.PushAsync(id, fx.Home, fx.Ct); + // This side saved 0.8 and a stack as a version, then set the offset to the library's own 0.5 without saving. + await EditAsync(two, id, s => Stack(Offset(s, 0.8), StackSetting.Mean), fx.Ct); + await two.CommitAsync(id, "local", cancellationToken: fx.Ct); + await EditAsync(two, id, s => Offset(s, 0.5), fx.Ct); + + var pulled = await two.PullAsync(id, fx.Home, fx.Ct); + Assert.Null(pulled.Status.Conflict, "nothing to choose: the working state holds the library's value"); + var working = (await two.OpenAsync(id, fx.Ct)).Working; + Assert.Equal((0.5, StackSetting.Mean), (working.Exposure.ExposureOffsetEv, working.Stack.Mode), "the working state is unchanged"); + var replayed = ProjectSettings.FromJson(two.Unpushed(id).Single().SettingsJson); + Assert.Equal((0.5, StackSetting.Mean), (replayed.Exposure.ExposureOffsetEv, replayed.Stack.Mode), "the replayed version agrees with the working state"); + Assert.True(pulled.Status is { State: WorkspaceState.Ahead, Modified: false }, "nothing left unsaved"); + await two.PushAsync(id, fx.Home, fx.Ct); + var head = ProjectSettings.FromJson((await fx.Home.HeadAsync(id, fx.Ct)).SettingsJson); + Assert.Equal((0.5, StackSetting.Mean), (head.Exposure.ExposureOffsetEv, head.Stack.Mode)); + } + private static double? Number(string? json) => json is null ? null : double.Parse(json, System.Globalization.CultureInfo.InvariantCulture); [Test]