From 31c1a2d9c6c4d1656a3bd79e66e99325aaf53492 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 6 Oct 2026 07:49:27 +0000 Subject: [PATCH] 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 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.App/Editor/EditorSession.cs | 20 ++- src/Titano.App/Editor/EditorViewModel.cs | 38 ++---- src/Titano.App/Editor/ExportTab.cs | 19 ++- src/Titano.App/Editor/SequenceJobs.cs | 46 +++++++ .../Editor/FakeRemoteSequenceApi.cs | 8 ++ .../Editor/RemoteSequenceSourceTests.cs | 124 ++++++++++++++++++ .../Editor/SavedCopiesTests.cs | 33 ++++- .../Editor/SequenceJobsTests.cs | 81 ++++++++++++ .../Api/RemoteEditingTests.cs | 29 ++++ 9 files changed, 356 insertions(+), 42 deletions(-) create mode 100644 src/Titano.App/Editor/SequenceJobs.cs create mode 100644 tests/Titano.App.Tests/Editor/SequenceJobsTests.cs diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs index 886e2440..daad9ac3 100644 --- a/src/Titano.App/Editor/EditorSession.cs +++ b/src/Titano.App/Editor/EditorSession.cs @@ -148,14 +148,16 @@ public sealed class EditorSession : IAsyncDisposable : [RenderRequest(export)]; /// - /// Makes a "Save both" copy of this PC's settings the project, as one undoable step; false when it stores the same values. + /// Makes a "Save both" copy of this PC's settings the project, as one undoable step; null when it stores the same values. /// + /// The restore, which its toast can take back while it is the last change. /// The copy cannot be read. - public async Task RestoreAsync(SavedCopy copy) + public async Task RestoreAsync(SavedCopy copy) { ArgumentNullException.ThrowIfNull(copy); var restored = await Task.Run(() => SavedCopies.Read(copy)); - return Edit(_ => restored); + var before = Project; + return Edit(_ => restored) ? new ProjectRestore(this, before, Project) : null; } /// The export of the project with preset chosen (own values, no batch). @@ -235,3 +237,15 @@ public sealed class EditorSession : IAsyncDisposable if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored)); } } + +/// +/// A "Save both" copy made the project (). Its Undo brings back the project from +/// before as a new step, and only while the restore is still the last change: after another edit, an undo or a merged +/// save it would take that change back instead. +/// +public sealed class ProjectRestore(EditorSession session, ProjectSettings before, ProjectSettings restored) +{ + public bool CanUndo => ReferenceEquals(session.Project, restored); + + public bool Undo() => CanUndo && session.Edit(_ => before); +} diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs index 975049ba..b717304e 100644 --- a/src/Titano.App/Editor/EditorViewModel.cs +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -40,7 +40,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable private readonly LatestRunner _corrections = new(Debounce); private readonly LatestRunner _plans = new(Debounce); private readonly DispatcherTimer _player; - private readonly Dictionary _jobs = []; + private readonly SequenceJobs _jobs; private readonly AsyncRelayCommand _analyse; private readonly AsyncRelayCommand _render; private readonly AsyncRelayCommand _cancelServerJob; @@ -83,6 +83,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable _encoders = encoders; _host = host; _dispatcher = Dispatcher.CurrentDispatcher; + _jobs = new SequenceJobs(session.Content.Sequence.Id); _renderer = new PreviewRenderer(session.Content, session.Source); Planner = new ExportPlanner(session.Content, encoders, host); _thumbnails = new EditorThumbnails(session.Source, session.Content.Count); @@ -181,10 +182,8 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable /// The Export "Sync" option: available, or why not. public ExportSyncGate SyncGate { get => _syncGate; private set => Set(ref _syncGate, value); } - /// The server job the header shows: one running, else one paused, else the oldest waiting. - private Job? ServerJob => IsRemote - ? _jobs.Values.OrderBy(j => j.State switch { JobState.Running => 0, JobState.Paused => 1, _ => 2 }).ThenBy(j => j.Started ?? j.Created).FirstOrDefault() - : null; + /// The server job the header shows (). + private Job? ServerJob => IsRemote ? _jobs.Shown : null; /// /// "3,600 frames · Canon EOS R5 · 2 s interval · 2 h 00 m · 3 warnings"; on the Export tab what the video will be: @@ -373,10 +372,10 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable public ExportPlan? Plan { get => _plan; private set => Set(ref _plan, value); } /// An analysis or render of this sequence is running: settings wait, viewing tools stay live. - public bool IsBusy => _jobs.Values.Any(j => j.State == JobState.Running); + public bool IsBusy => _jobs.IsBusy; /// A deep analysis of this sequence is queued, running or paused (Analyse would queue it twice). - public bool IsAnalysing => _jobs.Values.Any(j => j.Kind == JobKind.DeepAnalyse); + public bool IsAnalysing => _jobs.IsAnalysing; /// /// The project is shown, not changed: a server sequence for an account without the Edit right, or one whose frames @@ -573,7 +572,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable { await RefreshSyncGateAsync(); var jobs = await Session.Source.ListJobsAsync(CancellationToken.None); - foreach (var job in jobs) Track(job); + foreach (var job in jobs) _jobs.Track(job); foreach (var job in jobs.OrderBy(j => j.Finished)) LearnAnalysisSpeed(job); OnBusyChanged(); } @@ -875,13 +874,13 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable private void OnJobChanged(Job job) { - if (!Concerns(job)) return; + if (!_jobs.Concerns(job)) return; _dispatcher.BeginInvoke(() => { if (_disposed) return; - var wasActive = _jobs.ContainsKey(job.Id); + var wasActive = _jobs.IsActive(job.Id); // Progress alone (several times a second on a server) only moves the server job's text and bar. - if (Track(job)) OnBusyChanged(); + if (_jobs.Track(job)) OnBusyChanged(); else OnServerJobChanged(); LearnAnalysisSpeed(job); if (!wasActive) return; @@ -892,7 +891,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable /// /// The frames of the server sequence changed while it is open (any thread): everything that changes the project is - /// disabled and saying why, and a toast offers to fetch the proxies again. + /// disabled and says why, and a toast offers to fetch the proxies again. /// private void OnReadOnlyChanged() => _dispatcher.BeginInvoke(() => { @@ -951,21 +950,6 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable } } - /// An analysis or render of this sequence. - private bool Concerns(Job job) => - job.TargetIds.Contains(Session.Content.Sequence.Id) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render; - - /// Keeps the jobs of this sequence that wait, run or are paused. - /// Whether a job joined or left them or changed state (progress alone does not count). - private bool Track(Job job) - { - if (!Concerns(job)) return false; - if (job.State is not (JobState.Queued or JobState.Running or JobState.Paused)) return _jobs.Remove(job.Id); - var changed = !_jobs.TryGetValue(job.Id, out var known) || known.State != job.State; - _jobs[job.Id] = job; - return changed; - } - /// Seconds per frame of the latest finished deep analysis (any sequence): the cost Analyse announces. private void LearnAnalysisSpeed(Job job) { diff --git a/src/Titano.App/Editor/ExportTab.cs b/src/Titano.App/Editor/ExportTab.cs index 17e8cf69..ea37f3a6 100644 --- a/src/Titano.App/Editor/ExportTab.cs +++ b/src/Titano.App/Editor/ExportTab.cs @@ -563,31 +563,30 @@ public sealed class ExportTab : EditorTab private async Task RestoreAsync() { if (SelectedCopy is not { } copy) return; - var session = Editor.Session; - var before = session.Project; + ProjectRestore? restore; try { - if (!await session.RestoreAsync(copy)) - { - Editor.Shell.Notify(Loc.L("Editor.Copy.Same"), copy.Label); - return; - } + restore = await Editor.Session.RestoreAsync(copy); } catch (InvalidDataException ex) { Editor.Shell.ReportError(ex); return; } - var restored = session.Project; + if (restore is null) + { + Editor.Shell.Notify(Loc.L("Editor.Copy.Same"), copy.Label); + return; + } var editor = Editor; - bool Undoable() => ReferenceEquals(editor.Shell.Sequence.Editor, editor) && ReferenceEquals(session.Project, restored); editor.Shell.ShowToast(new Toast { Title = Loc.L("Editor.Copy.Restored"), Message = copy.Label, ActionText = Loc.L("Editor.Copy.Undo"), ActionToolTip = Loc.L("Tooltips.Editor.Copy.Undo"), - ActionCommand = new RelayCommand(() => session.Edit(_ => before), Undoable), + // Only in the editor that made it: another sequence opened meanwhile has its own project. + ActionCommand = new RelayCommand(() => restore.Undo(), () => ReferenceEquals(editor.Shell.Sequence.Editor, editor) && restore.CanUndo), }); } diff --git a/src/Titano.App/Editor/SequenceJobs.cs b/src/Titano.App/Editor/SequenceJobs.cs new file mode 100644 index 00000000..9707c2d1 --- /dev/null +++ b/src/Titano.App/Editor/SequenceJobs.cs @@ -0,0 +1,46 @@ +using Titano.Core.Model; + +namespace Titano.App.Editor; + +/// +/// The analyses and renders of the open sequence that wait, run or are paused, as the source reports them (BRIEF §12.3 +/// "while a job runs on this sequence, settings are disabled", §11.5): the editor's busy lock, whether Analyse would +/// queue a second analysis, and the server job the header of a server sequence shows. Call from one thread. +/// +public sealed class SequenceJobs(Guid sequenceId) +{ + private readonly Dictionary _active = []; + + /// An analysis or render runs: settings wait. + public bool IsBusy => _active.Values.Any(j => j.State == JobState.Running); + + /// A deep analysis waits, runs or is paused. + public bool IsAnalysing => _active.Values.Any(j => j.Kind == JobKind.DeepAnalyse); + + /// The job to show: one running, else one paused, else the oldest waiting; null when there is none. + public Job? Shown => _active.Values + .OrderBy(j => j.State switch { JobState.Running => 0, JobState.Paused => 1, _ => 2 }) + .ThenBy(j => j.Started ?? j.Created) + .FirstOrDefault(); + + /// An analysis or render of this sequence. + public bool Concerns(Job job) + { + ArgumentNullException.ThrowIfNull(job); + return job.TargetIds.Contains(sequenceId) && job.Kind is JobKind.DeepAnalyse or JobKind.LightAnalyse or JobKind.Render; + } + + /// The job is one of those that wait, run or are paused. + public bool IsActive(Guid jobId) => _active.ContainsKey(jobId); + + /// Takes in a job's new state. + /// Whether a job joined or left the active ones or changed state; progress alone does not count. + public bool Track(Job job) + { + if (!Concerns(job)) return false; + if (job.State is not (JobState.Queued or JobState.Running or JobState.Paused)) return _active.Remove(job.Id); + var changed = !_active.TryGetValue(job.Id, out var known) || known.State != job.State; + _active[job.Id] = job; + return changed; + } +} diff --git a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs index 11ef5dff..a94d87ad 100644 --- a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs +++ b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs @@ -41,6 +41,9 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList Jobs { get; } = []; + /// Thrown by the next read of a job (a failure the editor's event listener does not expect). + public Exception? FailNextJobRead { get; set; } + /// Someone else edits the settings before each of the next edits reaches the server (it is refused with 409). public Queue> EditsBefore { get; } = new(); @@ -116,6 +119,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList f.Id), Guid.CreateVersion7()]; + await Assert.ThrowsAsync(() => 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(() => 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(() => + source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation)); + await Assert.ThrowsAsync(() => + 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(() => + 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(); + 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(); + 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); diff --git a/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs b/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs index e3026fc0..836aec97 100644 --- a/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs +++ b/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs @@ -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); + } } diff --git a/tests/Titano.App.Tests/Editor/SequenceJobsTests.cs b/tests/Titano.App.Tests/Editor/SequenceJobsTests.cs new file mode 100644 index 00000000..845ed695 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/SequenceJobsTests.cs @@ -0,0 +1,81 @@ +using Titano.App.Editor; +using Titano.Core.Model; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +/// The jobs of the open sequence: the busy lock, Analyse queued twice, and the server job the header shows. +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, + }; +} diff --git a/tests/Titano.Server.Tests/Api/RemoteEditingTests.cs b/tests/Titano.Server.Tests/Api/RemoteEditingTests.cs index 26018cc8..90e1eb09 100644 --- a/tests/Titano.Server.Tests/Api/RemoteEditingTests.cs +++ b/tests/Titano.Server.Tests/Api/RemoteEditingTests.cs @@ -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 }; }