Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceHostTests.cs
T
Alby96andClaude Opus 5.5 a368dc8bf0 fix(projects): phase 5a fix round 2 of the projects engine
The sidecars stay the truth of a sequence's projects in the cases round 1's
checkers found still open, and no version or setting is lost on the way:

- An index-only Main meeting a Main another index made is written back as
  another project, and Main passes to theirs in one transaction through a
  free temporary name, so ux_projects_name and ux_projects_main never fail
  (the SqliteException used to escape ListAsync and leave the index and the
  sidecars disagreeing). A refusal is logged; the next reconcile settles it.
- The reconcile takes Main from the records, in step with the index, when
  another index passed it on: exactly one Main per sequence, names from the
  records where free.
- A project folder with versions and no record, of a project no index row
  names (a creation cut before its record), no longer holds the sequence
  back forever: it is left as it is and indexed once its record arrives.
- A record behind the index (a projects folder put back from an older
  backup) is made whole from the index: its missing versions and the record
  are written again, at every catch-up and before any append, rename or
  delete. Only a record ahead of the index or naming another version is
  refused, with a message that says so.
- An index meeting Main walks the chain down to the version the record names
  as mirrored (a bound, since that record write may lag project.json), so a
  lagging record never makes an External that reverts a newer push. When the
  record names a mirrored ancestor, settings written since merge with the
  unmirrored versions, as for an index that knows its mirror.
- The catch-up merge's External + Merge pair is resumable: an External head
  whose parent is a push no mirror wrote is finished into its Merge version
  next time, by this index or one rebuilt from the sidecars.
- A project deleted at the home has no head there, so a workspace copy of it
  reads Gone, never In sync; Remove local copy without discard says the
  project was deleted in the library.
- DatabaseExceptions are contained per sequence in the archive scan's project
  reconcile and in ProjectService reads.

Tests: SQLite (PostgreSQL-ready) for each scenario, including a cut between
the two catch-up versions, a 40,000-exclusion version through save, push and
rebuild, and the App's Remove local copy of a project deleted at home.

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

357 lines
21 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 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 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);
}
}