merge: integration branch claude/keen-knuth-uhxv8w (remote editor after review) into the Library workstream

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 20:38:30 +00:00
commit a4ceb89247
81 files changed
+3827 -263

No files matched your search

+44 -1
View File
@@ -54,7 +54,7 @@ internal static class EditorFixture
};
var report = deep ? DeepAnalyzer.AnalyzeAsync(new Frames(sequence)).GetAwaiter().GetResult() : null;
return new SequenceContent(row, frames, project ?? new ProjectSettings(), LightAnalyzer.Analyze(frames), report, sequence.Options.Width,
sequence.Options.Height, null, []);
sequence.Options.Height, null, [], []);
}
/// <summary>Synthetic frames as the deep analysis reads them.</summary>
@@ -83,6 +83,21 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
public List<ArchiveJobRequest> Submitted { get; } = [];
/// <summary>A server sequence: renders become one job per preset.</summary>
public bool IsRemote { get; init; }
public bool IsReadOnly { get; set; }
public bool IsOutdated { get; private set; }
/// <summary>Jobs cancelled and retried through the source.</summary>
public List<Guid> Cancelled { get; } = [];
public List<Guid> Retried { get; } = [];
/// <summary>Jobs <see cref="ListJobsAsync"/> returns.</summary>
public List<Job> Jobs { get; } = [];
public int Saves { get; private set; }
public int Decodes { get; private set; }
@@ -128,5 +143,33 @@ internal sealed class FakeSequenceSource(SyntheticSequence sequence, SequenceCon
return Task.FromResult(Guid.CreateVersion7());
}
public event Action<Job>? JobChanged;
public event Action? ReadOnlyChanged;
/// <summary>The server's frames changed under the proxies (as a server sequence finds out).</summary>
public void MarkOutdated()
{
IsOutdated = IsReadOnly = true;
ReadOnlyChanged?.Invoke();
}
public Task CancelJobAsync(Guid jobId, CancellationToken cancellationToken)
{
Cancelled.Add(jobId);
return Task.CompletedTask;
}
public Task RetryJobAsync(Guid jobId, CancellationToken cancellationToken)
{
Retried.Add(jobId);
return Task.CompletedTask;
}
public Task<IReadOnlyList<Job>> ListJobsAsync(CancellationToken cancellationToken) => Task.FromResult<IReadOnlyList<Job>>([.. Jobs]);
/// <summary>A job of the sequence changed (as the engine or the server reports it).</summary>
public void Report(Job job) => JobChanged?.Invoke(job);
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
}
@@ -9,8 +9,12 @@ using Titano.App.Infrastructure;
using Titano.App.Sections;
using Titano.App.Shell;
using Titano.App.Tests.Windows;
using Titano.Core.Export;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Testing;
using Titano.Ui.Controls;
using Titano.Ui.Theming;
using Titano.Ui.Visuals;
@@ -139,6 +143,88 @@ public sealed class EditorSmokeTests
}
});
/// <summary>
/// A server sequence opened with this PC's proxies (the sample server's Sunrise over Superga): the header names the
/// server, the preview shows a proxy, Save to and Sync wait for the server, and Render posts a server job.
/// </summary>
[Test]
public Task AServerSequenceOpensWithItsProxies() => ScreenHost.RunAsync(async () =>
{
var environment = AppEnvironment.ForCapture();
UiLanguage.Apply("en");
ThemeManager.Apply(AppTheme.Dark);
var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
var sample = SampleData.Configure(services);
var shell = new ShellViewModel(services);
var window = new MainWindow(shell)
{
WindowStartupLocation = WindowStartupLocation.Manual,
Left = -20000,
Top = -20000,
Width = 1200,
Height = 788,
ShowActivated = false,
ShowInTaskbar = false,
};
window.Show();
try
{
await sample.OpenEmptyAsync();
await shell.StartAsync();
await sample.FillAsync();
await services.Server.RestoreAsync();
await services.Sync.RefreshAsync();
await sample.CacheProxiesAsync();
var id = sample.ProxiedSequenceId;
shell.OpenSequence(id);
await shell.Sequence.OpenAsync(id);
var editor = Assert.NotNull(shell.Sequence.Editor);
Assert.True(editor.IsRemote);
Assert.Equal("Studio NAS", editor.RemoteText);
Assert.Equal(3, editor.FrameCount);
Assert.True(await editor.WhenIdleAsync(TimeSpan.FromSeconds(60)), "the editor settled");
await SettleAsync(window);
Assert.NotNull(editor.PreviewImage, "the preview shows a proxy");
var view = Find<SequenceView>(window).Single(v => v.IsVisible);
Assert.True(Find<StatusGlyph>(view).Any(g => g is { Kind: StatusKind.Remote, IsVisible: true, Text: "Studio NAS" }), "the header names the server");
Assert.Greater(Distinct(Render(window)), 40, "the remote editor drew almost nothing");
var export = editor.Tabs.OfType<ExportTab>().Single();
editor.SelectedTab = export;
await SettleAsync(window);
Assert.Equal(ExportSyncGate.Remote, editor.SyncGate);
Assert.False(Find<CheckBox>(view).Single(c => ReferenceEquals(c.DataContext, export) && c.IsVisible).IsEnabled, "Sync: the server's renders stay there");
Assert.False(Find<ComboBox>(view).Single(c => ReferenceEquals(c.ItemsSource, export.SaveChoices)).IsEnabled, "Save to: the server's exports folder");
Assert.True(editor.CanRender, editor.RenderBlockedReason ?? "renderable");
await editor.RenderAsync(JobPriority.User, batch: false);
var queued = Assert.Contains(await editor.Session.Source.ListJobsAsync(CancellationToken.None), _ => true);
Assert.Equal(JobKind.Render, queued.Kind);
// Without the Edit right a server sequence is only shown: every change is disabled and says why.
var content = EditorFixture.Content(EditorFixture.Sunset);
var looking = new EditorSession(new FakeSequenceSource(EditorFixture.Sunset, content) { IsRemote = true, IsReadOnly = true }, content, []);
var viewer = new EditorViewModel(shell, looking, [], EncoderHost.Client);
await using (viewer)
{
Assert.False(viewer.IsEditable);
Assert.Equal(Loc.L("Tooltips.Editor.ReadOnly"), viewer.LockedToolTip);
Assert.Equal(Loc.L("Tooltips.Editor.ReadOnly"), viewer.Frames.HeroToolTip);
Assert.False(viewer.Frames.SetHeroCommand.CanExecute(null));
Assert.False(viewer.OptimiseAllCommand.CanExecute(null));
Assert.False(viewer.AnalyseCommand.CanExecute(null));
}
}
finally
{
window.Close();
await shell.Sequence.CloseAsync();
shell.Dispose();
await services.DisposeAsync();
environment.DeleteCaptureData();
}
});
/// <summary>The measuring tool of each section has content.</summary>
private static void ExpectMeasure(SequenceView view, EditorTab tab)
{
@@ -1,12 +1,13 @@
using Titano.App.Editor;
using Titano.Core.Advice;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>Composed texts of the editor, crop margins and the waveform monitor.</summary>
/// <summary>Composed texts of the editor (the conflict prompt among them), crop margins and the waveform monitor.</summary>
public sealed class EditorTextTests
{
static EditorTextTests() => _ = EditorFixture.Sunset;
@@ -67,4 +68,21 @@ public sealed class EditorTextTests
Assert.LessOrEqual(Math.Abs(lit[0] - (LumaWaveform.Levels - 1) / 2.0), 1.0, "half grey sits halfway up");
Assert.Equal(255, waveform.Density[lit[0] * waveform.Columns], "every pixel of the column there");
}
[Test]
public void TheConflictPromptSaysWhatDiffersAndTakesTheServersValuesUnlessAsked()
{
var basis = new ProjectSettings();
var mine = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.5 }, HeroFrame = 3 };
var theirs = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.3 } };
var conflict = new ProjectConflictException("changed", theirs, ProjectMerge.Conflicts(basis, mine, theirs));
var request = EditorViewModel.ConflictRequest(conflict, "Harbour sunset", "Studio NAS");
Assert.Equal(Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.ExposureOffset"), 0.5.ToString("0.###", Loc.Culture),
0.3.ToString("0.###", Loc.Culture)), request.Detail, "only the setting both changed; the editor's value first");
Assert.Equal(Loc.L("Server.Sync.Action.TakeServer"), request.SafeText, "the safe default loses nothing: Ctrl+Z brings the editor's values back");
Assert.Equal(Loc.L("Server.Sync.Action.KeepMine"), request.ActionText);
Assert.True(request.IsDestructive, "Keep mine overwrites the server's values");
Assert.Contains("Studio NAS", request.Heading);
}
}
@@ -0,0 +1,76 @@
using System.IO;
using Titano.App.Editor;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Processing;
using Titano.Data.Sync;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>Export "Sync" (Export.html): when it applies, how the project remembers it, and the send it queues after a render.</summary>
public sealed class ExportSyncTests(TestContext context)
{
private const string Server = "https://nas.test:8443";
[Test]
public void TheOptionSaysWhyItCannotBeUsed()
{
Assert.Equal(ExportSyncGate.Available, ExportSync.Gate(false, Server, linked: true, canUpload: true));
Assert.Equal(ExportSyncGate.Remote, ExportSync.Gate(true, Server, linked: true, canUpload: true));
Assert.Equal(ExportSyncGate.SignedOut, ExportSync.Gate(false, null, linked: false, canUpload: false));
Assert.Equal(ExportSyncGate.NotLinked, ExportSync.Gate(false, Server, linked: false, canUpload: true));
Assert.Equal(ExportSyncGate.NoUpload, ExportSync.Gate(false, Server, linked: true, canUpload: false));
}
[Test]
public void TheProjectRemembersTheChoiceAndOlderProjectsReadItOff()
{
Assert.False(new ProjectSettings().Export.SyncToServer, "renders travel on request");
Assert.False(ProjectSettings.FromJson("""{"export":{"nameTemplate":"{title}"}}""").Export.SyncToServer);
var chosen = new ProjectSettings { Export = new ExportSettings { SyncToServer = true } };
Assert.Contains("\"syncToServer\": true", chosen.ToJson());
Assert.True(ProjectSettings.FromJson(chosen.ToJson()).Export.SyncToServer);
}
[Test]
public async Task AFinishedRenderIsSentOnlyWhenAskedLinkedAndAllowed()
{
var directory = context.CreateTempDirectory("export-sync");
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(directory, "index.db")));
var archives = new ArchiveService(db, new ArchiveServiceOptions { Owner = "test" });
var archive = await archives.CreateAsync(Path.Combine(directory, "archive"), "Test");
var sequence = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = archive.Id, Title = "Harbour sunset", Folder = "Harbour", FrameCount = 1 };
await db.Sequences.UpsertAsync(sequence);
var sync = new SyncService(db, archives, new SyncOptions { ProxyCacheDirectory = Path.Combine(directory, "proxies") });
await using var engine = new JobEngine(db, [], new JobEngineOptions { WorkerId = "test" });
var exports = new ExportSync(db, sync, engine);
Job Render(bool syncToServer, JobState state = JobState.Done) => new()
{
Id = Guid.CreateVersion7(),
Kind = JobKind.Render,
TargetIds = [sequence.Id],
ParametersJson = ProcessingJobs.Render(sequence, new ExportSettings { SyncToServer = syncToServer }, 1920, 1080).ParametersJson,
State = state,
};
Assert.Equal(ExportSyncGate.NotLinked, (await exports.SendAsync(Render(true), Server, canUpload: true))?.Gate, "the server does not have the sequence");
await sync.LinkAsync(Server, Guid.CreateVersion7(), sequence.Id);
Assert.Null(await exports.SendAsync(Render(false), Server, canUpload: true), "the export did not ask for it");
Assert.Equal(ExportSyncGate.SignedOut, (await exports.SendAsync(Render(true), null, canUpload: true))?.Gate, "no session, saved or open");
Assert.Equal(ExportSyncGate.NoUpload, (await exports.SendAsync(Render(true), Server, canUpload: false))?.Gate, "no Upload right");
Assert.Null(await exports.SendAsync(Render(true, JobState.Failed), Server, canUpload: true), "nothing was rendered");
var result = Assert.NotNull(await exports.SendAsync(Render(true), Server, canUpload: true));
Assert.Equal(ExportSyncGate.Available, result.Gate);
var send = Assert.NotNull(result.Send);
Assert.Equal(JobKind.UploadCommit, send.Kind);
Assert.Equal(SyncTransferKind.SendExports, SyncService.TransferKind(send));
Assert.SequenceEqual([sequence.Id], send.TargetIds);
Assert.Equal(send.Id, (await exports.SendAsync(Render(true), Server, canUpload: true))?.Send?.Id, "a send already waiting takes the next render too");
}
}
@@ -0,0 +1,188 @@
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Channels;
using Titano.App.Editor;
using Titano.Core.Model;
using Titano.Protocol;
using Titano.Protocol.Client;
namespace Titano.App.Tests.Editor;
/// <summary>
/// One server sequence as the API serves it to an editor: its frames, settings with a version that refuses stale edits
/// (409), recorded edits and posted jobs (with their priority, cancel and retry), jobs other clients run, an analysis
/// report and an event stream the test feeds.
/// </summary>
internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Guid> frames) : IRemoteSequenceApi
{
private readonly Lock _gate = new();
private readonly 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;
public int FramesVersion { get; set; } = 1;
public string? SettingsJson { get; set; }
public int SettingsVersion { get; set; } = 3;
public string? Report { get; set; }
public bool Gone { get; set; }
/// <summary>Every edit the server accepted or refused, in order.</summary>
public List<(UpdateSequenceRequest Request, bool Accepted)> Edits { get; } = [];
public List<CreateJobRequest> Posted { get; } = [];
/// <summary>Priorities set after jobs were posted (job, wire name).</summary>
public List<(Guid Job, string Priority)> Priorities { get; } = [];
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>Thrown by the next edit before it reaches the server (the connection dropped).</summary>
public Exception? FailNextEdit { 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();
public bool Disposed { get; private set; }
/// <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 Task<SequenceDto> GetSequenceAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult(Dto(id));
}
public Task<SequenceManifest> GetManifestAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate)
{
Check(id);
return Task.FromResult(new SequenceManifest(id, FramesVersion, SettingsVersion, SettingsJson, [],
[.. Frames.Select((frame, i) => new ManifestFrame(frame, i, $"IMG_{i:0000}.JPG", 1_000, "00", true, true))], [
new RenderDto(Guid.CreateVersion7(), "4K archive", "hevc", 3840, 2160, 24, 5, 2_000_000_000, DateTimeOffset.UtcNow.AddDays(-1), "studio-pc"),
]));
}
}
public Task<SequenceDto> UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken)
{
lock (_gate)
{
Check(id);
if (FailNextEdit is { } failure)
{
FailNextEdit = null;
throw failure;
}
if (EditsBefore.TryDequeue(out var theirs))
{
SettingsJson = theirs(SettingsJson);
SettingsVersion++;
}
if (request.ExpectedSettingsVersion is { } expected && expected != SettingsVersion)
{
Edits.Add((request, false));
throw new TitanoApiException(HttpStatusCode.Conflict, new ApiError("settings_conflict", "changed", SettingsVersion.ToString()));
}
Edits.Add((request, true));
SettingsJson = request.SettingsJson ?? SettingsJson;
SettingsVersion++;
return Task.FromResult(Dto(id));
}
}
public Task<string?> GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken)
{
lock (_gate)
{
Check(id);
return Task.FromResult(Report);
}
}
public Task<JobDto> CreateJobAsync(CreateJobRequest request, CancellationToken cancellationToken)
{
lock (_gate)
{
Posted.Add(request);
var job = Job(Guid.CreateVersion7(), request.Kind, "queued", request.Target[0]);
Jobs[job.Id] = job;
return Task.FromResult(job);
}
}
public Task<JobDto> GetJobAsync(Guid id, CancellationToken cancellationToken)
{
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"));
}
}
public Task<IReadOnlyList<JobDto>> ListActiveJobsAsync(CancellationToken cancellationToken)
{
lock (_gate) return Task.FromResult<IReadOnlyList<JobDto>>([.. Jobs.Values.Where(j => j.State is "queued" or "running" or "paused")]);
}
public Task<JobDto> CancelJobAsync(Guid id, CancellationToken cancellationToken) =>
Change(id, job => job with { State = "cancelled", Finished = DateTimeOffset.UtcNow });
public Task<JobDto> RetryJobAsync(Guid id, CancellationToken cancellationToken) => Change(id, job => job with { State = "queued", Error = null, Finished = null });
public Task<JobDto> SetJobPriorityAsync(Guid id, string priority, CancellationToken cancellationToken)
{
lock (_gate) Priorities.Add((id, priority));
return Change(id, job => job with { Priority = priority });
}
public async IAsyncEnumerable<ServerEvent> EventsAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
while (await _events.Reader.WaitToReadAsync(cancellationToken))
{
while (_events.Reader.TryRead(out var e)) yield return e;
}
}
public void Dispose() => Disposed = true;
private SequenceDto Dto(Guid id)
{
Check(id);
return new SequenceDto(id, sequence.Title, sequence.DisplayTitle, sequence.Folder, sequence.CameraMake, sequence.CameraModel, null,
sequence.FirstCapture, sequence.LastCapture, sequence.FrameCount, sequence.MedianInterval, 0, (long)SequenceStatus.ProxiesBuilt, 1, null, [], 0,
null, SettingsVersion, 1, 0, null, DateTimeOffset.UtcNow);
}
private Task<JobDto> Change(Guid id, Func<JobDto, JobDto> change)
{
lock (_gate)
{
if (!Jobs.TryGetValue(id, out var job)) throw new TitanoApiException(HttpStatusCode.NotFound, new ApiError("not_found", "job", "job"));
return Task.FromResult(Jobs[id] = change(job));
}
}
private void Check(Guid id)
{
if (Gone || id != sequence.Id) throw new TitanoApiException(HttpStatusCode.NotFound, new ApiError("not_found", "gone", "sequence"));
}
}
@@ -101,6 +101,42 @@ public sealed class ProjectStoreTests(TestContext context)
}
}
[Test]
public async Task SetHeroReachesTheLibraryThumbnail()
{
var (db, sequenceId, root) = await ArchiveAsync(6);
await using (db)
{
await using var source = new LocalSequenceSource(db, sequenceId, DecoderFactory.CreateClient(null), null,
new ArchiveServiceOptions { Owner = "test", LeaseWait = TimeSpan.FromSeconds(20) });
var changed = new List<Sequence>();
source.HeroChanged += changed.Add;
var content = await source.LoadAsync(context.Cancellation);
var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
await using (session)
{
Assert.True(session.SetHero(4));
Assert.True(await session.FlushAsync());
Assert.Equal(content.Frames[4].Id, (await db.Sequences.GetAsync(sequenceId))!.HeroFrameId, "the index names the hero frame");
Assert.Equal(content.Frames[4].Id, Assert.Contains(changed, _ => true).HeroFrameId, "the Library is told");
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.2 } });
Assert.True(await session.FlushAsync());
Assert.Count(1, changed);
Assert.True(session.Undo());
Assert.True(session.Undo());
Assert.True(await session.FlushAsync());
Assert.Null((await db.Sequences.GetAsync(sequenceId))!.HeroFrameId, "undoing Set hero brings back the first frame");
Assert.Count(2, changed);
}
// "Save both" copies kept by a sync conflict are listed with the sequence.
File.WriteAllText(Path.Combine(root, "Synthetic", ".titano", "project.this-pc-20261003-142200.json"), new ProjectSettings().ToJson());
Assert.Equal(new DateTime(2026, 10, 3, 14, 22, 0), Assert.Contains((await source.LoadAsync(context.Cancellation)).SavedCopies, _ => true).SavedAt);
}
}
[Test]
public async Task ASaveThatDoesNotReachTheIndexThrows()
{
@@ -0,0 +1,559 @@
using System.IO;
using System.Net.Http;
using Titano.App.Editor;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Model;
using Titano.Core.Project;
using Titano.Data.Processing;
using Titano.Data.Sync;
using Titano.Protocol;
using Titano.Testing;
namespace Titano.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 session.FlushAsync());
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 session.FlushAsync());
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();
});
}
await Assert.ThrowsAsync<IOException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 2 }, content.Project, context.Cancellation));
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.
await Assert.ThrowsAsync<InvalidOperationException>(() =>
source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
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;
await Assert.ThrowsAsync<InvalidOperationException>(() => source.LoadAsync(context.Cancellation));
await Assert.ThrowsAsync<InvalidOperationException>(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation));
}
}
[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);
/// <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];
}
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");
}
}
@@ -0,0 +1,91 @@
using System.IO;
using Titano.App.Editor;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>"Save both" copies of this PC's settings: listed newest first and restored as one undoable step.</summary>
public sealed class SavedCopiesTests(TestContext context)
{
[Test]
public void CopiesAreListedNewestFirst()
{
var meta = context.CreateTempDirectory("meta");
File.WriteAllText(Path.Combine(meta, "project.this-pc-20261001-090000.json"), new ProjectSettings().ToJson());
File.WriteAllText(Path.Combine(meta, "project.this-pc-20261003-142200.json"), new ProjectSettings().ToJson());
File.WriteAllText(Path.Combine(meta, "project.json"), new ProjectSettings().ToJson());
File.WriteAllText(Path.Combine(meta, "analysis.json"), "{}");
var copies = SavedCopies.List(meta);
Assert.SequenceEqual([new DateTime(2026, 10, 3, 14, 22, 0), new DateTime(2026, 10, 1, 9, 0, 0)], copies.Select(c => c.SavedAt));
Assert.Empty(SavedCopies.List(Path.Combine(meta, "missing")));
}
[Test]
public void AnUnreadableCopyIsReported()
{
var meta = context.CreateTempDirectory("meta");
var path = Path.Combine(meta, "project.this-pc-20261003-142200.json");
File.WriteAllText(path, "{ not json");
Assert.Throws<InvalidDataException>(() => SavedCopies.Read(new SavedCopy(path, DateTime.Now)));
Assert.Throws<InvalidDataException>(() => SavedCopies.Read(new SavedCopy(Path.Combine(meta, "gone.json"), DateTime.Now)));
}
[Test]
public async Task RestoringACopyIsOneUndoableStep()
{
var meta = context.CreateTempDirectory("meta");
var kept = new ProjectSettings { HeroFrame = 7, Exposure = new ExposureSettings { ExposureOffsetEv = -0.3 } };
var path = Path.Combine(meta, "project.this-pc-20261003-142200.json");
File.WriteAllText(path, kept.ToJson());
var copy = Assert.Contains(SavedCopies.List(meta), _ => true);
var content = EditorFixture.Content(EditorFixture.Sunset) with { SavedCopies = [copy] };
var source = new FakeSequenceSource(EditorFixture.Sunset, content);
await using var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var before = session.Project;
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.6 } });
var edited = session.Project;
Assert.NotNull(await session.RestoreAsync(copy));
Assert.True(ProjectMerge.SameValues(kept, session.Project));
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");
Assert.True(session.Undo());
Assert.True(ProjectMerge.SameValues(edited, session.Project), "undo brings back the project before the restore");
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,
};
}