Merge branch 'p5c-p4' into review2-p5c

This commit is contained in:
Alby96 committed 2026-11-04 16:04:09 +01:00
commit 66163542f9
19 files changed
+1595 -44

No files matched your search

@@ -37,7 +37,7 @@ public sealed class DesktopScheduleHostTests(TestContext context)
await fx.StartAsync();
var kept = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.ArchiveScan));
Assert.Equal((scan.Id, "every:2h"), (kept.Id, kept.Recurrence));
Assert.Count(3, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
Assert.Count(4, (await fx.Db.Schedules.ListAsync()).Where(s => s.IsSystem));
// Reset goes back to what the host seeds with.
Assert.Null((await fx.Scheduler!.ResetAsync(scan.Id)).Problem);
@@ -109,9 +109,9 @@ public sealed class DesktopScheduleHostTests(TestContext context)
Assert.Equal(fx.Clock.Now.AddDays(1), backup.NextRun);
// Chronos was closed for two days: the missed copy is made once at start (catch-up, as the housekeeping's run; the
// scan has none and just moves on).
// scan has none and just moves on; the workspace clean-up, with catch-up too, runs once as well).
fx.Clock.Advance(TimeSpan.FromDays(2.5));
Assert.Equal(2, await scheduler.RunDueAsync());
Assert.Equal(3,await scheduler.RunDueAsync());
var job = (await fx.Db.Jobs.ListByScheduleAsync(backup.Id)).Single();
Assert.Equal((JobKind.Backup, JobPriority.Background, JobState.Queued), (job.Kind, job.Priority, job.State));
Assert.Equal(0, await scheduler.RunDueAsync());
@@ -168,6 +168,23 @@ public sealed class DesktopScheduleHostTests(TestContext context)
Assert.Equal(ScheduleRecurrence.DailyAt(new TimeOnly(4, 0)).Next(fx.Clock.Now, TimeZoneInfo.Utc), housekeeping.NextRun);
}
/// <summary>Phase 5c: the workspace's clean-up is a system schedule of its own, seeded once, daily at 04:30 with catch-up.</summary>
[Test]
public async Task TheWorkspaceCleanUpIsSeededOnceAsASystemSchedule()
{
await using var fx = await ScheduleFixture.CreateAsync(context);
await fx.StartAsync();
var cleanup = Assert.NotNull(await fx.Db.Schedules.GetBySystemKeyAsync(DesktopScheduleHost.WorkspaceCleanup));
Assert.Equal(("daily:04:30", true, ScheduleActions.Cleanup, true), (cleanup.Recurrence, cleanup.CatchUp, cleanup.Action, cleanup.Enabled));
var parameters = ScheduleMapping.Parameters(cleanup);
Assert.SequenceEqual([WorkspaceCleanStep.StepName, WorkspaceTrashStep.StepName], parameters.Steps!);
Assert.Equal(0, parameters.OlderThanDays);
Assert.Equal(("Workspace media", "Workspace trash"), (ScheduleText.Step(WorkspaceCleanStep.StepName), ScheduleText.Step(WorkspaceTrashStep.StepName)));
await fx.StartAsync();
Assert.Count(1, (await fx.Db.Schedules.ListAsync()).Where(s => s.SystemKey == DesktopScheduleHost.WorkspaceCleanup));
}
[Test]
public async Task SchedulesWorkOnTheArchiveAtTheFolderWhileItIsOnline()
{
@@ -36,9 +36,9 @@ public sealed class ScheduledTabTests
shell.Jobs.TabIndex = 1;
await app.ExpectAsync<SchedulesView>("jobs-scheduled");
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Workspace clean-up", "Weekly integrity check", "Monthly orphans report"], schedules.Rows.Select(r => r.Name));
var items = app.FindAll<ListBoxItem>().Where(i => i.DataContext is ScheduleRowViewModel && i.IsVisible).ToList();
Assert.Count(5, items);
Assert.Count(6, items);
foreach (var item in items)
{
var row = (ScheduleRowViewModel)item.DataContext;
@@ -30,9 +30,9 @@ public sealed class SchedulesViewModelTests
using var vm = await fx.ViewModelAsync();
Assert.True(vm.IsRunning && vm.IsLoaded && vm.HasRows, "the schedules are listed");
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping"], vm.Rows.Select(r => r.Name));
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0))], vm.Rows.Select(r => r.WhenText));
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up"], vm.Rows.Select(r => r.ActionText));
Assert.SequenceEqual(["Archive scan", "Index backup", "Housekeeping", "Workspace clean-up"], vm.Rows.Select(r => r.Name));
Assert.SequenceEqual(["Every 10 minutes", "Every day", "Daily at " + ScheduleText.Time(new TimeOnly(4, 0)), "Daily at " + ScheduleText.Time(new TimeOnly(4, 30))], vm.Rows.Select(r => r.WhenText));
Assert.SequenceEqual(["Archive scan", "Index backup", "Clean-up", "Clean-up"], vm.Rows.Select(r => r.ActionText));
Assert.True(vm.Rows.All(r => r.IsSystem && r.IsEnabled && r.LastText == "never run" && r.LastKind == StatusKind.Offline), "nothing ran yet");
// The scan's next run is ten minutes away, today.
Assert.Equal(ScheduleText.Moment(fx.Clock.Now.AddMinutes(10)), vm.Rows[0].NextText);
@@ -41,9 +41,9 @@ public sealed class SchedulesViewModelTests
// A schedule the user creates joins the list after the system ones.
var created = await fx.Scheduler!.CreateAsync(new CreateScheduleRequest("Weekly check", ScheduleActions.Verify, new RecurrenceDto("weekly", Time: "02:30", Days: ["mon", "thu"])), null);
Assert.Null(created.Problem);
Assert.Equal("Weekly check", vm.Rows[3].Name);
Assert.Equal("Weekly check", vm.Rows[4].Name);
Assert.Equal(ScheduleText.DayShort(DayOfWeek.Monday) + ", " + ScheduleText.DayShort(DayOfWeek.Thursday) + " at " + ScheduleText.Time(new TimeOnly(2, 30)),
vm.Rows[3].WhenText);
vm.Rows[4].WhenText);
}
[Test]
@@ -141,11 +141,11 @@ public sealed class SchedulesViewModelTests
Assert.False(scan.DeleteCommand.CanExecute(null));
Assert.False(mine.ResetCommand.CanExecute(null));
await vm.DeleteAsync(mine);
Assert.Count(4, vm.Rows);
Assert.Count(5, vm.Rows);
answer = true;
vm.Selected = mine;
await vm.DeleteAsync(mine);
Assert.Count(3, vm.Rows);
Assert.Count(4, vm.Rows);
Assert.Null(vm.Selected);
Assert.Null(await fx.Db.Schedules.GetAsync(mine.Id));
@@ -172,7 +172,7 @@ public sealed class SchedulesViewModelTests
await vm.DeleteAsync(mine);
Assert.SequenceEqual([Loc.L("Jobs.Schedule.Failed")], toasts);
Assert.Count(4, vm.Rows);
Assert.Count(5, vm.Rows);
Assert.Contains(mine, vm.Rows);
Assert.NotNull(await fx.Db.Schedules.GetAsync(mine.Id));
}
@@ -0,0 +1,147 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Jobs;
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));
var closed = 0;
WorkspaceTrashResult? emptied = null;
var dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++);
Assert.Equal(2, dialog.Rows.Count);
Assert.Equal("2", dialog.Confirmation);
Assert.False(dialog.EraseCommand.CanExecute(null), "nothing typed");
dialog.Typed = "3";
Assert.False(dialog.CanErase, "the wrong number");
dialog.Typed = " 2 ";
Assert.True(dialog.CanErase && dialog.EraseCommand.CanExecute(null), "the number of entries");
// An entry added since the plan: refused, nothing erased, the dialog stays open with why.
var late = Directory.CreateDirectory(Path.Combine(folder, Guid.CreateVersion7().ToString("N") + "-" + DateTime.UtcNow.Ticks)).FullName;
File.WriteAllText(Path.Combine(late, "late.txt"), "late");
dialog.EraseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => dialog.ErrorText is { Length: > 0 }, "the emptying is refused");
Assert.Equal(0, closed);
Assert.Equal(3, (await host.PlanTrashAsync()).Items.Count);
// As planned again: erased for good, the dialog closed.
plan = await host.PlanTrashAsync();
dialog = new WorkspaceTrashDialogViewModel(plan, p => host.EmptyTrashAsync(p), r => emptied = r, _ => closed++) { Typed = "3" };
dialog.EraseCommand.Execute(null);
await WorkspaceTestBed.UntilAsync(() => closed == 1, "the dialog closes");
Assert.True(emptied is { Items: 3 }, "three entries erased");
Assert.True((await host.PlanTrashAsync()).IsEmpty, "the trash is empty");
// An empty trash offers nothing to erase.
var none = new WorkspaceTrashDialogViewModel(await host.PlanTrashAsync(), p => host.EmptyTrashAsync(p), null, _ => { }) { Typed = "0" };
Assert.False(none.CanErase);
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled"), none.EraseToolTip);
}
}