From 48d8158fd7b9b328e212724aa05bb0e59ec12e36 Mon Sep 17 00:00:00 2001 From: Alberto Balbo Date: Wed, 4 Nov 2026 12:54:46 +0100 Subject: [PATCH] fix(app): viewers open server sequences with proxies, the editor follows the sign-in An account without Edit is offered Open with proxies on a server that keeps projects and checks nothing out, since it could never push. The editor of a server's workspace project connects with the sign-in in use at each call, so a project opened signed out renders once signed in; SyncHost tells every session start and stop so workspace projects read their state again. Co-Authored-By: Claude Opus 5.5 --- src/Chronos.App/DesignTime/SampleData.cs | 5 +- .../Editor/WorkspaceSequenceSource.cs | 66 +++++++++++++++---- src/Chronos.App/Sections/SequenceViewModel.cs | 13 ++-- src/Chronos.App/Server/SyncHost.cs | 10 ++- src/Chronos.App/Server/SyncText.cs | 6 +- .../Chronos.App.Tests/Server/SyncHostTests.cs | 66 +++++++++++++++++++ .../Chronos.App.Tests/Server/SyncTextTests.cs | 4 +- .../Workspace/ServerHomeTests.cs | 19 +++++- 8 files changed, 165 insertions(+), 24 deletions(-) diff --git a/src/Chronos.App/DesignTime/SampleData.cs b/src/Chronos.App/DesignTime/SampleData.cs index d9832e4d..55b0072d 100644 --- a/src/Chronos.App/DesignTime/SampleData.cs +++ b/src/Chronos.App/DesignTime/SampleData.cs @@ -62,6 +62,9 @@ public sealed class SampleData private SampleData(AppServices services) => _services = services; + /// What the sample server says it can do (none: an older server, whose sequences open with proxies); tests set it. + public IReadOnlyList Capabilities { get; set; } = []; + /// The server-only sequence whose proxies keeps on this PC (Sunrise over Superga). public Guid ProxiedSequenceId => _sunrise; @@ -762,7 +765,7 @@ public sealed class SampleData { await Task.Delay(14, ct); if (!trusted.Contains(ServerFingerprint, StringComparer.OrdinalIgnoreCase)) throw new UntrustedCertificateException(ServerFingerprint); - return new ServerInfo("Studio NAS", "1.3.0", 1, [], ServerFingerprint, [], new ServerLimits(0, 0)); + return new ServerInfo("Studio NAS", "1.3.0", 1, sample.Capabilities, ServerFingerprint, [], new ServerLimits(0, 0)); } public Task LoginAsync(string username, string password, CancellationToken ct) diff --git a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs index 2dbbf536..549aed0d 100644 --- a/src/Chronos.App/Editor/WorkspaceSequenceSource.cs +++ b/src/Chronos.App/Editor/WorkspaceSequenceSource.cs @@ -32,11 +32,25 @@ public interface IProjectRenders } /// -/// A workspace project's home when it is a server (owner review 2, R8, phase 5b): the connection its analyses and renders -/// travel on, which the source owns; null while this PC is not signed in to that server (the project still opens from the -/// workspace, its jobs are refused saying so). +/// A workspace project's home when it is a server (owner review 2, R8, phase 5b): how the source connects for its analyses +/// and renders (: a connection the source owns, null while this PC is not signed in to that +/// server, when the project still opens from the workspace and its jobs are refused saying so), and the sign-in it would +/// connect with (): when that changes (signed in, out, or anew), the source connects again. /// -public sealed record WorkspaceServerHome(IRemoteSequenceApi? Api); +public sealed class WorkspaceServerHome(Func connect, Func session) +{ + /// One connection for good (null: never signed in), as a test or a capture holds it. + public WorkspaceServerHome(IRemoteSequenceApi? api) + : this(() => api, () => api) + { + } + + /// The sign-in would use now; compared by reference. + public object? Session => session(); + + /// A new connection of the current sign-in; null while signed out. + public IRemoteSequenceApi? Connect() => connect(); +} /// /// A workspace project open in the editor (owner review 2, R8: editing happens in the workspace, never inside the @@ -71,6 +85,9 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders private IRenderFrameSource? _frames; private IFrameSource? _pixels; private ServerJobs? _serverJobs; + private IRemoteSequenceApi? _api; + private object? _apiSession; + private bool _connected; private int _frameCount; private int _framesVersion = -1; private Guid[] _frameIds = []; @@ -273,12 +290,37 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders /// The server's jobs of the sequence, followed from now on; null while this PC is not signed in to the server. private ServerJobs? ServerJobsOf(Guid sequenceId, string title) { - if (_server?.Api is not { } api) return null; + if (Api() is not { } api) return null; + lock (_gate) + { + if (Volatile.Read(ref _disposed) == 1 || !ReferenceEquals(api, _api)) return null; + return _serverJobs ??= new ServerJobs(api, sequenceId, title, job => JobChanged?.Invoke(job)); + } + } + + /// + /// The connection of the sign-in in use now: made at first use, and again once the sign-in changed (the jobs followed + /// on the old one stop with it, so a project opened signed out renders once signed in); null while signed out. + /// + private IRemoteSequenceApi? Api() + { + if (_server is null) return null; + var session = _server.Session; + IRemoteSequenceApi? api, stale; + ServerJobs? staleJobs; lock (_gate) { if (Volatile.Read(ref _disposed) == 1) return null; - return _serverJobs ??= new ServerJobs(api, sequenceId, title, job => JobChanged?.Invoke(job)); + if (_connected && ReferenceEquals(session, _apiSession)) return _api; + (stale, staleJobs) = (_api, _serverJobs); + _serverJobs = null; + _api = api = _server.Connect(); + (_apiSession, _connected) = (session, true); } + // The jobs own their connection. + if (staleJobs is not null) _ = staleJobs.DisposeAsync().AsTask(); + else stale?.Dispose(); + return api; } /// The server's deep report when it describes these frames, else the copy the workspace took; whether one of another number of frames was read instead. @@ -325,7 +367,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders { if (Workspace is not { } workspace || MediaFramesVersion < 0) return false; if (_server is null) return await _db.Sequences.GetAsync(workspace.Home.SequenceId, cancellationToken) is { } row && row.FramesVersion != MediaFramesVersion; - if (_server.Api is not { } api) return false; + if (Api() is not { } api) return false; try { if ((await api.GetSequenceAsync(workspace.Home.SequenceId, cancellationToken)).FramesVersion != MediaFramesVersion) return true; @@ -463,7 +505,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders public async Task> ListJobsAsync(CancellationToken cancellationToken) { if (_server is null) return (await _db.Jobs.ListAsync(null, JobsListed, null, cancellationToken)).Items; - if (Volatile.Read(ref _serverJobs) is not { } jobs) return []; + if (Api() is null || Volatile.Read(ref _serverJobs) is not { } jobs) return []; try { return await jobs.ListAsync(cancellationToken); @@ -554,17 +596,18 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders if (_engine is not null) _engine.JobChanged -= OnJobChanged; List sources; ServerJobs? jobs; + IRemoteSequenceApi? api; lock (_gate) { sources = [.. _retired]; if (_frames is not null) sources.Add(_frames); _retired.Clear(); (_frames, _pixels) = (null, null); - (jobs, _serverJobs) = (_serverJobs, null); + (jobs, _serverJobs, api, _api) = (_serverJobs, null, _api, null); } // The server's connection is the source's: it closes with it, also when no read made the jobs' listener. if (jobs is not null) await jobs.DisposeAsync(); - else _server?.Api?.Dispose(); + else api?.Dispose(); foreach (var source in sources) { if (source is IAsyncDisposable disposable) await disposable.DisposeAsync(); @@ -574,8 +617,7 @@ public sealed class WorkspaceSequenceSource : ISequenceSource, IProjectRenders /// The server's jobs of the project's sequence, or why there are none. /// This PC is not signed in to the server of the project. private ServerJobs ServerJobsOrThrow() => - Volatile.Read(ref _serverJobs) - ?? (Workspace is { } workspace ? ServerJobsOf(workspace.Home.SequenceId, Project.ReadBundle().Sequence.Title ?? string.Empty) : null) + (Workspace is { } workspace ? ServerJobsOf(workspace.Home.SequenceId, Project.ReadBundle().Sequence.Title ?? string.Empty) : null) ?? throw new EditorException(Loc.L("Editor.Error.SignedOut")); /// diff --git a/src/Chronos.App/Sections/SequenceViewModel.cs b/src/Chronos.App/Sections/SequenceViewModel.cs index 17077732..dbc17373 100644 --- a/src/Chronos.App/Sections/SequenceViewModel.cs +++ b/src/Chronos.App/Sections/SequenceViewModel.cs @@ -726,12 +726,15 @@ public sealed class SequenceViewModel : SectionViewModel { TakeRequest(remoteId); workspace.Remember(remoteId, entry.ProjectId); - // Its analyses and renders travel on a connection of the signed-in session, when that is the project's server. - var api = string.Equals(sync.Server, entry.Home.Server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null; - return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, new WorkspaceServerHome(api)), - entry.SequenceTitle)); + // Its analyses and renders travel on a connection of the signed-in session, when that is the project's server: + // made again whenever the sign-in changes, so a project opened signed out renders once signed in. + var server = entry.Home.Server; + var editorHome = new WorkspaceServerHome(() => string.Equals(sync.Server, server, StringComparison.OrdinalIgnoreCase) ? sync.ConnectEditor() : null, + () => sync.Session); + return new ServerOpen((new WorkspaceSequenceSource(workspace.Sync, entry.ProjectId, db, decoder, services.Engine, editorHome), entry.SequenceTitle)); } - if (sync.ServerHome(remoteId) is not { } home) return null; + // An account that may not edit checks nothing out: it is shown with proxies, read-only, as on an older server. + if (!sync.Policy.CanEdit || sync.ServerHome(remoteId) is not { } home) return null; TakeRequest(remoteId); try { diff --git a/src/Chronos.App/Server/SyncHost.cs b/src/Chronos.App/Server/SyncHost.cs index 4bb5e7cc..c01162f2 100644 --- a/src/Chronos.App/Server/SyncHost.cs +++ b/src/Chronos.App/Server/SyncHost.cs @@ -100,7 +100,8 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo /// /// A project of a sequence of the signed-in server changed there (the server's key, and its projectChanged), or, - /// with null, changes may have been missed while its events were lost (any thread). + /// with null, changes may have been missed while its events were lost, or the session with that server started or + /// stopped (its projects become reachable, or offline) (any thread). /// public event Action? ProjectChanged; @@ -139,6 +140,9 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo engine.JobChanged += OnJobChanged; } + /// The sign-in uses now (another object once signed in anew); null while signed out. + public object? Session => Volatile.Read(ref _credentials); + /// A connection for the editor of a sequence of the signed-in server; null while signed out. public IRemoteSequenceApi? ConnectEditor() => Volatile.Read(ref _credentials) is { } c ? EditorFactory(c.Address, c.Token, c.Fingerprints) : null; @@ -260,7 +264,10 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo await previous.ConfigureAwait(false); if (Volatile.Read(ref _running) is { } running && wanted is { } same && running.Credentials.Address == same.Address && running.Credentials.Token == same.Token) return; + var stopped = Volatile.Read(ref _running)?.Remote.Server; await StopAsync().ConfigureAwait(false); + // The projects of the server left are offline now: their state is read again. + if (stopped is not null) ProjectChanged?.Invoke(stopped, null); if (wanted is not { } start || Service is not { } service) { Changed?.Invoke(); @@ -274,6 +281,7 @@ public sealed class SyncHost(AppServices services) : ISyncConnector, IAsyncDispo Volatile.Write(ref _running, new Running(agent, remote, start)); Log.Info("sync", $"Comparing with {remote.Server}"); Changed?.Invoke(); + ProjectChanged?.Invoke(remote.Server, null); } private async Task StopAsync() diff --git a/src/Chronos.App/Server/SyncText.cs b/src/Chronos.App/Server/SyncText.cs index cafaee5a..0f6cce9f 100644 --- a/src/Chronos.App/Server/SyncText.cs +++ b/src/Chronos.App/Server/SyncText.cs @@ -235,15 +235,15 @@ public static class SyncText actions.Add(SyncAction.Upload); break; // A server that keeps projects edits its sequences in the workspace; an older one's open with proxies, the - // workspace offered disabled with the reason (phase 5b). - case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly when rights.KeepsProjects: + // workspace offered disabled with the reason (phase 5b). An account that may not edit only looks: with proxies. + case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly when rights is { KeepsProjects: true, CanEdit: true }: actions.Add(SyncAction.OpenInWorkspace); if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals); break; case SyncStatus.RemoteOnly or SyncStatus.ProxiesOnly: actions.Add(SyncAction.OpenWithProxies); if (rights.CanFetchOriginals) actions.Add(SyncAction.DownloadOriginals); - actions.Add(SyncAction.OpenInWorkspace); + if (!rights.KeepsProjects) actions.Add(SyncAction.OpenInWorkspace); break; case SyncStatus.LocalAhead when entry.Link is { MissingRemote: > 0 }: if (rights.CanUpload) actions.Add(SyncAction.Upload); diff --git a/tests/Chronos.App.Tests/Server/SyncHostTests.cs b/tests/Chronos.App.Tests/Server/SyncHostTests.cs index b19f0780..68c0611e 100644 --- a/tests/Chronos.App.Tests/Server/SyncHostTests.cs +++ b/tests/Chronos.App.Tests/Server/SyncHostTests.cs @@ -1,7 +1,10 @@ +using System.Collections.Concurrent; using System.Diagnostics; using Chronos.App.DesignTime; using Chronos.App.Infrastructure; using Chronos.App.Tests.Uploader; +using Chronos.Data.Projects; +using Chronos.Protocol; using Chronos.Testing; namespace Chronos.App.Tests.Server; @@ -58,4 +61,67 @@ public sealed class SyncHostTests environment.DeleteCaptureData(); } } + + /// + /// Phase 5b glue: a server that keeps projects is the home of its sequences' workspace projects while signed in to it, + /// never another server's; each session start and stop is told as "changes may have been missed", so the workspace + /// reads its projects' state again (offline once signed out, reachable once signed in anew). + /// + [Test] + [WindowsOnly] + public void TheSignedInServerIsTheHomeOfItsProjectsAndEverySessionChangeIsTold() + { + var environment = AppEnvironment.ForCapture(); + try + { + SingleThreadedContext.Run(async () => + { + await using var services = new AppServices(environment, new AppSettings { Language = "en" }, () => { }, new NoDialogs()); + var sample = SampleData.Configure(services); + sample.Capabilities = [ServerCapabilities.Projects]; + await sample.OpenEmptyAsync(); + await sample.FillAsync(); + services.Settings.RenderNodeOptIn = false; + var told = new ConcurrentQueue<(string Server, ProjectChangedEvent? Change)>(); + services.Sync.ProjectChanged += (server, change) => told.Enqueue((server, change)); + var sequence = Guid.CreateVersion7(); + + await services.Server.RestoreAsync(); + await UntilAsync(() => services.Sync.Agent is not null && !told.IsEmpty, "session started and told"); + var server = Assert.NotNull(services.Sync.Server); + Assert.True(services.Sync.HasProjects, "the server keeps projects"); + var home = Assert.NotNull(services.Sync.ServerHome(sequence)); + var reached = (ServerProjectHome)Assert.NotNull(services.Sync.ProjectHome(home)); + Assert.Equal(sequence, reached.SequenceId); + Assert.Null(services.Sync.ProjectHome(home with { Server = "https://other.example:8443" })); + Assert.Same(reached.Client, ((ServerProjectHome)services.Sync.ProjectHome(home)!).Client); + + // Signed out: told again, and its projects have no home to reach (offline) until signed in anew. + var before = told.Count; + services.Server.Disconnect(); + await UntilAsync(() => told.Count > before && services.Sync.Agent is null, "session stop told"); + Assert.Null(services.Sync.ProjectHome(home)); + Assert.False(services.Sync.HasProjects); + before = told.Count; + await services.Server.RestoreAsync(); + await UntilAsync(() => told.Count > before && services.Sync.Agent is not null, "new session told"); + Assert.NotNull(services.Sync.ProjectHome(home)); + Assert.True(told.All(t => t.Server == server && t.Change is null), "only session changes were told"); + }); + } + finally + { + environment.DeleteCaptureData(); + } + } + + private static async Task UntilAsync(Func condition, string what) + { + var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(10)); + while (!condition()) + { + Assert.True(DateTime.UtcNow < until, what); + await Task.Delay(20); + } + } } diff --git a/tests/Chronos.App.Tests/Server/SyncTextTests.cs b/tests/Chronos.App.Tests/Server/SyncTextTests.cs index 8edd70d6..a3cfcc18 100644 --- a/tests/Chronos.App.Tests/Server/SyncTextTests.cs +++ b/tests/Chronos.App.Tests/Server/SyncTextTests.cs @@ -82,7 +82,9 @@ public sealed class SyncTextTests // Owner review 2, R8, phase 5b: the workspace replaces Open with proxies, and the originals can still come down. var projects = Editor with { KeepsProjects = true }; Assert.SequenceEqual([SyncAction.OpenInWorkspace, SyncAction.DownloadOriginals], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), projects)); - Assert.SequenceEqual([SyncAction.OpenInWorkspace], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer with { KeepsProjects = true })); + // An account that may not edit only looks, with proxies: it is offered no workspace copy it could not push. + Assert.SequenceEqual([SyncAction.OpenWithProxies], SyncText.Actions(Entry(SyncStatus.ProxiesOnly, local: null), Viewer with { KeepsProjects = true })); + Assert.SequenceEqual([SyncAction.OpenWithProxies], SyncText.Actions(Entry(SyncStatus.RemoteOnly, local: null), Viewer with { KeepsProjects = true })); Assert.True(SyncText.IsEnabled(SyncAction.OpenInWorkspace, projects), "a server that keeps projects opens them"); Assert.Equal(Loc.L("Tooltips.Server.Sync.OpenInWorkspace"), SyncText.ToolTip(Entry(SyncStatus.RemoteOnly, local: null), SyncAction.OpenInWorkspace, projects)); // An older server's row says why its workspace action is disabled; the other actions are not. diff --git a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs index 335dd7e8..82011cda 100644 --- a/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs +++ b/tests/Chronos.App.Tests/Workspace/ServerHomeTests.cs @@ -2,6 +2,7 @@ using System.Globalization; using System.Text.Json; using Chronos.App.Editor; using Chronos.App.Infrastructure; +using Chronos.App.Tests.Editor; using Chronos.App.Workspace; using Chronos.Core.Imaging.Decoders; using Chronos.Core.Localization; @@ -143,7 +144,10 @@ public sealed class ServerHomeTests(TestContext context) var told = new List(); host.HomeChanged += told.Add; - var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine, new WorkspaceServerHome(null)); + // Opened signed out; the sign-in made later is the one the source connects with. + FakeRemoteSequenceApi? signedIn = null; + var source = new WorkspaceSequenceSource(host.Sync, projectId, bed.Db, DecoderFactory.CreateClient(null), bed.Engine, + new WorkspaceServerHome(() => signedIn, () => signedIn)); var content = await source.LoadAsync(bed.Ct); var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20)); var ui = new RecordingUi(); @@ -160,6 +164,19 @@ public sealed class ServerHomeTests(TestContext context) Assert.Empty(await source.ListJobsAsync(bed.Ct)); var refused = await Assert.ThrowsAsync(() => source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct)); Assert.Equal(Loc.L("Editor.Error.SignedOut"), refused.Message); + // Signed in since: the render goes to the server on that sign-in's connection; signed in anew, on the new one's. + var first = new FakeRemoteSequenceApi(await bed.RowAsync(), []); + signedIn = first; + await source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct); + Assert.Equal(1, first.Posted.Count); + var second = new FakeRemoteSequenceApi(await bed.RowAsync(), []); + signedIn = second; + await source.SubmitAsync(session.RenderRequests(session.Project.Export)[0], bed.Ct); + Assert.Equal((1, 1), (first.Posted.Count, second.Posted.Count)); + var until = DateTime.UtcNow + TimeSpan.FromSeconds(TestTiming.Budget(10)); + while (!first.Disposed && DateTime.UtcNow < until) await Task.Delay(20, bed.Ct); + Assert.True(first.Disposed, "the old sign-in's connection closes"); + signedIn = null; // In step with the server: the render names the version it holds, whose settings the server renders. Assert.True(await menu.ReadyToRenderAsync(), "nothing to send");