Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceCleanupHostTests.cs
T
Alby96andClaude Opus 5.5 db389a54f2
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
feat: owner review 2 phase 5c: originals, local render, clean-up and the workspace settings (#18)
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>
2026-11-04 20:03:52 +01:00

138 lines
7.7 KiB
C#

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()));
}
}