merge: third-pass sync and editor fixes (W-2, W-3, W-4, W-16)

Merge branch fix3/sync-editor into the verification branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 20:02:15 +00:00
commit 8897363e60
21 files changed
+1038 -79

No files matched your search

+32 -4
View File
@@ -77,6 +77,9 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
{
private readonly SyntheticFrameSource _pixels = new(sequence);
/// <summary>The frames the session read last (opened with, or loaded since).</summary>
private IReadOnlyList<Frame> _read = content.Frames;
public ProjectSettings Stored { get; set; } = content.Project;
public SequenceContent Content { get; set; } = content;
@@ -114,11 +117,36 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
/// <summary>Thrown by the next load (the sequence read again after a job).</summary>
public Exception? FailNextLoad { get; set; }
public Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
/// <summary>Awaited by the next load once it has read the sequence (a read that is slow to complete).</summary>
public Task? NextLoadGate { get; set; }
/// <summary>Times the sequence was read (<see cref="LoadAsync"/>).</summary>
public int Loads { get; private set; }
public async Task<SequenceContent> LoadAsync(CancellationToken cancellationToken)
{
if (FailNextLoad is not { } failure) return Task.FromResult(Content with { Project = Stored });
FailNextLoad = null;
return Task.FromException<SequenceContent>(failure);
if (FailNextLoad is { } failure)
{
FailNextLoad = null;
throw failure;
}
Loads++;
var content = Content with { Project = Stored };
if (NextLoadGate is { } gate)
{
NextLoadGate = null;
await gate;
}
_read = content.Frames;
return content;
}
/// <summary>Whether <see cref="Content"/> holds the frames read last; a server sequence becomes outdated when not.</summary>
public Task<bool> FramesCurrentAsync(CancellationToken cancellationToken)
{
var current = _read.Select(f => f.Id).SequenceEqual(Content.Frames.Select(f => f.Id));
if (!current && IsRemote) MarkOutdated();
return Task.FromResult(current);
}
public async ValueTask<ImageBuffer?> DecodeAsync(int index, int maxLongEdge, DecodePurpose purpose, CancellationToken cancellationToken)
@@ -98,6 +98,160 @@ public sealed class EditorSessionTests
}
}
[Test]
public async Task AnEditMadeBeforeInsertedFramesWereReadIsSavedOnTheFramesItNamed()
{
var (session, source) = OpenShort();
await using (session)
{
Assert.True(session.SetExcluded([3], true));
Assert.True(await session.FlushAsync());
// Two earlier photos are inserted (a download, an import, a scan): the stored exclusion moved with its frame.
var frames = session.Content.Frames;
InsertEarlier(source, 2);
source.Stored = source.Stored with { ExcludedFrames = [5] };
source.FailNextSave = new FramesChangedException("frames changed");
// The editor still shows the frames it read when the user excludes another one.
Assert.True(session.SetExcluded([6], true));
Assert.True(await session.FlushAsync());
Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again");
Assert.SequenceEqual([5, 8], source.Stored.ExcludedFrames);
Assert.SequenceEqual([frames[3].Id, frames[6].Id], session.Project.ExcludedFrames.Select(i => session.Content.Frames[i].Id));
Assert.True(session.Undo());
Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames");
Assert.True(session.Undo());
Assert.Empty(session.Project.ExcludedFrames);
}
}
[Test]
public async Task AReadAfterFramesWereInsertedMovesTheOpenProjectWithThem()
{
var (session, source) = OpenShort();
await using (session)
{
Assert.True(session.SetExcluded([3], true));
Assert.True(session.SetHero(4));
Assert.True(await session.FlushAsync());
InsertEarlier(source, 2);
source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 };
await session.ReloadAsync();
Assert.SequenceEqual([5], session.Project.ExcludedFrames);
Assert.Equal(6, session.Project.HeroFrame);
Assert.True(session.Undo());
Assert.Null(session.Project.HeroFrame);
Assert.SequenceEqual([5], session.Project.ExcludedFrames, "the step before Set hero names the same frame");
Assert.True(await session.FlushAsync());
Assert.SequenceEqual([5], source.Stored.ExcludedFrames);
Assert.Null(source.Stored.HeroFrame);
}
}
[Test]
public async Task ARenderAfterFramesWereInsertedEmbedsThePositionsOfTheFramesTheUserChose()
{
var (session, source) = OpenShort();
await using (session)
{
Assert.True(session.SetExcluded([3], true));
Assert.True(session.SetHero(4));
Assert.True(await session.FlushAsync());
var frames = session.Content.Frames;
// Two earlier photos are inserted and the index moves the stored positions; the user renders without an edit.
InsertEarlier(source, 2);
source.Stored = source.Stored with { ExcludedFrames = [5], HeroFrame = 6 };
await session.EnsureFramesAsync();
var requests = session.RenderRequests(session.Project.Export);
Assert.Equal(frames.Count + 2, session.Content.Count, "the frames were read again");
var parameters = JsonSerializer.Deserialize(requests[0].ParametersJson!, ProtocolJson.Default.RenderJobParameters)!;
var embedded = ProjectSettings.FromJson(parameters.SettingsJson!);
Assert.SequenceEqual([5], embedded.ExcludedFrames);
Assert.Equal(6, embedded.HeroFrame);
Assert.Equal(frames[3].Id, session.Content.Frames[embedded.ExcludedFrames[0]].Id);
Assert.Equal(frames[4].Id, session.Content.Frames[embedded.HeroFrame!.Value].Id);
Assert.True(session.Undo());
Assert.Null(session.Project.HeroFrame);
Assert.SequenceEqual([5], session.Project.ExcludedFrames, "undo steps name the same frames");
// Frames that did not change are not read again.
var loads = source.Loads;
await session.EnsureFramesAsync();
Assert.Equal(loads, source.Loads);
}
}
[Test]
public async Task AServerSequenceWhoseFramesChangedIsOutdatedBeforeItsRender()
{
var sequence = EditorFixture.Sequence(12);
var content = EditorFixture.Content(sequence, deep: false);
var source = new FakeSequenceSource(sequence, content) { IsRemote = true };
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
InsertEarlier(source, 1);
await session.EnsureFramesAsync();
Assert.True(source.IsOutdated);
Assert.True(session.IsReadOnly);
Assert.Equal(0, source.Loads, "its proxies are not the server's frames: nothing is read");
Assert.Equal(12, session.Content.Count);
}
}
[Test]
public async Task ReadsThatOverlapFollowTheFramesInTheOrderTheyWereRead()
{
var (session, source) = OpenShort();
await using (session)
{
Assert.True(session.SetExcluded([3], true));
Assert.True(await session.FlushAsync());
var frames = session.Content.Frames;
// A job ends after an earlier photo was inserted, and its read of the sequence is slow to complete.
InsertEarlier(source, 1);
source.Stored = source.Stored with { ExcludedFrames = [4] };
var slow = new TaskCompletionSource();
source.NextLoadGate = slow.Task;
var first = session.ReloadAsync();
// Another job ends after two more were inserted: its read waits for the first one and follows its frames.
InsertEarlier(source, 2);
source.Stored = source.Stored with { ExcludedFrames = [6] };
var second = session.ReloadAsync();
slow.SetResult();
await Task.WhenAll(first, second);
Assert.Equal(frames.Count + 3, session.Content.Count);
Assert.SequenceEqual([6], session.Project.ExcludedFrames);
Assert.Equal(frames[3].Id, session.Content.Frames[6].Id);
}
}
/// <summary>A short sequence without its analysis, whose frame ids are all different (the synthetic ids repeat every 64 frames).</summary>
private static (EditorSession Session, FakeSequenceSource Source) OpenShort()
{
var sequence = EditorFixture.Sequence(12);
var content = EditorFixture.Content(sequence, deep: false);
var source = new FakeSequenceSource(sequence, content);
return (new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)), source);
}
/// <summary>Photos captured before the first frame join the source's sequence, as an insertion renumbers it.</summary>
private static void InsertEarlier(FakeSequenceSource source, int count)
{
var first = source.Content.Frames[0];
var early = Enumerable.Range(0, count).Select(i => first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(i - count) });
IReadOnlyList<Frame> frames = [.. early.Concat(source.Content.Frames).Select((f, i) => f with { Index = i })];
source.Content = source.Content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) };
}
[Test]
public async Task AFailedSaveStaysPendingUntilItIsStored()
{
@@ -14,6 +14,7 @@ using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Advice;
using Titano.Core.Analysis;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
@@ -299,6 +300,36 @@ public sealed class EditorSmokeTests
}
});
/// <summary>
/// Frames inserted under the editor (a sync download, an import of earlier photos) move the frame on screen with its
/// photo: what the frame actions (Exclude, Set hero, a keyframe) apply to stays the photo the user looks at.
/// </summary>
[Test]
public Task TheFrameOnScreenStaysWhenFramesAreInsertedBeforeIt() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
var content = EditorFixture.Content(EditorFixture.Sunset, deep: false);
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
var editor = new EditorViewModel(app.Shell, new EditorSession(source, content, []), [], EncoderHost.Client);
await using (editor)
{
editor.CurrentIndex = 5;
var shown = content.Frames[5].Id;
// An earlier photo arrives and the last frame goes: as many frames as before, each one place later.
var first = content.Frames[0];
IReadOnlyList<Titano.Core.Model.Frame> frames =
[.. new[] { first with { Id = Guid.CreateVersion7(), CapturedAt = first.CapturedAt!.Value.AddMinutes(-1) } }.Concat(content.Frames.SkipLast(1))
.Select((f, i) => f with { Index = i })];
source.Content = content with { Frames = frames, Light = LightAnalyzer.Analyze(frames) };
await editor.Session.ReloadAsync();
Assert.Equal(6, editor.CurrentIndex);
Assert.Equal(shown, editor.Session.Content.Frames[editor.CurrentIndex].Id);
Assert.Equal(6, editor.Frames.Selected?.Index);
}
});
/// <summary>The measuring tool of each section has content.</summary>
private static void ExpectMeasure(SequenceView view, EditorTab tab)
{
@@ -1,4 +1,5 @@
using System.Collections.Concurrent;
using System.IO;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
@@ -17,7 +18,8 @@ namespace Titano.App.Tests.Editor;
internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Guid> frames) : IRemoteSequenceApi
{
private readonly Lock _gate = new();
private readonly Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
private readonly TaskCompletionSource _subscribed = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Channel<ServerEvent> _events = Channel.CreateUnbounded<ServerEvent>();
/// <summary>The server's frames in order (another list when frames are added or removed on the server).</summary>
public IReadOnlyList<Guid> Frames { get; set; } = frames;
@@ -54,12 +56,18 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
public bool Disposed { get; private set; }
/// <summary>Completes once the editor's listener has opened an event stream (the stream open then is the one it reads).</summary>
public Task Subscribed => _subscribed.Task;
/// <summary>A job of the server, as <c>GET /jobs/{id}</c> returns it.</summary>
public JobDto Job(Guid id, string kind, string state, Guid? target = null, long done = 0, long total = 0) =>
new(id, kind, [target ?? sequence.Id], sequence.DisplayTitle, state, "user", done, total, null, null, null, null, 0, null, DateTimeOffset.UtcNow,
state == "queued" ? null : DateTimeOffset.UtcNow, state is "done" or "failed" ? DateTimeOffset.UtcNow : null);
public void Publish(ServerEvent e) => _events.Writer.TryWrite(e);
public void Publish(ServerEvent e) => Volatile.Read(ref _events).Writer.TryWrite(e);
/// <summary>The event socket drops: the stream open now fails, and the next one starts empty.</summary>
public void DropEvents() => Interlocked.Exchange(ref _events, Channel.CreateUnbounded<ServerEvent>()).Writer.TryComplete(new IOException("connection lost"));
public Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
{
@@ -98,6 +106,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
Edits.Add((request, false));
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed", SettingsVersion.ToString()));
}
if (request.ExpectedFramesVersion is { } frames && frames != FramesVersion)
{
Edits.Add((request, false));
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("frames_conflict", "frames changed", FramesVersion.ToString()));
}
Edits.Add((request, true));
SettingsJson = request.SettingsJson ?? SettingsJson;
SettingsVersion++;
@@ -158,9 +171,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
while (await _events.Reader.WaitToReadAsync(cancellationToken))
var events = Volatile.Read(ref _events).Reader;
_subscribed.TrySetResult();
while (await events.WaitToReadAsync(cancellationToken))
{
while (_events.Reader.TryRead(out var e)) yield return e;
while (events.TryRead(out var e)) yield return e;
}
}
@@ -138,6 +138,83 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
[Test]
public async Task AnEditorOpenWhileEarlierPhotosArriveSavesOnTheFramesTheUserChose()
{
var (db, sequenceId, root) = await ArchiveAsync(10);
await using (db)
{
var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) };
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options);
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.SetExcluded([5], true));
Assert.True(session.SetHero(6));
Assert.True(await session.FlushAsync());
// Three photos taken before the others are found in the folder (a sync download, an import or a scan
// inserts them the same way): the index moves the stored positions with their frames.
await InsertEarlierAsync(db, root, content, options, 3);
var moved = ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!);
Assert.SequenceEqual([8], moved.ExcludedFrames);
Assert.Equal(9, moved.HeroFrame);
// The editor still shows the ten frames it read; the user excludes the eighth of them.
Assert.Equal(10, session.Content.Count);
Assert.True(session.SetExcluded([7], true));
Assert.True(await session.FlushAsync());
Assert.Equal(13, session.Content.Count, "the frames were read again before the save");
Assert.SequenceEqual([8, 10], session.Project.ExcludedFrames);
Assert.Equal(9, session.Project.HeroFrame);
var row = (await db.Sequences.GetAsync(sequenceId))!;
var stored = ProjectSettings.FromJson(row.SettingsJson!);
var frames = session.Content.Frames;
Assert.SequenceEqual([content.Frames[5].Id, content.Frames[7].Id], stored.ExcludedFrames.Select(i => frames[i].Id), "the photos the user chose");
Assert.Equal(content.Frames[6].Id, frames[stored.HeroFrame!.Value].Id);
Assert.Equal(content.Frames[6].Id, row.HeroFrameId);
Assert.Equal(row.SettingsJson, File.ReadAllText(Path.Combine(root, "Synthetic", ".titano", "project.json")));
// Undo takes back the user's last step on the new frames too.
Assert.True(session.Undo());
Assert.True(await session.FlushAsync());
Assert.SequenceEqual([8], ProjectSettings.FromJson((await db.Sequences.GetAsync(sequenceId))!.SettingsJson!).ExcludedFrames);
}
}
}
[Test]
public async Task ARenderAfterEarlierPhotosArriveEmbedsTheFramesTheUserChose()
{
var (db, sequenceId, root) = await ArchiveAsync(10);
await using (db)
{
var options = new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) };
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null, options);
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.SetExcluded([5], true));
Assert.True(await session.FlushAsync());
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
// Earlier photos arrive while the editor is open; the user renders without another edit.
await InsertEarlierAsync(db, root, content, options, 3);
Assert.False(await source.FramesCurrentAsync(context.Cancellation));
await session.EnsureFramesAsync(context.Cancellation);
var request = session.RenderRequests(session.Project.Export)[0];
Assert.True(await source.FramesCurrentAsync(context.Cancellation));
Assert.Equal(13, session.Content.Count);
var embedded = ProjectSettings.FromJson(ProcessingJobs.ReadRender(request.ParametersJson).Parameters.SettingsJson!);
Assert.SequenceEqual([content.Frames[5].Id], embedded.ExcludedFrames.Select(i => session.Content.Frames[i].Id), "the photo the user excluded");
}
}
}
[Test]
public async Task ASaveThatDoesNotReachTheIndexThrows()
{
@@ -192,6 +269,25 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
/// <summary>
/// Writes <paramref name="count"/> photos taken before the sequence's first frame into its folder and scans the
/// archive: they are inserted in front, and the index moves the stored positions with their frames.
/// </summary>
private async Task InsertEarlierAsync(TitanoDatabase db, string root, SequenceContent content, ArchiveServiceOptions options, int count)
{
var sequence = EditorFixture.Sequence(count);
var first = content.Frames[0].CapturedAt!.Value;
for (var i = 0; i < count; i++)
{
using var image = sequence.Render(i);
var exif = ExifWriter.BuildJpegApp1(sequence.Metadata[i] with { CapturedAt = first.AddMinutes(i - count) });
File.WriteAllBytes(Path.Combine(root, "Synthetic", $"EARLY_{i + 1}.JPG"),
JpegEncoder.Encode(image, new JpegEncodeOptions { Quality = 90, App1Segments = [exif[4..]] }));
}
var archive = (await db.Archives.GetAsync(content.Sequence.ArchiveId, context.Cancellation))!;
await new ArchiveService(db, options).Indexer.ScanAsync(archive, ScanMode.Full, null, _ => ValueTask.CompletedTask, context.Cancellation);
}
/// <summary>A temporary archive with one adopted folder of synthetic JPEGs, indexed.</summary>
private async Task<(TitanoDatabase Db, Guid SequenceId, string Root)> ArchiveAsync(int frames)
{
@@ -159,7 +159,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
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 session.FlushAsync());
Assert.True(await FlushAfterChoiceAsync(session));
Assert.Null(session.Conflict);
var stored = ProjectSettings.FromJson(api.SettingsJson!);
@@ -181,7 +181,7 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
await found.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.True(session.ResolveConflict(keepMine: false));
Assert.True(await session.FlushAsync());
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");
@@ -433,6 +433,77 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
}
[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()
{
@@ -546,6 +617,13 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
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++)
@@ -167,6 +167,47 @@ public sealed class ProjectSettingsTests
Assert.Null(ProjectSettings.MoveFramePositions("""{ "heroFrame": 1, "HeroFrame": 1 }""", new Dictionary<int, int> { [1] = 2 }));
}
[Test]
public void AnEditorsPositionsFollowFramesInsertedUnderItAsTheIndexMovedTheStoredOnes()
{
// An editor read four frames; a download then inserted two earlier photos, one of which an exclusion waited for.
var photos = Enumerable.Range(0, 6).Select(Photo).ToList();
var ids = Enumerable.Range(0, 6).Select(_ => Guid.CreateVersion7()).ToList();
IReadOnlyList<Guid> before = ids[2..];
var after = ids.Select((id, i) => new Titano.Core.Model.Frame
{
Id = id,
SequenceId = Guid.Empty,
Index = i,
RelativePath = $"s/IMG_{i}.JPG",
FileName = $"IMG_{i}.JPG",
Sha256 = photos[i].Sha256,
Size = photos[i].Size,
CapturedAt = photos[i].CapturedAt,
}).ToList();
var project = new ProjectSettings
{
ExcludedFrames = [1, 3],
HeroFrame = 0,
Camera = new CameraSettings { Keyframes = [new CameraKey(2, 0.5, 0.5, 1, 0)] },
Exposure = new ExposureSettings { DeflickerWindow = new Auto<int>().WithManual(41) },
PendingFrames = [new PendingFrame { Sha256 = photos[1].Sha256, Size = photos[1].Size, Excluded = true }],
};
var followed = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.FollowFrames(project.ToJson(), before, after)));
Assert.SequenceEqual([1, 3, 5], followed.ExcludedFrames);
Assert.Equal(2, followed.HeroFrame);
Assert.SequenceEqual([4], followed.Camera.Keyframes.Select(k => k.Frame));
Assert.Equal(41, followed.Exposure.DeflickerWindow.Manual);
Assert.Null(followed.PendingFrames);
// The same frames: nothing moves. A frame the editor read that is gone: positions stay, as the index leaves them.
Assert.Null(ProjectSettings.FollowFrames(new ProjectSettings { ExcludedFrames = [1] }.ToJson(), ids, after));
var removed = after.Where(f => f.Id != ids[3]).Select((f, i) => f with { Index = i }).ToList();
Assert.Null(ProjectSettings.FollowFrames(new ProjectSettings { ExcludedFrames = [1, 3] }.ToJson(), before, removed));
}
[Test]
public void PositionsCrossToAnotherCopyByPhotoAndWaitForPhotosItLacks()
{
@@ -283,6 +324,102 @@ public sealed class ProjectSettingsTests
Assert.Null(cleared.PendingFrames);
}
[Test]
public void APhotoHeldTwiceKeepsEachCopysPositions()
{
// The server adopted a folder holding photo 1 twice ('IMG_0001.JPG', 'IMG_0001 (1).JPG'); this PC keeps it once.
var photos = Enumerable.Range(0, 3).Select(Photo).ToList();
var server = Frames([photos[0], photos[1], photos[1], photos[2]]);
var here = Frames(photos);
var project = new ProjectSettings
{
ExcludedFrames = [2],
HeroFrame = 2,
Camera = new CameraSettings { Keyframes = [new CameraKey(1, 0.1, 0.5, 1, 0), new CameraKey(2, 0.2, 0.5, 1, 0)] },
};
// The second copy, which the deep analysis flags as a duplicate, is excluded there: this PC still renders its only copy.
var taken = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(project.ToJson(), server, here)));
Assert.Empty(taken.ExcludedFrames);
Assert.Null(taken.HeroFrame);
Assert.SequenceEqual([1], taken.Camera.Keyframes.Select(k => k.Frame));
Assert.Equal(0.1, taken.Camera.Keyframes[0].CenterX);
var waiting = Assert.NotNull(taken.PendingFrames);
Assert.Count(1, waiting);
Assert.True(waiting[0] is { Excluded: true, Hero: true, Occurrence: 1 } && waiting[0].Sha256 == photos[1].Sha256);
Assert.Count(1, waiting[0].Keyframes);
Assert.Equal(0.2, waiting[0].Keyframes[0].CenterX);
Assert.Contains("\"occurrence\": 1", taken.ToJson());
// Sent back after an edit of something else, every position lands on the copy it named.
var edited = taken with { Exposure = new ExposureSettings { ExposureOffsetEv = 0.3 } };
var back = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(edited.ToJson(), here, server)));
Assert.SequenceEqual([2], back.ExcludedFrames);
Assert.Equal(2, back.HeroFrame);
Assert.SequenceEqual([1, 2], back.Camera.Keyframes.Select(k => k.Frame));
Assert.SequenceEqual([0.1, 0.2], back.Camera.Keyframes.Select(k => k.CenterX));
Assert.Null(back.PendingFrames);
// Both copies excluded there: this PC excludes its copy, and the server gets both back.
var both = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(new ProjectSettings { ExcludedFrames = [1, 2] }.ToJson(), server, here)));
Assert.SequenceEqual([1], both.ExcludedFrames);
var excluded = Assert.NotNull(both.PendingFrames);
Assert.Count(1, excluded);
Assert.True(excluded[0] is { Excluded: true, Hero: false, Occurrence: 1 });
var returned = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(both.ToJson(), here, server)));
Assert.SequenceEqual([1, 2], returned.ExcludedFrames);
Assert.Null(returned.PendingFrames);
}
[Test]
public void TheCopiesOfAPhotoAreToldApartByTheirOrder()
{
var time = new DateTime(2026, 9, 28, 18, 0, 0);
var hashed = new FramePhoto(new string('a', 64), 100, time);
var other = new FramePhoto(new string('b', 64), 200, time);
var unhashed = new FramePhoto(null, 100, time);
// The frame at 3 has not been hashed yet: it may be a copy of the photo, or another photo of the same size taken in
// the same second. The frames with the photo's hash are its copies; size and capture time match the unhashed one.
var frames = Frames([other, hashed, other, unhashed, hashed]);
Assert.SequenceEqual([1, 4], new[] { 0, 1, 2 }.Select(n => frames.IndexOf(hashed, n)).OfType<int>());
Assert.Null(frames.IndexOf(hashed, 2));
Assert.SequenceEqual([1, 3, 4], new[] { 0, 1, 2 }.Select(n => frames.IndexOf(unhashed, n)).OfType<int>());
Assert.SequenceEqual([0, 0, 1, 1, 1], Enumerable.Range(0, 5).Select(frames.Occurrence));
Assert.Equal(0, frames.Occurrence(9));
Assert.Equal(2, frames.IndexOf(new FramePhoto(new string('B', 64), 0, null), 1));
// Without a frame holding its hash, a hashed photo is the frames not hashed yet with its size and capture time.
Assert.Equal(3, frames.IndexOf(new FramePhoto(new string('c', 64), 100, time)));
}
[Test]
public void APhotoNotHashedYetDoesNotTakeThePositionsOfAnotherWithItsSizeAndTime()
{
// Two photos of a burst share size and capture time (a RAW of constant size, no sub-second times). The server has
// not hashed the first yet; this PC has hashed both and does not have the third photo yet.
var time = new DateTime(2026, 9, 28, 18, 0, 0);
var (first, second) = (new FramePhoto(new string('a', 64), 100, time), new FramePhoto(new string('b', 64), 100, time));
var server = Frames([first with { Sha256 = null }, second, Photo(3)]);
var here = Frames([first, second]);
// The second photo excluded on the server is the second here, and back; the first stays the hero on both.
var project = new ProjectSettings { ExcludedFrames = [1, 2], HeroFrame = 0 };
var taken = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(project.ToJson(), server, here)));
Assert.SequenceEqual([1], taken.ExcludedFrames);
Assert.Equal(0, taken.HeroFrame);
var waiting = Assert.NotNull(taken.PendingFrames);
Assert.True(waiting is [{ Excluded: true, Occurrence: 0 }] && waiting[0].Sha256 == Photo(3).Sha256, "only the third photo waits");
var back = ProjectSettings.FromJson(Assert.NotNull(ProjectSettings.TranslateFramePositions(taken.ToJson(), here, server)));
Assert.SequenceEqual([1, 2], back.ExcludedFrames);
Assert.Equal(0, back.HeroFrame);
Assert.Null(back.PendingFrames);
// A copy that has not hashed its first frame still finds the second photo by its hash, not on that frame.
Assert.Equal(1, server.IndexOf(second));
Assert.Equal(0, server.Occurrence(1));
Assert.Equal(0, server.IndexOf(first));
}
[Test]
public void AProjectNamingNoFrameCrossesAsItIs()
{
@@ -174,6 +174,8 @@ internal sealed class FakeSyncRemote : ISyncRemote
"original" when CorruptOnce == frameId => [.. frame.Bytes.Select(b => (byte)~b)],
"original" => frame.Bytes,
"proxy" or "thumb" when FailAssets => throw new TitanoApiException(HttpStatusCode.InternalServerError, new ApiError("internal", "failed")),
// A proxy a client or render node sent is served as soon as it is filed, like the manifest says.
"proxy" when SentProxies.TryGetValue(frameId, out var sent) => sent,
"proxy" when (sequence.Status & SequenceStatus.ProxiesBuilt) != 0 => frame.Proxy,
"thumb" when (sequence.Status & SequenceStatus.ThumbsBuilt) != 0 => frame.Proxy[..Math.Min(frame.Proxy.Length, 64)],
_ => throw NotFound(),
@@ -159,6 +159,74 @@ public sealed class SyncAgentTests(TestContext context)
Assert.Equal(2, (await DownloadsAsync(f)).Count);
}
[Test]
public async Task ThumbnailsStandingInAreReplacedOnceTheServerOffersTheirProxies()
{
await using var f = await SyncFixture.CreateAsync(context);
// The server cannot decode these originals and waits for their proxies; one frame (missing or damaged) never gets
// one, so the sequence's proxy flag never comes.
var remote = f.Remote.Add("Fog", f.NewPhotos(3), status: SequenceStatus.ThumbsBuilt);
remote.Undecodable = true;
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
Assert.True(Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id)).Files.All(file => new FileInfo(file!).Length == 64), "thumbnails stand in");
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
await agent.RefreshAsync(f.Ct);
Assert.Count(1, await DownloadsAsync(f));
// Another PC sends the proxies of two frames; the server's proxy pass then records the sequence's state.
foreach (var frame in remote.Frames.Take(2)) f.Remote.SentProxies[frame.Id] = frame.Proxy;
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
await agent.RefreshAsync(f.Ct);
var refresh = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(refresh.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual([remote.Frames[0].Proxy.Length, remote.Frames[1].Proxy.Length, 64], opened.Files.Select(file => (int)new FileInfo(file!).Length));
// The frame still waiting keeps its thumbnail; nothing is queued again until the server's sequence changes.
await agent.RefreshAsync(f.Ct);
Assert.Count(2, await DownloadsAsync(f));
}
[Test]
public async Task AStandInDownloadThatFailedIsQueuedAgainAfterItsBackoff()
{
await using var f = await SyncFixture.CreateAsync(context);
var remote = f.Remote.Add("Fog", f.NewPhotos(3), status: SequenceStatus.ThumbsBuilt);
remote.Undecodable = true;
var engine = await f.StartEngineAsync();
await f.RefreshAsync();
var first = await f.Sync.EnqueueDownloadAsync(engine, f.Server, remote.Id, "Fog", SyncDownloadMode.Proxies, null);
await f.Archive.WaitForAsync(first.Id, JobState.Done);
await using var agent = new SyncAgent(f.Sync, f.Remote, () => new SyncPolicy(KeepProxiesOffline: true), engine, EventsOnly);
agent.Start();
await WaitAsync(() => agent.Snapshot is not null, "first comparison");
// Two frames' proxies reach the server, but their download fails (the server restarts meanwhile).
foreach (var frame in remote.Frames.Take(2)) f.Remote.SentProxies[frame.Id] = frame.Proxy;
remote.UpdatedAt = DateTimeOffset.UtcNow.AddSeconds(1);
f.Remote.FailAssets = true;
await agent.RefreshAsync(f.Ct);
var failed = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id);
await f.Archive.WaitForAsync(failed.Id, JobState.Failed);
// The server's sequence does not change again: once the backoff has passed, the download is queued anyway.
f.Remote.FailAssets = false;
await WaitAsync(async () =>
{
await agent.RefreshAsync(f.Ct);
return (await DownloadsAsync(f)).Count == 3;
}, "the download queued again");
var retry = Assert.Contains(await DownloadsAsync(f), j => j.Id != first.Id && j.Id != failed.Id);
await f.Archive.WaitForAsync(retry.Id, JobState.Done);
var opened = Assert.NotNull(f.Sync.OpenRemote(f.Server, remote.Id));
Assert.SequenceEqual([remote.Frames[0].Proxy.Length, remote.Frames[1].Proxy.Length, 64], opened.Files.Select(file => (int)new FileInfo(file!).Length));
}
private static async Task<IReadOnlyList<Job>> DownloadsAsync(SyncFixture f) =>
(await f.Db.Jobs.ListAsync(null, JobKind.Download, 100, null, f.Ct)).Items;