fix(app): exit stops the node and engine off the UI thread; node follows trust and hardware choices

AppServices disposal and archive polling no longer continue on the UI
thread that App.OnExit blocks, so exit stops everything instead of timing
out. The render node never starts in capture mode, restarts when a trusted
certificate or the hardware preference changes, and starts again after the
server refused it. Local renders apply Settings > Rendering hardware use.

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-02 23:16:23 +00:00
1 parent f7a1c158f4
commit e8dca63605
4 files changed
+186 -32

No files matched your search

+38 -19
View File
@@ -31,12 +31,17 @@ namespace Titano.App.Infrastructure;
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory and the
/// update check. Started after the window shows, stopped when the app exits. The last archive is reopened at start and
/// rescanned every <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers). The render node runs while
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open.
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open (never in capture
/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
/// (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread, which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
/// <summary>The quick preview preset: the one render "Hardware for previews only" leaves on the GPU.</summary>
private const string PreviewPresetId = "720p-preview";
private static readonly Lazy<HttpClient> Http = new(() => new HttpClient { Timeout = TimeSpan.FromSeconds(20) });
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
@@ -136,11 +141,18 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
/// <summary>Starts or stops the render node to match the opt-in and the server session (BRIEF §14.7).</summary>
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
public void UpdateRenderNode() =>
_renderNode.Update(Settings.RenderNodeOptIn && _server.IsConnected && Processing is not null && _server.Flow is { Address: { } address, Token: { } token }
? new RenderNodeSession(address, token)
: null);
_renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
_server.Flow.Address, _server.Flow.Token, _server.Fingerprints, AllowsHardware(Settings.HardwareEncoding, ExportResolver.CustomId)));
/// <summary>Settings › Rendering: whether a render of <paramref name="presetId"/> may use hardware encoders.</summary>
public static bool AllowsHardware(HardwarePreference preference, string presetId) => preference switch
{
HardwarePreference.PreferHardware => true,
HardwarePreference.HardwareForPreviews => presetId.Equals(PreviewPresetId, StringComparison.OrdinalIgnoreCase),
_ => false,
};
/// <summary>Opens (or creates) the index at <paramref name="databasePath"/>, migrates it and starts the job engine.</summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
@@ -169,33 +181,36 @@ public sealed class AppServices : IAsyncDisposable
Thumbnails = new ThumbnailService(database, Settings.ThumbnailMemoryItems);
}
/// <summary>Stops polling, the render node and the engine, then closes the index. The app's exit waits for this on the UI
/// thread, so nothing here continues on it.</summary>
public async ValueTask DisposeAsync()
{
await _stopping.CancelAsync();
await _polling;
await _stopping.CancelAsync().ConfigureAwait(false);
await _polling.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _renderNode.DisposeAsync();
await _renderNode.DisposeAsync().ConfigureAwait(false);
(Jobs as IDisposable)?.Dispose();
if (Engine is not null) await Engine.DisposeAsync();
if (Engine is not null) await Engine.DisposeAsync().ConfigureAwait(false);
Thumbnails?.Dispose();
Server.Dispose();
if (Database is not null) await Database.DisposeAsync();
if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false);
}
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically.</summary>
/// <summary>Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically,
/// off the UI thread (disposal waits for it there).</summary>
private async Task PollAsync(string root, CancellationToken ct)
{
try
{
if (Archives is null) return;
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct);
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
using var timer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct);
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
}
while (await timer.WaitForNextTickAsync(ct));
while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -222,12 +237,14 @@ public sealed class AppServices : IAsyncDisposable
UpdateRenderNode();
}
/// <summary>Media Foundation (hardware first, software H.264) then managed encoders; frames spill into the cache folder
/// within the memory budget of Settings › Rendering (Auto: a quarter of the installed memory).</summary>
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
/// encoders; frames spill into the cache folder within the memory budget of Settings › Rendering (Auto: a quarter of
/// the installed memory).</summary>
private ProcessingOptions ProcessingOptions(ArchiveServiceOptions archive) => new()
{
Archive = archive,
Encoders = [new MediaFoundationEncoderProvider(), new ManagedEncoderProvider()],
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
FrameWindow = new FrameWindowOptions
@@ -243,12 +260,12 @@ public sealed class AppServices : IAsyncDisposable
/// The render node of <paramref name="session"/>: this PC's encoders (Media Foundation, then managed), downloads and
/// outputs in the cache folder within its size limit.
/// </summary>
private IAsyncDisposable StartRenderNode(RenderNodeSession session)
private IRenderNode StartRenderNode(RenderNodeSession session)
{
var processing = Processing ?? throw new InvalidOperationException("The index is not open.");
var cache = CacheStore.Folder(Environment, Settings);
CacheStore.Prepare(cache);
var client = new TitanoClient(session.Address, new CertificatePinning(_server.Fingerprints), $"Titano ({System.Environment.MachineName})")
var client = new TitanoClient(session.Address, new CertificatePinning(session.TrustedFingerprints), $"Titano ({System.Environment.MachineName})")
{
Token = session.Token,
};
@@ -263,8 +280,10 @@ public sealed class AppServices : IAsyncDisposable
}
/// <summary>A started node and the client it owns.</summary>
private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IAsyncDisposable
private sealed class RunningNode(RenderNodeClient node, TitanoClient client) : IRenderNode
{
public Task Completion => node.Completion;
public async ValueTask DisposeAsync()
{
await node.DisposeAsync().ConfigureAwait(false);
@@ -2,20 +2,45 @@ using Titano.Core.Diagnostics;
namespace Titano.App.Infrastructure;
/// <summary>The server session a render node works for: a change of either value means another node.</summary>
public sealed record RenderNodeSession(Uri Address, string Token);
/// <summary>
/// What a render node runs with: the server session (address and token), the certificates it may trust and whether it
/// offers hardware encoders. A change of any of them means another node.
/// </summary>
public sealed record RenderNodeSession(Uri Address, string Token, IReadOnlyCollection<string> TrustedFingerprints, bool Hardware)
{
/// <summary>
/// The session a node should run for, or null when it should be off: the user offers this PC
/// (<paramref name="offered"/>), a server session is open and signed in.
/// </summary>
public static RenderNodeSession? For(bool offered, bool connected, Uri? address, string? token, IReadOnlyCollection<string> trustedFingerprints,
bool hardware) =>
offered && connected && address is not null && token is not null ? new RenderNodeSession(address, token, trustedFingerprints, hardware) : null;
public bool Equals(RenderNodeSession? other) =>
other is not null && Address == other.Address && Token == other.Token && Hardware == other.Hardware
&& TrustedFingerprints.Order(StringComparer.Ordinal).SequenceEqual(other.TrustedFingerprints.Order(StringComparer.Ordinal), StringComparer.Ordinal);
public override int GetHashCode() => HashCode.Combine(Address, Token, Hardware, TrustedFingerprints.Count);
}
/// <summary>A started render node.</summary>
public interface IRenderNode : IAsyncDisposable
{
/// <summary>Completes when the node has stopped, by itself (refused by the server) or when disposed.</summary>
Task Completion { get; }
}
/// <summary>
/// Keeps this PC's render node (BRIEF §14.7) in line with "Offer this PC as render node" and the server session:
/// <see cref="Update"/> starts the node for the wanted session, restarts it for another session and stops it when none
/// is wanted. Switches run one after the other, off the caller's thread, and never fail: a node that cannot start is
/// logged and stays off until the next update.
/// <see cref="Update"/> starts the node for the wanted session, restarts it for another session or when it stopped by
/// itself, and stops it when none is wanted. Switches run one after the other, off the caller's thread, and never fail:
/// a node that cannot start is logged and stays off until the next update.
/// </summary>
public sealed class RenderNodeHost(Func<RenderNodeSession, IAsyncDisposable> start) : IAsyncDisposable
public sealed class RenderNodeHost(Func<RenderNodeSession, IRenderNode> start) : IAsyncDisposable
{
private readonly Lock _gate = new();
private Task _switching = Task.CompletedTask;
private (RenderNodeSession Session, IAsyncDisposable Node)? _running;
private (RenderNodeSession Session, IRenderNode Node)? _running;
private bool _disposed;
/// <summary>The session the node runs for; null when it is off.</summary>
@@ -66,9 +91,10 @@ public sealed class RenderNodeHost(Func<RenderNodeSession, IAsyncDisposable> sta
private async Task SwitchAsync(RenderNodeSession? wanted)
{
(RenderNodeSession Session, IAsyncDisposable Node)? running;
(RenderNodeSession Session, IRenderNode Node)? running;
lock (_gate) running = _running;
if (running?.Session == wanted) return;
// A node the server refused has stopped by itself: the same session starts it again (the right may be granted now).
if (running?.Session == wanted && running?.Node.Completion.IsCompleted != true) return;
if (running is { } old)
{
lock (_gate) _running = null;