feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings (#18)
CI / Build and test (push) Successful in 9m26s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 8s
Release / Build, test and publish (push) Successful in 14m31s
CI / PostgreSQL 16 integration (push) Successful in 9m53s
CI / PostgreSQL 17 integration (push) Successful in 9m22s
CI / Docker image (push) Successful in 44s
Release / Server image (push) Successful in 1m36s

Originals in the workspace, local render and send home with provenance, the workspace clean-up, size limit and trash, moving the workspace folder, and the complete Settings › Workspace page (owner review 2, R8, phase 5c). One adversarial review round (35 findings, 32 fixed), a copy-cancel race fixed, 184 strings in all 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 #18.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-04 20:03:52 +01:00
1 parent 81c303f484
commit db389a54f2
364 files changed
+17417 -595

No files matched your search

@@ -137,7 +137,7 @@ public sealed class ServerHomeTests(TestContext context)
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
@@ -0,0 +1,137 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
using Chronos.App.Settings;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// The desktop's side of the workspace clean-up (phase 5c, P4): the <c>workspace-clean</c> and <c>workspace-trash</c> steps
/// run by a Cleanup job with no archive, the project open in Edit kept, a removal refused (its renders queued to be sent)
/// while renders wait, and the trash emptied only as planned, once its number of entries is typed.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceCleanupHostTests(TestContext context)
{
static WorkspaceCleanupHostTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
[Test]
public async Task TheScheduledCleanUpRunsWithoutAnArchiveAndKeepsTheProjectOpenInEdit()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings { WorkspaceAutoSync = false, WorkspaceCleanAfterDays = 30 };
var host = bed.Host(settings);
var mainId = await bed.CheckoutAsync(host);
settings.WorkspaceOpened[mainId] = DateTimeOffset.UtcNow - 40 * Day;
var project = host.Store.Find(mainId)!;
Assert.True(Directory.Exists(project.ProxiesDirectory), "copied");
// Open in Edit: kept, with why.
Guid? open = mainId;
host.OpenProject = () => open;
var kept = Assert.NotNull(await host.CleanAsync(cleanAfter: true));
Assert.Empty(kept.Cleaned);
Assert.True(kept.Kept is [{ Reason: WorkspaceKeep.Open }], "kept while open");
Assert.Equal("open in Edit", WorkspaceCleanStep.Reason(WorkspaceKeep.Open));
Assert.True(Directory.Exists(project.ProxiesDirectory), "the media stay");
// The schedule's Cleanup job, with no archive: the media go, the trash is only reported.
open = null;
await using var jobs = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(bed.Directory, "jobs.db")), bed.Ct);
var service = new ArchiveService(jobs, new ArchiveServiceOptions { CleanupSteps = [new WorkspaceCleanStep(() => host), new WorkspaceTrashStep(() => host)] });
await using var engine = new JobEngine(jobs, service.CreateJobHandlers(), new JobEngineOptions { WorkerId = "cleanup", PollInterval = TimeSpan.FromMilliseconds(50) });
await engine.StartAsync(bed.Ct);
var job = await engine.EnqueueAsync(ArchiveJobs.Cleanup(null, [WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], 0), cancellationToken: bed.Ct);
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
while ((await jobs.Jobs.GetAsync(job.Id, bed.Ct))!.State is JobState.Queued or JobState.Running)
{
Assert.True(DateTime.UtcNow < deadline, "the clean-up job did not finish");
await Task.Delay(50, bed.Ct);
}
var done = (await jobs.Jobs.GetAsync(job.Id, bed.Ct))!;
Assert.Equal(JobState.Done, done.State, done.Error ?? done.LogTail);
Assert.Contains("Workspace: projects cleaned: 1", done.LogTail);
Assert.Contains(Loc.L("Jobs.Log.WorkspaceTrash", Formatting.Count(0), Formatting.Bytes(0)), done.LogTail);
Assert.False(Directory.Exists(project.ProxiesDirectory), "the media went");
Assert.True(host.Store.Find(mainId) is not null && File.Exists(project.BundlePath), "the copy and its work stay");
Assert.False((await host.FindAsync(mainId))!.HasMedia, "opening it copies the media again");
}
[Test]
public async Task RendersNotSentBlockTheRemovalAndAreQueuedToBeSent()
{
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)!;
Directory.CreateDirectory(project.ExportsDirectory);
File.WriteAllText(project.ExportFile("clip.mp4"), "rendered");
project.WriteRenders(WorkspaceRenders.Empty.With(new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.mp4", new string('a', 64), 8,
"preset", "h264", 1920, 1080, 25, 4, mainId, null, null, DateTimeOffset.UtcNow, WorkspaceRenderEntry.Pending, null)));
var plan = await host.PlanRemovalAsync(mainId);
Assert.True(plan is { UnsentRenders: 1, IsSafe: false }, "a render waits");
var dialog = new RemoveCopyDialogViewModel(plan, _ => Task.CompletedTask, () => Task.CompletedTask, () => true, _ => { });
Assert.Contains(dialog.Facts, f => f.Label == Loc.L("Editor.RemoveCopy.UnsentRenders") && f.Value == Formatting.Count(1));
Assert.False(dialog.RemoveCommand.CanExecute(null), "not while renders wait");
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.RemoveLocalCopyAsync(mainId, discard: false));
Assert.Equal(Loc.L("Errors.Workspace.UnsentRenders"), refused.Message);
Assert.NotNull(host.Store.Find(mainId), "nothing was removed");
var sends = (await bed.Db.Jobs.ListAsync(null, JobKind.WorkspaceSend, cancellationToken: bed.Ct)).Items;
var send = Assert.Contains(sends, j => j.TargetIds.Contains(bed.SequenceId));
Assert.Equal(mainId, WorkspaceJobs.SendParameters(send)!.ProjectId);
}
[Test]
public async Task TheTrashIsEmptiedAsPlannedOnceItsNumberIsTyped()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host();
Assert.True((await host.PlanTrashAsync()).IsEmpty, "no trash yet");
var folder = WorkspaceTrash.FolderOf(host.Root);
foreach (var name in new[] { "a", "b" })
{
var entry = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
File.WriteAllText(Path.Combine(entry, name + ".txt"), "kept aside " + name);
}
var usage = await host.UsageAsync();
Assert.Equal(2L * "kept aside a".Length, usage.TrashBytes);
var plan = await host.PlanTrashAsync();
Assert.Equal((2, 2L * "kept aside a".Length), (plan.Items.Count, plan.Bytes));
// The Empty… confirmation lists both entries and asks for their number typed.
var request = Assert.NotNull(WorkspaceSettingsRows.TrashRequest(plan));
Assert.Equal("2", request.TypedConfirmation);
Assert.True(request.IsDestructive, "erasing for good is destructive");
// An entry added since the plan: refused, nothing erased.
var late = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
File.WriteAllText(Path.Combine(late, "late.txt"), "late");
var refused = await Assert.ThrowsAsync<WorkspaceException>(() => host.EmptyTrashAsync(plan));
Assert.Equal(Loc.L("Errors.Workspace.TrashChanged"), refused.Message);
Assert.Equal(3, (await host.PlanTrashAsync()).Items.Count);
// As planned again: erased for good.
plan = await host.PlanTrashAsync();
var emptied = await host.EmptyTrashAsync(plan);
Assert.Equal(3, emptied.Items);
Assert.True((await host.PlanTrashAsync()).IsEmpty, "the trash is empty");
// An empty trash offers nothing to erase.
Assert.Null(WorkspaceSettingsRows.TrashRequest(await host.PlanTrashAsync()));
}
}
@@ -266,7 +266,8 @@ public sealed class WorkspaceFallbackTests(TestContext context)
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.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], dialog.CopyFacts.Select(f => f.Label));
Assert.Equal(Formatting.Bytes(facts.OriginalsBytes!.Value), dialog.CopyFacts[2].Value);
Assert.Equal(Formatting.Bytes(facts.Bytes), dialog.CopyFacts[0].Value);
Assert.False(dialog.IsShortOfSpace);
@@ -75,6 +75,102 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Empty(older.WorkspaceRecent);
}
[Test]
public void ThePhase5cWorkspaceSettingsHaveTheirDefaultsAndSurviveTheSettingsFile()
{
var fresh = new AppSettings();
Assert.Equal((100, BundleMedia.Proxies, true, 30, WorkspaceOpenPolicy.LastUsed),
(fresh.WorkspaceSizeLimitGb, fresh.WorkspaceDefaultMedia, fresh.WorkspaceVersionOnRender, fresh.WorkspaceCleanAfterDays, fresh.WorkspaceOpenProject));
Assert.Empty(fresh.WorkspaceOpened);
// A settings file of phase 5b gets them too.
var older = AppSettings.Parse("""{ "Theme": "Light", "WorkspaceKeptVersions": 50 }""")!;
Assert.Equal((100, BundleMedia.Proxies, true, 30, WorkspaceOpenPolicy.LastUsed, 50),
(older.WorkspaceSizeLimitGb, older.WorkspaceDefaultMedia, older.WorkspaceVersionOnRender, older.WorkspaceCleanAfterDays, older.WorkspaceOpenProject,
older.WorkspaceKeptVersions));
Assert.Empty(older.WorkspaceOpened);
var project = Guid.CreateVersion7();
var at = new DateTimeOffset(2026, 11, 4, 9, 30, 0, TimeSpan.FromHours(1));
var settings = new AppSettings
{
WorkspaceSizeLimitGb = 0,
WorkspaceDefaultMedia = BundleMedia.Originals,
WorkspaceVersionOnRender = false,
WorkspaceCleanAfterDays = 0,
WorkspaceOpenProject = WorkspaceOpenPolicy.Ask,
};
settings.WorkspaceOpened[project] = at;
var copy = AppSettings.Parse(settings.ToJson())!;
Assert.Equal((0, BundleMedia.Originals, false, 0, WorkspaceOpenPolicy.Ask),
(copy.WorkspaceSizeLimitGb, copy.WorkspaceDefaultMedia, copy.WorkspaceVersionOnRender, copy.WorkspaceCleanAfterDays, copy.WorkspaceOpenProject));
Assert.Equal(at, copy.WorkspaceOpened[project]);
Assert.Contains("\"Ask\"", settings.ToJson());
}
[Test]
public void WhenEachProjectWasOpenedStaysOnThisPc()
{
var project = Guid.CreateVersion7();
var sequence = Guid.CreateVersion7();
var at = new DateTimeOffset(2026, 11, 4, 9, 30, 0, TimeSpan.Zero);
var mine = new AppSettings { WorkspaceFolder = @"D:\Fast\Workspace", WorkspaceSizeLimitGb = 250, WorkspaceOpenProject = WorkspaceOpenPolicy.Main };
mine.WorkspaceRecent[sequence] = project;
mine.WorkspaceOpened[project] = at;
// Reset puts the preferences back and keeps what this PC knows of its projects.
var reset = mine.ResetKeepingState();
Assert.Equal((AppSettings.DefaultWorkspaceSizeLimitGb, WorkspaceOpenPolicy.LastUsed), (reset.WorkspaceSizeLimitGb, reset.WorkspaceOpenProject));
Assert.Equal((@"D:\Fast\Workspace", project, at), (reset.WorkspaceFolder, reset.WorkspaceRecent[sequence], reset.WorkspaceOpened[project]));
// Export carries the preferences, not this PC's projects.
var exported = AppSettings.Parse(mine.ForExport().ToJson())!;
Assert.Equal((250, WorkspaceOpenPolicy.Main, (string?)null), (exported.WorkspaceSizeLimitGb, exported.WorkspaceOpenProject, exported.WorkspaceFolder));
Assert.Empty(exported.WorkspaceOpened);
Assert.Empty(exported.WorkspaceRecent);
Assert.Equal(at, mine.WorkspaceOpened[project]);
// Import takes another PC's preferences and keeps this PC's projects.
var theirs = new AppSettings { WorkspaceSizeLimitGb = 40, WorkspaceFolder = @"E:\Elsewhere" };
theirs.WorkspaceOpened[Guid.CreateVersion7()] = at.AddDays(-3);
var imported = mine.KeepLocalIn(AppSettings.Parse(theirs.ToJson())!);
Assert.Equal((40, @"D:\Fast\Workspace"), (imported.WorkspaceSizeLimitGb, imported.WorkspaceFolder));
Assert.Equal(at, imported.WorkspaceOpened.Values.Single());
Assert.Count(1, imported.WorkspaceOpened);
}
[Test]
public void OpeningAProjectRecordsWhenAndSavesIt()
{
var local = context.CreateTempDirectory("local");
var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
var settings = new AppSettings();
var saves = 0;
var host = new WorkspaceHost(installed, settings, () => saves++, () => null, () => null, () => null);
var project = Guid.CreateVersion7();
var at = new DateTimeOffset(2026, 11, 4, 10, 0, 0, TimeSpan.Zero);
host.RecordOpened(project, at);
Assert.Equal((at, 1), (settings.WorkspaceOpened[project], saves));
host.RecordOpened(project);
Assert.True(settings.WorkspaceOpened[project] > at, "opened again later");
Assert.Equal(2, saves);
Assert.False(host.IsMoving);
}
[Test]
public void AProjectWithRendersNotSentIsNotSafeToRemoveAndOriginalsNeedTheirRoom()
{
var plan = new WorkspaceRemovalPlan(Guid.CreateVersion7(), "Main", 12, 1_000, 0, false, false, false);
Assert.True(plan.IsSafe);
Assert.False((plan with { UnsentRenders = 1 }).IsSafe);
Assert.True((plan with { LastOriginals = 3 }).IsSafe, "the last originals go to the trash, never deleted");
var facts = new WorkspaceCopyFacts(1_000, 1_000 + WorkspaceJobs.CopySpaceReserve + 500, 2_000);
Assert.False(facts.TooLittleSpaceFor(BundleMedia.Proxies));
Assert.True(facts.TooLittleSpaceFor(BundleMedia.Originals));
Assert.False((facts with { Free = null }).TooLittleSpaceFor(BundleMedia.Originals), "a drive whose room is unknown is tried");
}
[Test]
public void SettingsWorkspaceRowsStoreEachChoiceAtOnce()
{
@@ -0,0 +1,204 @@
using System.Globalization;
using System.IO;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Export;
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.Protocol.Client;
using Chronos.Testing;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: a workspace project that holds its originals renders on this PC (<see cref="JobKind.WorkspaceRender"/>),
/// also when its home is a server, and Settings › Workspace › Version on render saves a changed project as a version first.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceLocalRenderTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
private static readonly ExportSettings Mjpeg = new()
{
Preset = new Auto<string>().WithManual("mjpeg-avi"),
Overrides = new ExportOverrides { Width = 96, Height = 64 },
NameTemplate = "clip-{codec}",
};
static WorkspaceLocalRenderTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheOriginalsRenderOnThisPcEvenForAServerHome()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
// Named the server's, as a copy downloaded from the server leaves it.
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
var home = new BundleHome(BundleHome.ServerKind, bed.SequenceId, null, Server);
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = home } });
// Not signed in to the server: a render from the originals runs here all the same.
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome((IRemoteSequenceApi?)null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(source is { IsServerHome: true, RendersLocally: true, UnsentRenders: 0 });
var requests = session.RenderRequests(Mjpeg);
var request = requests.Single();
Assert.Equal(JobKind.WorkspaceRender, request.Kind);
Assert.SequenceEqual([bed.SequenceId], request.Targets);
var parameters = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = request.Kind, ParametersJson = request.ParametersJson }));
Assert.Equal((projectId, host.Store.Root, Server), (parameters.ProjectId, parameters.WorkspaceRoot, parameters.Server));
var (render, _) = ProcessingJobs.ReadRender(parameters.RenderJson);
Assert.NotNull(render.SettingsJson, "the portable settings travel with the job");
// Queued on this PC's engine and listed beside the server's jobs (the render itself is the Data tests': this bed decodes nothing).
var jobId = await source.SubmitAsync(request, bed.Ct);
var queued = Assert.NotNull(await bed.Db.Jobs.GetAsync(jobId, bed.Ct));
Assert.Equal(JobKind.WorkspaceRender, queued.Kind);
Assert.Contains(await source.ListJobsAsync(bed.Ct), j => j.Id == jobId);
await WorkspaceTestBed.UntilAsync(() => bed.Db.Jobs.GetAsync(jobId).GetAwaiter().GetResult()?.State is JobState.Done or JobState.Failed, "the render ends");
// A render the ledger holds and the home has not taken: listed with the others, not sent.
var output = Path.Combine(folder.ExportsDirectory, "clip-MJPEG.avi");
Directory.CreateDirectory(folder.ExportsDirectory);
await File.WriteAllBytesAsync(output, [1, 2, 3], bed.Ct);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), jobId, "clip-MJPEG.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
projectId, null, null, DateTimeOffset.UtcNow);
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry));
var reread = await source.LoadAsync(bed.Ct);
Assert.Equal(1, source.UnsentRenders);
Assert.Equal((entry.RenderId, output), (reread.Renders[0].Id, reread.Renders[0].OutputPath));
}
}
[Test]
public async Task ProxiesOnlyAsksWithItsPlanAndRemovesNothingUntilConfirmed()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var checkout = await host.CheckoutAsync(bed.SequenceId, null, null, BundleMedia.Originals, cancellationToken: bed.Ct);
await bed.WaitForJobAsync(checkout.Copy.Id);
var projectId = checkout.Project.Id;
var folder = host.Store.Find(projectId)!;
var (source, session) = await bed.OpenAsync(host, projectId);
var ui = new RecordingUi { ConfirmAnswer = false };
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
Assert.True(menu.HoldsOriginals);
Assert.False(menu.CopyOriginalsCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Editor.Project.HasOriginals"), menu.CopyOriginalsToolTip, "says why it is disabled");
Assert.Equal(Loc.L("Tooltips.Editor.Project.ProxiesOnly"), menu.ProxiesOnlyToolTip);
var originals = Directory.GetFiles(folder.OriginalsDirectory).Length;
Assert.Equal(4, originals);
var plan = await host.PlanProxiesOnlyAsync(projectId, bed.Ct);
Assert.Equal(4, plan.Originals + plan.ToTrash);
// Asked first, with the plan: kept on Keep.
var command = (AsyncRelayCommand)menu.ProxiesOnlyCommand;
command.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Confirmations.Count == 1 && !command.IsRunning, "the question");
var asked = ui.Confirmations[0];
Assert.Equal(Loc.L("Editor.ProxiesOnly.Title", menu.Name), asked.Heading);
Assert.True(asked.IsDestructive);
Assert.Contains(Loc.L("Editor.ProxiesOnly.Originals", Formatting.Count(plan.Originals)), asked.Detail!);
if (plan.ToTrash > 0) Assert.Contains(Loc.L("Editor.ProxiesOnly.ToTrash", Formatting.Count(plan.ToTrash)), asked.Detail!);
Assert.Equal(originals, Directory.GetFiles(folder.OriginalsDirectory).Length, "nothing removed on Keep");
Assert.True(menu.HoldsOriginals);
// Confirmed: every original the library holds goes, any other to the trash; the proxies stay.
ui.ConfirmAnswer = true;
command.Execute(null);
await WorkspaceTestBed.UntilAsync(() => ui.Confirmations.Count == 2 && !command.IsRunning, "the removal");
Assert.False(Directory.Exists(folder.OriginalsDirectory));
Assert.Equal(Loc.L("Editor.Workspace.OriginalsRemoved"), ui.Toasts[^1].Title);
Assert.False(menu.HoldsOriginals);
Assert.False(menu.ProxiesOnlyCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Editor.Project.ProxiesAlready"), menu.ProxiesOnlyToolTip, "says why it is disabled");
Assert.True(folder.ReadMedia()!.Frames.All(f => f.File is not null && File.Exists(folder.MediaFile(f.File))));
}
}
[Test]
public async Task SendAgainQueuesTheRendersNotSentAndOnlyThose()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 2);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var projectId = await bed.CheckoutAsync(host);
var folder = host.Store.Find(projectId)!;
Assert.False(await host.SendRendersAsync(projectId, bed.Ct), "nothing waits to be sent");
Assert.False(await host.RenderSendPendingAsync(projectId, bed.SequenceId, bed.Ct));
Directory.CreateDirectory(folder.ExportsDirectory);
await File.WriteAllBytesAsync(Path.Combine(folder.ExportsDirectory, "clip.avi"), [1, 2, 3], bed.Ct);
var entry = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "clip.avi", new string('0', 64), 3, "Custom", "Mjpeg", 96, 64, 25, 0.16,
projectId, null, null, DateTimeOffset.UtcNow);
using (await folder.LockAsync(TimeSpan.FromSeconds(TestTiming.Budget(10)), bed.Ct)) folder.WriteRenders(WorkspaceRenders.Empty.With(entry.AsFailed("cut")));
// A send that failed leaves its render unsent: Send again queues one send of every such render.
Assert.Equal(1, WorkspaceCleaner.UnsentRenders(folder));
Assert.True(await host.SendRendersAsync(projectId, bed.Ct));
var sends = (await bed.Db.Jobs.ListAsync(null, 50, null, bed.Ct)).Items.Where(j => j.Kind == JobKind.WorkspaceSend).ToList();
Assert.Equal(1, sends.Count);
var parameters = Assert.NotNull(WorkspaceJobs.SendParameters(sends[0]));
Assert.Equal((projectId, host.Store.Root), (parameters.ProjectId, parameters.WorkspaceRoot));
Assert.Empty(parameters.RenderIds);
}
[Test]
public async Task VersionOnRenderSavesAChangedProjectFirst()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
Assert.True(settings is { WorkspaceVersionOnRender: true, WorkspaceAutoSync: true }, "on by default");
var host = bed.Host(settings);
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();
var folder = host.Store.Find(projectId)!;
var before = folder.Versions().Count;
// Nothing changed: nothing saved.
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before, folder.Versions().Count);
// Changed: saved as a version noted Render and sent (Sync automatically); the render names it.
Assert.True(session.SetHero(2));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
var saved = folder.Versions()[^1];
Assert.Equal((before + 1, Loc.L("Editor.Workspace.RenderNote")), (folder.Versions().Count, saved.Note));
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
Assert.Equal(Loc.L("Editor.Workspace.SavedForRender", Formatting.Count(folder.ReadBundle().Workspace!.Base!.Number)), ui.Toasts[^1].Title);
var (render, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal(folder.ReadBundle().Workspace!.Base!.VersionId, render.ProjectVersionId);
// Off: the project renders as it is, no version saved.
settings.WorkspaceVersionOnRender = false;
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
Assert.True(await menu.ReadyToRenderAsync());
Assert.Equal(before + 1, folder.Versions().Count);
Assert.Empty(ui.Confirmations);
}
}
}
@@ -0,0 +1,224 @@
using System.Globalization;
using System.IO;
using Chronos.App.Infrastructure;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Jobs;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Settings › Workspace › Move… (phase 5c, P6) as the desktop runs it: the plan and its confirmation, the open project
/// closed first, the workspace held while the move waits or runs, the setting switched only once the move verified
/// everything, a failed move that leaves both as they were, and a move stopped before it ended taken up again.
/// </summary>
[Category("workspace")]
public sealed class WorkspaceMoveTests(TestContext context)
{
static WorkspaceMoveTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheWorkspaceWaitsForTheMoveAndFollowsTheFolderOnlyOnceItEnded()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var mainId = await bed.CheckoutAsync(bed.Host(settings));
await using var moves = await MovesAsync(bed, settings);
var host = moves.Host;
var from = host.Root;
var target = Path.Combine(bed.Directory, "moved workspace");
var plan = await host.PlanMoveAsync(target);
Assert.True(plan.CanMove, plan.Refusal);
Assert.Equal((from, Path.GetFullPath(target), true), (plan.From, plan.To, plan.SameVolume));
var project = Assert.NotNull(plan.Projects.SingleOrDefault());
Assert.Equal(mainId, project.ProjectId);
Assert.True(plan.Files >= project.Files && project.Files > 0 && plan.Bytes > 0);
var failures = new List<string>();
var closes = 0;
var close = true;
Task<bool> CloseProject()
{
closes++;
return Task.FromResult(close);
}
// Declined, or the open project kept open: nothing is queued.
var dialogs = new MoveDialogs { Folder = target, Answer = false };
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
var asked = Assert.NotNull(dialogs.Asked.SingleOrDefault());
Assert.Equal(Loc.L("Settings.Workspace.MovePlan.Message", plan.From, plan.To), asked.Message);
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.Projects", Formatting.Count(1)), asked.Detail);
Assert.Contains(Loc.L("Settings.Workspace.MovePlan.SameVolume"), 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.MoveAsync(host, dialogs, CloseProject, failures.Add));
Assert.False(host.IsMoving);
// Queued: until it ends the workspace opens, copies, syncs and changes folder no more, and is not moved twice.
close = true;
Assert.True(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
Assert.Empty(failures);
Assert.True(host.IsMoving);
var moving = Loc.L("Errors.Workspace.Moving");
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.ProjectsOfAsync(bed.SequenceId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.SyncAsync(mainId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.QueueCopyAsync(mainId))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.CheckoutAsync(bed.SequenceId, mainId, null))).Message);
Assert.Equal(moving, (await Assert.ThrowsAsync<WorkspaceException>(() => host.UseFolderAsync(Path.Combine(bed.Directory, "elsewhere")))).Message);
Assert.False(await WorkspaceFolderChange.MoveAsync(host, dialogs, CloseProject, failures.Add));
Assert.SequenceEqual([moving], failures);
Assert.Equal(((string?)null, 0), (settings.WorkspaceFolder, moves.Saves), "the setting waits for the move");
await moves.Engine.StartAsync(context.Cancellation);
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
await moves.WaitAsync(job.Id, JobState.Done);
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
Assert.Equal((Path.GetFullPath(target), 1), (settings.WorkspaceFolder, moves.Saves));
Assert.Equal(Path.GetFullPath(target), host.Root);
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
Assert.Equal(mainId, (await host.ListAsync()).Single().ProjectId);
Assert.False(Directory.Exists(Path.Combine(from, mainId.ToString("N"))), "the project left the folder");
}
[Test]
public async Task AMoveThatFailsLeavesTheSettingAndTheWorkspaceWhereTheyWere()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var mainId = await bed.CheckoutAsync(bed.Host(settings));
await using var moves = await MovesAsync(bed, settings);
var host = moves.Host;
var from = host.Root;
var target = Path.Combine(bed.Directory, "target");
// A workspace job waiting refuses the plan.
var copy = await moves.Engine.EnqueueAsync(JobKind.WorkspaceCopy, [bed.SequenceId], "copy", null, cancellationToken: context.Cancellation);
Assert.Equal(Loc.L("Errors.Workspace.JobsRunning"), (await host.PlanMoveAsync(target)).Refusal);
await moves.Engine.CancelAsync(copy.Id, context.Cancellation);
var plan = await host.PlanMoveAsync(target);
await host.QueueMoveAsync(plan);
// Meanwhile the target became a workspace of its own: the job refuses it.
_ = new WorkspaceStore(target);
await moves.Engine.StartAsync(context.Cancellation);
var job = Assert.NotNull((await moves.Db.Jobs.ListAsync(null, JobKind.WorkspaceMove, 5, cancellationToken: context.Cancellation)).Items.SingleOrDefault());
var failed = await moves.WaitAsync(job.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Workspace.MoveTargetNotEmpty", Path.GetFullPath(target)), failed.Error);
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
Assert.Equal(((string?)null, 0, from), (settings.WorkspaceFolder, moves.Saves, host.Root));
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
Assert.Empty(new WorkspaceStore(target).List());
}
[Test]
public async Task AMoveStoppedBeforeItEndedIsOfferedAgainAndGoesOn()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var settings = new AppSettings();
var mainId = await bed.CheckoutAsync(bed.Host(settings));
await using var moves = await MovesAsync(bed, settings);
var host = moves.Host;
var from = host.Root;
var target = Path.Combine(bed.Directory, "target");
// The program closed as the move began: its journal is in the folder, and no job waits for it.
var plan = await host.PlanMoveAsync(target);
using (var closed = new CancellationTokenSource())
{
await closed.CancelAsync();
await Assert.ThrowsAsync<OperationCanceledException>(() => new WorkspaceMover(from, target).MoveAsync(plan.Fingerprint, cancellationToken: closed.Token));
}
Assert.True(host.IsMoving, "a journal holds the workspace");
Assert.Equal(Loc.L("Errors.Workspace.Moving"), (await Assert.ThrowsAsync<WorkspaceException>(() => host.FindAsync(mainId))).Message);
var journal = Assert.NotNull(await host.UnfinishedMoveAsync());
Assert.Equal((Path.GetFullPath(target), WorkspaceMoveStage.Moving), (journal.To, journal.Stage));
var job = await host.ResumeMoveAsync(journal);
Assert.Null(await host.UnfinishedMoveAsync());
await moves.Engine.StartAsync(context.Cancellation);
var done = await moves.WaitAsync(job.Id, JobState.Done);
Assert.Contains(Loc.L("Archive.Log.WorkspaceMoveResumed", Path.Combine(from, WorkspaceMover.JournalFile)), done.LogTail);
await WorkspaceTestBed.UntilAsync(() => !host.IsMoving, "the workspace is let go");
Assert.Equal(Path.GetFullPath(target), settings.WorkspaceFolder);
Assert.Equal(mainId, Assert.NotNull(await host.FindAsync(mainId)).ProjectId);
Assert.Null(await host.UnfinishedMoveAsync());
}
/// <summary>
/// A workspace over the bed's folder whose move jobs run on an engine of their own (over an index of their own, so the
/// bed's engine never takes them), which tells the workspace once a move ended; the engine is started by the test.
/// </summary>
private async Task<Moves> MovesAsync(WorkspaceTestBed bed, AppSettings settings)
{
var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("moves"), "index.db")), context.Cancellation);
var moves = new Moves(db);
var options = new WorkspaceJobOptions(WorkspaceJobOptions.For(bed.Archives).Processing, () => false, (f, t) => moves.Host.MovedAsync(f, t));
moves.Engine = new JobEngine(db, WorkspaceJobs.CreateHandlers(db, bed.Archives, null, options),
new JobEngineOptions { Workers = 1, WorkerId = "moves", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) });
moves.Host = new WorkspaceHost(bed.Environment, settings, () => moves.Saves++, () => db, () => bed.Archives, () => moves.Engine)
{
LockWait = TimeSpan.FromSeconds(TestTiming.Budget(10)),
};
return moves;
}
private sealed class Moves(ChronosDatabase db) : IAsyncDisposable
{
public ChronosDatabase Db { get; } = db;
public JobEngine Engine { get; set; } = null!;
public WorkspaceHost Host { get; set; } = null!;
public int Saves { get; set; }
public async Task<Job> WaitAsync(Guid jobId, JobState expected)
{
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(60));
while (true)
{
var job = await Db.Jobs.GetAsync(jobId);
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);
}
}
public async ValueTask DisposeAsync()
{
await Engine.DisposeAsync();
await Db.DisposeAsync();
}
}
/// <summary>Dialogs that pick <see cref="Folder"/> and answer every confirmation with <see cref="Answer"/>, recording what they were asked.</summary>
private sealed class MoveDialogs : 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,188 @@
using System.IO;
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.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Testing;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Phase 5c in Edit: "Open in workspace" offers the originals (Settings › Workspace › Media first, the proxies when the
/// drive has no room), and Settings › Workspace › Open project picks the project a sequence with several opens.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
[Category("workspace")]
public sealed class WorkspaceOpenPolicyTests(TestContext context)
{
private static readonly SequenceProject Main = new() { Id = Guid.CreateVersion7(), SequenceId = Guid.CreateVersion7(), Name = ProjectService.MainName, IsMain = true };
[Test]
public void TheOpenDialogStartsWithTheMediaOfTheSettingsWhenTheyFit()
{
UiLanguage.Apply("en");
var room = new WorkspaceCopyFacts(10_000_000, 100_000_000_000, 4_000_000_000);
using var proxies = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room);
Assert.True(proxies is { IsProxies: true, IsOriginals: false, CanCopyOriginals: true });
Assert.Equal(BundleMedia.Proxies, proxies.Media);
Assert.Contains(proxies.CopyFacts, f => f.Label == Loc.L("Editor.OpenWorkspace.Originals"));
using var originals = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: room, defaultMedia: BundleMedia.Originals);
Assert.True(originals is { IsOriginals: true, IsProxies: false, IsShortOfSpace: false });
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady"), originals.OriginalsToolTip);
originals.OpenCommand.Execute(null);
Assert.Equal(new OpenChoice(Main.Id, null, BundleMedia.Originals), originals.Choice.Result);
// The drive has room for the proxies, not the originals: they are offered disabled, why in the tooltip.
var tight = new WorkspaceCopyFacts(10_000_000, WorkspaceJobs.CopySpaceReserve + 20_000_000, 4_000_000_000);
using var refused = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, copy: tight, defaultMedia: BundleMedia.Originals);
Assert.True(refused is { IsProxies: true, CanCopyOriginals: false, IsShortOfSpace: false });
refused.IsOriginals = true;
Assert.False(refused.IsOriginals, "never chosen without room");
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.NoRoomOriginals"), refused.OriginalsToolTip);
refused.OpenCommand.Execute(null);
Assert.Equal(BundleMedia.Proxies, refused.Choice.Result!.Media);
// Not measured (a server out of reach): offered, the copy measures again before it writes.
using var unmeasured = new OpenInWorkspaceDialogViewModel("Harbour", [Main], _ => { }, server: true);
Assert.True(unmeasured.CanCopyOriginals);
Assert.Equal(Loc.L("Tooltips.Editor.OpenWorkspace.OriginalsReady.Server"), unmeasured.OriginalsToolTip);
unmeasured.IsOriginals = true;
Assert.Equal(BundleMedia.Originals, unmeasured.Media);
}
[Test]
public Task TheOriginalsAreCopiedAndTheOpenProjectFollowsTheSettings() => ScreenHost.RunAsync(async () =>
{
var directory = context.CreateTempDirectory("workspace-open-policy");
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,
WorkspaceDefaultMedia = BundleMedia.Originals,
};
var services = new AppServices(environment, settings, () => { }, new NoDialogs());
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 section = shell.Sequence;
// The originals, as the settings say: copied beside the proxies, and the project's menu offers Proxies only.
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenInWorkspaceDialogViewModel, "Open in workspace asks the first time");
var ask = (OpenInWorkspaceDialogViewModel)section.Dialog!;
Assert.True(ask.IsOriginals, "the settings' media first");
ask.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens once its media are copied");
var mainId = section.OpenProjectId!.Value;
var menu = Assert.NotNull(section.Editor!.Project);
Assert.True(menu.HoldsOriginals);
var media = services.Workspace.Store.Find(mainId)!.ReadMedia()!;
Assert.True(media.HoldsOriginals && media.Frames.All(f => f.HasOriginal), "every frame has its original");
Assert.True(settings.WorkspaceOpened.ContainsKey(mainId), "the open is recorded for the clean-up");
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
// A second project here, opened last.
var vertical = (await services.Archives!.Projects.CreateAsync(sequenceId, "Vertical", cancellationToken: context.Cancellation)).Id;
var checkout = await services.Workspace.CheckoutAsync(sequenceId, vertical, null);
await WorkspaceTestBed.UntilAsync(() => services.Database!.Jobs.GetAsync(checkout.Copy.Id).GetAwaiter().GetResult()?.State == JobState.Done, "its media are copied");
services.Workspace.Remember(sequenceId, vertical);
// Last used: Vertical.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.LastUsed;
Assert.Equal(vertical, await OpenAsync(shell, sequenceId));
// Main, whichever opened last.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Main;
Assert.Equal(mainId, await OpenAsync(shell, sequenceId));
// Ask: the projects here are listed, the one opened last first; closing it opens nothing.
settings.WorkspaceOpenProject = WorkspaceOpenPolicy.Ask;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks");
var which = (OpenProjectDialogViewModel)section.Dialog!;
Assert.Equal(2, which.Projects.Count);
Assert.Equal(mainId, which.SelectedProject!.Entry.ProjectId);
which.CloseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is null, "closed without a choice");
Assert.Null(section.Editor);
shell.KeepSequence(null);
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Dialog is OpenProjectDialogViewModel, "Open which project? asks again");
which = (OpenProjectDialogViewModel)section.Dialog!;
which.SelectedProject = which.Projects.Single(p => p.Entry.ProjectId == vertical);
which.OpenCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project chosen opens");
Assert.Equal(vertical, section.OpenProjectId);
}
finally
{
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
}
});
/// <summary>Opens the sequence in Edit as the settings say and returns the project that opened, closed again.</summary>
private static async Task<Guid> OpenAsync(ShellViewModel shell, Guid sequenceId)
{
var section = shell.Sequence;
shell.OpenSequence(sequenceId);
await WorkspaceTestBed.UntilAsync(() => section.Editor is not null, "the project opens");
Assert.Null(section.Dialog);
var opened = section.OpenProjectId!.Value;
Assert.True(await section.ConfirmCloseAsync());
await section.CloseAsync();
shell.KeepSequence(null);
return opened;
}
/// <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 nothing and decline every confirmation.</summary>
private sealed class NoDialogs : 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;
}
}
@@ -53,7 +53,7 @@ public sealed class WorkspaceSectionTests(TestContext context)
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(ask.IsProxies && ask.CanCopyOriginals, "the proxies first, the originals offered (Settings › Workspace › Media)");
Assert.True(section.ShowsPicker && !section.IsLoading, "the picker shows behind the dialog, not the progress bar");
ask.OpenCommand.Execute(null);
Assert.Null(section.Dialog);
@@ -143,7 +143,8 @@ public sealed class WorkspaceSectionTests(TestContext context)
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");
Assert.SequenceEqual([Loc.L("Editor.OpenWorkspace.Size"), Loc.L("Editor.OpenWorkspace.Free"), Loc.L("Editor.OpenWorkspace.Originals")], 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"));