Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
T
Alby96andClaude Opus 5.5 7692ab402e fix(workspace): a cancelled copy clears only media no other copy writes; a deletion keeps late versions
Owner review 2, phase 5a, fix round 5.

- A cancelled workspace copy clears its partial media only under the project's
  lease, after checking again that the job is still cancelled, that no other
  copy of the same root and project is queued, running or paused, and that no
  copy in this process is writing. The engine now waits for a paused job's run
  to end before calling the cancel handler, so the clean-up is never skipped.
- The clean-up never recreates a project folder that was removed meanwhile
  (the lease no longer creates the folder). The next list removes a project
  folder that holds only lease files nobody holds, older than the lease.
- A Main this Chronos cannot read (newer or damaged) refuses the open at once
  only when nothing else can be offered. Otherwise Open in workspace lists it
  disabled, with the reason as its tooltip. The refusal's action tooltip is
  now Remove copy.
- The removal plan counts a conflict the same way the sync status does: a
  conflict that a settling replay took past its commit point is not work
  left.
- A healed record is stamped after both the record's time and the index's, so
  the next rename made elsewhere is taken.
- A trash folder holds back the rebuild of a lost record only when it is this
  sequence's deletion: its record names this sequence or cannot be read, or it
  has no record, is within a one-day grace and holds no version of another
  project. What was seen of folders that are gone or have a record again is
  forgotten.
- When a deletion wins, version files pushed into the live folder before the
  deletion arrived are moved beside the deleted record in the trash, never
  deleted.

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

411 lines
24 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.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Settings;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data.Workspaces;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// The desktop's workspace (owner review 2, R8): where it lives, what it remembers, its projects' states as the picker
/// shows them, new, renamed and deleted projects, the removal of a local copy that never loses unsent work, the pruning
/// of old versions, and Settings › Workspace.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceHostTests(TestContext context)
{
static WorkspaceHostTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void TheWorkspaceLivesBesideTheIndexUnlessSettingsSayOtherwise()
{
var local = context.CreateTempDirectory("local");
var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
Assert.Equal(Path.Combine(local, "Chronos", "workspace"), WorkspaceHost.DefaultRoot(installed));
var stick = context.CreateTempDirectory("stick");
File.WriteAllText(Path.Combine(stick, PortableMode.MarkerFileName), "");
var portable = AppEnvironment.From(AppPaths.Resolve(stick, local, []));
Assert.Equal(Path.Combine(stick, "data", "workspace"), WorkspaceHost.DefaultRoot(portable));
var settings = new AppSettings();
var host = new WorkspaceHost(installed, settings, () => { }, () => null, () => null, () => null);
Assert.Equal(WorkspaceHost.DefaultRoot(installed), host.Root);
Assert.True(host.IsEnabled);
Assert.False(host.IsAvailable, "no index yet");
var elsewhere = Path.Combine(context.CreateTempDirectory("fast-disk"), "Chronos workspace");
settings.WorkspaceFolder = elsewhere;
Assert.Equal(elsewhere, host.Root);
Assert.Equal(elsewhere, host.Store.Root, "the store follows the folder");
Assert.FileExists(Path.Combine(elsewhere, WorkspaceStore.ManifestFile));
// A capture (sample data without an engine) edits its library as before.
var capture = AppEnvironment.ForCapture();
try
{
Assert.False(new WorkspaceHost(capture, new AppSettings(), () => { }, () => null, () => null, () => null).IsEnabled);
}
finally
{
capture.DeleteCaptureData();
}
}
[Test]
public void TheWorkspaceSettingsSurviveTheSettingsFile()
{
var sequence = Guid.CreateVersion7();
var project = Guid.CreateVersion7();
var settings = new AppSettings { WorkspaceFolder = @"D:\Fast\Workspace", WorkspaceAutoSync = false, WorkspaceKeptVersions = 50 };
settings.WorkspaceRecent[sequence] = project;
var copy = AppSettings.Parse(settings.ToJson())!;
Assert.Equal((@"D:\Fast\Workspace", false, 50), (copy.WorkspaceFolder, copy.WorkspaceAutoSync, copy.WorkspaceKeptVersions));
Assert.Equal(project, copy.WorkspaceRecent[sequence]);
// A settings file written before the workspace existed gets its defaults: sync on, 20 versions.
var older = AppSettings.Parse("""{ "Theme": "Light" }""")!;
Assert.Equal((null, true, 20), (older.WorkspaceFolder, older.WorkspaceAutoSync, older.WorkspaceKeptVersions));
Assert.Empty(older.WorkspaceRecent);
}
[Test]
public void SettingsWorkspaceRowsStoreEachChoiceAtOnce()
{
var settings = new AppSettings();
var saves = 0;
var opened = 0;
var rows = new WorkspaceSettingsRows(settings, () => saves++, () => @"C:\Users\me\AppData\Local\Chronos\workspace", () => opened++);
Assert.Equal(@"C:\Users\me\AppData\Local\Chronos\workspace", rows.Folder);
rows.OpenCommand.Execute(null);
Assert.Equal(1, opened);
Assert.True(rows.AutoSync);
rows.AutoSync = false;
Assert.Equal((false, 1), (settings.WorkspaceAutoSync, saves));
rows.AutoSync = false;
Assert.Equal(1, saves, "nothing to store");
Assert.SequenceEqual(WorkspaceSettingsRows.KeptPresets, rows.KeptChoices.Select(c => c.Value));
Assert.Equal(20, rows.SelectedKept.Value);
Assert.Equal(Loc.Plural("Settings.Workspace.Versions", 50), rows.KeptChoices.Single(c => c.Value == 50).Label);
rows.SelectedKept = rows.KeptChoices.Single(c => c.Value == 50);
Assert.Equal((50, 2), (settings.WorkspaceKeptVersions, saves));
// A value set by hand is listed with the presets; one below 1 is shown as the 1 the workspace applies.
settings.WorkspaceKeptVersions = 0;
Assert.Equal(1, rows.SelectedKept.Value);
Assert.Contains(1, rows.KeptChoices.Select(c => c.Value));
rows.Reset();
Assert.Equal((true, 20), (settings.WorkspaceAutoSync, settings.WorkspaceKeptVersions));
// The page comes right after Storage.
var pages = Enum.GetValues<SettingsPage>().ToList();
Assert.Equal(pages.IndexOf(SettingsPage.Storage) + 1, pages.IndexOf(SettingsPage.Workspace));
Assert.Equal(Loc.L("Settings.Page.Workspace"), new SettingsPageItem(SettingsPage.Workspace, ["Settings.Workspace.Kept"]).Label);
}
[Test]
public void ProjectNamesAndTheirStatesReadAsThePickerShowsThem()
{
Assert.Equal(Loc.L("Editor.Project.Main"), WorkspaceText.ProjectName("Main", isMain: true));
Assert.Equal("Main", WorkspaceText.ProjectName("Main", isMain: false), "only the sequence's Main is translated");
Assert.Null(ProjectNames.Validate("Vertical social", ["Main"]));
Assert.Equal(Loc.L("Errors.Workspace.NameTaken"), ProjectNames.Validate(" main ", ["Main"]));
Assert.Equal(Loc.L("Errors.Workspace.InvalidName"), ProjectNames.Validate(" ", []));
Assert.Equal(Loc.L("Errors.Workspace.InvalidName"), ProjectNames.Validate(new string('x', 61), []));
var sibling = WorkspaceHost.SiblingName(new string('y', 60));
Assert.True(sibling.Length <= 60 && sibling.EndsWith(")", StringComparison.Ordinal), sibling);
var status = new WorkspaceStatus(WorkspaceState.Ahead, false, 2, 0, false, false, false, null, null, null);
Assert.Equal((Loc.L("Editor.Workspace.State.Ahead"), StatusKind.Queued), (WorkspaceText.State(status), WorkspaceText.Kind(status)));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Ahead", "2"), WorkspaceText.StateToolTip(status));
Assert.Equal((Loc.L("Editor.Workspace.State.Syncing"), StatusKind.Running), (WorkspaceText.State(status, syncing: true), WorkspaceText.Kind(status, syncing: true)));
var offline = status with { State = WorkspaceState.Offline, Offline = true };
Assert.Equal((StatusKind.Offline, Loc.L("Tooltips.Editor.Workspace.State.OfflineAhead", "2")), (WorkspaceText.Kind(offline), WorkspaceText.StateToolTip(offline)));
foreach (var state in Enum.GetValues<WorkspaceState>())
{
var each = status with { State = state };
Assert.NotEqual("Editor.Workspace.State." + state, WorkspaceText.State(each), "every state has its text");
}
var entry = new WorkspaceEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "Main", true, new BundleHome(BundleHome.ArchiveKind, Guid.CreateVersion7()),
"Harbour sunset", HasMedia: true, DateTimeOffset.UtcNow);
var item = new WorkspaceProjectItem(entry, null);
Assert.Equal(Loc.L("Editor.Workspace.State.Reading"), item.StateText);
item.Status = status with { State = WorkspaceState.InSync };
Assert.Equal((Loc.L("Editor.Workspace.State.InSync"), StatusKind.Synced), (item.StateText, item.StateKind));
Assert.Equal(string.Join(Loc.Separator, Loc.L("Editor.Project.Main"), "Harbour sunset", Loc.L("Editor.Workspace.State.InSync")), item.Description);
Assert.Equal(Loc.L("Editor.Workspace.State.MediaRemoved"), new WorkspaceProjectItem(entry with { HasMedia = false }, null).StateText);
}
[Test]
public async Task TheWorkspaceRemembersTheProjectOpenedLast()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var saved = 0;
var settings = new AppSettings();
var host = new WorkspaceHost(bed.Environment, settings, () => saved++, () => bed.Db, () => bed.Archives, () => bed.Engine);
Assert.Null(await host.LastUsedAsync(bed.SequenceId));
var main = await bed.CheckoutAsync(host);
Assert.Equal(main, settings.WorkspaceRecent[bed.SequenceId]);
var vertical = await bed.CheckoutAsync(host, newName: "Vertical social");
Assert.Equal(vertical, (await host.LastUsedAsync(bed.SequenceId))!.ProjectId, "the project checked out last");
host.Remember(bed.SequenceId, main);
Assert.Equal(main, (await host.LastUsedAsync(bed.SequenceId))!.ProjectId);
Assert.True(saved >= 3);
var listed = await host.ProjectsOfAsync(bed.SequenceId);
Assert.Equal(2, listed.Count);
Assert.True(listed.All(p => p.HasMedia));
Assert.SequenceEqual(["Main", "Vertical social"], listed.OrderBy(p => p.Name, StringComparer.Ordinal).Select(p => p.Name), "names as the library has them");
// The home's projects are those of the library: Main, made from the sequence's settings, and the new one.
var home = await host.HomeProjectsAsync(bed.SequenceId);
Assert.Equal((2, "Main"), (home.Count, home[0].Name));
// A project gone from the workspace is forgotten.
settings.WorkspaceRecent[bed.SequenceId] = Guid.CreateVersion7();
Assert.Contains((await host.LastUsedAsync(bed.SequenceId))!.ProjectId, new[] { main, vertical });
}
[Test]
public async Task NewRenamedAndDeletedProjectsReachTheLibrary()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host();
var mainId = await bed.CheckoutAsync(host);
var (source, session) = await bed.OpenAsync(host, mainId);
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.3 } });
await menu.SaveVersionAsync(null);
// New project…: the name is checked as it is typed; the project starts from this one's last version in the library.
menu.NewProjectCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Open is ProjectNameDialogViewModel, "the name dialog");
var naming = (ProjectNameDialogViewModel)ui.Open!;
naming.Name.Text = "main";
Assert.False(naming.SaveCommand.CanExecute(null), "Main is taken");
Assert.Equal(Loc.L("Errors.Workspace.NameTaken"), naming.SaveToolTip);
naming.Name.Text = "Vertical social";
naming.SaveCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Opened.Count == 1, "the new project opens");
var (sequenceId, verticalId) = ui.Opened[0];
Assert.Equal(bed.SequenceId, sequenceId);
var head = await host.HomeOfSequence(bed.SequenceId).HeadAsync(verticalId, bed.Ct);
Assert.Equal(0.3, ProjectSettings.FromJson(head.SettingsJson).Exposure.ExposureOffsetEv);
}
// Rename: in the library and in the workspace's working state.
var verticalId2 = (await host.HomeProjectsAsync(bed.SequenceId)).Single(p => !p.IsMain).Id;
await bed.CheckoutAsync(host, verticalId2);
Assert.Equal("Vertical", await host.RenameAsync(verticalId2, " Vertical "));
Assert.Equal("Vertical", host.Store.Find(verticalId2)!.ReadBundle().Workspace!.Name);
Assert.Contains((await host.HomeProjectsAsync(bed.SequenceId)), p => p.Name == "Vertical");
// Delete project…: confirmed, sent first, then gone from the library's list and from the workspace (kept in the library's trash).
var (verticalSource, verticalSession) = await bed.OpenAsync(host, verticalId2);
var deleting = new RecordingUi { ConfirmAnswer = false };
await using (verticalSession)
using (var menu = new ProjectMenuViewModel(host, verticalSource, verticalSession, deleting))
{
verticalSession.Edit(p => p with { HeroFrame = 1 });
Assert.True(menu.DeleteCommand.CanExecute(null));
menu.DeleteCommand.Execute(null);
Assert.Count(1, deleting.Confirmations);
Assert.Equal(0, deleting.Closed, "kept: nothing happens");
deleting.ConfirmAnswer = true;
menu.DeleteCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => deleting.Toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Deleted", "Vertical")), "the project is deleted");
Assert.Equal(1, deleting.Closed);
}
Assert.DoesNotContain(verticalId2, (await host.HomeProjectsAsync(bed.SequenceId)).Select(p => p.Id));
Assert.Null(host.Store.Find(verticalId2));
var row = await bed.RowAsync();
var trash = Path.Combine(new Chronos.Core.Archiving.ArchivePaths((await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath).Sequence(row.Folder).ProjectsTrashDirectory);
Assert.True(Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(verticalId2.ToString("N"), StringComparison.Ordinal)),
"the deleted project's versions wait in the library's project trash");
}
[Test]
public async Task ALocalCopyGoesOnlyOnceTheLibraryHoldsItsWorkOrTheUserDiscardsIt()
{
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 (source, session) = await bed.OpenAsync(host, mainId);
await using (session)
{
Assert.True(source.Workspace!.IsMain);
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.3 } });
Assert.True(await session.FlushAsync());
}
var plan = await host.PlanRemovalAsync(mainId);
Assert.True(plan is { Modified: true, Unsent: 0, Conflict: false, Offline: false, IsSafe: false });
Assert.True(plan.Files >= 4 + 2, "the proxies, the media index and the working state");
Assert.Greater(plan.Bytes, 0);
var discards = new List<bool>();
var asked = 0;
var dialog = new RemoveCopyDialogViewModel(plan, d =>
{
discards.Add(d);
return Task.CompletedTask;
}, () => Task.CompletedTask, () => ++asked > 1, _ => { });
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while work is not in the library");
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), dialog.RemoveToolTip);
Assert.True(dialog.SendFirstCommand.CanExecute(null) && dialog.DiscardCommand.CanExecute(null));
// Discard changes asks for the typed confirmation first: refused, nothing is removed; confirmed, it is.
dialog.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => asked == 1 && dialog.DiscardCommand.CanExecute(null), "the confirmation is asked");
Assert.Empty(discards, "refused: nothing discarded");
dialog.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => discards.Count == 1, "confirmed: discarded");
Assert.True(discards[0]);
var request = RemoveCopyDialogViewModel.DiscardRequest("Main");
Assert.True(request is { IsDestructive: true, TypedConfirmation: "Main" } && request.TypedPrompt is { Length: > 0 });
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Unsent"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
// Send first: saved and sent, then the library's copy is read back and checked before the local one goes.
await host.SaveVersionAsync(mainId, "Before removal");
await host.SyncAsync(mainId);
Assert.True((await host.PlanRemovalAsync(mainId)).IsSafe);
var folder = host.Store.Find(mainId)!.Folder;
await host.RemoveLocalCopyAsync(mainId, discard: false);
Assert.Null(host.Store.Find(mainId));
Assert.False(Directory.Exists(Path.Combine(folder, WorkspaceProject.MediaFolder)), "the copied photos are gone");
Assert.Equal(0.3, ProjectSettings.FromJson((await bed.RowAsync()).SettingsJson!).Exposure.ExposureOffsetEv, "the work is in the library");
// Discard changes: the unsent versions and the working state are kept aside in the workspace's trash, never erased.
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
var (_, verticalSession) = await bed.OpenAsync(host, vertical);
await using (verticalSession)
{
verticalSession.Edit(p => p with { HeroFrame = 2 });
Assert.True(await verticalSession.FlushAsync());
}
var unsent = (await host.SaveVersionAsync(vertical, "Not sent")).Version!;
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
var aside = Assert.Contains(Directory.EnumerateDirectories(Path.Combine(host.Root, WorkspaceHost.TrashFolder)),
d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal));
Assert.FileExists(Path.Combine(aside, WorkspaceProject.BundleFile));
Assert.True(Directory.EnumerateFiles(Path.Combine(aside, WorkspaceProject.VersionsFolder)).Any(f => f.Contains(unsent.Id.ToString("N"), StringComparison.OrdinalIgnoreCase)
|| f.Contains(unsent.Id.ToString(), StringComparison.OrdinalIgnoreCase)), "the version never sent is kept");
Assert.False(Directory.Exists(Path.Combine(aside, WorkspaceProject.MediaFolder)), "the photos, copies the library can make again, are not");
Assert.Empty(host.Store.List());
}
[Test]
public async Task AConflictASettlingReplayTookPastItsCommitPointIsNoWorkLeftForTheRemoval()
{
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)!;
var basis = project.ReadBundle().Workspace!.Base!;
var conflict = $$"""
"conflict": { "theirsVersionId": "{{basis.VersionId}}", "theirsNumber": {{basis.Number}}, "baseVersionId": "{{Guid.CreateVersion7()}}",
"mine": [], "differences": [], "found": "2026-11-01T10:00:00+00:00" }
""";
// A take of the library's values cut after its base moved (before sync.json said so): the choice is applied.
await File.WriteAllTextAsync(project.SyncPath,
$$"""{ {{conflict}}, "replay": { "ontoBase": "{{basis.VersionId}}", "replaced": [], "replayed": [], "adopted": [], "settles": true } }""");
Assert.NotNull(project.ReadSync().Conflict, "still in sync.json");
Assert.Null(project.OpenConflict());
Assert.Null((await host.StatusAsync(mainId)).Conflict);
var plan = await host.PlanRemovalAsync(mainId);
Assert.True(plan is { Conflict: false, IsSafe: true }, "counted as the status reads it");
// A conflict still waiting for a choice counts.
await File.WriteAllTextAsync(project.SyncPath, $$"""{ {{conflict}} }""");
Assert.NotNull(project.OpenConflict());
Assert.True((await host.PlanRemovalAsync(mainId)) is { Conflict: true, IsSafe: false });
}
[Test]
public async Task ACopyOfAProjectDeletedInTheLibraryReadsGoneAndGoesOnlyWhenDiscarded()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
Assert.Equal(WorkspaceState.InSync, (await host.StatusAsync(vertical)).State);
// Another PC deletes it in the library: never in step, and the copy goes only when its user discards it.
await bed.Archives.Projects.DeleteAsync(vertical, bed.Ct);
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(vertical)).State);
Assert.True((await host.PlanRemovalAsync(vertical)).Gone);
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(vertical, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.DeletedAtHome"), refused.Message);
Assert.NotNull(host.Store.Find(vertical), "nothing was removed");
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
}
[Test]
public async Task ARemovalThatCannotMoveAFilePutsTheCopyBackWholeAndSaysSo()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var vertical = await bed.CheckoutAsync(host, newName: "Vertical");
var project = host.Store.Find(vertical)!;
var bundle = File.ReadAllBytes(project.BundlePath);
var held = Path.Combine(project.Folder, "notes.txt");
File.WriteAllText(held, "mine");
// Another program holds a file of the copy: what was moved aside goes back, the working state with it.
using (new FileStream(held, FileMode.Open, FileAccess.Read, FileShare.None))
await Assert.ThrowsAsync<IOException>(() => host.RemoveLocalCopyAsync(vertical, discard: true));
Assert.SequenceEqual(bundle, File.ReadAllBytes(project.BundlePath), "the working state is back");
Assert.Contains(await host.ListAsync(), e => e.ProjectId == vertical && e.IsReadable);
Assert.True(Directory.Exists(project.MediaDirectory) && Directory.Exists(project.VersionsDirectory), "the copy is whole");
var trash = Path.Combine(host.Root, WorkspaceHost.TrashFolder);
Assert.False(Directory.Exists(trash) && Directory.EnumerateDirectories(trash).Any(d => Path.GetFileName(d).StartsWith(vertical.ToString("N"), StringComparison.Ordinal)),
"nothing is left aside");
// The file let go: removed.
await host.RemoveLocalCopyAsync(vertical, discard: true);
Assert.Null(host.Store.Find(vertical));
}
[Test]
public async Task OlderVersionsArePrunedPastKeptVersionsOnlyOnceTheLibraryHoldsThem()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceKeptVersions = 2 });
var mainId = await bed.CheckoutAsync(host);
var (_, session) = await bed.OpenAsync(host, mainId);
await using (session)
{
for (var i = 1; i <= 5; i++)
{
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = i / 10.0 } });
Assert.True(await session.FlushAsync());
await host.SaveVersionAsync(mainId, $"Step {i}");
}
}
var project = host.Store.Find(mainId)!;
var kept = project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order().ToList();
Assert.SequenceEqual([5, 6], kept, "the base and the one before it");
var history = await host.HistoryAsync(mainId);
Assert.Equal(6, history.Versions.Count, "the library keeps every version");
// An old version restores from the library.
var first = history.Versions.Single(v => v.Number == 2);
var restored = await host.RestoreAsync(mainId, first.Id);
Assert.Approximately(0.1, restored.Exposure.ExposureOffsetEv, 1e-9);
}
}