Files
Chronos/tests/Chronos.App.Tests/Workspace/WorkspaceLocalRenderTests.cs
T
Alby96andClaude Opus 5.5 9ad8c6f7a9 feat: wire separate homes into the desktop (owner review 5 P3.2)
The desktop now uses the per-home layout from P3.1: each home keeps its
own projects, proxies and originals, and a server is known by its id
whichever address reaches it.

- Settings keep the known servers (id, name, last address, certificate,
  aliases, originals archive). Reset and Import keep them; Export leaves
  them out.
- SyncHost records each server the first time it signs in with an id. It
  names the cache and workspace folders by that id, and re-keys the
  folders a server had under its addresses at sign-in. The re-key waits
  while transfer or workspace jobs are pending.
- Download originals goes to the server's own archive. It is created
  beside this PC's archive at the first download, and a toast says
  where. A sequence that already has a local copy keeps receiving into
  that copy's archive. A server without an id keeps the 1.0 behaviour.
- At start, after the index opens and before any job runs, the folders
  are sorted into their homes. A toast reports the result: sorted,
  pending or failed.
- The workspace host gives each home's store its own sync. Find, List,
  usage, clean-up and the trash plan and empty cover every home. Server
  comparisons go through the identity, so a project stays Online when
  its server is reached by another address.
- The render-node downloads and the server import staging move into the
  server's folder of the cache. The cache trim keeps `servers`, and the
  scheduled scan also scans the originals archives.
- Settings shows the Home folders rows (Workspace) and the Known servers
  table (Server). The diagnostics bundle lists the homes.
- The dead `AppPaths.CreateDirectories` and `ThumbnailsDirectory` are
  removed.

Refs #66

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

220 lines
13 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Globalization;
using System.IO;
using Chronos.App.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.Core.Video;
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.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.SyncOf(projectId), 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.Find(projectId)!.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");
// Save frame: a still job on this PC too, with the frame, its photo and the portable settings.
Assert.True(session.CanSaveFrames, "a workspace project saves frames");
var still = Assert.NotNull(session.StillRequests(Mjpeg, VideoCodec.PngSequence, 1)).Single();
Assert.Equal(JobKind.WorkspaceRender, still.Kind);
var stillJob = Assert.NotNull(WorkspaceJobs.RenderParameters(new Job { Id = Guid.CreateVersion7(), Kind = still.Kind, ParametersJson = still.ParametersJson }));
Assert.Equal((projectId, Server), (stillJob.ProjectId, stillJob.Server));
var (frame, _) = ProcessingJobs.ReadRender(stillJob.RenderJson);
Assert.True(frame.IsStill);
Assert.Equal(1, frame.StillFrame);
Assert.Equal(content.Frames[1].Sha256?.ToLowerInvariant(), frame.StillPhoto);
Assert.Equal(("pngsequence", projectId), (frame.Codec, frame.ProjectId));
Assert.NotNull(frame.SettingsJson, "the portable settings travel with the still");
Assert.Null(frame.ProjectVersionId, "another export than the saved one: no version holds these settings");
// 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.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.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.Find(projectId)!.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.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);
}
}
}