Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceMenuTests.cs
T
Alby96andClaude Opus 5.5 e23cba3ee1 fix(workspace): phase 5a fix round 2, workspace sync and copy
A Save both, a recorded conflict and a damaged version file could each leave
a local version out of the chain or a copy half-made at the home. This round
makes every one of these end with nothing lost and nothing half done.

- Save both retry: a journaled copy somebody else sent a version to (or one
  deleted since) is left as it is, and a new copy takes every local version.
  A divergence met at the copy while sending also makes a new copy, once.
- Keep mine, Take server, or a pull that settles a conflict after a Save both
  was cut short first send the rest of the journaled versions to that copy,
  if it is still this workspace's. The journal is cleared at the commit point.
- A conflict of format met past local versions the home already stored
  (their answer lost) now moves the base onto them, like any other conflict.
  The conflict, the base and the chain then name one version. A save-both
  journal follows the base when it moves.
- A conflict recorded before stays while the home holds no version after
  the base. A base that has reached the conflict's head clears it.
- Take server no longer replays or sends the version it saves first when,
  replayed, that version holds only the server's values. It stays in
  versions/.replaced for the undo. The test checks the exact history again.
- Version files after the base that cannot be read, or that do not follow
  from it, are listed (WorkspaceProject.UnreadableVersions). The new state
  WorkspaceState.Damaged shows them. Commit, push, pull and resolve refuse to
  go past them. A damaged file whose version the home holds takes the home's
  copy at the next sync, and the damaged file is kept aside. Remove local
  copy counts these files as unsent.
- PushOutcome.TooLarge raises its own WorkspaceSyncException message. The
  desktop says Errors.Workspace.VersionTooLarge for it and for
  ProjectVersionTooLargeException when a local commit is too large.
- The editor maps LeaseUnavailableException from opening a busy project to
  Errors.Workspace.Busy.
- The copy job no longer deletes, during the pass, a proxy that the editor's
  current media name. RemoveStale removes it after the commit. A resumed run
  does not keep such a file as a frame whose photo changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:31:18 +01:00

335 lines
18 KiB
C#

using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Sync;
using Chronos.Ui.Controls;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// The editor and the project menu of a workspace project as review 2's phase 5a found them wanting (owner review 2, R8):
/// saves that merge positions photo by photo and ask where both changed a setting, Take the library's as one undo step,
/// the chip read again after edits, conflicts that wait for the open dialog, Send first that shows the conflict it met,
/// Open project, read-only after a pull, a workspace inside a library, and how differences and authors read.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceMenuTests(TestContext context)
{
private static ProjectSettings Exposure(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } };
[Test]
public async Task SavesMergeExclusionsPhotoByPhotoAndAskWhereBothChangedASetting()
{
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);
var conflicts = new List<ProjectConflictException>();
session.ConflictFound += conflicts.Add;
await using (session)
{
var folder = host.Store.Find(projectId)!;
// A sync wrote another PC's exclusion of frame 5 while the editor's exclusion of frame 2 waited for its save.
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { ExcludedFrames = [5] } });
Assert.True(session.SetExcluded([2], excluded: true));
Assert.True(await session.FlushAsync());
Assert.SequenceEqual([2, 5], folder.ReadBundle().Project.ExcludedFrames, "both exclusions are kept");
Assert.SequenceEqual([2, 5], session.Project.ExcludedFrames, "the editor shows the other one too");
Assert.Empty(conflicts);
// The same setting to another value meanwhile: asked, never decided for the editor.
stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 0.5) });
Assert.True(session.Edit(p => Exposure(p, 0.9)));
Assert.False(await session.FlushAsync(), "nothing is stored until the user chooses");
Assert.Count(1, conflicts);
var conflict = conflicts[0];
Assert.Contains(conflict.Differences, d => d.Path == "exposure.exposureOffsetEv");
Assert.Equal(0.5, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
var request = EditorViewModel.LibraryConflictRequest(conflict, "Harbour");
Assert.Equal(Loc.L("Editor.Workspace.Conflict.TakeHome"), request.SafeText);
Assert.Contains("0.9", request.Detail!);
Assert.True(session.ResolveConflict(keepMine: true));
Assert.True(await session.FlushAsync());
Assert.Equal(0.9, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
Assert.SequenceEqual([2, 5], folder.ReadBundle().Project.ExcludedFrames);
}
}
[Test]
public async Task TakingTheLibrarysValuesIsOneUndoStepThatKeepsItsOtherChanges()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var here = bed.Host();
var there = bed.Host(name: "other-pc");
var mainId = await bed.CheckoutAsync(here);
await bed.CheckoutAsync(there);
var (sourceA, sessionA) = await bed.OpenAsync(there, mainId);
var (sourceB, sessionB) = await bed.OpenAsync(here, mainId);
var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
await using (sessionA)
await using (sessionB)
using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
{
// The other PC changes the exposure and the camera; this one the exposure only.
sessionA.Edit(p => Exposure(p, 0.1) with { Camera = p.Camera with { OffsetY = 0.2 } });
await a.SaveVersionAsync(null);
sessionB.Edit(p => Exposure(p, 0.7));
await b.SyncAsync();
var dialog = Assert.NotNull(uiB.Open as ConflictDialogViewModel);
Assert.Count(1, dialog.Differences);
dialog.TakeHomeCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is null, "take the library's settles it");
Assert.Equal((0.1, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
var toast = uiB.Toasts[^1];
Assert.Equal(Loc.L("Editor.Workspace.TookLibrary"), toast.Title);
// Its Undo brings this PC's exposure back, not the camera the library alone changed; Ctrl+Z takes the take back alike.
toast.Action!();
Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
Assert.True(sessionB.Undo());
Assert.Equal(0.1, sessionB.Project.Exposure.ExposureOffsetEv);
Assert.True(sessionB.Undo());
Assert.Equal((0.7, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
Assert.True(await sessionB.FlushAsync());
var working = here.Store.Find(mainId)!.ReadBundle().Project;
Assert.Equal((0.7, 0.2), (working.Exposure.ExposureOffsetEv, working.Camera.OffsetY), "the values brought back are stored");
}
}
[Test]
public async Task TheChipFollowsEditsAndABackgroundConflictWaitsForTheOpenDialog()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var here = bed.Host();
var there = bed.Host(name: "other-pc");
var mainId = await bed.CheckoutAsync(here);
await bed.CheckoutAsync(there);
var (sourceA, sessionA) = await bed.OpenAsync(there, mainId);
var (sourceB, sessionB) = await bed.OpenAsync(here, mainId);
var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
await using (sessionA)
await using (sessionB)
using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
{
await b.RefreshAsync();
Assert.Equal(Loc.L("Editor.Workspace.State.InSync"), b.StateText);
sessionB.Edit(p => Exposure(p, 0.7));
await WorkspaceTestBed.UntilAsync(() => b.StateText == Loc.L("Editor.Workspace.State.Modified"), "the chip says the work is not saved as a version");
sessionA.Edit(p => Exposure(p, 0.1));
await a.SaveVersionAsync(null);
// The user types a note in Save version when an automatic sync (after an analysis) meets the conflict.
b.SaveVersionCommand.Execute(null);
var saving = Assert.NotNull(uiB.Open as SaveVersionDialogViewModel);
saving.Note = "Warmer";
await b.SyncAsync(quiet: true);
Assert.Same(saving, uiB.Open, "the open dialog stays");
Assert.Equal("Warmer", saving.Note);
Assert.Equal(WorkspaceState.Conflict, b.Status!.State);
await b.SyncAsync(quiet: true);
Assert.Count(1, uiB.Waiting, "asked once");
uiB.CloseDialog(saving);
Assert.NotNull(uiB.Open as ConflictDialogViewModel, "asked once the dialog closed");
}
}
[Test]
public async Task SendFirstShowsTheConflictItMeetsAndRemovesNothing()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var here = bed.Host();
var there = bed.Host(name: "other-pc");
var mainId = await bed.CheckoutAsync(here);
await bed.CheckoutAsync(there);
var (sourceA, sessionA) = await bed.OpenAsync(there, mainId);
var (sourceB, sessionB) = await bed.OpenAsync(here, mainId);
var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
await using (sessionA)
await using (sessionB)
using (var a = new ProjectMenuViewModel(there, sourceA, sessionA, uiA))
using (var b = new ProjectMenuViewModel(here, sourceB, sessionB, uiB))
{
sessionA.Edit(p => Exposure(p, 0.1));
await a.SaveVersionAsync(null);
sessionB.Edit(p => Exposure(p, 0.7));
Assert.True(await sessionB.FlushAsync());
b.RemoveCopyCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is RemoveCopyDialogViewModel, "the plan shows");
var removing = (RemoveCopyDialogViewModel)uiB.Open!;
removing.SendFirstCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is ConflictDialogViewModel, "the conflict is asked, not hidden behind Discard");
Assert.Equal(0, uiB.Closed, "the editor stays open");
Assert.NotNull(here.Store.Find(mainId), "nothing was removed");
}
}
[Test]
public async Task OpenProjectOffersTheLibrarysOtherProjects()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var host = bed.Host();
var mainId = await bed.CheckoutAsync(host);
var vertical = await host.CreateProjectAsync(bed.SequenceId, "Vertical", null);
var (source, session) = await bed.OpenAsync(host, mainId);
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
menu.OpenProjectCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Open is OpenInWorkspaceDialogViewModel, "the projects are listed");
var dialog = (OpenInWorkspaceDialogViewModel)ui.Open!;
Assert.SequenceEqual(["Vertical"], dialog.Projects.Select(p => p.Project.Name), "the open project is not offered");
dialog.IsNew = true;
dialog.NewName.Text = "Main";
Assert.False(dialog.CanOpen, "the open project's name is taken");
dialog.IsExisting = true;
dialog.SelectedProject = dialog.Projects[0];
dialog.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Opened.Count == 1, "the project opens");
Assert.Equal((bed.SequenceId, vertical.Id), ui.Opened[0]);
}
}
[Test]
public async Task APullOfANewerChronossSettingsTurnsTheEditorReadOnly()
{
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);
var raised = 0;
source.ReadOnlyChanged += () => raised++;
await using (session)
{
Assert.False(session.IsReadOnly);
var folder = host.Store.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
Assert.True(session.IsReadOnly);
Assert.Equal(1, raised, "the editor is told, and shows it");
Assert.False(session.HasPendingSave, "no save that could never be stored waits");
Assert.False(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync(), "operations that store the last edit go on");
}
}
[Test]
public async Task AWorkspaceInsideALibraryIsRefusedBeforeAnythingIsWritten()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var row = await bed.RowAsync();
var root = (await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath;
var inside = Path.Combine(root, "Chronos", "data", "workspace");
var host = bed.Host(new AppSettings { WorkspaceFolder = inside });
Assert.Empty(await host.ListAsync());
Assert.Null(await host.FindAsync(Guid.NewGuid()));
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, null, null));
Assert.Equal(Loc.L("Errors.Workspace.InsideLibraryEdit", inside), refused.Message);
Assert.False(Directory.Exists(inside), "nothing was written there");
}
[Test]
public void ACopyTheLibraryNoLongerHasCanOnlyBeDiscarded()
{
var plan = new WorkspaceRemovalPlan(Guid.NewGuid(), "Vertical", 3, 100, 0, false, false, true, Gone: true);
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => false, _ => { });
Assert.False(dialog.RemoveCommand.CanExecute(null) || dialog.SendFirstCommand.CanExecute(null));
Assert.True(dialog.HasUnsent && dialog.DiscardCommand.CanExecute(null));
Assert.Equal(Loc.L("Errors.Workspace.ProjectGone"), dialog.RemoveToolTip);
// The chip keeps what the library said last when the working state is read again after an edit.
var basis = new BundleBase(Guid.NewGuid(), 2, new string('a', 64));
var gone = new WorkspaceStatus(WorkspaceState.Gone, false, 0, 0, true, false, false, null, basis, null);
var edited = new WorkspaceStatus(WorkspaceState.Modified, true, 0, 0, false, false, false, null, basis, null);
Assert.Equal(WorkspaceState.Gone, ProjectMenuViewModel.WithLocal(gone, edited).State);
var behind = gone with { State = WorkspaceState.Behind, Behind = 2, Offline = false };
Assert.Equal((WorkspaceState.Behind, 2), (ProjectMenuViewModel.WithLocal(behind, edited).State, ProjectMenuViewModel.WithLocal(behind, edited).Behind));
Assert.Equal(WorkspaceState.Modified, ProjectMenuViewModel.WithLocal(behind, edited with { Base = basis with { VersionId = Guid.NewGuid() } }).State,
"a base that moved since says nothing of how far the library is ahead");
// A version saved here that cannot be read outranks what the library said.
Assert.Equal(WorkspaceState.Damaged, ProjectMenuViewModel.WithLocal(behind, edited with { Damaged = 1 }).State);
}
[Test]
public void ADamagedVersionAndOneTooLargeReadAsSuch()
{
var damaged = new WorkspaceStatus(WorkspaceState.Damaged, false, 1, 0, false, false, false, null, null, null) { Damaged = 1 };
Assert.Equal((Loc.L("Editor.Workspace.State.Damaged"), StatusKind.Error), (WorkspaceText.State(damaged), WorkspaceText.Kind(damaged)));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Damaged"), WorkspaceText.StateToolTip(damaged));
Assert.Equal(Loc.L("Errors.Workspace.Damaged"), WorkspaceText.Failure(new InvalidDataException("a version file cannot be read")));
// Too large: a version saved here (refused before it was written) and one the library refused say the same, with the limit.
var tooLarge = Loc.L("Errors.Workspace.VersionTooLarge", ProjectSidecars.MaxVersionBytes >> 20);
Assert.Contains("64", tooLarge);
Assert.Equal(tooLarge, WorkspaceText.Failure(new ProjectVersionTooLargeException("over the limit")));
Assert.Equal(tooLarge, WorkspaceText.Failure(new WorkspaceSyncException(PushOutcome.TooLarge, "over the limit")));
Assert.Equal(tooLarge, Chronos.App.Shell.ErrorText.For(new ProjectVersionTooLargeException("over the limit")));
Assert.Equal(Loc.L("Errors.Workspace.Refused"), WorkspaceText.Failure(new WorkspaceSyncException(PushOutcome.Invalid, "not this project's")));
}
[Test]
public void DifferencesNameTheirSettingsAndAuthorsReadAsThePc()
{
var lines = WorkspaceText.ConflictLines(
[
new SettingsDifference("hero", "{\"hero\":true}", "{\"hero\":true}"),
new SettingsDifference("pendingFrames.sha:ab12#0.keyframes", "[]", "[{\"x\":1}]"),
new SettingsDifference("pendingFrames.sha:cd34#0.excluded", "true", "false"),
], 10);
Assert.Count(3, lines);
Assert.Contains(lines, l => l.Contains(Loc.L("Server.Setting.HeroFrame"), StringComparison.Ordinal));
Assert.Contains(lines, l => l.Contains(Loc.L("Server.Setting.Keyframes"), StringComparison.Ordinal));
Assert.Contains(lines, l => l.Contains(Loc.L("Server.Setting.ExcludedFrames"), StringComparison.Ordinal));
Assert.False(lines.Any(l => l.Contains(Loc.L("Server.Setting.Other"), StringComparison.Ordinal)), "every line names its setting");
ProjectVersion Made(string? client, string? author = null) => new()
{
Id = Guid.NewGuid(),
ProjectId = Guid.NewGuid(),
Number = 1,
SettingsJson = "{}",
ContentHash = new string('0', 64),
ClientName = client,
Author = author,
};
Assert.Equal("STUDIO-PC", WorkspaceText.Author(Made("chronos@STUDIO-PC")));
Assert.Equal("STUDIO-PC", WorkspaceText.Author(Made("Chronos on STUDIO-PC")));
Assert.Equal("STUDIO-PC", WorkspaceText.Author(Made("STUDIO-PC")));
Assert.Equal("Alberto", WorkspaceText.Author(Made("STUDIO-PC", "Alberto")));
Assert.Equal(Environment.MachineName, WorkspaceHost.ClientName);
}
[Test]
public async Task CompareNamesExclusionsAsTheSettingTheyAre()
{
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);
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
var head = (await host.HistoryAsync(projectId)).Versions[0];
Assert.True(session.SetExcluded([1, 3], excluded: true));
var lines = menu.Compare(head);
Assert.Count(1, lines);
Assert.Contains(Loc.L("Server.Setting.ExcludedFrames"), lines[0]);
}
}
}