Files
Chronos/tests/Chronos.App.Tests/Editor/RemoteSequenceSourceTests.cs
T
Alby96 03d32f18d3 feat(projects): workspace projects with linear versions, the local archive as their home
Owner review 2, phase 5a (R8): editing moves out of the library into a workspace on a fast disk, and a
sequence gets several projects, each with a linear version history pushed and pulled like git.

- Core: ProjectSettings keeps members a newer Chronos wrote (Extra) and reads a newer settings format
  read-only; ProjectContent is the portable form of a version (every frame position parked by photo,
  canonical text, SHA-256 content hash); ProjectBundle format 2 adds the workspace section, and a file
  without it is still written as format 1. JobKind.WorkspaceCopy = 20 (19 kept for Convert).
- Data: migration 0009 (projects, project_versions, the render's project columns); ProjectService on
  ArchiveService.Projects keeps projects as sidecars first (.chronos/projects/<id>/), then the index,
  under the sequence lease: create, rename, delete into the projects' trash, history, push with
  fast-forward, idempotent repeat, divergence and hash checks. Main is made from the sequence's settings
  and mirrored both ways, so every older code path keeps working; outside writes become "external"
  versions, a mirror a crash cut short is completed or merged. Full scans and rebuilds take the projects
  back from their sidecars.
- ProjectMerge moves from the App to Data/Projects, merges pending frames photo by photo and replays
  unpushed commits on a moved head.
- Workspaces: WorkspaceStore, WorkspaceSync (checkout, save, commit, push, pull with replay and merge,
  conflicts settled by keep mine / take server / save both, restore, status) and the WorkspaceCopy job
  (proxies copied hash-verified and resumable; originals refused until phase 5c).
- Renders of a project version place its positions on the frames and record the project and version.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
(cherry picked from commit c4c1802884e403db8759ed0501f770a67a047f20)
2026-10-27 22:51:32 +01:00

645 lines
32 KiB
C#

using Chronos.Data.Projects;
using System.IO;
using System.Net.Http;
using Chronos.App.Editor;
using Chronos.Core.Codecs.Jpeg;
using Chronos.Core.Diagnostics.Synthetic;
using Chronos.Core.Imaging;
using Chronos.Core.Imaging.Decoders;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Data.Processing;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
namespace Chronos.App.Tests.Editor;
/// <summary>
/// A server sequence in the editor (BRIEF §14.5): proxies from the cache, the project from the server with its
/// version, saves that merge a change made meanwhile on the server, and analyses and renders posted as server jobs.
/// </summary>
public sealed class RemoteSequenceSourceTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
[Test]
public async Task TheProjectComesFromTheServerAndFramesFromTheProxies()
{
var (source, api, _) = Open(frames: 6, cached: 5);
await using (source)
{
api.SettingsJson = new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = 0.4 } }.ToJson();
var content = await source.LoadAsync(context.Cancellation);
Assert.True(source.IsRemote);
Assert.Equal(6, content.Count);
Assert.Equal(0.4, content.Project.Exposure.ExposureOffsetEv);
Assert.Equal(3, content.Sequence.SettingsVersion);
Assert.Null(content.ExportsFolder, "renders of a server sequence are not on this PC");
Assert.Equal(string.Empty, content.Renders.Single().OutputPath);
Assert.Empty(content.SavedCopies);
Assert.Null(content.Deep, "never analysed on the server");
using (var frame = await source.DecodeAsync(2, 32, DecodePurpose.Thumbnail, context.Cancellation))
{
Assert.NotNull(frame);
Assert.LessOrEqual(Math.Max(frame!.Width, frame.Height), 32);
}
Assert.Null(await source.DecodeAsync(5, 32, DecodePurpose.Render, context.Cancellation), "a frame without a cached proxy");
Assert.Null(await source.DecodeAsync(9, 32, DecodePurpose.Render, context.Cancellation));
}
}
[Test]
public async Task TheServersAnalysisIsUsedWhenItDescribesTheseFrames()
{
var sunset = EditorFixture.Sequence(8);
var (source, api, _) = Open(sunset);
await using (source)
{
api.Report = EditorFixture.Content(sunset).Deep!.ToJson();
Assert.NotNull((await source.LoadAsync(context.Cancellation)).Deep);
api.Report = EditorFixture.Content(EditorFixture.Sequence(9)).Deep!.ToJson();
Assert.Null((await source.LoadAsync(context.Cancellation)).Deep, "a report of other frames is not shown");
}
}
[Test]
public async Task SavesSendTheVersionTheyWereMadeFrom()
{
var (source, api, _) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var first = content.Project with { Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.5 } };
var stored = await source.SaveProjectAsync(first, content.Project, context.Cancellation);
Assert.True(ProjectMerge.SameValues(first, stored));
var second = stored with { Exposure = stored.Exposure with { ExposureOffsetEv = 0.7 } };
await source.SaveProjectAsync(second, stored, context.Cancellation);
Assert.SequenceEqual([3, 4], api.Edits.Select(e => e.Request.ExpectedSettingsVersion ?? -1));
Assert.True(api.Edits.All(e => e.Accepted));
Assert.Equal(5, api.SettingsVersion);
Assert.Equal(0.7, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
Assert.Null(api.Edits[0].Request.Title, "only the settings travel");
Assert.Null(api.Edits[0].Request.Tags);
// Nothing changed, nothing sent.
Assert.True(ProjectMerge.SameValues(second, await source.SaveProjectAsync(second, second, context.Cancellation)));
Assert.Count(2, api.Edits);
}
}
[Test]
public async Task AChangeMadeOnTheServerMeanwhileIsMergedNotOverwritten()
{
var (source, api, _) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
api.EditsBefore.Enqueue(json =>
{
var theirs = ProjectSettings.FromJson(json ?? "{}");
return (theirs with { Camera = theirs.Camera with { OffsetY = -0.2 } }).ToJson();
});
var mine = content.Project with { Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.5 } };
var merged = await source.SaveProjectAsync(mine, content.Project, context.Cancellation);
Assert.Equal(0.5, merged.Exposure.ExposureOffsetEv);
Assert.Equal(-0.2, merged.Camera.OffsetY, "the server's change is kept");
Assert.SequenceEqual([false, true], api.Edits.Select(e => e.Accepted), "the 409 is followed by a merged edit");
Assert.Equal(4, api.Edits[1].Request.ExpectedSettingsVersion);
var stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal(0.5, stored.Exposure.ExposureOffsetEv);
Assert.Equal(-0.2, stored.Camera.OffsetY);
}
}
[Test]
public async Task ASettingBothChangedWaitsForTheUsersChoice()
{
var (source, api, _) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
api.EditsBefore.Enqueue(json =>
{
var theirs = ProjectSettings.FromJson(json ?? "{}");
return (theirs with { Exposure = theirs.Exposure with { ExposureOffsetEv = 0.3 } }).ToJson();
});
var mine = content.Project with { Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.5 } };
var conflict = await Assert.ThrowsAsync<ProjectConflictException>(() => source.SaveProjectAsync(mine, content.Project, context.Cancellation));
var difference = Assert.Contains(conflict.Differences, _ => true);
Assert.Equal(("exposure.exposureOffsetEv", "0.5", "0.3"), (difference.Path, difference.Mine, difference.Theirs));
Assert.Equal(0.3, conflict.Server.Exposure.ExposureOffsetEv);
// Asked again without overwriting anything until the editor names the server's settings as its basis.
await Assert.ThrowsAsync<ProjectConflictException>(() => source.SaveProjectAsync(mine, content.Project, context.Cancellation));
Assert.SequenceEqual([false], api.Edits.Select(e => e.Accepted));
Assert.Equal(0.3, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
var kept = await source.SaveProjectAsync(mine, conflict.Server, context.Cancellation);
Assert.Equal(0.5, kept.Exposure.ExposureOffsetEv);
Assert.Equal(0.5, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
}
}
[Test]
public async Task KeepMineSavesTheEditorsValuesWithTheServersOtherChanges()
{
var (source, api, _) = Open();
var content = await source.LoadAsync(context.Cancellation);
await using var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var found = new TaskCompletionSource<ProjectConflictException>(TaskCreationOptions.RunContinuationsAsynchronously);
session.ConflictFound += conflict => found.TrySetResult(conflict);
api.EditsBefore.Enqueue(ChangedOnTheServer);
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } });
var conflict = await found.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.Same(conflict, session.Conflict);
Assert.False(await session.FlushAsync(), "the change waits for the choice");
Assert.True(session.ResolveConflict(keepMine: true));
Assert.True(await FlushAfterChoiceAsync(session));
Assert.Null(session.Conflict);
var stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.5, -0.2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY), "the editor's offset and the server's framing");
Assert.True(ProjectMerge.SameValues(stored, session.Project));
Assert.False(session.ResolveConflict(keepMine: false), "settled once");
}
[Test]
public async Task TakeServerShowsTheServersValuesAndCtrlZBringsTheEditorsBack()
{
var (source, api, _) = Open();
var content = await source.LoadAsync(context.Cancellation);
await using var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var found = new TaskCompletionSource<ProjectConflictException>(TaskCreationOptions.RunContinuationsAsynchronously);
session.ConflictFound += conflict => found.TrySetResult(conflict);
api.EditsBefore.Enqueue(ChangedOnTheServer);
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 }, HeroFrame = 2 });
await found.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.True(session.ResolveConflict(keepMine: false));
Assert.True(await FlushAfterChoiceAsync(session));
var stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.3, -0.2, (int?)2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY, stored.HeroFrame),
"the server's values where both changed; the editor's other change is saved");
Assert.True(ProjectMerge.SameValues(stored, session.Project));
Assert.True(session.Undo());
Assert.True(await session.FlushAsync());
stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.5, -0.2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY), "undo brings the editor's value back, the server's framing stays");
}
[Test]
public async Task AReloadDoesNotMergeOverAConflictingChange()
{
var (source, api, _) = Open();
var content = await source.LoadAsync(context.Cancellation);
await using var session = new EditorSession(source, content, [], TimeSpan.FromHours(1));
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } });
// An analysis ends on the server while someone there set the same setting; this editor's change was not sent yet.
api.SettingsJson = ChangedOnTheServer(api.SettingsJson);
api.SettingsVersion++;
api.FailNextEdit = new HttpRequestException("offline");
var found = 0;
session.ConflictFound += _ => Interlocked.Increment(ref found);
await session.ReloadAsync(context.Cancellation);
Assert.Equal(0.5, session.Project.Exposure.ExposureOffsetEv, "not merged over");
Assert.False(await session.FlushAsync(), "the retry meets the server's change and asks");
Assert.Equal(1, Volatile.Read(ref found));
Assert.Equal(0.3, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
}
[Test]
public async Task ConflictsThatKeepComingAreReported()
{
var (source, api, _) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
for (var i = 1; i <= 3; i++)
{
var offset = i / 10.0;
api.EditsBefore.Enqueue(json =>
{
var theirs = ProjectSettings.FromJson(json ?? "{}");
return (theirs with { Camera = theirs.Camera with { OffsetX = offset } }).ToJson();
});
}
var conflict = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.SaveConflict"), conflict.Message, "the toast shows the editor's own sentence");
Assert.False(api.Edits.Any(e => e.Accepted));
}
}
[Test]
public async Task TheHeroTravelsAsAFrameOfTheSequence()
{
var (source, api, remote) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var hero = await source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation);
var other = await source.SaveProjectAsync(hero with { Exposure = hero.Exposure with { ExposureOffsetEv = 0.1 } }, hero, context.Cancellation);
await source.SaveProjectAsync(other with { HeroFrame = null }, other, context.Cancellation);
Assert.SequenceEqual([remote.Frames[2].Id, (Guid?)null, Guid.Empty], api.Edits.Select(e => e.Request.HeroFrameId));
}
}
[Test]
public async Task AnAccountWithoutTheEditRightOnlyLooks()
{
var (source, api, _) = Open(readOnly: true);
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
Assert.True(source.IsReadOnly);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.IsReadOnly);
Assert.False(session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } }));
Assert.False(session.SetHero(3));
Assert.Empty(session.OptimiseAll());
Assert.False(session.Undo());
Assert.True(await session.FlushAsync(), "nothing waits for a save");
}
// The source refuses a change as well; the same project is no change.
var refused = await Assert.ThrowsAsync<EditorException>(() =>
source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.RemoteReadOnly"), refused.Message);
Assert.True(ProjectMerge.SameValues(content.Project, await source.SaveProjectAsync(content.Project, content.Project, context.Cancellation)));
Assert.Empty(api.Edits);
}
}
[Test]
public async Task AnalysesAndRendersArePostedToTheServerOnePerPreset()
{
var (source, api, remote) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.IsRemote);
await session.SubmitAsync(session.AnalysisRequest());
var export = session.Project.Export with { Preset = new Auto<string>().WithManual("4k-hevc"), Batch = ["1440p-h264", "4k-h264"] };
// The preset, then each batch preset.
var renders = session.RenderRequests(export);
Assert.Count(3, renders);
foreach (var request in renders) await session.SubmitAsync(request);
Assert.SequenceEqual(["deep-analyse", "render", "render", "render"], api.Posted.Select(p => p.Kind));
Assert.True(api.Posted.All(p => p.Target.SequenceEqual([remote.Sequence.Id])));
var presets = api.Posted.Skip(1).Select(p => ProcessingJobs.ReadRender(p.ParametersJson).Export).ToList();
Assert.True(presets.All(e => e.Batch.Count == 0), "a server job renders one preset");
Assert.SequenceEqual(["4k-hevc", "1440p-h264", "4k-h264"], presets.Select(e => e.Preset.Manual));
}
}
}
[Test]
public void ThisPcRendersABatchAsOneJob()
{
var content = EditorFixture.Content(EditorFixture.Sunset);
var session = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content), content, []);
var requests = session.RenderRequests(session.Project.Export with { Batch = ["1440p-h264", "4k-h264"] });
Assert.Count(1, requests);
Assert.Count(2, ProcessingJobs.ReadRender(requests[0].ParametersJson).Export.Batch);
}
[Test]
public async Task TheServersJobEventsReachTheEditor()
{
var (source, api, remote) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
var seen = new List<Job>();
source.JobChanged += job =>
{
lock (seen) seen.Add(job);
};
var id = await source.SubmitAsync(ProcessingJobs.DeepAnalysis([remote.Sequence.Id]), context.Cancellation);
Assert.Equal(JobState.Queued, Last(seen).State);
api.Jobs[id] = api.Job(id, "deep-analyse", "running");
api.Publish(new JobStateEvent(id, "running", null));
await WaitAsync(() => Last(seen).State == JobState.Running);
api.Publish(new JobProgressEvent(id, 10, 20, 2.5, 4));
await WaitAsync(() => Last(seen).ProgressDone == 10);
Assert.Equal(TimeSpan.FromSeconds(4), Last(seen).Eta);
// Another client's job on another sequence is not this editor's business.
var foreign = Guid.CreateVersion7();
api.Jobs[foreign] = api.Job(foreign, "render", "running", Guid.CreateVersion7());
api.Publish(new JobStateEvent(foreign, "running", null));
api.Jobs[id] = api.Job(id, "deep-analyse", "done", done: 20, total: 20);
api.Publish(new JobStateEvent(id, "done", null));
await WaitAsync(() => Last(seen).State == JobState.Done);
lock (seen) Assert.False(seen.Any(j => j.Id == foreign));
var other = Guid.CreateVersion7();
api.Jobs[other] = api.Job(other, "render", "queued");
api.Jobs[foreign] = api.Job(foreign, "render", "queued", Guid.CreateVersion7());
Assert.SequenceEqual([other], (await source.ListJobsAsync(context.Cancellation)).Select(j => j.Id), "active jobs of this sequence only");
// A late progress event of the finished job does not bring it back to running.
api.Publish(new JobProgressEvent(id, 19, 20, 2.5, 1));
api.Jobs[other] = api.Job(other, "render", "running");
api.Publish(new JobStateEvent(other, "running", null));
await WaitAsync(() => Last(seen).Id == other);
lock (seen) Assert.Equal(JobState.Done, seen.Last(j => j.Id == id).State);
}
Assert.True(api.Disposed, "closing the editor closes its connection");
}
[Test]
public async Task ASequenceGoneFromTheServerReadsAsMissing()
{
var (source, api, _) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
api.Gone = true;
Assert.Equal(Loc.L("Editor.Error.Missing"), (await Assert.ThrowsAsync<EditorException>(() => source.LoadAsync(context.Cancellation))).Message);
var gone = await Assert.ThrowsAsync<EditorException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.Missing"), gone.Message);
}
}
[Test]
public async Task ProxiesOfOtherFramesAreNotEdited()
{
var (source, api, remote) = Open();
await using (source)
{
// A frame added on the server since the proxies were fetched: positions in the project would point elsewhere.
api.Frames = [.. remote.Frames.Select(f => f.Id), Guid.CreateVersion7()];
await Assert.ThrowsAsync<ProxiesOutdatedException>(() => source.LoadAsync(context.Cancellation));
Assert.True(source.IsOutdated);
Assert.True(source.IsReadOnly);
}
(source, api, remote) = Open();
await using (source)
{
// The same frames in another order are other frames too.
api.Frames = [.. remote.Frames.Select(f => f.Id).Reverse()];
await Assert.ThrowsAsync<ProxiesOutdatedException>(() => source.LoadAsync(context.Cancellation));
}
}
[Test]
public async Task FramesChangedOnTheServerWhileOpenStopSavesAndRenders()
{
var (source, api, remote) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var changes = 0;
source.ReadOnlyChanged += () => Interlocked.Increment(ref changes);
// A change that keeps the frames (settings, a new version number) changes nothing.
api.FramesVersion = 2;
api.Publish(new SequenceChangedEvent(remote.Sequence.Id, "settings", 2, api.SettingsVersion));
await Task.Delay(200);
Assert.False(source.IsOutdated, "the same frames");
api.Frames = [.. remote.Frames.Skip(1).Select(f => f.Id)];
api.FramesVersion = 3;
api.Publish(new SequenceChangedEvent(Guid.CreateVersion7(), "frames", 7, 1));
api.Publish(new SequenceChangedEvent(remote.Sequence.Id, "frames", 3, api.SettingsVersion));
// The flag is set before the event is raised: wait for the event, which comes last.
await WaitAsync(() => Volatile.Read(ref changes) > 0);
Assert.True(source.IsOutdated);
Assert.True(source.IsReadOnly);
Assert.Equal(1, Volatile.Read(ref changes));
await Assert.ThrowsAsync<ProxiesOutdatedException>(() =>
source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
await Assert.ThrowsAsync<ProxiesOutdatedException>(() =>
source.SubmitAsync(ProcessingJobs.Render(remote.Sequence, new ExportSettings(), 1920, 1080), context.Cancellation));
await source.SubmitAsync(ProcessingJobs.DeepAnalysis([remote.Sequence.Id]), context.Cancellation);
Assert.Empty(api.Edits);
Assert.SequenceEqual(["deep-analyse"], api.Posted.Select(p => p.Kind), "an analysis reads the server's own frames");
}
}
[Test]
public async Task SavesNameTheirFramesAndTheServerRefusesThemOnceItsFramesChanged()
{
var (source, api, remote) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
var stored = await source.SaveProjectAsync(content.Project with { ExcludedFrames = [1] }, content.Project, context.Cancellation);
// A new frames version over the same frames: the save goes through at that version.
api.FramesVersion = 2;
stored = await source.SaveProjectAsync(stored with { HeroFrame = 2 }, stored, context.Cancellation);
Assert.SequenceEqual([1, 1, 2], api.Edits.Select(e => e.Request.ExpectedFramesVersion ?? -1));
Assert.SequenceEqual([true, false, true], api.Edits.Select(e => e.Accepted));
// An earlier photo reaches the server (a scan, an upload) and its positions move with their frames, before
// any event reaches this editor: the server refuses the edit made on the old frames, which stays unsaved.
api.Frames = [Guid.CreateVersion7(), .. remote.Frames.Select(f => f.Id)];
api.FramesVersion = 3;
api.SettingsJson = (ProjectSettings.FromJson(api.SettingsJson!) with { ExcludedFrames = [2], HeroFrame = 3 }).ToJson();
var refused = await Assert.ThrowsAsync<ProxiesOutdatedException>(() =>
source.SaveProjectAsync(stored with { ExcludedFrames = [1, 4] }, stored, context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.FramesChanged"), refused.Message);
Assert.True(source.IsOutdated);
Assert.False(api.Edits[^1].Accepted);
Assert.SequenceEqual([2], ProjectSettings.FromJson(api.SettingsJson!).ExcludedFrames, "the server keeps the positions it moved");
}
}
[Test]
public async Task FramesChangedWhileTheEventsWereLostAreFoundOnReconnecting()
{
var (source, api, remote) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
// The listener reads the stream open when it subscribes: it must have subscribed for the drop to reach it.
await api.Subscribed.WaitAsync(TimeSpan.FromSeconds(10), context.Cancellation);
api.DropEvents();
api.Frames = [.. remote.Frames.Skip(1).Select(f => f.Id)];
api.FramesVersion = 2;
// The listener reconnects after its first delay (2 s) and compares the frames again.
await WaitAsync(() => source.IsOutdated);
Assert.True(source.IsReadOnly);
}
}
[Test]
public async Task ARenderIsRefusedOnceTheServersFramesChangedWithoutAnEvent()
{
var (source, api, remote) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
// A new frames version over the same frames: they are still this PC's.
api.FramesVersion = 2;
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
Assert.False(source.IsOutdated);
// A server scan inserts an earlier photo and sends no event: the check before a render finds it.
api.Frames = [Guid.CreateVersion7(), .. remote.Frames.Select(f => f.Id)];
api.FramesVersion = 3;
Assert.False(await source.FramesCurrentAsync(context.Cancellation));
Assert.True(source.IsOutdated);
var refused = await Assert.ThrowsAsync<ProxiesOutdatedException>(() =>
source.SubmitAsync(ProcessingJobs.Render(remote.Sequence, new ExportSettings(), 1920, 1080), context.Cancellation));
Assert.Equal(Loc.L("Editor.Error.FramesChanged"), refused.Message);
Assert.Empty(api.Posted);
}
}
[Test]
public async Task AConflictFoundOnOtherFramesIsNotMergedOntoThem()
{
var (source, api, remote) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
api.EditsBefore.Enqueue(json =>
{
api.Frames = [.. remote.Frames.Select(f => f.Id), Guid.CreateVersion7()];
return json ?? "{}";
});
await Assert.ThrowsAsync<ProxiesOutdatedException>(() =>
source.SaveProjectAsync(content.Project with { ExcludedFrames = [1] }, content.Project, context.Cancellation));
Assert.SequenceEqual([false], api.Edits.Select(e => e.Accepted));
Assert.True(source.IsOutdated);
}
}
[Test]
public async Task QueuedRendersKeepTheirPriorityAndJobsCanBeCancelledAndRetried()
{
var (source, api, remote) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
var seen = new List<Job>();
source.JobChanged += job =>
{
lock (seen) seen.Add(job);
};
var render = ProcessingJobs.Render(remote.Sequence, new ExportSettings(), 1920, 1080);
var now = await source.SubmitAsync(render, context.Cancellation);
var later = await source.SubmitAsync(render with { Priority = JobPriority.Normal }, context.Cancellation);
Assert.SequenceEqual([(later, "normal")], api.Priorities, "Render now stays at the user's priority; Add to queue waits behind it");
await source.CancelJobAsync(now, context.Cancellation);
Assert.Equal(JobState.Cancelled, Last(seen).State);
Assert.Equal("cancelled", api.Jobs[now].State);
await source.RetryJobAsync(now, context.Cancellation);
Assert.Equal((now, JobState.Queued), (Last(seen).Id, Last(seen).State));
}
}
[Test]
public async Task TheEventListenerOutlivesAFailureAndClosingReleasesTheConnection()
{
var (source, api, remote) = Open();
await using (source)
{
await source.LoadAsync(context.Cancellation);
var seen = new List<Job>();
source.JobChanged += job =>
{
lock (seen) seen.Add(job);
};
var id = await source.SubmitAsync(ProcessingJobs.DeepAnalysis([remote.Sequence.Id]), context.Cancellation);
api.Jobs[id] = api.Job(id, "deep-analyse", "running");
// A failure the listener has no special case for (a body that is not a job) does not end it.
api.FailNextJobRead = new ArgumentNullException("dto");
api.Publish(new JobStateEvent(id, "running", null));
api.Publish(new JobStateEvent(id, "running", null));
await WaitAsync(() => Last(seen).State == JobState.Running);
}
Assert.True(api.Disposed);
}
private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(int frames = 6, int cached = int.MaxValue,
bool readOnly = false) =>
Open(EditorFixture.Sequence(frames), cached, readOnly);
/// <summary>A server sequence whose first <paramref name="cached"/> proxies are on this PC (synthetic JPEGs).</summary>
private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(SyntheticSequence sunset, int cached = int.MaxValue,
bool readOnly = false)
{
var folder = context.CreateTempDirectory("proxies");
var sequence = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Title = "Harbour sunset",
Folder = "2026/2026-09-28 Synthetic",
FrameCount = sunset.Count,
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
var frames = sunset.Frames.Select((f, i) => f with { Id = Guid.CreateVersion7(), SequenceId = sequence.Id, Flags = i < cached ? f.Flags : f.Flags | FrameFlags.Missing })
.ToList();
var files = new string?[frames.Count];
for (var i = 0; i < files.Length && i < cached; i++)
{
using var image = sunset.Render(i);
files[i] = Path.Combine(folder, frames[i].Id.ToString("N") + ".jpg");
File.WriteAllBytes(files[i]!, JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90 }));
}
var remote = new RemoteSequence(Server, sequence, frames, files);
var api = new FakeRemoteSequenceApi(sequence, [.. frames.Select(f => f.Id)]) { SettingsJson = new ProjectSettings().ToJson() };
return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null), readOnly), api, remote);
}
/// <summary>Someone on the server sets the exposure offset to 0.3 and moves the framing.</summary>
private static string ChangedOnTheServer(string? json)
{
var theirs = ProjectSettings.FromJson(json ?? "{}");
return (theirs with { Exposure = theirs.Exposure with { ExposureOffsetEv = 0.3 }, Camera = theirs.Camera with { OffsetY = -0.2 } }).ToJson();
}
private static Job Last(List<Job> seen)
{
lock (seen) return seen[^1];
}
/// <summary>
/// Stores the change after the user settled a conflict. The test's thread is not the saver's: a retry that started
/// before the choice may still be failing on the old basis, and a flush that arrives meanwhile reports it, so one more
/// flush (on the UI thread the choice cannot land inside a retry) is answered by the attempt made after the choice.
/// </summary>
private static async Task<bool> FlushAfterChoiceAsync(EditorSession session) => await session.FlushAsync() || await session.FlushAsync();
private static async Task WaitAsync(Func<bool> condition)
{
for (var i = 0; i < 200; i++)
{
try
{
if (condition()) return;
}
catch (ArgumentOutOfRangeException)
{
// Nothing seen yet.
}
await Task.Delay(25);
}
Assert.True(condition(), "timed out waiting");
}
}