Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceEditorTests.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
19 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Data.Workspaces;
using Chronos.Testing;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// The editor over a workspace project (owner review 2, R8): its source (the media's frames, the working state saved
/// there and merged, never the library), renders at the home, and the project menu: Save version, Sync, Restore and the
/// conflicts a sync meets.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceEditorTests(TestContext context)
{
private static ProjectSettings Exposure(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } };
private static double ExposureOf(string? json) => ProjectSettings.FromJson(json!).Exposure.ExposureOffsetEv;
[Test]
public async Task TheEditorEditsTheWorkspaceAndNeverTheLibrary()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var host = bed.Host();
var libraryBefore = (await bed.RowAsync()).SettingsJson;
var projectId = await bed.CheckoutAsync(host);
var (source, session) = await bed.OpenAsync(host, projectId);
await using (session)
{
var frames = await bed.Db.Frames.ListBySequenceAsync(bed.SequenceId, -1, 100);
Assert.SequenceEqual(frames.Select(f => f.Id), session.Content.Frames.Select(f => f.Id), "the media's frames are the home's");
Assert.Equal(bed.SequenceId, session.Content.Sequence.Id);
Assert.False(session.IsRemote || session.IsReadOnly);
Assert.Contains("exports", session.Content.ExportsFolder!);
Assert.True(source.Workspace is { IsMain: true, Home.IsArchive: true });
using (var thumbnail = await source.DecodeAsync(2, 32, DecodePurpose.Thumbnail, bed.Ct))
Assert.True(thumbnail is { Width: > 0 } && Math.Max(thumbnail.Width, thumbnail.Height) <= 32);
Assert.Null(await source.DecodeAsync(99, 32, DecodePurpose.Thumbnail, bed.Ct));
Assert.True(await source.FramesCurrentAsync(bed.Ct));
Assert.False(await source.HomeFramesChangedAsync(bed.Ct));
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(await session.FlushAsync());
var folder = host.Store.Find(projectId)!;
Assert.Equal(0.4, folder.ReadBundle().Project.Exposure.ExposureOffsetEv);
Assert.Equal(libraryBefore, (await bed.RowAsync()).SettingsJson, "editing never writes the library");
Assert.Equal(WorkspaceState.Modified, (await host.StatusAsync(projectId)).State);
// The working state written meanwhile by someone else (a pull, a copy): both changes survive the next save.
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = stored.Project with { Camera = stored.Project.Camera with { OffsetY = 0.25 } } });
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
var merged = folder.ReadBundle().Project;
Assert.Equal((3, 0.25, 0.4), (merged.HeroFrame ?? -1, merged.Camera.OffsetY, merged.Exposure.ExposureOffsetEv));
Assert.Equal(0.25, session.Project.Camera.OffsetY, "the editor shows what was merged in");
}
}
[Test]
public async Task AProjectASyncKeepsBusyOpensOnceItIsFree()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 3);
var host = bed.Host();
var projectId = await bed.CheckoutAsync(host);
var impatient = new WorkspaceSync(host.Store, "Chronos test") { LockWait = TimeSpan.FromMilliseconds(200) };
var source = new WorkspaceSequenceSource(impatient, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine);
await using (source)
{
// A long sync or copy holds the project: the editor says so in words, and nothing was read.
using (await host.Store.Find(projectId)!.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(5)), bed.Ct))
{
var busy = await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Busy"), busy.Message);
}
Assert.Equal(3, (await source.LoadAsync(bed.Ct)).Frames.Count);
}
}
[Test]
public async Task SaveVersionSendsItAndTheLibraryTakesMain()
{
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))
{
await menu.RefreshAsync();
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(Loc.L("Editor.Project.Main"), menu.Name);
Assert.Equal(Loc.L("Editor.Workspace.State.InSync"), menu.StateText);
Assert.False(menu.DeleteCommand.CanExecute(null), "Main holds the sequence's settings");
Assert.Equal(Loc.L("Errors.Workspace.MainKept"), menu.DeleteToolTip);
session.Edit(p => Exposure(p, 0.4));
// Save version… asks for a note; saving sends the version at once (Sync automatically is on by default).
menu.SaveVersionCommand.Execute(null);
var dialog = Assert.NotNull(ui.Open as SaveVersionDialogViewModel);
dialog.Note = " Warmer ";
dialog.SaveCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Open is null, "the dialog closes once the version is saved");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(0.4, ExposureOf((await bed.RowAsync()).SettingsJson), "Main's version is the sequence's settings");
Assert.Equal(Loc.L("Editor.Workspace.SavedSent", "2"), ui.Toasts[^1].Title);
Assert.Contains(bed.SequenceId, ui.SequencesChanged);
var history = await host.HistoryAsync(projectId);
Assert.Equal(("Warmer", ProjectVersionKind.Commit, 2), (history.Versions[0].Note, history.Versions[0].Kind, history.Versions[0].Number));
Assert.Equal(ProjectVersionKind.Imported, history.Versions[^1].Kind);
Assert.Empty(history.Unsent);
// Nothing new: no version.
await menu.SaveVersionAsync(null);
Assert.Equal(Loc.L("Editor.Workspace.NothingNew"), ui.Toasts[^1].Title);
// Without Sync automatically the version waits here until Sync sends it.
host.Settings.WorkspaceAutoSync = false;
session.Edit(p => Exposure(p, 0.6));
await menu.SaveVersionAsync("Brighter");
Assert.Equal((WorkspaceState.Ahead, 1), (menu.Status!.State, menu.Status.Ahead));
Assert.Equal(Loc.L("Editor.Workspace.Saved", "3"), ui.Toasts[^1].Title);
Assert.Equal(0.4, ExposureOf((await bed.RowAsync()).SettingsJson), "not sent yet");
var unsent = await host.HistoryAsync(projectId);
Assert.True(unsent.Unsent.Contains(unsent.Versions[0].Id) && unsent.Versions[0].Note == "Brighter", "the version not sent is listed first");
await menu.SyncAsync();
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(0.6, ExposureOf((await bed.RowAsync()).SettingsJson));
}
}
[Test]
public async Task RendersRunAtTheHomeWithThePortableSettingsAndTheVersion()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var projectId = await bed.CheckoutAsync(host);
var (_, session) = await bed.OpenAsync(host, projectId);
await using (session)
{
Assert.True(session.SetHero(2));
Assert.True(await session.FlushAsync());
var unsaved = session.RenderRequests(session.Project.Export);
var request = Assert.Contains(unsaved, r => r.Kind == JobKind.Render);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var (parameters, _) = ProcessingJobs.ReadRender(request.ParametersJson);
Assert.Equal<Guid?>(projectId, parameters.ProjectId);
Assert.Null(parameters.ProjectVersionId, "an unsaved working state names no version");
Assert.False(parameters.UseProxies, "the home renders its originals");
var portable = ProjectSettings.FromJson(parameters.SettingsJson!);
Assert.Null(portable.HeroFrame, "positions travel by photo");
Assert.Contains(portable.PendingFrames!, f => f.Hero);
// A version saved here and not sent yet may reach the home under another id (a replay): the render names none.
var saved = (await host.SaveVersionAsync(projectId, null)).Version!;
var (unsent, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Null(unsent.ProjectVersionId, "a version not sent names no version");
Assert.Equal<Guid?>(projectId, unsent.ProjectId);
// Sent, the home holds it under its id: the render names it.
await host.SyncAsync(projectId);
var (versioned, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<Guid?>(saved.Id, versioned.ProjectVersionId);
Assert.Equal(parameters.SettingsJson, versioned.SettingsJson);
}
}
[Test]
public async Task RestoreIsOneUndoStepAndLosesNothing()
{
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))
{
session.Edit(p => Exposure(p, 0.3));
await menu.SaveVersionAsync("Warm");
var warm = (await host.HistoryAsync(projectId)).Versions[0];
session.Edit(p => Exposure(p, 0.6));
Assert.True(await session.FlushAsync());
// Compare: what differs between now and that version.
var lines = menu.Compare(warm);
Assert.Count(1, lines);
Assert.Contains("0.6", lines[0]);
Assert.Contains("0.3", lines[0]);
// History › Restore: the version is the project again, as one step; the unsaved 0.6 was saved as a version first.
menu.HistoryCommand.Execute(null);
var history = Assert.NotNull(ui.Open as HistoryDialogViewModel);
await WorkspaceTestBed.UntilAsync(() => history.Rows.Count > 0, "the history lists the versions");
Assert.SequenceEqual(["2", "1"], history.Rows.Select(r => r.Number));
Assert.False(history.Rows.Any(r => r.IsCurrent), "the working state (0.6) is no version yet");
Assert.Equal(Loc.L("Editor.History.Kind.Imported"), history.Rows[1].KindText);
await history.CompareAsync(warm);
Assert.Equal(Loc.L("Editor.History.Compared", "2"), history.ComparedTitle);
await history.RestoreAsync(warm);
Assert.Null(ui.Open);
Assert.Equal(0.3, session.Project.Exposure.ExposureOffsetEv);
Assert.Equal(Loc.L("Editor.Workspace.Restored", "2"), ui.Toasts[^1].Title);
var all = await host.HistoryAsync(projectId);
Assert.Contains(all.Versions, v => v.Number == 3 && v.Kind == ProjectVersionKind.Commit && Math.Abs(ExposureOfVersion(v) - 0.6) < 1e-9);
// The toast's Undo brings 0.6 back as a new step; Ctrl+Z after that takes the restore back too.
ui.Toasts[^1].Action!();
Assert.Equal(0.6, session.Project.Exposure.ExposureOffsetEv);
Assert.True(session.Undo());
Assert.Equal(0.3, session.Project.Exposure.ExposureOffsetEv);
// The next version records the restore.
await menu.SaveVersionAsync(null);
var restored = (await host.HistoryAsync(projectId)).Versions[0];
Assert.Equal((ProjectVersionKind.Restore, warm.Id), (restored.Kind, restored.RestoredFrom!.Value));
}
static double ExposureOfVersion(ProjectVersion version) => ProjectSettings.FromJson(version.SettingsJson).Exposure.ExposureOffsetEv;
}
[Test]
public async Task ConflictsAreAskedOnlyWhenBothChangedTheSameSetting()
{
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);
Assert.Equal(mainId, await bed.CheckoutAsync(there));
var (sourceA, sessionA) = await bed.OpenAsync(here, mainId);
var (sourceB, sessionB) = await bed.OpenAsync(there, mainId);
var (uiA, uiB) = (new RecordingUi(), new RecordingUi());
await using (sessionA)
await using (sessionB)
using (var a = new ProjectMenuViewModel(here, sourceA, sessionA, uiA))
using (var b = new ProjectMenuViewModel(there, sourceB, sessionB, uiB))
{
// Different settings: merged without a question, both in the library and in both editors.
sessionA.Edit(p => Exposure(p, 0.3));
await a.SaveVersionAsync(null);
sessionB.Edit(p => p with { Camera = p.Camera with { OffsetY = 0.2 } });
await b.SaveVersionAsync(null);
Assert.Empty(uiB.Dialogs.OfType<ConflictDialogViewModel>());
Assert.Equal((0.3, 0.2), (sessionB.Project.Exposure.ExposureOffsetEv, sessionB.Project.Camera.OffsetY));
await a.SyncAsync();
Assert.Equal((0.3, 0.2), (sessionA.Project.Exposure.ExposureOffsetEv, sessionA.Project.Camera.OffsetY));
// The same setting to different values: asked, keep mine.
sessionA.Edit(p => Exposure(p, 0.5));
await a.SaveVersionAsync(null);
sessionB.Edit(p => Exposure(p, 0.9));
await b.SaveVersionAsync(null);
var conflict = Assert.NotNull(uiB.Open as ConflictDialogViewModel);
Assert.Equal(WorkspaceState.Conflict, b.Status!.State);
Assert.False(b.CanSaveVersion, "no version until the conflict is settled");
Assert.Contains(conflict.Differences, l => l.Contains("0.9") && l.Contains("0.5"));
conflict.KeepMineCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => uiB.Open is null, "keep mine settles it");
Assert.Equal(WorkspaceState.InSync, b.Status!.State);
Assert.Equal(0.9, ExposureOf((await bed.RowAsync()).SettingsJson));
Assert.Equal(0.9, sessionB.Project.Exposure.ExposureOffsetEv);
// Again, take the library's (the other PC took this one's values first: its sync is in step).
await a.SyncAsync();
Assert.Equal(0.9, sessionA.Project.Exposure.ExposureOffsetEv);
sessionA.Edit(p => Exposure(p, 0.1));
await a.SaveVersionAsync(null);
sessionB.Edit(p => Exposure(p, 0.7));
await b.SaveVersionAsync(null);
await b.ResolveAsync(ConflictChoice.TakeServer);
Assert.Equal(0.1, sessionB.Project.Exposure.ExposureOffsetEv);
Assert.Equal(0.1, ExposureOf((await bed.RowAsync()).SettingsJson));
// And save both: this workspace's versions go to a sibling project, this one takes the library's.
await a.SyncAsync();
sessionA.Edit(p => Exposure(p, -0.2));
await a.SaveVersionAsync(null);
sessionB.Edit(p => Exposure(p, 0.8));
await b.SaveVersionAsync(null);
var both = Assert.NotNull(uiB.Open as ConflictDialogViewModel);
Assert.Equal(WorkspaceHost.SiblingName("Main"), both.SiblingName);
await b.ResolveAsync(ConflictChoice.SaveBoth);
Assert.Equal(-0.2, sessionB.Project.Exposure.ExposureOffsetEv);
var projects = await there.HomeProjectsAsync(bed.SequenceId);
var sibling = Assert.Contains(projects, p => p.Name == WorkspaceHost.SiblingName("Main"));
var head = await there.HomeOfSequence(bed.SequenceId).HeadAsync(sibling.Id, bed.Ct);
Assert.Equal(0.8, ProjectSettings.FromJson(head.SettingsJson).Exposure.ExposureOffsetEv, "nothing is lost: the sibling holds this side's values");
Assert.Equal(Loc.L("Editor.Workspace.SavedAs", sibling.Name), uiB.Toasts[^1].Title);
// The toast opens the sibling, which no other way lists while this project is the sequence's here.
uiB.Toasts[^1].Action!();
Assert.Equal((bed.SequenceId, sibling.Id), uiB.Opened[^1]);
}
}
[Test]
public async Task UpdateMediaFollowsTheLibrarysNewFramesByPhoto()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 6);
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 excluded = session.Content.Frames[2].Id;
Assert.True(session.SetExcluded([2], excluded: true));
Assert.True(await session.FlushAsync());
await bed.InsertEarlierFrameAsync();
await menu.RefreshAsync();
Assert.True(menu.HasMediaUpdate, "the library's frames moved past the workspace's");
Assert.Equal(Loc.L("Editor.Workspace.MediaChanged"), menu.MediaUpdateText);
Assert.Equal(6, session.Content.Count, "the editor keeps the frames it holds meanwhile");
menu.UpdateMediaCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => session.Content.Count == 7 && !menu.IsUpdatingMedia && !menu.HasMediaUpdate, "the new media are read");
Assert.SequenceEqual([3], session.Project.ExcludedFrames, "the exclusion follows its photo");
Assert.Equal(excluded, session.Content.Frames[3].Id);
Assert.True(session.Edit(p => Exposure(p, 0.2)));
Assert.True(await session.FlushAsync(), "saves go on over the new frames");
Assert.SequenceEqual([3], host.Store.Find(projectId)!.ReadBundle().Project.ExcludedFrames);
}
}
}