refactor(editor): the open sequence's jobs in their own type; restore undo as an object

WIP of the interrupted fix stage.

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-06 07:49:27 +00:00
1 parent 757695f037
commit 31c1a2d9c6
9 files changed
+356 -42

No files matched your search

@@ -41,6 +41,9 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
public Dictionary<Guid, JobDto> Jobs { get; } = [];
/// <summary>Thrown by the next read of a job (a failure the editor's event listener does not expect).</summary>
public Exception? FailNextJobRead { get; set; }
/// <summary>Someone else edits the settings before each of the next edits reaches the server (it is refused with 409).</summary>
public Queue<Func<string?, string>> EditsBefore { get; } = new();
@@ -116,6 +119,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
{
lock (_gate)
{
if (FailNextJobRead is { } failure)
{
FailNextJobRead = null;
throw failure;
}
return Jobs.TryGetValue(id, out var job)
? Task.FromResult(job)
: throw new TitanoApiException(HttpStatusCode.NotFound, new ApiError("not_found", "job", "job"));
@@ -271,6 +271,130 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
}
[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));
await WaitAsync(() => 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 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);
@@ -48,9 +48,9 @@ public sealed class SavedCopiesTests(TestContext context)
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.6 } });
var edited = session.Project;
Assert.True(await session.RestoreAsync(copy));
Assert.NotNull(await session.RestoreAsync(copy));
Assert.True(ProjectMerge.SameValues(kept, session.Project));
Assert.False(await session.RestoreAsync(copy), "the same values again change nothing");
Assert.Null(await session.RestoreAsync(copy), "the same values again change nothing");
await session.FlushAsync();
Assert.True(ProjectMerge.SameValues(kept, source.Stored), "the restored project is saved");
@@ -59,4 +59,33 @@ public sealed class SavedCopiesTests(TestContext context)
Assert.True(session.Undo());
Assert.True(ProjectMerge.SameValues(before, session.Project));
}
[Test]
public async Task TheUndoOfARestoreTakesBackOnlyTheRestore()
{
var meta = context.CreateTempDirectory("meta");
var path = Path.Combine(meta, "project.this-pc-20261003-142200.json");
File.WriteAllText(path, new ProjectSettings { Exposure = new ExposureSettings { ExposureOffsetEv = -0.3 } }.ToJson());
var copy = Assert.Contains(SavedCopies.List(meta), _ => true);
var content = EditorFixture.Content(EditorFixture.Sunset);
await using var session = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content), content, [], TimeSpan.FromMilliseconds(20));
session.Edit(p => p with { HeroFrame = 4 });
var before = session.Project;
var restore = Assert.NotNull(await session.RestoreAsync(copy));
Assert.True(restore.CanUndo);
Assert.True(restore.Undo());
Assert.True(ProjectMerge.SameValues(before, session.Project), "the project from before the restore");
Assert.False(restore.CanUndo, "taken back once");
Assert.True(session.Undo(), "the undo of the restore is a step of its own");
Assert.Equal(-0.3, session.Project.Exposure.ExposureOffsetEv);
// An edit after the restore: its Undo would take that edit back, so it no longer applies.
session.Edit(p => p with { HeroFrame = 5 });
restore = Assert.NotNull(await session.RestoreAsync(copy));
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.9 } });
Assert.False(restore.CanUndo);
Assert.False(restore.Undo());
Assert.Equal(0.9, session.Project.Exposure.ExposureOffsetEv);
}
}
@@ -0,0 +1,81 @@
using Titano.App.Editor;
using Titano.Core.Model;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>The jobs of the open sequence: the busy lock, Analyse queued twice, and the server job the header shows.</summary>
public sealed class SequenceJobsTests
{
private static readonly Guid Sunset = Guid.CreateVersion7();
[Test]
public void OnlyAnalysesAndRendersOfTheSequenceCount()
{
var jobs = new SequenceJobs(Sunset);
Assert.False(jobs.Track(Job(JobKind.Render, JobState.Running, Guid.CreateVersion7())), "another sequence");
Assert.False(jobs.Track(Job(JobKind.Proxies, JobState.Running)), "not an analysis or a render");
Assert.Null(jobs.Shown);
Assert.False(jobs.IsBusy);
}
[Test]
public void StatesChangeTheLockProgressAloneDoesNot()
{
var jobs = new SequenceJobs(Sunset);
var render = Job(JobKind.Render, JobState.Queued);
Assert.True(jobs.Track(render), "joined");
Assert.True(jobs.IsActive(render.Id));
Assert.False(jobs.IsBusy, "waiting does not lock the settings");
Assert.True(jobs.Track(render with { State = JobState.Running }), "started");
Assert.True(jobs.IsBusy);
Assert.False(jobs.Track(render with { State = JobState.Running, ProgressDone = 40, ProgressTotal = 96 }), "progress only");
Assert.Equal(40, jobs.Shown!.ProgressDone);
Assert.True(jobs.Track(render with { State = JobState.Paused }));
Assert.False(jobs.IsBusy, "a paused render holds nothing");
Assert.True(jobs.Track(render with { State = JobState.Failed }), "left");
Assert.False(jobs.IsActive(render.Id));
Assert.False(jobs.Track(render with { State = JobState.Failed }), "an ended job that is not tracked changes nothing");
}
[Test]
public void AnAnalysisWaitingOrPausedStillCountsAsQueued()
{
var jobs = new SequenceJobs(Sunset);
var analysis = Job(JobKind.DeepAnalyse, JobState.Paused);
jobs.Track(analysis);
Assert.True(jobs.IsAnalysing, "Analyse would queue a second one");
jobs.Track(analysis with { State = JobState.Done });
Assert.False(jobs.IsAnalysing);
}
[Test]
public void TheHeaderShowsTheRunningJobThenThePausedThenTheOldestWaiting()
{
var jobs = new SequenceJobs(Sunset);
var now = DateTimeOffset.UtcNow;
var later = Job(JobKind.Render, JobState.Queued) with { Created = now };
var first = Job(JobKind.Render, JobState.Queued) with { Created = now.AddMinutes(-5) };
var paused = Job(JobKind.DeepAnalyse, JobState.Paused) with { Created = now.AddMinutes(-9), Started = now.AddMinutes(-8) };
var running = Job(JobKind.Render, JobState.Running) with { Created = now.AddMinutes(-1), Started = now };
foreach (var job in new[] { later, first }) jobs.Track(job);
Assert.Equal(first.Id, jobs.Shown!.Id);
jobs.Track(paused);
Assert.Equal(paused.Id, jobs.Shown!.Id);
jobs.Track(running);
Assert.Equal(running.Id, jobs.Shown!.Id);
jobs.Track(running with { State = JobState.Done });
Assert.Equal(paused.Id, jobs.Shown!.Id);
}
private static Job Job(JobKind kind, JobState state, Guid? target = null) => new()
{
Id = Guid.CreateVersion7(),
Kind = kind,
TargetIds = [target ?? Sunset],
State = state,
Created = DateTimeOffset.UtcNow,
};
}
@@ -137,5 +137,34 @@ public sealed class RemoteEditingTests(TestContext context)
Assert.SequenceEqual(posted.Select(j => j.Id).Order(), queued.Where(j => j.Kind == JobKind.Render).Select(j => j.Id).Order());
}
[Test]
public async Task TheJobListFiltersByKindAndGoesOnPastThePage()
{
await using var server = await TestServer.StartAsync(context);
var (_, _, token) = await server.UserAsync("alberto", "editor");
using var client = Client(server, token);
var target = Guid.CreateVersion7();
var created = DateTimeOffset.UtcNow;
// Paused, so no worker claims them: a render of the editor's sequence behind a busy server's thumbnails.
Job Paused(JobKind kind, int age) => new()
{
Id = Guid.CreateVersion7(), Kind = kind, TargetIds = [target], State = JobState.Paused, Created = created.AddSeconds(-age),
};
var render = Paused(JobKind.Render, 300);
await server.Database.Jobs.EnqueueAsync(render);
for (var i = 0; i < 205; i++) await server.Database.Jobs.EnqueueAsync(Paused(JobKind.Thumbs, i));
var renders = await client.ListJobsAsync("paused", "render", null, context.Cancellation);
Assert.SequenceEqual([render.Id], renders.Items.Select(j => j.Id));
Assert.Null(renders.NextCursor);
var first = await client.ListJobsAsync("paused", null, null, context.Cancellation);
Assert.NotNull(first.NextCursor, "more than a page");
Assert.False(first.Items.Any(j => j.Id == render.Id), "the oldest job is past the first page");
var rest = await client.ListJobsAsync("paused", null, first.NextCursor, context.Cancellation);
Assert.Null(rest.NextCursor);
Assert.Equal(206, first.Items.Concat(rest.Items).Select(j => j.Id).Distinct().Count());
}
private static TitanoClient Client(TestServer server, string token) => new(server.HttpBase, new CertificatePinning([]), "tests") { Token = token };
}