feat: owner review 2 phase 5a: workspace and projects with a local home (#14)
CI / Build and test (push) Successful in 9m43s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 27s
CI / PostgreSQL 16 integration (push) Failing after 8m41s
CI / PostgreSQL 17 integration (push) Successful in 12m37s
CI / Docker image (push) Successful in 56s
Release / Build, test and publish (push) Successful in 14m59s
Release / Server image (push) Successful in 1m51s

Edit opens a sequence as a project of a workspace folder outside the library. Projects have linear version histories kept as sidecars in .chronos/projects/, Main mirrors the sequence's settings, and sync merges setting by setting. Migration 0009, JobKind.WorkspaceCopy = 20, Settings › Workspace, and 241 new strings in 38 languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #14.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 09:22:08 +01:00
1 parent efa87f68ce
commit 9b24cf74fc
370 files changed
+29237 -287

No files matched your search

@@ -0,0 +1,334 @@
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);
}
}
}
@@ -0,0 +1,365 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
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;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// The ways on that review 2's phase 5a fix round 2 gave the workspace (owner review 2, R8): another workspace folder when
/// the one in use is refused, a copy whose working state cannot be read listed as damaged and removed only after a plan,
/// the half media of a cancelled first copy, the copy's size and the drive's free space before it starts, a conflict of
/// format that offers only Save both, a read-only library named as such, and pruning that keeps a version the library
/// cannot give back.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceFallbackTests(TestContext context)
{
static WorkspaceFallbackTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task AnotherWorkspaceFolderIsUsedAfterItsPlanAndNothingIsMoved()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var saves = 0;
var host = new WorkspaceHost(bed.Environment, settings, () => saves++, () => bed.Db, () => bed.Archives, () => bed.Engine)
{
LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)),
};
var mainId = await bed.CheckoutAsync(host);
var first = host.Root;
var before = saves;
var row = await bed.RowAsync();
var library = (await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath;
// A folder inside a library is refused, and nothing changes.
var inside = Path.Combine(library, "workspace");
Assert.True((await host.PlanFolderAsync(inside)).InsideLibrary);
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.UseFolderAsync(inside));
Assert.True(refused.FolderRefused);
Assert.Equal(Loc.L("Errors.Workspace.InsideLibraryFolder", Path.GetFullPath(inside)), refused.Message);
Assert.Equal(((string?)null, before, first), (settings.WorkspaceFolder, saves, host.Root));
Assert.False(Directory.Exists(inside), "nothing was written there");
// The plan counts what stays and what is found; using the folder names it in the settings and lists its projects.
var other = Path.Combine(bed.Directory, "other workspace");
var plan = await host.PlanFolderAsync(other);
Assert.Equal(new WorkspaceFolderPlan(first, Path.GetFullPath(other), 1, 0, false), plan);
Assert.False(plan.IsSame);
Assert.True((await host.PlanFolderAsync(first + Path.DirectorySeparatorChar)).IsSame);
await host.UseFolderAsync(other);
Assert.Equal((Path.GetFullPath(other), before + 1), (settings.WorkspaceFolder, saves));
Assert.Equal(Path.GetFullPath(other), host.Root);
Assert.Empty(await host.ListAsync());
Assert.FileExists(Path.Combine(first, mainId.ToString("N"), WorkspaceProject.BundleFile));
// Chosen back, the default is named by no setting and its project is listed again.
Assert.Equal(new WorkspaceFolderPlan(Path.GetFullPath(other), first, 0, 1, false), await host.PlanFolderAsync(first));
await host.UseFolderAsync(first);
Assert.Equal(((string?)null, before + 2), (settings.WorkspaceFolder, saves));
Assert.Equal(mainId, (await host.ListAsync()).Single().ProjectId);
}
[Test]
public async Task ChoosingAFolderAsksItsPlanAndClosesTheProjectFirst()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var host = bed.Host(settings);
await bed.CheckoutAsync(host);
var first = host.Root;
var library = (await bed.Db.Archives.GetAsync((await bed.RowAsync()).ArchiveId))!.RootPath;
var failures = new List<string>();
var closes = 0;
var close = true;
Task<bool> CloseProject()
{
closes++;
return Task.FromResult(close);
}
// Nothing picked, or the folder in use: nothing asked.
var dialogs = new ScriptedDialogs { Folder = null };
Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
dialogs.Folder = first;
Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
Assert.Empty(dialogs.Asked);
// Inside a library: refused with why, without asking.
dialogs.Folder = Path.Combine(library, "inside");
Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
Assert.SequenceEqual([Loc.L("Errors.Workspace.InsideLibraryFolder", Path.GetFullPath(dialogs.Folder!))], failures);
Assert.Empty(dialogs.Asked);
// Declined, or the open project kept open: the folder stays.
var other = Path.Combine(bed.Directory, "elsewhere");
dialogs.Folder = other;
dialogs.Answer = false;
Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
Assert.Count(1, dialogs.Asked);
var asked = dialogs.Asked[0];
Assert.Equal(Loc.L("Settings.Workspace.ChangeMessage", Path.GetFullPath(other), first), asked.Message);
Assert.Contains(Loc.L("Settings.Workspace.ProjectsLeft", Formatting.Count(1)), asked.Detail);
Assert.Contains(Loc.L("Settings.Workspace.ProjectsFound", Formatting.Count(0)), asked.Detail);
Assert.True(asked is { IsDestructive: false, ActionText.Length: > 0, ActionToolTip.Length: > 0, SafeToolTip.Length: > 0 });
Assert.Equal(0, closes, "nothing closed before the plan is confirmed");
dialogs.Answer = true;
close = false;
Assert.False(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
Assert.Equal((1, first), (closes, host.Root));
close = true;
Assert.True(await WorkspaceFolderChange.ChooseAsync(host, dialogs, CloseProject, failures.Add));
Assert.Equal((Path.GetFullPath(other), 2), (host.Root, closes));
Assert.Count(1, failures);
}
[Test]
public void SettingsWorkspaceChangesTheFolderOnlyWhereItCan()
{
var settings = new AppSettings();
var changes = 0;
var rows = new WorkspaceSettingsRows(settings, () => { }, () => @"D:\Workspace", () => { }, () =>
{
changes++;
return Task.CompletedTask;
});
Assert.True(rows.CanChange && rows.ChangeCommand.CanExecute(null));
rows.ChangeCommand.Execute(null);
Assert.Equal(1, changes);
var capture = new WorkspaceSettingsRows(settings, () => { }, () => @"D:\Workspace", () => { });
Assert.False(capture.CanChange || capture.ChangeCommand.CanExecute(null));
}
[Test]
public async Task ACopyWhoseWorkingStateCannotBeReadIsListedAsDamagedAndGoesOnlyByDiscard()
{
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 (_, session) = await bed.OpenAsync(host, mainId);
await using (session)
{
session.Edit(p => p with { HeroFrame = 2 });
Assert.True(await session.FlushAsync());
}
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);
var listed = all[0];
Assert.True(listed is { Damaged: true, HasMedia: false });
Assert.Equal(mainId, listed.ProjectId);
Assert.True((await host.FindAsync(mainId))!.Damaged);
Assert.Empty(await host.ProjectsOfAsync(bed.SequenceId), "a copy that cannot say its sequence is not one of it");
var item = new WorkspaceProjectItem(listed, null);
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<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.Damaged"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
await host.RemoveLocalCopyAsync(mainId, discard: true);
Assert.Null(host.Store.Find(mainId));
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<InvalidDataException>(() => 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<WorkspaceException>(() => host.PlanRemovalAsync(mainId));
Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), planned.Message);
var discarded = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: true));
Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), discarded.Message);
var checkedOut = await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, mainId, null));
Assert.Equal(Loc.L("Errors.Workspace.NewerCopy"), checkedOut.Message);
await Assert.ThrowsAsync<WorkspaceException>(() => 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 OpenInWorkspaceShowsTheCopysSizeAndTheFreeSpace()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host();
var facts = await host.CopyFactsAsync(bed.SequenceId);
Assert.Greater(facts.Bytes, 0);
Assert.NotNull(facts.Free);
Assert.False(facts.TooLittleSpace, "the test drive has room for four small proxies");
var dialog = new OpenInWorkspaceDialogViewModel("Synthetic", await host.HomeProjectsAsync(bed.SequenceId), _ => { }, copy: facts);
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free")], dialog.CopyFacts.Select(f => f.Label));
Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value);
Assert.False(dialog.IsShortOfSpace);
var short_ = new OpenInWorkspaceDialogViewModel("Synthetic", [], _ => { }, copy: new WorkspaceCopyFacts(1_000_000, 1_000_000));
Assert.True(short_.IsShortOfSpace);
Assert.Equal(Loc.L("Errors.Workspace.NoRoom"), short_.CopyFacts[1].Reason);
var unknown = new OpenInWorkspaceDialogViewModel("Synthetic", [], _ => { }, copy: new WorkspaceCopyFacts(1_000_000, null));
Assert.Equal((false, Loc.L("Server.Sync.None")), (unknown.IsShortOfSpace, unknown.CopyFacts[1].Value));
Assert.Empty(new OpenInWorkspaceDialogViewModel("Synthetic", [], _ => { }).CopyFacts);
Assert.False(new WorkspaceCopyFacts(1_000, 1_000 + WorkspaceJobs.CopySpaceReserve).TooLittleSpace);
Assert.True(new WorkspaceCopyFacts(1_000, 999 + WorkspaceJobs.CopySpaceReserve).TooLittleSpace);
}
[Test]
public void AConflictOfFormatOffersOnlySaveBothAndSaysWhy()
{
var newer = new ConflictDialogViewModel("Main", "Main (STUDIO-PC)", ["Version 1 here, 2 in the library"], _ => Task.CompletedTask, _ => { },
newerFormat: true);
Assert.False(newer.CanMerge || newer.KeepMineCommand.CanExecute(null) || newer.TakeHomeCommand.CanExecute(null));
Assert.True(newer.SaveBothCommand.CanExecute(null));
Assert.SequenceEqual([Loc.L("Editor.Workspace.Conflict.NewerFormat")], newer.Differences);
Assert.Equal(Loc.L("Editor.Workspace.Conflict.NewerMessage", "Main"), newer.Message);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.NewerFormat"), newer.DifferencesToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.SaveBothNewer", "Main (STUDIO-PC)"), newer.SaveBothToolTip);
var merge = new ConflictDialogViewModel("Main", "Main (STUDIO-PC)", ["Hero frame 2 here, 3 in the library"], _ => Task.CompletedTask, _ => { });
Assert.True(merge.CanMerge && merge.KeepMineCommand.CanExecute(null) && merge.TakeHomeCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.SaveBoth", "Main (STUDIO-PC)"), merge.SaveBothToolTip);
// The format's numbers never reach the lines: one line names the cause.
var lines = WorkspaceText.ConflictLines([new SettingsDifference(ProjectMerge.FormatPath, "1", "2"), new SettingsDifference("hero", "2", "3")], 10);
Assert.SequenceEqual([Loc.L("Editor.Workspace.Conflict.NewerFormat")], lines);
}
[Test]
public void AReadOnlyLibraryIsNamedAsSuchNotAsOffline()
{
var readOnly = new ArchiveOfflineException(@"E:\Library", ArchiveAvailability.ReadOnly);
Assert.Equal(Loc.L("Errors.Workspace.ReadOnlyHome"), WorkspaceText.Failure(new HomeUnavailableException(readOnly.Message, readOnly)));
Assert.Equal(Loc.L("Errors.Workspace.ReadOnlyHome"), WorkspaceText.Failure(readOnly));
var offline = new ArchiveOfflineException(@"E:\Library", ArchiveAvailability.Offline);
Assert.Equal(Loc.L("Errors.Workspace.Offline"), WorkspaceText.Failure(new HomeUnavailableException(offline.Message, offline)));
Assert.Equal(Loc.L("Errors.Workspace.Offline"), WorkspaceText.Failure(new HomeUnavailableException("The project's home cannot be reached from this PC.")));
}
[Test]
public async Task PruningKeepsAVersionTheLibraryCannotGiveBack()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings { WorkspaceKeptVersions = 100 };
var host = bed.Host(settings);
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)!;
Assert.SequenceEqual([1, 2, 3, 4, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
// The library's file of version 2 is damaged: the workspace's copy is the only good one left, so it stays.
var second = project.Versions().Single(v => v.Number == 2);
var row = await bed.RowAsync();
var library = (await bed.Db.Archives.GetAsync(row.ArchiveId))!.RootPath;
var damaged = new ArchivePaths(library).Sequence(row.Folder).VersionPath(mainId, 2, second.Id);
Assert.FileExists(damaged);
await File.WriteAllTextAsync(damaged, "{ damaged", bed.Ct);
settings.WorkspaceKeptVersions = 2;
Assert.Equal(3, await host.PruneAsync(mainId, host.HomeOfSequence(bed.SequenceId)));
Assert.SequenceEqual([2, 5, 6], project.Versions().Where(v => v.StoredAt is not null).Select(v => v.Number).Order());
}
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/>, recording what they were asked.</summary>
private sealed class ScriptedDialogs : IAppDialogs
{
public string? Folder { get; set; }
public bool Answer { get; set; }
public List<ConfirmRequest> 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<string, string, Task<string?>> signIn) => false;
}
}
@@ -0,0 +1,410 @@
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);
}
}
@@ -0,0 +1,377 @@
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 SaveBothOfAProjectDeletedInTheLibrarySaysItIsGoneOnceAndOffersTheCopy()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context);
var here = bed.Host();
var there = bed.Host(name: "other-pc");
var sideId = await bed.CheckoutAsync(here, newName: "Side");
await bed.CheckoutAsync(there, sideId);
var (sourceA, sessionA) = await bed.OpenAsync(there, sideId);
var (sourceB, sessionB) = await bed.OpenAsync(here, sideId);
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));
await b.SyncAsync();
uiB.CloseDialog(Assert.NotNull(uiB.Open as ConflictDialogViewModel));
// Another PC deletes the project in the library while the choice is made here.
await bed.Archives.Projects.DeleteAsync(sideId, bed.Ct);
var before = uiB.Toasts.Count;
await b.ResolveAsync(ConflictChoice.SaveBoth);
Assert.Equal(WorkspaceState.Gone, b.Status!.State);
Assert.Null(b.Status.Conflict, "nothing is left to answer");
Assert.Null(uiB.Open, "the conflict is not asked again");
var said = uiB.Toasts.Skip(before).ToList();
Assert.Count(1, said.Where(t => t.Message == Loc.L("Errors.Workspace.DeletedAtHome")).ToList());
var copy = Assert.Contains(said, t => t.Action is not null);
Assert.Equal(b.Name, copy.Message, "the copy Save both made is offered");
Assert.False(b.SaveVersionCommand.CanExecute(null), "nothing can be sent to it");
Assert.Equal(0.7, sessionB.Project.Exposure.ExposureOffsetEv, "the work stays in the editor");
Assert.Equal(0.7, here.Store.Find(sideId)!.ReadBundle().Project.Exposure.ExposureOffsetEv);
}
}
[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);
// A conflict recorded here asks nothing of a project the library no longer has.
var recorded = new WorkspaceConflict(Guid.NewGuid(), 3, basis.VersionId, [], [], DateTimeOffset.UtcNow);
var stillGone = ProjectMenuViewModel.WithLocal(gone, edited with { State = WorkspaceState.Conflict, Conflict = recorded });
Assert.Equal((WorkspaceState.Gone, (WorkspaceConflict?)null), (stillGone.State, stillGone.Conflict));
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]);
}
}
}
@@ -0,0 +1,98 @@
using System.IO;
using Chronos.Core.Project;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// The editor of a workspace project whose home moved to settings of a newer Chronos (owner review 2, R8): shown read-only,
/// never merged with this Chronos's, the editor usable whatever its undo steps hold.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceNewerFormatTests(TestContext context)
{
private static ProjectSettings Exposure(ProjectSettings p, double ev) => p with { Exposure = p.Exposure with { ExposureOffsetEv = ev } };
[Test]
public async Task AnEditorWithUndoStepsTakesANewerChronossSettingsReadOnly()
{
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);
await using (session)
{
// Edited, saved and kept as a version: every edit is stored, the undo steps stay.
Assert.True(session.Edit(p => Exposure(p, 0.4)));
Assert.True(session.Edit(p => p with { ExcludedFrames = [2] }));
Assert.True(await session.FlushAsync());
Assert.NotNull(await host.CommitAsync(projectId, bed.Ct));
Assert.True(session.History.CanUndo);
// A pull with nothing of this PC's waiting moved the working state onto a newer Chronos's settings.
var folder = host.Store.Find(projectId)!;
var stored = folder.ReadBundle();
folder.WriteBundle(stored with { Project = Exposure(stored.Project, 1.5) with { Version = ProjectSettings.CurrentVersion + 1 } });
await session.ReloadAsync();
Assert.True(session.IsReadOnly);
Assert.True(session.Project.IsNewerFormat);
Assert.Equal(1.5, session.Project.Exposure.ExposureOffsetEv);
Assert.False(session.History.CanUndo, "no step brings this Chronos's values back over the newer ones");
Assert.False(session.Undo());
Assert.False(session.Edit(p => Exposure(p, 0.2)));
Assert.False(session.HasPendingSave);
// Read again (another analysis, another pull): the editor stays as it is.
await session.ReloadAsync();
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<string>();
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());
}
}
}
@@ -0,0 +1,402 @@
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Tests.Editor;
using Chronos.App.Tests.Windows;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Workspaces;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Edit opens this PC's sequences as workspace projects (owner review 2, R8), on the real services without a window:
/// "Open in workspace" asks the first time, the media are copied by a job and the project opens; the library is written
/// only by a version saved; the picker lists the project in its Workspace group with its state; the next open takes the
/// project opened last without asking; a project file of format 1 gives its settings to Main.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
[Category("workspace")]
public sealed class WorkspaceSectionTests(TestContext context)
{
[Test]
public Task OpenInWorkspaceAsksCopiesAndOpensAndThePickerListsTheProject() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-section");
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 services = new AppServices(environment, settings, () => { }, new DeclineDialogs());
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var db = services.Database!;
var libraryBefore = (await db.Sequences.GetAsync(sequenceId))!.SettingsJson;
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.Equal(Loc.L("Editor.Project.Main"), ask.SelectedProject!.Label, "Main, made from the sequence's settings, is offered first");
Assert.True(ask.IsProxies && !ask.CanCopyOriginals, "proxies; the originals come later");
Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar");
ask.OpenCommand.Execute(null);
Assert.Null(section.Dialog);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens once its media are copied");
var editor = section.Editor!;
Assert.True(editor.Session.Source is WorkspaceSequenceSource);
var project = Assert.NotNull(editor.Project);
Assert.Equal(Loc.L("Editor.Project.Main"), project.Name);
await WorkspaceTestBed.UntilAsync(() => project.Status is not null, "its state is read");
Assert.Equal(WorkspaceState.InSync, project.Status!.State);
Assert.Equal(section.OpenProjectId!.Value, settings.WorkspaceRecent[sequenceId]);
Assert.True(File.Exists(Path.Combine(WorkspaceHost.DefaultRoot(environment), section.OpenProjectId.Value.ToString("N"), WorkspaceProject.BundleFile)),
"the project lives in the workspace beside the index");
// Edited in the workspace; the library takes it with the version saved.
editor.Session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.4 } });
Assert.True(await editor.Session.FlushAsync());
Assert.Equal(libraryBefore, (await db.Sequences.GetAsync(sequenceId))!.SettingsJson, "editing never writes the library");
await project.SaveVersionAsync("Warmer");
Assert.Equal(0.4, ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!).Exposure.ExposureOffsetEv);
// The picker: the Workspace group lists the project with its state, above the library's sequences.
section.ChangeSequenceCommand.Execute(null);
await section.Picker.Loading;
await section.Picker.WorkspaceLoadedAsync();
var item = Assert.Contains(section.Picker.WorkspaceItems, i => i.ProjectId == section.OpenProjectId);
Assert.True(section.Picker.HasWorkspaceItems);
Assert.Same(item, section.Picker.SelectedProject);
Assert.Equal(Loc.L("Editor.Workspace.State.InSync"), item.StateText);
Assert.Contains(section.Picker.Items, i => i.Id == sequenceId);
await section.PickProjectAsync(item);
Assert.False(section.IsPicking, "the open project shows again");
Assert.Same(editor, section.Editor);
// Closed, then asked for again: the project opened last opens without a question.
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "it opens again");
Assert.Null(section.Dialog);
Assert.Equal(0.4, section.Editor!.Session.Project.Exposure.ExposureOffsetEv);
// A project file of format 1 gives its settings to Main, as one undo step.
var file = Path.Combine(directory, "Harbour.chronos");
var bundle = new ProjectBundle(new BundleArchive(Guid.CreateVersion7(), "Elsewhere", null), new BundleSequence(sequenceId, "Synthetic", "Harbour", 6),
section.Editor.Session.Project with { Camera = section.Editor.Session.Project.Camera with { OffsetY = 0.3 } }, DateTimeOffset.UtcNow);
bundle.Save(file);
await new ProjectFiles(shell).OpenAsync(file);
Assert.Equal(0.3, section.Editor.Session.Project.Camera.OffsetY);
Assert.True(section.Editor.Session.Undo());
Assert.Equal(0.0, section.Editor.Session.Project.Camera.OffsetY);
Assert.True(await section.Editor.Session.FlushAsync());
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
[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<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
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")));
// Nothing knows its name: the toast names no folder id.
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Removed")), "the removal is said");
Assert.Null(toasts.Single(t => t.Title == Loc.L("Editor.Workspace.Removed")).Message);
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
[Test]
public Task AMainThisChronosCannotReadSaysWhyAtOnceAndADamagedOneOffersItsRemoval() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-unreadable-main");
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 dialogs = new ScriptedDialogs();
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<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
((OpenInWorkspaceDialogViewModel)section.Dialog!).OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "Main opens");
var mainId = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
var folder = Path.Combine(services.Workspace.Root, mainId.ToString("N"));
var bundle = Path.Combine(folder, WorkspaceProject.BundleFile);
// Saved by a newer Chronos: said at once, nothing offered over it, nothing asked.
await WriteWhenFreeAsync(bundle,
$$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Synthetic" }, "workspace": { "projectId": "{{mainId}}", "name": "Main", "isMain": true } }""");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Message == Loc.L("Errors.Workspace.NewerCopy")), "a newer Main is refused");
var newer = toasts.Single(t => t.Message == Loc.L("Errors.Workspace.NewerCopy"));
Assert.True(newer is { Title: var title, IsError: true, ActionCommand: null } && title == Loc.L("Editor.Workspace.OpenFailed"));
Assert.True(section.Dialog is null && section.Editor is null, "nothing asked, nothing opened");
Assert.FileExists(bundle);
shell.KeepSequence(null);
// Damaged: said at once, with Remove local copy; its Discard keeps the files aside, named as the copy is known.
await WriteWhenFreeAsync(bundle, "{ not a project");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Message == Loc.L("Errors.Workspace.Damaged")), "a damaged Main is refused");
var damaged = toasts.Single(t => t.Message == Loc.L("Errors.Workspace.Damaged"));
Assert.Equal((Loc.L("Editor.Workspace.OpenFailed"), true, Loc.L("Editor.Project.RemoveCopy"), Loc.L("Tooltips.Editor.Project.RemoveCopy")),
(damaged.Title, damaged.IsError, damaged.ActionText, damaged.ActionToolTip));
Assert.True(section.Dialog is null && section.Editor is null, "nothing asked, nothing opened");
damaged.ActionCommand!.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is RemoveCopyDialogViewModel, "its removal is offered");
var remove = (RemoveCopyDialogViewModel)section.Dialog!;
Assert.True(remove.Plan.Damaged, "removed as a damaged copy");
Assert.Equal(Loc.L("Editor.RemoveCopy.Title", Loc.L("Editor.Project.Main")), remove.Heading);
remove.DiscardCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => toasts.Any(t => t.Title == Loc.L("Editor.Workspace.Removed")), "the copy goes");
Assert.False(Directory.Exists(folder));
var removed = toasts.Single(t => t.Title == Loc.L("Editor.Workspace.Removed"));
Assert.Equal(Loc.L("Editor.Project.Main"), removed.Message, "named as the index knows it, never by its folder");
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
[Test]
public Task AMainThisChronosCannotReadIsListedDisabledWhileAnotherProjectCanOpen() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-unreadable-main-others");
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 services = new AppServices(environment, settings, () => { }, new ScriptedDialogs());
await services.AttachAsync(await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(environment.DatabasePath)), startEngine: true);
var shell = new ShellViewModel(services);
var toasts = new List<Toast>();
shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
try
{
var sequenceId = await SequenceAsync(services, Path.Combine(directory, "archive"));
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
((OpenInWorkspaceDialogViewModel)section.Dialog!).OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "Main opens");
var mainId = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
var bundle = Path.Combine(services.Workspace.Root, mainId.ToString("N"), WorkspaceProject.BundleFile);
// Damaged: the sequence has another project, so it is asked which; Main is listed, disabled, why in its tooltip.
await WriteWhenFreeAsync(bundle, "{ not a project");
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace offers the other project");
var asked = (OpenInWorkspaceDialogViewModel)section.Dialog!;
var main = asked.Projects.Single(p => p.Project.IsMain);
Assert.True(main is { IsAvailable: false } && main.ToolTip == Loc.L("Tooltips.Editor.Workspace.State.DamagedCopy"), "a damaged Main is listed as it is");
Assert.Equal(vertical, asked.SelectedProject?.Project.Id);
asked.SelectedProject = main;
Assert.Equal(vertical, asked.SelectedProject?.Project.Id, "never chosen");
Assert.True(asked.CanOpen && asked.HasProjects);
asked.CloseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is null, "closed without a choice");
Assert.False(toasts.Any(t => t.Message == Loc.L("Errors.Workspace.Damaged")), "nothing refused");
shell.KeepSequence(null);
// Saved by a newer Chronos: the same, and the other project opens; Main's copy is left as it is.
var newer = $$"""{ "format": "chronos-project", "formatVersion": 9, "sequence": { "title": "Synthetic" }, "workspace": { "projectId": "{{mainId}}", "name": "Main", "isMain": true } }""";
await WriteWhenFreeAsync(bundle, newer);
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace offers the other project");
asked = (OpenInWorkspaceDialogViewModel)section.Dialog!;
main = asked.Projects.Single(p => p.Project.IsMain);
Assert.True(main is { IsAvailable: false } && main.ToolTip == Loc.L("Tooltips.Editor.Workspace.State.NewerCopy"), "a newer Main is listed as it is");
asked.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the other project opens");
Assert.Equal(vertical, section.OpenProjectId);
Assert.False(toasts.Any(t => t.Message == Loc.L("Errors.Workspace.NewerCopy")), "nothing refused");
Assert.Equal(newer, await File.ReadAllTextAsync(bundle));
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// <summary>Writes <paramref name="path"/> once the project's last background read (its state, after the close) lets go of it.</summary>
private static async Task WriteWhenFreeAsync(string path, string text)
{
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(20));
while (true)
{
try
{
await File.WriteAllTextAsync(path, text);
return;
}
catch (IOException) when (DateTime.UtcNow < until)
{
await Task.Delay(50);
}
}
}
/// <summary>An archive with one sequence of six synthetic photos, indexed.</summary>
private async Task<Guid> SequenceAsync(AppServices services, string root)
{
var archives = services.Archives!;
var archive = await archives.CreateAsync(root, "Test");
var sequence = EditorFixture.Sequence(6);
var folder = Path.Combine(root, "Synthetic");
Directory.CreateDirectory(folder);
for (var i = 0; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
return (await services.Database!.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
}
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/> (yes first), recording what they were asked.</summary>
private sealed class ScriptedDialogs : IAppDialogs
{
public string? Folder { get; set; }
public bool Answer { get; set; } = true;
public List<ConfirmRequest> 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<string, string, Task<string?>> signIn) => false;
}
/// <summary>Dialogs that pick nothing and decline every confirmation.</summary>
private sealed class DeclineDialogs : IAppDialogs
{
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request) => false;
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
}
@@ -0,0 +1,240 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Tests.Editor;
using Chronos.App.Workspace;
using Chronos.Core.Archiving;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Metadata;
using Chronos.Core.Model;
using Chronos.Core.Windows.Shell;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// This PC's archive with one sequence of synthetic photos as the projects' home, its job engine (the workspace copy
/// registered), and workspaces of the desktop that edit it (owner review 2, R8). No window: the view models run on the
/// test's thread.
/// </summary>
internal sealed class WorkspaceTestBed : IAsyncDisposable
{
private readonly TestContext _context;
private WorkspaceTestBed(TestContext context, string directory, ChronosDatabase db, ArchiveService archives, JobEngine engine, Guid sequenceId,
AppEnvironment environment)
{
_context = context;
Directory = directory;
Db = db;
Archives = archives;
Engine = engine;
SequenceId = sequenceId;
Environment = environment;
}
static WorkspaceTestBed() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
public string Directory { get; }
public ChronosDatabase Db { get; }
public ArchiveService Archives { get; }
public JobEngine Engine { get; }
public Guid SequenceId { get; }
/// <summary>An installed copy's environment (not a capture): its data folder under the test's own local app data.</summary>
public AppEnvironment Environment { get; }
public CancellationToken Ct => _context.Cancellation;
public static async Task<WorkspaceTestBed> CreateAsync(TestContext context, int frames = 8)
{
var directory = context.CreateTempDirectory("workspace-app");
var root = Path.Combine(directory, "archive");
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(TestTiming.Budget(20)) });
var archive = await archives.CreateAsync(root, "Test");
var sequence = EditorFixture.Sequence(frames);
var folder = Path.Combine(root, "Synthetic");
System.IO.Directory.CreateDirectory(folder);
for (var i = 0; i < sequence.Count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i]);
File.WriteAllBytes(Path.Combine(folder, $"IMG_{i + 1:0000}.JPG"), JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
await archives.Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
var sequenceId = (await db.Sequences.ListLocationsAsync(archive.Id, context.Cancellation)).Single().Id;
var engine = new JobEngine(db, [.. archives.CreateJobHandlers(), .. WorkspaceJobs.CreateHandlers(db, archives)],
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(context.Cancellation);
var app = System.IO.Directory.CreateDirectory(Path.Combine(directory, "app")).FullName;
var local = System.IO.Directory.CreateDirectory(Path.Combine(directory, "local")).FullName;
var environment = AppEnvironment.From(AppPaths.Resolve(app, local, []));
return new WorkspaceTestBed(context, directory, db, archives, engine, sequenceId, environment);
}
/// <summary>A workspace of this PC (in its own folder when <paramref name="name"/> is given: another PC's, for conflicts).</summary>
public WorkspaceHost Host(AppSettings? settings = null, string? name = null)
{
settings ??= new AppSettings();
if (name is not null) settings.WorkspaceFolder = Path.Combine(Directory, name);
return new WorkspaceHost(Environment, settings, () => { }, () => Db, () => Archives, () => Engine) { LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)) };
}
/// <summary>The sequence's row in the index now.</summary>
public async Task<Sequence> RowAsync() => (await Db.Sequences.GetAsync(SequenceId))!;
/// <summary>A photo taken before the others added to the sequence at its home (as an import of earlier photos does): every frame moves one place.</summary>
public async Task InsertEarlierFrameAsync()
{
var row = await RowAsync();
var archive = (await Db.Archives.GetAsync(row.ArchiveId))!;
var synthetic = EditorFixture.Sequence(1);
using var image = synthetic.Render(0);
var metadata = synthetic.Metadata[0] with { CapturedAt = row.FirstCapture!.Value.AddSeconds(-30) };
var bytes = JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 80, App1Segments = [ExifWriter.BuildJpegApp1(metadata)[4..]] });
var staging = Path.Combine(new ArchivePaths(archive.RootPath).StagingDirectory, "uploads");
System.IO.Directory.CreateDirectory(staging);
var path = Path.Combine(staging, Guid.NewGuid().ToString("N") + ".part");
await File.WriteAllBytesAsync(path, bytes, Ct);
await Archives.Ingest.CommitAsync(new IngestRequest(archive.Id, SequenceId, null, null, path, "IMG_0000.JPG", bytes.Length,
Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(bytes)), null, null), Ct);
}
/// <summary>A project of the sequence checked out into <paramref name="host"/>'s workspace and its media copied (Main by default).</summary>
public async Task<Guid> CheckoutAsync(WorkspaceHost host, Guid? projectId = null, string? newName = null)
{
var checkout = await host.CheckoutAsync(SequenceId, projectId, newName, cancellationToken: Ct);
await WaitForJobAsync(checkout.Copy.Id);
return checkout.Project.Id;
}
/// <summary>The project open in an editor session over the workspace (saves 20 ms after each edit).</summary>
public async Task<(WorkspaceSequenceSource Source, EditorSession Session)> OpenAsync(WorkspaceHost host, Guid projectId)
{
var source = new WorkspaceSequenceSource(host.Sync, projectId, Db, DecoderFactory.CreateClient(null), Engine);
var content = await source.LoadAsync(Ct);
return (source, new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)));
}
/// <summary>Waits until the job ends; it must end as <paramref name="expected"/>.</summary>
public async Task<Job> WaitForJobAsync(Guid jobId, JobState expected = JobState.Done)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
while (true)
{
var job = await Db.Jobs.GetAsync(jobId, Ct);
if (job is { State: JobState.Done or JobState.Failed or JobState.Cancelled })
{
Assert.Equal(expected, job.State, job.Error ?? job.LogTail);
return job;
}
if (DateTime.UtcNow > deadline) Assert.Fail($"Job {jobId} still {job?.State} after its time budget");
await Task.Delay(50, Ct);
}
}
/// <summary>Polls <paramref name="condition"/> until it holds, within the time budget.</summary>
public static async Task UntilAsync(Func<bool> condition, string what, double seconds = 60)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(seconds));
while (!condition())
{
if (DateTime.UtcNow > deadline) Assert.Fail($"Not reached in time: {what}");
await Task.Delay(50);
}
}
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Db.DisposeAsync();
}
}
/// <summary>The window a project menu lives in, as the tests see it: dialogs opened, toasts said, projects opened and closed.</summary>
internal sealed class RecordingUi : IWorkspaceUi
{
public List<ArchiveDialogViewModel> Dialogs { get; } = [];
public ArchiveDialogViewModel? Open { get; private set; }
public List<(string Title, string? Message, bool IsError, Action? Action)> Toasts { get; } = [];
public List<ConfirmRequest> Confirmations { get; } = [];
/// <summary>What every confirmation answers.</summary>
public bool ConfirmAnswer { get; set; } = true;
public List<(Guid SequenceId, Guid ProjectId)> Opened { get; } = [];
public int Closed { get; private set; }
public List<Guid> SequencesChanged { get; } = [];
/// <summary>Dialogs waiting for the open one to close (<see cref="ShowDialogWhenFree"/>).</summary>
public Queue<ArchiveDialogViewModel> Waiting { get; } = new();
public ArchiveDialogViewModel? Dialog => Open;
public void ShowDialog(ArchiveDialogViewModel dialog)
{
Open?.Dispose();
Dialogs.Add(dialog);
Open = dialog;
}
public void ShowDialogWhenFree(ArchiveDialogViewModel dialog)
{
if (Open is null) ShowDialog(dialog);
else Waiting.Enqueue(dialog);
}
public void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(Open, dialog)) return;
dialog.Dispose();
Open = null;
while (Waiting.TryDequeue(out var next))
{
if (next.IsClosed) continue;
ShowDialog(next);
break;
}
}
public bool Confirm(ConfirmRequest request)
{
Confirmations.Add(request);
return ConfirmAnswer;
}
public void Notify(string title, string? message = null, string? actionText = null, string? actionToolTip = null, Action? action = null, bool isError = false) =>
Toasts.Add((title, message, isError, action));
public Task OpenProjectAsync(Guid sequenceId, Guid projectId)
{
Opened.Add((sequenceId, projectId));
return Task.CompletedTask;
}
public Task<bool> CloseProjectAsync()
{
Closed++;
return Task.FromResult(true);
}
public Task SequenceChangedAsync(Guid sequenceId)
{
SequencesChanged.Add(sequenceId);
return Task.CompletedTask;
}
}