diff --git a/src/Titano.App/Editor/RemoteSequenceSource.cs b/src/Titano.App/Editor/RemoteSequenceSource.cs index a237f17e..b856f5ce 100644 --- a/src/Titano.App/Editor/RemoteSequenceSource.cs +++ b/src/Titano.App/Editor/RemoteSequenceSource.cs @@ -44,6 +44,7 @@ public sealed class RemoteSequenceSource : ISequenceSource private readonly Task _listening; private ProjectSettings? _stored; private int _version; + private int _disposed; public RemoteSequenceSource(RemoteSequence remote, IRemoteSequenceApi api, ImageDecoder decoder) { @@ -162,6 +163,7 @@ public sealed class RemoteSequenceSource : ISequenceSource public async ValueTask DisposeAsync() { + if (Interlocked.Exchange(ref _disposed, 1) == 1) return; await _stopping.CancelAsync(); await _listening; _stopping.Dispose(); diff --git a/src/Titano.Data/Sync/ProxyCache.cs b/src/Titano.Data/Sync/ProxyCache.cs index 09c3de2d..91d056b6 100644 --- a/src/Titano.Data/Sync/ProxyCache.cs +++ b/src/Titano.Data/Sync/ProxyCache.cs @@ -20,8 +20,10 @@ namespace Titano.Data.Sync; /// public sealed class RemoteSequence { - internal RemoteSequence(string server, Sequence sequence, IReadOnlyList frames, IReadOnlyList files) + /// Absolute path of each frame's proxy in frame order; null (and the frame flagged missing) when it is not cached. + public RemoteSequence(string server, Sequence sequence, IReadOnlyList frames, IReadOnlyList files) { + if (files.Count != frames.Count) throw new ArgumentException("One file entry per frame is required.", nameof(files)); Server = server; Sequence = sequence; Frames = frames; diff --git a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs index 1ff6d311..03a24d8a 100644 --- a/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorSmokeTests.cs @@ -9,8 +9,10 @@ using Titano.App.Infrastructure; using Titano.App.Sections; using Titano.App.Shell; using Titano.App.Tests.Windows; +using Titano.Core.Model; using Titano.Core.Project; using Titano.Testing; +using Titano.Ui.Controls; using Titano.Ui.Theming; using Titano.Ui.Visuals; @@ -138,6 +140,74 @@ public sealed class EditorSmokeTests } }); + /// + /// 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. + /// + [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(window).Single(v => v.IsVisible); + Assert.True(Find(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().Single(); + editor.SelectedTab = export; + await SettleAsync(window); + Assert.Equal(ExportSyncGate.Remote, editor.SyncGate); + Assert.False(Find(view).Single(c => ReferenceEquals(c.DataContext, export) && c.IsVisible).IsEnabled, "Sync: the server's renders stay there"); + Assert.False(Find(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); + } + finally + { + window.Close(); + await shell.Sequence.CloseAsync(); + shell.Dispose(); + await services.DisposeAsync(); + environment.DeleteCaptureData(); + } + }); + /// The measuring tool of each section has content. private static void ExpectMeasure(SequenceView view, EditorTab tab) { diff --git a/tests/Titano.App.Tests/Editor/ExportSyncTests.cs b/tests/Titano.App.Tests/Editor/ExportSyncTests.cs new file mode 100644 index 00000000..5d1646d1 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/ExportSyncTests.cs @@ -0,0 +1,74 @@ +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; + +/// Export "Sync" (Export.html): when it applies, how the project remembers it, and the send it queues after a render. +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.Null(await exports.SendAsync(Render(true), Server, canUpload: true), "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.Null(await exports.SendAsync(Render(true), null, canUpload: true), "signed out"); + Assert.Null(await exports.SendAsync(Render(true), Server, canUpload: false), "no Upload right"); + Assert.Null(await exports.SendAsync(Render(true, JobState.Failed), Server, canUpload: true), "nothing was rendered"); + + var send = Assert.NotNull(await exports.SendAsync(Render(true), Server, canUpload: true)); + 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))!.Id, "a send already waiting takes the next render too"); + } +} diff --git a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs new file mode 100644 index 00000000..29c6fc98 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs @@ -0,0 +1,142 @@ +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; + +/// +/// One server sequence as the API serves it to an editor: settings with a version that refuses stale edits (409), +/// recorded edits and posted jobs, jobs other clients run, an analysis report and an event stream the test feeds. +/// +internal sealed class FakeRemoteSequenceApi(Sequence sequence) : IRemoteSequenceApi +{ + private readonly Lock _gate = new(); + private readonly Channel _events = Channel.CreateUnbounded(); + + public string? SettingsJson { get; set; } + + public int SettingsVersion { get; set; } = 3; + + public string? Report { get; set; } + + public bool Gone { get; set; } + + /// Every edit the server accepted or refused, in order. + public List<(UpdateSequenceRequest Request, bool Accepted)> Edits { get; } = []; + + public List Posted { get; } = []; + + public Dictionary Jobs { get; } = []; + + /// Someone else edits the settings before each of the next edits reaches the server (it is refused with 409). + public Queue> EditsBefore { get; } = new(); + + public bool Disposed { get; private set; } + + /// A job of the server, as GET /jobs/{id} returns it. + 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 GetSequenceAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) return Task.FromResult(Dto(id)); + } + + public Task GetManifestAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) + { + Check(id); + return Task.FromResult(new SequenceManifest(id, 1, SettingsVersion, SettingsJson, [], [], [ + new RenderDto(Guid.CreateVersion7(), "4K archive", "hevc", 3840, 2160, 24, 5, 2_000_000_000, DateTimeOffset.UtcNow.AddDays(-1), "studio-pc"), + ])); + } + } + + public Task UpdateSequenceAsync(Guid id, UpdateSequenceRequest request, CancellationToken cancellationToken) + { + lock (_gate) + { + Check(id); + 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 GetAnalysisReportAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) + { + Check(id); + return Task.FromResult(Report); + } + } + + public Task 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 GetJobAsync(Guid id, CancellationToken cancellationToken) + { + lock (_gate) + { + return Jobs.TryGetValue(id, out var job) + ? Task.FromResult(job) + : throw new TitanoApiException(HttpStatusCode.NotFound, new ApiError("not_found", "job", "job")); + } + } + + public Task> ListActiveJobsAsync(CancellationToken cancellationToken) + { + lock (_gate) return Task.FromResult>([.. Jobs.Values.Where(j => j.State is "queued" or "running" or "paused")]); + } + + public async IAsyncEnumerable 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 void Check(Guid id) + { + if (Gone || id != sequence.Id) throw new TitanoApiException(HttpStatusCode.NotFound, new ApiError("not_found", "gone", "sequence")); + } +} diff --git a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs index 463ccef8..448c8e1d 100644 --- a/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs +++ b/tests/Titano.App.Tests/Editor/ProjectStoreTests.cs @@ -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(); + 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() { diff --git a/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs new file mode 100644 index 00000000..477fc3d7 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/RemoteSequenceSourceTests.cs @@ -0,0 +1,292 @@ +using System.IO; +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; + +/// +/// 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. +/// +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 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(() => 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 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().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(); + 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"); + } + 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(() => source.LoadAsync(context.Cancellation)); + await Assert.ThrowsAsync(() => source.SaveProjectAsync(content.Project with { HeroFrame = 1 }, content.Project, context.Cancellation)); + } + } + + private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(int frames = 6, int cached = int.MaxValue) => + Open(EditorFixture.Sequence(frames), cached); + + /// A server sequence whose first proxies are on this PC (synthetic JPEGs). + private (RemoteSequenceSource Source, FakeRemoteSequenceApi Api, RemoteSequence Remote) Open(SyntheticSequence sunset, int cached = int.MaxValue) + { + 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) { SettingsJson = new ProjectSettings().ToJson() }; + return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null)), api, remote); + } + + private static Job Last(List seen) + { + lock (seen) return seen[^1]; + } + + private static async Task WaitAsync(Func 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"); + } +} diff --git a/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs b/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs new file mode 100644 index 00000000..e3026fc0 --- /dev/null +++ b/tests/Titano.App.Tests/Editor/SavedCopiesTests.cs @@ -0,0 +1,62 @@ +using System.IO; +using Titano.App.Editor; +using Titano.Core.Project; +using Titano.Testing; + +namespace Titano.App.Tests.Editor; + +/// "Save both" copies of this PC's settings: listed newest first and restored as one undoable step. +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(() => SavedCopies.Read(new SavedCopy(path, DateTime.Now))); + Assert.Throws(() => 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.True(await session.RestoreAsync(copy)); + Assert.True(ProjectMerge.SameValues(kept, session.Project)); + Assert.False(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)); + } +}