Files
Chronos/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs
T
Alby96andClaude Opus 5.5 26bab759fe feat(app): workspace projects whose home is a server, pushed and pulled like this PC's archive
Owner review 2, R8, phase 5b (client part), ported onto the final phase 5a.
A Chronos Server with the "projects" capability is now the home of
workspace projects. A server sequence is edited in the workspace like a
local one, not inside the library, and its versions sync with the server
"like git".

- Data: ServerProjectHome is an IProjectHome over ChronosClient.
  - These are HomeUnavailableException, so the workspace shows Offline: a
    server out of reach, an expired sign-in, a 503 (lease, offline archive,
    projects_unreadable), a 409 folder_in_use, and a server without projects.
  - 404 sequence/project/version and refused names are ProjectException;
    other refusals keep their meaning.
  - A deleted project's head is 404 project, so final 5a's HeadAsync NotFound
    rule reads it as Gone. The original 5b's IsLiveAsync and
    WorkspaceStatus.Gone are dropped. IProjectHome gains rename and delete.
- Data: WorkspaceJobs.CopyFromServer downloads into the workspace, through
  the desktop's session, the proxies of one frames version (or the
  thumbnails standing in for them), with the aliases of the server's
  conversions. It is rebuilt on final 5a's copy handler:
  - the copy:frame:fv:folder checkpoint, EnsureSpace (from the server's proxy
    sizes), WritingMedia, and the cancelled-copy clean-up;
  - the editor's current file is never overwritten;
  - each file is hashed as it arrives and checked on disk, four at a time.
  It never writes this PC's archive. Originals are still refused until 5c.
- Data: SyncAgent passes on the server's projectChanged events, and after a
  lost event stream it reports that changes may have been missed.
- App: SyncHost gives the server home over one session client. The Server
  screen offers Open in workspace, disabled with its reason on older
  servers, whose sequences keep opening with proxies.
- App: Edit opens or checks out server projects with final 5a's refusals:
  unreadable copies, a disabled damaged or newer Main, a refused folder. The
  "sequence left the index" refusal now applies only to projects of this
  PC's archive.
- App: the picker and the chip follow projectChanged (Server newer, Not on
  server). Every state, conflict, delete, remove and failure text uses its
  ".Server" form when one exists (WorkspaceText.ForHome). That includes 5a's
  newer-format conflict, the save conflict, the taken-values toast, Gone and
  version-too-large.
- App: a render of a server project first offers to send what is not on the
  server, then renders the version the server holds. Offline, Gone, Damaged
  and missing media hold the render. Analyses and renders run as server jobs
  (ServerJobs, shared with RemoteSequenceSource).
- Pruning keeps final 5a's rule: a version is pruned only after HoldsAsync
  reads it back.
- Strings in en and it; ARCHITECTURE, DECISIONS and CHANGELOG.

Tests:
- ServerProjectHome error mapping, using a fake handler.
- Against the in-process server:
  - two workspaces on one project: fast-forward, replay and merge, keep mine,
    take server, save both, restore;
  - the copy job verifying, resuming and following new frames;
  - a project deleted on the server (Gone from its head; a push sends
    nothing);
  - an offline server.
- SyncAgent project events.
- App tests for the host, the project menu and renders of a server home.

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

303 lines
19 KiB
C#

using System.Globalization;
using System.Text.Json;
using Chronos.App.Editor;
using Chronos.App.Infrastructure;
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 });
var server = new FakeServer(bed);
Connect(host, server);
var projectId = await CheckoutAsync(bed, host);
var told = new List<WorkspaceHomeChange>();
host.HomeChanged += told.Add;
var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine, new WorkspaceServerHome(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();
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);
// 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());
}
}
/// <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; } = [];
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();
}
}
}