Files
Chronos/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
T
Alby96andClaude Opus 5.5 fca6c8dfea feat(server): route renders by settings format and adapted size; gate older servers
Owner review 1, phase 4 (P5). A render job now carries the output size its
settings give (RenderSize, proportions win) and the settings format it needs,
resolved on the server before the job is split, so only nodes that read that
format and whose encoder takes the frame claim it, and a job no online node
can read no longer waits for one. Nodes and the server announce the format
they read; settings of a newer Chronos fail saying so.

Encoder size limits are read as long edge x short edge: Media Foundation's
software H.264 encoder, announced as 4096x2304, accepts portrait 2160x3840
(probed on this PC), so EncoderSelector and the provider take either
orientation and cap a portrait frame against the turned limit.

On the desktop, Sync and Send-and-render are disabled with the
NeedsNewerServer tooltip while the server reads an older format than the
working settings need.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 19:48:23 +01:00

372 lines
23 KiB
C#

using System.Globalization;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
using Chronos.App.Tests.Editor;
using Chronos.App.Workspace;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Processing;
using Chronos.Data.Projects;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Workspace;
/// <summary>
/// Workspace projects whose home is a server (owner review 2, R8, phase 5b), as the desktop handles them: the home asked
/// through the signed-in session (offline without it), the copy downloaded from the server, the states the server's
/// changes and deletions lead to, its texts, and renders of what the server holds only. The server here is this PC's
/// archive seen through a home that names a server, so its versions, pushes and merges are the engine's own.
/// </summary>
[Category("workspace")]
public sealed class ServerHomeTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
static ServerHomeTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public async Task TheServerIsTheHomeWhileThisPcIsSignedInToIt()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host();
var named = ServerHome(bed);
Assert.Null(host.HomeOf(named), "no session: the server cannot be asked");
await Assert.ThrowsAsync<HomeUnavailableException>(() => host.HomeProjectsAsync(named, bed.Ct));
Assert.Equal(Loc.L("Errors.Workspace.Offline.Server"), WorkspaceText.Failure(new HomeUnavailableException("down"), server: true));
var server = new FakeServer(bed);
Connect(host, server);
Assert.Same(server, host.HomeOf(named));
Assert.Null(host.HomeOf(named with { Server = "https://elsewhere:8443" }), "another server than the session's");
Assert.Equal("Main", (await host.HomeProjectsAsync(named, bed.Ct)).Single().Name);
// Checked out from the server: its media are downloaded by a copy job that names the server, never this PC's archive.
var checkout = await host.CheckoutAsync(named, null, null, cancellationToken: bed.Ct);
var bundle = host.Store.Find(checkout.Project.Id)!.ReadBundle();
Assert.Equal((BundleHome.ServerKind, Server, bed.SequenceId), (bundle.Workspace!.Home.Kind, bundle.Workspace.Home.Server, bundle.Workspace.Home.SequenceId));
using (var parameters = JsonDocument.Parse(checkout.Copy.ParametersJson!))
{
var root = parameters.RootElement;
Assert.Equal((Server, checkout.Project.Id.ToString(), BundleMedia.Proxies),
(root.GetProperty("server").GetString(), root.GetProperty("projectId").GetString(), root.GetProperty("media").GetString()));
}
Assert.SequenceEqual([bed.SequenceId], checkout.Copy.TargetIds);
// This test bed's engine has no session to download through: the job says to connect.
var failed = await bed.WaitForJobAsync(checkout.Copy.Id, JobState.Failed);
Assert.Equal(Loc.L("Errors.Sync.NotConnected"), failed.Error);
var entry = Assert.NotNull(await host.FindAsync(checkout.Project.Id));
Assert.True(entry.IsServerHome && !entry.HasMedia, "listed as the server's, without media yet");
}
[Test]
public async Task AServerProjectsStateFollowsWhatTheServerSays()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal(WorkspaceState.InSync, status.State);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.InSync.Server"), WorkspaceText.StateToolTip(status, server: true));
// Another PC sends a version: this one reads as Server newer.
var other = bed.Host(name: "other-pc");
var otherId = await bed.CheckoutAsync(other);
Assert.Equal(projectId, otherId);
var session = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, session.Working with { HeroFrame = 2 }, bed.Ct);
await other.SaveVersionAsync(projectId, null, bed.Ct);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Behind, 1), (status.State, status.Behind));
Assert.Equal(Loc.L("Editor.Workspace.State.Behind.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Editor.Workspace.State.Behind"), WorkspaceText.State(status));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Behind.Server", "1"), WorkspaceText.StateToolTip(status, server: true));
// Signed out, or the server out of reach: offline, its work kept.
server.Reachable = false;
Assert.Equal(WorkspaceState.Offline, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
server.Reachable = true;
host.ServerHomes = null;
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Offline, true), (status.State, status.Offline));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Offline.Server"), WorkspaceText.StateToolTip(status, server: true));
Connect(host, server);
// Deleted on the server (its head answers 404 project): not on the server, with its copy kept here as it was.
server.Deleted.Add(projectId);
status = await host.StatusAsync(projectId, cancellationToken: bed.Ct);
Assert.Equal((WorkspaceState.Gone, 0), (status.State, status.Behind));
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), WorkspaceText.State(status, server: true));
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.State.Gone.Server"), WorkspaceText.StateToolTip(status, server: true));
Assert.Equal(StatusKind.Warning, WorkspaceText.Kind(status));
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
// A server that answers 404 for the project itself (deleted with its sequence) is gone too.
server.Deleted.Clear();
server.Missing = true;
Assert.Equal(WorkspaceState.Gone, (await host.StatusAsync(projectId, cancellationToken: bed.Ct)).State);
}
[Test]
public void TheServersProjectChangesReachOnlyTheProjectsItIsHomeOf()
{
var local = context.CreateTempDirectory("local");
var environment = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, []));
var host = new WorkspaceHost(environment, new AppSettings(), () => { }, () => null, () => null, () => null);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
// Missed changes (the event stream came back) are told for every project of that server.
host.OnServerProjectChanged(Server, null);
Assert.Equal(new WorkspaceHomeChange(Server, null, null), told.Single());
// A project this workspace does not hold is not told (and the workspace without an index holds none).
host.OnServerProjectChanged(Server, new ProjectChangedEvent(Guid.CreateVersion7(), Guid.CreateVersion7(), ProjectChanges.Pushed, 2, Guid.CreateVersion7()));
Assert.Count(1, told);
}
[Test]
public async Task TheEditorFollowsTheServerAndRendersOnlyWhatItHolds()
{
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
// Opened signed out; the sign-in made later is the one the source connects with.
FakeRemoteSequenceApi? signedIn = null;
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => signedIn, () => signedIn));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
Assert.True(source.IsServerHome && source.IsRemote && menu.IsServerHome, "analyses and renders run on the server");
Assert.Equal(Loc.L("Errors.Workspace.MainKept"), menu.DeleteToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Project.Rename.Server"), menu.RenameToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Project.RemoveCopy.Server"), menu.RemoveCopyToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.Workspace.UpdateMedia.Server"), menu.UpdateMediaToolTip);
// Not signed in to the server: the project opens, its jobs are refused saying so.
Assert.Empty(await source.ListJobsAsync(bed.Ct));
var refused = await Assert.ThrowsAsync<EditorException>(() => source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct));
Assert.Equal(Loc.L("Editor.Error.SignedOut"), refused.Message);
// Signed in since: the render goes to the server on that sign-in's connection; signed in anew, on the new one's.
var first = new FakeRemoteSequenceApi(await bed.RowAsync(), []);
signedIn = first;
await source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct);
Assert.Equal(1, first.Posted.Count);
var second = new FakeRemoteSequenceApi(await bed.RowAsync(), []);
signedIn = second;
await source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct);
Assert.Equal((1, 1), (first.Posted.Count, second.Posted.Count));
var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(10));
while (!first.Disposed && DateTime.UtcNow < until) await Task.Delay(20, bed.Ct);
Assert.True(first.Disposed, "the old sign-in's connection closes");
signedIn = null;
// In step with the server: the render names the version it holds, whose settings the server renders.
Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");
Assert.Empty(ui.Confirmations);
var basis = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
var (held, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?, string?)>((projectId, basis.VersionId, null), (held.ProjectId, held.ProjectVersionId, held.SettingsJson));
// A change not sent: the render of the working state names the project alone, and is offered to be sent first.
Assert.True(session.SetHero(3));
Assert.True(await session.FlushAsync());
var (unsent, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, Guid?)>((projectId, null), (unsent.ProjectId, unsent.ProjectVersionId));
Assert.NotNull(unsent.SettingsJson);
ui.ConfirmAnswer = false;
Assert.False(await menu.ReadyToRenderAsync(), "kept here: nothing renders");
Assert.Equal(Loc.L("Editor.Workspace.SendFirst.Title"), ui.Confirmations.Single().Heading);
Assert.Equal(WorkspaceState.Modified, menu.Status!.State);
ui.ConfirmAnswer = true;
Assert.True(await menu.ReadyToRenderAsync(), "saved and sent: the server holds it");
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
var sent = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!;
Assert.NotEqual(basis.VersionId, sent.VersionId);
var (version, _) = ProcessingJobs.ReadRender(session.RenderRequests(session.Project.Export)[0].ParametersJson);
Assert.Equal<(Guid?, string?)>((sent.VersionId, null), (version.ProjectVersionId, version.SettingsJson));
Assert.Equal(3, ProjectSettings.FromJson(Assert.NotNull((await bed.RowAsync()).SettingsJson)).HeroFrame, "the server holds the version");
// The server out of reach: the render waits, said in a toast.
server.Reachable = false;
Assert.True(session.SetHero(1));
Assert.True(await session.FlushAsync());
Assert.False(await menu.ReadyToRenderAsync());
Assert.Equal(Loc.L("Editor.Workspace.RenderHeld"), ui.Toasts[^1].Title);
Assert.False(ui.Toasts[^1].IsError, "out of reach is no error");
server.Reachable = true;
await menu.SaveVersionAsync(null);
await menu.SyncAsync();
Assert.Equal(WorkspaceState.InSync, menu.Status!.State);
// Another PC sends a version and the server says so: the chip reads Server newer at once.
var other = bed.Host(name: "other-pc");
await bed.CheckoutAsync(other);
var theirs = await other.Sync.OpenAsync(projectId, bed.Ct);
await other.Sync.SaveAsync(projectId, theirs.Working with { Exposure = theirs.Working.Exposure with { ExposureOffsetEv = 0.7 } }, bed.Ct);
var stored = (await other.SaveVersionAsync(projectId, null, bed.Ct)).Version!;
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, stored.Number, stored.Id));
Assert.Equal(projectId, told.Single().ProjectId);
await WorkspaceTestBed.UntilAsync(() => menu.Status?.State == WorkspaceState.Behind, "the chip follows the server's change");
Assert.Equal(Loc.L("Editor.Workspace.State.Behind.Server"), menu.StateText);
// A change of another server, or of a project this workspace does not hold, is not told.
host.OnServerProjectChanged("https://elsewhere:8443", new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Pushed, 9, Guid.CreateVersion7()));
host.OnServerProjectChanged(Server, new ProjectChangedEvent(Guid.CreateVersion7(), projectId, ProjectChanges.Pushed, 9, Guid.CreateVersion7()));
Assert.Count(1, told);
await menu.SyncAsync();
Assert.Equal(0.7, session.Project.Exposure.ExposureOffsetEv);
// Deleted on the server: the chip says so, the copy and the editor stay.
server.Deleted.Add(projectId);
host.OnServerProjectChanged(Server, new ProjectChangedEvent(bed.SequenceId, projectId, ProjectChanges.Deleted, stored.Number, stored.Id));
await WorkspaceTestBed.UntilAsync(() => menu.Status?.State == WorkspaceState.Gone, "the chip says the project is gone");
Assert.Equal(Loc.L("Editor.Workspace.State.Gone.Server"), menu.StateText);
Assert.False(await menu.ReadyToRenderAsync(), "nothing to render it from");
Assert.True(ui.Toasts[^1].IsError);
Assert.NotNull(host.Store.Find(projectId)?.ReadMedia());
}
}
[Test]
public async Task AServerThatReadsAnOlderFormatIsNotSentSettingsItCannotRead()
{
Assert.Null(ServerJobs.NeedsNewerServer(ProjectSettings.BaseVersion, ProjectSettings.BaseVersion));
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), ServerJobs.NeedsNewerServer(2, ProjectSettings.BaseVersion));
// A server that says no format reads the base one; a session-less home too.
Assert.Equal(ProjectSettings.BaseVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(new ServerInfo("Studio NAS", "1.3.0", 1, [], null, [], new ServerLimits(0, 0))));
Assert.Equal(ProjectSettings.BaseVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(null));
Assert.Equal(ProjectSettings.CurrentVersion, Chronos.App.Server.SyncHost.SettingsFormatOf(
new ServerInfo("Studio NAS", "1.4.0", 1, [], null, [], new ServerLimits(0, 0), SettingsFormat: ProjectSettings.CurrentVersion)));
await using var bed = await WorkspaceTestBed.CreateAsync(context, frames: 4);
var host = bed.Host(new AppSettings { WorkspaceAutoSync = false, WorkspaceVersionOnRender = false });
var server = new FakeServer(bed) { SettingsFormat = ProjectSettings.BaseVersion };
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine,
new WorkspaceServerHome(() => null, () => null));
var content = await source.LoadAsync(bed.Ct);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var ui = new RecordingUi();
await using (session)
using (var menu = new ProjectMenuViewModel(host, source, session, ui))
{
await menu.RefreshAsync();
// A change of the base format goes to the older server as before.
Assert.True(session.SetHero(2));
Assert.Null(menu.PushBlockedReason);
Assert.True(menu.SyncCommand.CanExecute(null));
// A turn needs format 2: Sync is disabled saying why, and a render of it is held.
Assert.True(session.Edit(p => p with { Camera = p.Camera with { Rotate = 90 } }));
Assert.True(await session.FlushAsync());
Assert.Equal(Loc.L("Tooltips.Server.NeedsNewerServer"), menu.PushBlockedReason);
Assert.Equal(menu.PushBlockedReason, menu.SyncToolTip);
Assert.False(menu.SyncCommand.CanExecute(null));
Assert.False(await menu.ReadyToRenderAsync(), "the server cannot read it");
Assert.Equal((Loc.L("Editor.Workspace.RenderHeld"), true), (ui.Toasts[^1].Title, ui.Toasts[^1].IsError));
var before = host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId;
await menu.SyncAsync();
Assert.Equal(before, host.Store.Find(projectId)!.ReadBundle().Workspace!.Base!.VersionId, "nothing was sent");
// A server of this format takes it.
server.SettingsFormat = ProjectSettings.CurrentVersion;
Assert.Null(menu.PushBlockedReason);
Assert.True(menu.SyncCommand.CanExecute(null));
}
}
/// <summary>The home a workspace project of the test sequence names on <see cref="Server"/>.</summary>
private static BundleHome ServerHome(WorkspaceTestBed bed) => new(BundleHome.ServerKind, bed.SequenceId, null, Server);
/// <summary>The host signed in to <paramref name="server"/>, as the desktop's SyncHost gives it.</summary>
private static void Connect(WorkspaceHost host, FakeServer server) =>
host.ServerHomes = home => string.Equals(home.Server, Server, StringComparison.OrdinalIgnoreCase) && home.SequenceId == server.Inner.SequenceId ? server : null;
/// <summary>
/// Main checked out with its media copied from the archive, then named the server's: as a copy downloaded from the
/// server leaves it (that download is the server tests' own).
/// </summary>
private static async Task<Guid> CheckoutAsync(WorkspaceTestBed bed, WorkspaceHost host)
{
var projectId = await bed.CheckoutAsync(host);
var folder = host.Store.Find(projectId)!;
var bundle = folder.ReadBundle();
folder.WriteBundle(bundle with { Workspace = bundle.Workspace! with { Home = ServerHome(bed) } });
return projectId;
}
/// <summary>A server that keeps the archive's projects: reachable or not, with projects deleted there, or none of the sequence's.</summary>
private sealed class FakeServer(WorkspaceTestBed bed) : IProjectHome
{
public ArchiveProjectHome Inner { get; } = new(bed.Db, bed.Archives.Projects, bed.SequenceId);
public bool Reachable { get; set; } = true;
/// <summary>The server answers 404 for the sequence's projects (deleted with their sequence).</summary>
public bool Missing { get; set; }
public HashSet<Guid> Deleted { get; } = [];
/// <summary>The settings format the server reads, as its info says.</summary>
public int SettingsFormat { get; set; } = ProjectSettings.CurrentVersion;
public async Task<HomeSequence> SequenceAsync(CancellationToken cancellationToken)
{
var sequence = await Reach(() => Inner.SequenceAsync(cancellationToken));
return sequence with { Home = ServerHome(bed), Archive = sequence.Archive with { Id = ServerProjectHome.ArchiveIdOf(Server), Path = null } };
}
public Task<IReadOnlyList<SequenceProject>> ListAsync(CancellationToken cancellationToken) => Reach(() => Inner.ListAsync(cancellationToken));
public Task<SequenceProject> CreateAsync(string name, Guid? fromVersionId, string? author, CancellationToken cancellationToken) =>
Reach(() => Inner.CreateAsync(name, fromVersionId, author, cancellationToken));
/// <remarks>A project deleted there has no head (404 <c>project</c>), as the server answers.</remarks>
public Task<ProjectVersion> HeadAsync(Guid projectId, CancellationToken cancellationToken) =>
Deleted.Contains(projectId)
? throw new ProjectException(ProjectError.NotFound, "deleted on the server")
: Reach(() => Inner.HeadAsync(projectId, cancellationToken));
public Task<ProjectVersion?> GetVersionAsync(Guid projectId, Guid versionId, CancellationToken cancellationToken) =>
Reach(() => Inner.GetVersionAsync(projectId, versionId, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> VersionsAfterAsync(Guid projectId, int afterNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => Inner.VersionsAfterAsync(projectId, afterNumber, limit, cancellationToken));
public Task<IReadOnlyList<ProjectVersion>> HistoryAsync(Guid projectId, int? beforeNumber, int limit, CancellationToken cancellationToken) =>
Reach(() => Inner.HistoryAsync(projectId, beforeNumber, limit, cancellationToken));
public Task<PushResult> PushAsync(Guid projectId, ProjectVersion version, CancellationToken cancellationToken) =>
Deleted.Contains(projectId)
? throw new ProjectException(ProjectError.NotFound, "deleted on the server")
: Reach(() => Inner.PushAsync(projectId, version, cancellationToken));
public Task<HomeFrames> FramesAsync(CancellationToken cancellationToken) => Reach(() => Inner.FramesAsync(cancellationToken));
private Task<T> Reach<T>(Func<Task<T>> call)
{
if (!Reachable) throw new HomeUnavailableException("The server cannot be reached.");
if (Missing) throw new ProjectException(ProjectError.NotFound, "not on the server");
return call();
}
}
}