From b344d2a527dc32016c69a339b4a7c367b896e353 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:02:15 +0000 Subject: [PATCH 1/8] fix(archive): polling follows the archive folder; the index follows an archive.json changed elsewhere MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The desktop's rescans run for the whole session and each one targets the archive at Settings › Archive's folder (as the Import and Archive screens do), so an archive created on the first run, chosen in Settings, relinked or imported with settings is rescanned from the next tick on, and Rescan every always reaches a live timer. The folder of the start is reopened (relink, interrupted renames) as soon as its archive.json is there, so an unplugged drive or a folder without an archive no longer stops polling for the session. - ArchiveService.RefreshSettingsAsync reads archive.json and registers the archive again when its name, templates or proxy size changed elsewhere (a server's admin panel, another PC); null when the file cannot be read, is newer or belongs to another archive. Desktop rescans and the server's polling call it first, so imports, uploads and the admin panel follow the shared settings without a restart. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.App/Infrastructure/AppServices.cs | 95 +++++++++++++++---- src/Titano.Data/Archiving/ArchiveService.cs | 50 ++++++++-- src/Titano.Server/Storage/ArchivePolling.cs | 8 +- .../Infrastructure/AppServicesTests.cs | 47 +++++++++ .../Archiving/ArchiveSettingsTests.cs | 33 +++++++ .../Storage/ArchiveModuleTests.cs | 22 +++++ 6 files changed, 224 insertions(+), 31 deletions(-) diff --git a/src/Titano.App/Infrastructure/AppServices.cs b/src/Titano.App/Infrastructure/AppServices.cs index 699422bf..d4f3c278 100644 --- a/src/Titano.App/Infrastructure/AppServices.cs +++ b/src/Titano.App/Infrastructure/AppServices.cs @@ -3,6 +3,7 @@ using System.IO; using System.Net.Http; using System.Reflection; using Titano.App.About; +using Titano.App.Archiving; using Titano.App.Import; using Titano.App.Jobs; using Titano.App.Library; @@ -32,13 +33,13 @@ namespace Titano.App.Infrastructure; /// managed encoders), the one of this PC with the handlers of , /// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync /// with the signed-in server (). Started after the window shows, stopped when the app exits. The -/// last archive is reopened at start and rescanned every (Settings › Archive; BRIEF §7: -/// polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the next one on (memory -/// budget, quality profile, analysis parameters through ; parallelism as the engine's -/// workers). The render node runs while the user offers this PC () and a -/// server session is open (never in capture mode). Renders and the render node use hardware encoders as Settings › -/// Rendering allows (). Disposal never needs the UI thread, -/// which waits for it. +/// archive at Settings › Archive's folder is reopened at start and rescanned every , as is one +/// chosen later (BRIEF §7: polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the +/// next one on (memory budget, quality profile, analysis parameters through ; parallelism +/// as the engine's workers). The render node runs while the user offers this PC () +/// and a server session is open (never in capture mode). Renders and the render node use hardware encoders as +/// Settings › Rendering allows (). Disposal never needs the UI +/// thread, which waits for it. /// public sealed class AppServices : IAsyncDisposable { @@ -228,7 +229,7 @@ public sealed class AppServices : IAsyncDisposable Devices.Start(); var database = Database; _backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token)); - if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token); + _polling = PollAsync(_stopping.Token); } /// Uses an already open index (capture, tests) instead of opening one; sample data keeps the engine stopped. @@ -258,35 +259,89 @@ public sealed class AppServices : IAsyncDisposable if (Database is not null) await Database.DisposeAsync().ConfigureAwait(false); } - /// Reopens the last archive (relinking a moved one, finishing interrupted renames) and rescans it periodically, - /// off the UI thread (disposal waits for it there). - private async Task PollAsync(string root, CancellationToken ct) + /// The period of the rescans while they run (Settings › Archive › Rescan every); null before the index opens. + internal TimeSpan? PollingPeriod => _pollTimer?.Period; + + /// + /// One rescan of the polling, off the UI thread: the archive the Import and Archive screens work on + /// (, the one at Settings › Archive's folder) first takes the settings another process + /// sharing it wrote into its archive.json (also on a read-only share), then gets an incremental scan while it is + /// online. Returns that archive; null when the index holds none. + /// + internal Task RescanAsync(CancellationToken ct = default) => Task.Run(async () => { + if (Database is not { } db || Archives is not { } archives) return null; + var archive = CurrentArchive.Pick(await db.Archives.ListAsync(ct).ConfigureAwait(false), Settings.LastArchivePath); + if (archive is null) return null; + var availability = ArchiveService.GetAvailability(archive); + if (availability != ArchiveAvailability.Offline) await archives.RefreshSettingsAsync(archive.Id, ct).ConfigureAwait(false); + if (availability == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false); + return archive; + }, ct); + + /// + /// Rescans the archive now and every () until the app exits, which + /// waits for it on the UI thread. Each rescan follows the archive folder: one chosen on the first run, in Settings or + /// by a relink is rescanned from the next tick on, the one before no longer. The archive at the folder of the start is + /// first reopened (a moved one relinked, interrupted renames finished), at each tick until its archive.json is there + /// (an unplugged drive), unless the folder changed meanwhile: whatever changed it opened the new archive. + /// + private async Task PollAsync(CancellationToken ct) + { + var reopen = Settings.LastArchivePath is { Length: > 0 } start ? start : null; + // Settings › Archive changes the period of this timer (ApplyJobSettings). + using var timer = _pollTimer = new PeriodicTimer(ScanInterval); try { - if (Archives is null) return; - var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false); - // Settings › Archive changes the period of this timer (ApplyJobSettings). - using var timer = _pollTimer = new PeriodicTimer(ScanInterval); do { - if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false); + if (reopen is not null + && (!string.Equals(reopen, Settings.LastArchivePath, StringComparison.OrdinalIgnoreCase) || await ReopenAsync(reopen, ct).ConfigureAwait(false))) + reopen = null; + try + { + await RescanAsync(ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or ArgumentException) + { + // The next tick tries again (a share that dropped, an archive removed from the index meanwhile). + Log.Warning("archive", "The archive could not be rescanned", ex); + } } while (await timer.WaitForNextTickAsync(ct).ConfigureAwait(false)); } catch (OperationCanceledException) when (ct.IsCancellationRequested) { } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException) - { - Log.Warning("archive", $"The archive at {root} could not be opened", ex); - } finally { _pollTimer = null; } } + /// + /// Registers the archive at again as at open; false while its archive.json is not there. A + /// damaged or newer one is not tried again: the archive the index holds at the folder is still rescanned. + /// + private async Task ReopenAsync(string root, CancellationToken ct) + { + if (Archives is not { } archives) return true; + try + { + return await Task.Run(async () => + { + if (!File.Exists(new ArchivePaths(root).ManifestPath)) return false; + await archives.OpenAsync(root, ct).ConfigureAwait(false); + return true; + }, ct).ConfigureAwait(false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException or NewerFormatException) + { + Log.Warning("archive", $"The archive at {root} could not be opened", ex); + return true; + } + } + /// /// A restore staged in Settings › Advanced replaces the index file before the index is opened, so it also recovers an /// index that no longer opens (). diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs index 562d9e42..ddd1fce3 100644 --- a/src/Titano.Data/Archiving/ArchiveService.cs +++ b/src/Titano.Data/Archiving/ArchiveService.cs @@ -147,17 +147,31 @@ public sealed class ArchiveService : IJobHandlerProvider public async Task GetSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default) { var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false); - var paths = new ArchivePaths(archive.RootPath); - try + return TryReadManifest(archive) is { } manifest + ? ArchiveSettings.Of(manifest) + : new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate }, + new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy()); + } + + /// + /// The settings in the archive's archive.json, with its index row brought up to them when another process + /// sharing the archive changed the file (a server's admin panel, another PC's Settings): imports and uploads take their + /// templates and proxy size from that row. Null while the file cannot be read (offline, damaged, newer, of another + /// archive): the row stays as it is, and only 's stand-ins are known. + /// + public async Task RefreshSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default) + { + var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false); + if (TryReadManifest(archive) is not { } manifest) return null; + if (manifest.Name != archive.Name || manifest.LayoutTemplates.Folder != archive.FolderTemplate || manifest.LayoutTemplates.File != archive.FileTemplate + || manifest.ProxyPolicy.LongEdge != archive.ProxyLongEdge) { - if (File.Exists(paths.ManifestPath)) return ArchiveSettings.Of(ManifestStore.ReadArchive(paths.ManifestPath)); + // Read without the settings lease, as at open: an edit made meanwhile writes its own row, and the next refresh + // settles a file that changes again. + await RegisterAsync(new ArchivePaths(archive.RootPath), manifest, cancellationToken).ConfigureAwait(false); + Log.Info("archive", $"Settings of {archive.RootPath} changed elsewhere: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}"); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) - { - Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex); - } - return new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate }, - new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy()); + return ArchiveSettings.Of(manifest); } /// @@ -325,6 +339,24 @@ public sealed class ArchiveService : IJobHandlerProvider return archive; } + /// The archive's archive.json; null (logged) while it cannot be read or when it belongs to another archive. + private static ArchiveManifest? TryReadManifest(Archive archive) + { + var paths = new ArchivePaths(archive.RootPath); + try + { + if (!File.Exists(paths.ManifestPath)) return null; + var manifest = ManifestStore.ReadArchive(paths.ManifestPath); + if (manifest.Id == archive.Id) return manifest; + Log.Warning("archive", $"{paths.ManifestPath} belongs to archive {manifest.Id}, not {archive.Id}; the index's settings are used"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) + { + Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex); + } + return null; + } + private async Task LoadArchiveAsync(Guid archiveId, CancellationToken cancellationToken) => await _db.Archives.GetAsync(archiveId, cancellationToken).ConfigureAwait(false) ?? throw new ArgumentException($"Unknown archive {archiveId}.", nameof(archiveId)); diff --git a/src/Titano.Server/Storage/ArchivePolling.cs b/src/Titano.Server/Storage/ArchivePolling.cs index fe5bb2e4..739d6451 100644 --- a/src/Titano.Server/Storage/ArchivePolling.cs +++ b/src/Titano.Server/Storage/ArchivePolling.cs @@ -10,9 +10,11 @@ namespace Titano.Server.Storage; /// Polls the archive (BRIEF §7: by modification time and size, no file-system watchers): an incremental scan at start /// and every while the archive is online, so photos already in an adopted folder and sequences /// another writer adds (a desktop sharing the archive, files copied in by hand) are indexed without an administrator's -/// rescan. A scan or rebuild of the archive that is waiting, running or paused is not queued again. +/// rescan. Settings such a writer changed in archive.json reach the index first, so uploads and the admin panel follow +/// them. A scan or rebuild of the archive that is waiting, running or paused is not queued again. /// -public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, JobEngineHost jobs, TimeProvider time, ILogger logger) +public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, ArchiveService archives, JobEngineHost jobs, TimeProvider time, + ILogger logger) : BackgroundService { /// The desktop's rhythm (it polls its archive the same way). @@ -26,6 +28,8 @@ public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, Job if (!jobs.CanRun(JobKind.Scan)) return null; var current = archive.Current; if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null; + if (await archives.RefreshSettingsAsync(current.Id, cancellationToken) is not null && await db.Archives.GetAsync(current.Id, cancellationToken) is { } row) + archive.Current = current = row; foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild }) { foreach (var state in Pending) diff --git a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs index 7d442036..187a40b0 100644 --- a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs +++ b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs @@ -51,6 +51,53 @@ public sealed class AppServicesTests } } + /// BRIEF §7: polling follows the archive folder, also one chosen after the start (first run, Settings, relink). + [Test] + [WindowsOnly] + public void RescansFollowTheArchiveFolderChosenAfterTheStart() + { + var environment = AppEnvironment.ForCapture(); + try + { + SingleThreadedContext.Run(async () => + { + // The first run: the index opens before any archive folder is set. + var settings = new AppSettings { Language = "en" }; + var services = new AppServices(environment, settings, () => { }, new NoDialogs()); + try + { + await services.OpenAsync(environment.DatabasePath); + Assert.Null(await services.RescanAsync()); + // The rescans run all the same: Settings › Archive › Rescan every reaches them. + settings.ScanIntervalMinutes = 30; + services.SaveSettings(); + Assert.Equal(TimeSpan.FromMinutes(30), services.PollingPeriod); + + // The first-run dialog creates an archive: the next rescan is of it. + await services.ArchiveSetup.CreateAsync(Path.Combine(environment.DataDirectory, "first")); + Assert.Equal("first", (await services.RescanAsync())?.Name); + + // Settings › Archive moves to another archive: the next rescan is of that one, no longer of the first. + var second = Path.Combine(environment.DataDirectory, "second"); + await new ArchiveService(services.Database!).CreateAsync(second, "Second"); + settings.LastArchivePath = second; + services.SaveSettings(); + var rescanned = Assert.NotNull(await services.RescanAsync()); + Assert.Equal("Second", rescanned.Name); + Assert.Contains((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items, j => j.TargetIds.Contains(rescanned.Id)); + } + finally + { + Assert.True(services.DisposeAsync().AsTask().Wait(TimeSpan.FromSeconds(10)), "services stopped"); + } + }); + } + finally + { + environment.DeleteCaptureData(); + } + } + /// BRIEF §6.2: a restore staged in Settings › Advanced recovers an index that no longer opens. [Test] [WindowsOnly] diff --git a/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs b/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs index 258b2bd7..fe5ab3bb 100644 --- a/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs +++ b/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs @@ -114,6 +114,39 @@ public sealed class ArchiveSettingsTests(TestContext context) fx.Service.UpdateSettingsAsync(fx.Archive.Id, s => s with { Proxies = s.Proxies with { LongEdge = 2560 } }, fx.Ct)); var shown = await fx.Service.GetSettingsAsync(fx.Archive.Id, fx.Ct); Assert.Equal((1280, FrameImageRenderer.ThumbnailLongEdge), (shown.Proxies.LongEdge, shown.Thumbnails.LongEdge)); + // A refresh reports that only the index's stand-ins are known: the thumbnail size above is not the archive's. + Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); + } + + [Test] + public async Task ARefreshBringsTheIndexUpToSettingsChangedElsewhere() + { + await using var fx = await ArchiveFixture.CreateAsync(context); + // Another process sharing the archive (a server's admin panel) changed archive.json: this index still has the old row. + var manifest = ManifestStore.ReadArchive(fx.Paths.ManifestPath); + ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with + { + Name = "Shared", + LayoutTemplates = manifest.LayoutTemplates with { Folder = "{year}/{camera}" }, + ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 }, + ThumbnailPolicy = manifest.ThumbnailPolicy with { LongEdge = 480 }, + }); + Assert.Equal(fx.Archive.FolderTemplate, (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.FolderTemplate); + + var settings = Assert.NotNull(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); + Assert.Equal(("{year}/{camera}", 2560, 480), (settings.Templates.Folder, settings.Proxies.LongEdge, settings.Thumbnails.LongEdge)); + var row = (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!; + Assert.Equal(("Shared", "{year}/{camera}", 2560), (row.Name, row.FolderTemplate, row.ProxyLongEdge)); + + // The drive is unplugged: nothing is known beyond the index, which stays as it is. + File.Move(fx.Paths.ManifestPath, fx.Paths.ManifestPath + ".away"); + Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); + Assert.Equal("{year}/{camera}", (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.FolderTemplate); + + // The folder now holds another archive: its settings are neither shown nor registered as this one's. + ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { Id = Guid.CreateVersion7(), Name = "Other" }); + Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); + Assert.Equal("Shared", (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.Name); } [Test] diff --git a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs index 9112850f..68520d42 100644 --- a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs +++ b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs @@ -102,6 +102,28 @@ public sealed class ArchiveModuleTests(TestContext context) await UntilIndexedAsync(server, archive.Id, "garden"); } + [Test] + public async Task SettingsADesktopChangedInArchiveJsonReachTheServerAtTheNextPoll() + { + await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); + var archive = server.Services.GetRequiredService(); + // A desktop sharing the archive changed its folder template and proxy size in archive.json. + var path = new ArchivePaths(archive.Root).ManifestPath; + var manifest = ManifestStore.ReadArchive(path); + ManifestStore.WriteArchive(path, manifest with + { + LayoutTemplates = manifest.LayoutTemplates with { Folder = "{camera}/{date}" }, + ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 }, + }); + + await server.Services.GetRequiredService().PollAsync(context.Cancellation); + + // Uploads (the index row) and the admin panel (the served archive) follow it. + Assert.Equal(("{camera}/{date}", 2560), (archive.Current.FolderTemplate, archive.Current.ProxyLongEdge)); + var row = Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, context.Cancellation)); + Assert.Equal(("{camera}/{date}", 2560), (row.FolderTemplate, row.ProxyLongEdge)); + } + private static async Task UntilIndexedAsync(TestServer server, Guid archiveId, string folder) { var until = DateTime.UtcNow + TimeSpan.FromSeconds(30); From 8eaaef508535fd8ca029e7f6de81b4153586cfe2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:02:23 +0000 Subject: [PATCH 2/8] fix(startup): Start with Windows honours an entry Task Manager turned off Task Manager's Startup tab keeps the Run value and writes a StartupApproved\Run value whose odd first byte means off. The client and the Uploader now show such an entry as off; ticking the box removes the marker so the entry runs again, unticking removes it with the Run value, and re-pointing the command after an update leaves it as it is. Core/IO/StartupApproval holds the rule; the registry hive is injectable for tests. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- .../Infrastructure/StartWithWindows.cs | 80 +++++++++++++---- src/Titano.Core/IO/StartupApproval.cs | 16 ++++ .../Infrastructure/StartupRegistration.cs | 75 +++++++++------- .../Infrastructure/StartWithWindowsTests.cs | 86 +++++++++++++++++++ .../Foundation/StartupApprovalTests.cs | 21 +++++ 5 files changed, 231 insertions(+), 47 deletions(-) create mode 100644 src/Titano.Core/IO/StartupApproval.cs create mode 100644 tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs diff --git a/src/Titano.App/Infrastructure/StartWithWindows.cs b/src/Titano.App/Infrastructure/StartWithWindows.cs index 1140c26c..72e54c2f 100644 --- a/src/Titano.App/Infrastructure/StartWithWindows.cs +++ b/src/Titano.App/Infrastructure/StartWithWindows.cs @@ -20,37 +20,48 @@ public interface IStartWithWindows /// /// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts Titano minimised at sign-in, so inserted /// cards are noticed (BRIEF §12.4) without a window in the way. The registry stays the source of truth because Task -/// Manager can turn it off. There is one value for every copy of Titano: a copy shows it as on only when it starts -/// that copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller -/// removes it with the Uploader's when it starts a program of the folder it removes. +/// Manager can turn it off: an entry it turned off () shows as off, and ticking the box +/// turns it on again. There is one value for every copy of Titano: a copy shows it as on only when it starts that +/// copy, and never takes it over or removes it unless the user ticks or unticks the box there. The uninstaller removes +/// it with the Uploader's when it starts a program of the folder it removes. /// -public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWithWindows +/// This copy's program; the running one by default. +/// The registry hive holding the entries; HKEY_CURRENT_USER by default (tests pass a scratch key). +public sealed class RunKeyStartWithWindows(string? executable = null, RegistryKey? root = null) : IStartWithWindows { /// Starts the main window minimised on the taskbar. public const string MinimizedOption = "--minimized"; private readonly string? _executable = executable ?? Environment.ProcessPath; + private readonly RegistryKey _root = root ?? Registry.CurrentUser; - public bool IsEnabled => StartupCommand.Starts(Read(), _executable); + /// The entry starts this copy and Task Manager has not turned it off. + public bool IsEnabled => StartupCommand.Starts(Read(), _executable) && !StartupApproval.IsTurnedOff(ReadApproval()); public void SetEnabled(bool enabled) { - if (_executable is null) return; - try + if (_executable is not { } executable) return; + Update(key => { - using var key = Registry.CurrentUser.CreateSubKey(StartupCommand.RunKey, writable: true); - if (enabled) key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(_executable, MinimizedOption), RegistryValueKind.String); - else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, _executable)) key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false); - } - catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) - { - Log.Warning("startup", "Run key not updated", ex); - } + if (enabled) + { + key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String); + // Task Manager's "Disable" outlives a new command: ticking the box undoes it. + DeleteApproval(); + } + else if (StartupCommand.Starts(key.GetValue(StartupCommand.ClientValue) as string, executable)) + { + key.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false); + DeleteApproval(); + } + }); } + /// The command follows a renamed program; an entry Task Manager turned off stays off. public void Refresh() { - if (Follows(Read(), _executable, File.Exists)) SetEnabled(true); + if (_executable is { } executable && Follows(Read(), executable, File.Exists)) + Update(key => key.SetValue(StartupCommand.ClientValue, StartupCommand.Format(executable, MinimizedOption), RegistryValueKind.String)); } /// @@ -65,11 +76,11 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi && string.Equals(StartupCommand.Folder(command), folder, StringComparison.OrdinalIgnoreCase); } - private static string? Read() + private string? Read() { try { - using var key = Registry.CurrentUser.OpenSubKey(StartupCommand.RunKey); + using var key = _root.OpenSubKey(StartupCommand.RunKey); return key?.GetValue(StartupCommand.ClientValue) as string; } catch (Exception ex) when (ex is SecurityException or IOException) @@ -77,6 +88,39 @@ public sealed class RunKeyStartWithWindows(string? executable = null) : IStartWi return null; } } + + /// Task Manager's switch for the entry; null when it never touched it. + private byte[]? ReadApproval() + { + try + { + using var key = _root.OpenSubKey(StartupApproval.RunKey); + return key?.GetValue(StartupCommand.ClientValue) as byte[]; + } + catch (Exception ex) when (ex is SecurityException or IOException) + { + return null; + } + } + + private void DeleteApproval() + { + using var key = _root.OpenSubKey(StartupApproval.RunKey, writable: true); + key?.DeleteValue(StartupCommand.ClientValue, throwOnMissingValue: false); + } + + private void Update(Action change) + { + try + { + using var key = _root.CreateSubKey(StartupCommand.RunKey, writable: true); + change(key); + } + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) + { + Log.Warning("startup", "Run key not updated", ex); + } + } } /// Screenshots, tests and portable copies (which leave nothing in the registry) never touch the user's sign-in programs. diff --git a/src/Titano.Core/IO/StartupApproval.cs b/src/Titano.Core/IO/StartupApproval.cs new file mode 100644 index 00000000..8d1eae74 --- /dev/null +++ b/src/Titano.Core/IO/StartupApproval.cs @@ -0,0 +1,16 @@ +namespace Titano.Core.IO; + +/// +/// Whether Windows runs a sign-in entry (). Task Manager's Startup tab and Settings › Apps › +/// Startup turn an entry off without touching its Run value: they write a binary value of the same name under +/// whose first byte is odd while the entry is off (0x03) and even once it is on again (0x02). An +/// entry without that value is on. Rewriting the Run value leaves it as it is, so turning an entry back on means +/// removing it. +/// +public static class StartupApproval +{ + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run"; + + /// The entry is turned off according to its StartupApproved (null when it has none). + public static bool IsTurnedOff(byte[]? state) => state is { Length: > 0 } && (state[0] & 1) != 0; +} diff --git a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs index 4badfff3..ed5eedee 100644 --- a/src/Titano.Uploader/Infrastructure/StartupRegistration.cs +++ b/src/Titano.Uploader/Infrastructure/StartupRegistration.cs @@ -1,3 +1,4 @@ +using System.IO; using System.Security; using Microsoft.Win32; using Titano.Core.Diagnostics; @@ -15,49 +16,65 @@ public interface IStartupRegistration /// /// HKCU\Software\Microsoft\Windows\CurrentVersion\Run value that starts the uploader in the tray at sign-in. -/// The registry stays the source of truth because Task Manager can turn it off. Uninstalling removes the value when -/// it starts the Uploader the uninstaller removes ( names it for both). +/// The registry stays the source of truth because Task Manager can turn it off: an entry it turned off +/// () shows as off, and ticking the box turns it on again. Uninstalling removes the value +/// when it starts the Uploader the uninstaller removes ( names it for both). /// -public sealed class RunKeyStartupRegistration : IStartupRegistration +/// The Uploader's program; the running one by default. +/// The registry hive holding the entries; HKEY_CURRENT_USER by default (tests pass a scratch key). +public sealed class RunKeyStartupRegistration(string? executable = null, RegistryKey? root = null) : IStartupRegistration { private const string RunKey = StartupCommand.RunKey; private const string ValueName = StartupCommand.UploaderValue; - public bool IsEnabled + private readonly string? _executable = executable ?? Environment.ProcessPath; + private readonly RegistryKey _root = root ?? Registry.CurrentUser; + + /// The entry exists and Task Manager has not turned it off. + public bool IsEnabled => HasEntry && !StartupApproval.IsTurnedOff(Read(StartupApproval.RunKey) as byte[]); + + private bool HasEntry => Read(RunKey) is string { Length: > 0 }; + + private string Command => StartupCommand.Format(_executable ?? string.Empty, CommandLine.TrayOption); + + public void SetEnabled(bool enabled) => Update(key => { - get - { - try - { - using var key = Registry.CurrentUser.OpenSubKey(RunKey); - return key?.GetValue(ValueName) is string { Length: > 0 }; - } - catch (SecurityException) - { - return false; - } - } + if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); + else key.DeleteValue(ValueName, throwOnMissingValue: false); + // Task Manager's "Disable" outlives a new command: ticking the box undoes it, and unticking leaves nothing behind. + using var approval = _root.OpenSubKey(StartupApproval.RunKey, writable: true); + approval?.DeleteValue(ValueName, throwOnMissingValue: false); + }); + + /// Points an existing entry at the current executable (after an update moved it); one Task Manager turned off stays off. + public void Refresh() + { + if (HasEntry) Update(key => key.SetValue(ValueName, Command, RegistryValueKind.String)); } - private static string Command => $"\"{Environment.ProcessPath}\" {CommandLine.TrayOption}"; - - public void SetEnabled(bool enabled) + private object? Read(string subKey) { try { - using var key = Registry.CurrentUser.CreateSubKey(RunKey, writable: true); - if (enabled) key.SetValue(ValueName, Command, RegistryValueKind.String); - else key.DeleteValue(ValueName, throwOnMissingValue: false); + using var key = _root.OpenSubKey(subKey); + return key?.GetValue(ValueName); } - catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException) + catch (Exception ex) when (ex is SecurityException or IOException) + { + return null; + } + } + + private void Update(Action change) + { + try + { + using var key = _root.CreateSubKey(RunKey, writable: true); + change(key); + } + catch (Exception ex) when (ex is SecurityException or UnauthorizedAccessException or IOException) { Log.Warning("startup", "Run key not updated", ex); } } - - /// Points an existing entry at the current executable (after an update moved it). - public void Refresh() - { - if (IsEnabled) SetEnabled(true); - } } diff --git a/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs b/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs index 7148dc8a..a0ef5c86 100644 --- a/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs +++ b/tests/Titano.App.Tests/Infrastructure/StartWithWindowsTests.cs @@ -1,6 +1,8 @@ +using Microsoft.Win32; using Titano.App.Infrastructure; using Titano.Core.IO; using Titano.Testing; +using Titano.Uploader.Infrastructure; namespace Titano.App.Tests.Infrastructure; @@ -31,6 +33,77 @@ public sealed class StartWithWindowsTests Assert.False(RunKeyStartWithWindows.Follows(installed, null, Gone)); } + [Test] + [WindowsOnly] + public void AnEntryTaskManagerTurnedOffShowsOffUntilTheBoxIsTickedAgain() + { + // A scratch hive of its own: the user's sign-in entries are never touched. + var hive = @"Software\Titano.StartupTests." + Guid.NewGuid().ToString("N"); + try + { + using var root = Registry.CurrentUser.CreateSubKey(hive, writable: true); + var startup = new RunKeyStartWithWindows(Installed, root); + startup.SetEnabled(true); + Assert.True(startup.IsEnabled); + + // Task Manager › Startup › Disable keeps the Run value and writes the switch apart. + TurnOff(root, StartupCommand.ClientValue); + Assert.False(startup.IsEnabled, "shown as off"); + Assert.True(StartupCommand.Starts(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue) as string, Installed), "the command stays"); + + // An update renamed the program: the command follows it, and the entry stays off. + const string renamed = @"C:\Users\ada\AppData\Local\Programs\Titano\Titano.next.exe"; + var updated = new RunKeyStartWithWindows(renamed, root); + updated.Refresh(); + Assert.True(StartupCommand.Starts(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue) as string, renamed)); + Assert.False(updated.IsEnabled, "still off after the update"); + + // Ticking the box turns it on again; unticking leaves nothing behind. + updated.SetEnabled(true); + Assert.True(updated.IsEnabled); + Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.ClientValue)); + TurnOff(root, StartupCommand.ClientValue); + updated.SetEnabled(false); + Assert.Null(Value(root, StartupCommand.RunKey, StartupCommand.ClientValue)); + Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.ClientValue)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false); + } + } + + [Test] + [WindowsOnly] + public void TheUploadersEntryHonoursTaskManagerToo() + { + var hive = @"Software\Titano.StartupTests." + Guid.NewGuid().ToString("N"); + try + { + using var root = Registry.CurrentUser.CreateSubKey(hive, writable: true); + var uploader = @"C:\Users\ada\AppData\Local\Programs\Titano\Uploader\Titano.Uploader.exe"; + var startup = new RunKeyStartupRegistration(uploader, root); + startup.SetEnabled(true); + Assert.True(startup.IsEnabled); + + TurnOff(root, StartupCommand.UploaderValue); + Assert.False(startup.IsEnabled, "shown as off"); + startup.Refresh(); + Assert.False(startup.IsEnabled, "a refresh keeps it off"); + + startup.SetEnabled(true); + Assert.True(startup.IsEnabled); + TurnOff(root, StartupCommand.UploaderValue); + startup.SetEnabled(false); + Assert.Null(Value(root, StartupCommand.RunKey, StartupCommand.UploaderValue)); + Assert.Null(Value(root, StartupApproval.RunKey, StartupCommand.UploaderValue)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false); + } + } + [Test] public void ScreenshotsAndPortableCopiesKeepTheChoiceInMemory() { @@ -42,4 +115,17 @@ public sealed class StartWithWindowsTests startup.SetEnabled(false); Assert.False(startup.IsEnabled); } + + /// What Task Manager writes when the user disables an entry: 0x03, three zero bytes, then when. + private static void TurnOff(RegistryKey root, string name) + { + using var approved = root.CreateSubKey(StartupApproval.RunKey, writable: true); + approved.SetValue(name, new byte[] { 0x03, 0, 0, 0, 0x60, 0x1B, 0x3C, 0x92, 0x8A, 0x3F, 0xDB, 0x01 }, RegistryValueKind.Binary); + } + + private static object? Value(RegistryKey root, string subKey, string name) + { + using var key = root.OpenSubKey(subKey); + return key?.GetValue(name); + } } diff --git a/tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs b/tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs new file mode 100644 index 00000000..1edaea59 --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/StartupApprovalTests.cs @@ -0,0 +1,21 @@ +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +/// The switch Task Manager's Startup tab keeps apart from a sign-in entry's command. +public sealed class StartupApprovalTests +{ + [Test] + public void AnOddFirstByteMeansTurnedOff() + { + // As Task Manager writes them: a state, three zero bytes, then the time it was turned off. + Assert.True(StartupApproval.IsTurnedOff([0x03, 0, 0, 0, 0x60, 0x1B, 0x3C, 0x92, 0x8A, 0x3F, 0xDB, 0x01])); + Assert.True(StartupApproval.IsTurnedOff([0x01, 0, 0, 0])); + Assert.False(StartupApproval.IsTurnedOff([0x02, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])); + Assert.False(StartupApproval.IsTurnedOff([0x06, 0, 0, 0])); + // Never touched in Task Manager, or a value of another type: the entry is on. + Assert.False(StartupApproval.IsTurnedOff(null)); + Assert.False(StartupApproval.IsTurnedOff([])); + } +} From 815782a708ab8537797b712c26c369b8e690311a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:02:33 +0000 Subject: [PATCH 3/8] fix(app): a portable copy in a OneDrive folder keeps its index outside it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit BRIEF §6.2 forbids a SQLite index in a synchronised folder. AppEnvironment.Detect now resolves the data folder through Core.Windows' AppPaths and OneDriveFolders: a portable copy whose .\data would lie under a OneDrive sync root (a OneDrive folder, or a Desktop or Documents folder backed up into one) keeps its data in %LOCALAPPDATA%\Titano and stays portable otherwise; AppEnvironment.SyncedFolder names the OneDrive folder so the user can be told. The pure choice lives in Core/IO/DataLocation (tested on Linux); reading the OneDrive accounts key no longer fails start-up when it cannot be read. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- docs/ARCHITECTURE.md | 2 +- src/Titano.App/App.xaml.cs | 2 + .../Infrastructure/AppEnvironment.cs | 26 ++++--- src/Titano.Core.Windows/Shell/AppPaths.cs | 36 +++++----- .../Shell/OneDriveFolders.cs | 32 +++++---- src/Titano.Core.Windows/Shell/PortableMode.cs | 4 +- src/Titano.Core/IO/DataLocation.cs | 52 ++++++++++++++ .../Infrastructure/UploaderEnvironment.cs | 3 +- .../Infrastructure/AppEnvironmentTests.cs | 34 ++++++++++ .../Foundation/DataLocationTests.cs | 68 +++++++++++++++++++ .../Shell/AppPathsTests.cs | 34 +++++++--- .../Shell/OneDriveFoldersTests.cs | 39 +++++++++++ 12 files changed, 279 insertions(+), 53 deletions(-) create mode 100644 src/Titano.Core/IO/DataLocation.cs create mode 100644 tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs create mode 100644 tests/Titano.Core.Tests/Foundation/DataLocationTests.cs create mode 100644 tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index cfdc756a..343b9ef8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -92,7 +92,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S | Host | Composition root | What it runs | |---|---|---| -| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) | +| Titano (desktop) | `App/Infrastructure/AppServices` | SQLite index in `%LOCALAPPDATA%\Titano` (or `.\data` when portable, unless the copy is in a OneDrive folder); `ArchiveService` with WIC first, then managed decoders; `ProcessingService` with Media Foundation, then managed encoders; one `JobEngine` with the handlers of both; thumbnails; `ServerSession`; `SyncHost` while signed in (sync engine and agent, upload and download handlers, metered hold, editors of server sequences); the render node while opted in and signed in; update check and download (`About/UpdateCheck`, `About/UpdateDownload`, `About/UpdateFlow`: the setup, or the portable zip for a portable copy, verified against `SHA256SUMS`, resumable, cancellable, failing after 60 s without data); diagnostics bundle; daily index backups and the restore staged in Settings › Advanced (`DatabaseBackups`) | | Titano Server | `Server/Hosting/ServerHost.Build` | Options from `server.json` + `TITANO_*`; PostgreSQL (or SQLite on Windows); `ArchiveModule` then `ProcessingModule` register job handler providers; `JobEngineHost` (renders only managed formats and MP4 jobs no render node can take, BRIEF §14.7); `RenderNodeService`/`RenderNodeMonitor`; `UploadService`; `EventHub` (WebSocket); embedded admin panel; LAN discovery beacon; Windows service host; daily backups of an SQLite index (`DatabaseBackupService`) | | Titano Uploader | `Uploader/App.xaml.cs` | `TitanoClient`, persisted queue, watch folders; no database | | Titano Setup | `Setup/Program` | TPK1 payload extraction, registry, shortcuts, file types named in setup's language, silent mode, uninstaller; only what starts a program its log or payload lists is changed: Windows services of those programs stopped once the programs have closed, started again (also after a failure) or deleted through the Service Control Manager (an elevated `/SERVICES … /NAMES` step when needed), sign-in entries of those programs removed, shared shortcuts handed to the product that keeps the program; the Server only for all users inside Program Files; "Remove my data" limited to the programs no other installed product uses | diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs index 52a7fee7..9da130e6 100644 --- a/src/Titano.App/App.xaml.cs +++ b/src/Titano.App/App.xaml.cs @@ -45,6 +45,8 @@ public partial class App : Application // Capture runs in CI: mirror the log to stderr so failures are visible in the job output. Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log); Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}"); + // Settings tells the user once the window is up. + if (Environment.SyncedFolder is { } synced) Log.Warning("app", $"This portable copy runs in the OneDrive folder {synced}: its data is kept outside it"); var projectFile = capture ? null : ProjectFileArgument(e.Args); if (!capture) diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs index 349f91bd..06c60555 100644 --- a/src/Titano.App/Infrastructure/AppEnvironment.cs +++ b/src/Titano.App/Infrastructure/AppEnvironment.cs @@ -1,18 +1,22 @@ using System.IO; +using Titano.Core.Windows.Shell; namespace Titano.App.Infrastructure; /// -/// Where the client keeps its data (BRIEF §6.2): %LOCALAPPDATA%\Titano, or .\data next to the -/// executable when portable.txt exists. Never inside Documents/OneDrive (SQLite corrupts in synced folders). +/// Where the client keeps its data (BRIEF §6.2, ): %LOCALAPPDATA%\Titano, or .\data +/// next to the executable when portable.txt exists. Never inside a folder OneDrive synchronises (SQLite corrupts +/// there): a portable copy in one keeps its data in %LOCALAPPDATA%\Titano, and Settings tells the user so +/// (). /// public sealed class AppEnvironment { - private AppEnvironment(string dataDirectory, bool portable, bool isCapture) + private AppEnvironment(string dataDirectory, bool portable, bool isCapture, string? syncedFolder = null) { DataDirectory = dataDirectory; IsPortable = portable; IsCapture = isCapture; + SyncedFolder = syncedFolder; Directory.CreateDirectory(DataDirectory); Directory.CreateDirectory(LogDirectory); Directory.CreateDirectory(CacheDirectory); @@ -24,20 +28,20 @@ public sealed class AppEnvironment /// A throw-away environment for --capture: nothing of the user's data is read or written. public bool IsCapture { get; } + /// The OneDrive folder this portable copy runs from; its data is in %LOCALAPPDATA%\Titano instead of .\data. Null otherwise. + public string? SyncedFolder { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); public string CacheDirectory => Path.Combine(DataDirectory, "cache"); public string BackupDirectory => Path.Combine(DataDirectory, "backups"); public string DatabasePath => Path.Combine(DataDirectory, "titano.db"); public string SettingsPath => Path.Combine(DataDirectory, "settings.json"); - public static AppEnvironment Detect() - { - var exeDir = AppContext.BaseDirectory; - if (File.Exists(Path.Combine(exeDir, "portable.txt"))) - return new AppEnvironment(Path.Combine(exeDir, "data"), portable: true, isCapture: false); - var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); - return new AppEnvironment(Path.Combine(local, "Titano"), portable: false, isCapture: false); - } + /// The environment of this process: its executable's folder and the user's OneDrive folders decide. + public static AppEnvironment Detect() => From(AppPaths.Resolve()); + + /// The environment at (its folders are created). + public static AppEnvironment From(AppPaths paths) => new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.PortableSyncRoot); /// A fresh temporary data folder for screenshots and smoke tests; delete it with . public static AppEnvironment ForCapture() => diff --git a/src/Titano.Core.Windows/Shell/AppPaths.cs b/src/Titano.Core.Windows/Shell/AppPaths.cs index e2cfd70e..7bd02b74 100644 --- a/src/Titano.Core.Windows/Shell/AppPaths.cs +++ b/src/Titano.Core.Windows/Shell/AppPaths.cs @@ -1,22 +1,28 @@ +using Titano.Core.IO; + namespace Titano.Core.Windows.Shell; /// -/// Where the desktop programs keep their data (BRIEF §6.2): %LOCALAPPDATA%\Titano, or .\data next to the -/// executable in portable mode. SQLite corrupts inside synchronised folders, so a data root under OneDrive is -/// reported by and refused by . +/// Where the desktop programs keep their data (BRIEF §6.2, ): %LOCALAPPDATA%\Titano, or +/// .\data next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable +/// copy in a OneDrive folder keeps its data in %LOCALAPPDATA%\Titano instead ( +/// names that folder to tell the user), and a data root still under OneDrive is reported by +/// and refused by . /// public sealed class AppPaths { - public const string ProductFolderName = "Titano"; + public const string ProductFolderName = DataLocation.ProductFolderName; public const string DatabaseFileName = "titano.db"; - private AppPaths(string dataRoot, bool isPortable, string? syncedFolder) + private AppPaths(DataLocation location) { - DataRoot = dataRoot; - IsPortable = isPortable; - SyncedFolder = syncedFolder; + DataRoot = location.Root; + IsPortable = location.IsPortable; + SyncedFolder = location.SyncedFolder; + PortableSyncRoot = location.PortableSyncRoot; } + /// A portable copy, also when its data had to go to %LOCALAPPDATA%\Titano. public bool IsPortable { get; } public string DataRoot { get; } @@ -34,6 +40,9 @@ public sealed class AppPaths public bool IsInSyncedFolder => SyncedFolder is not null; + /// The OneDrive sync root a portable copy runs from, whose data is in %LOCALAPPDATA%\Titano instead; null otherwise. + public string? PortableSyncRoot { get; } + /// Paths for this process: the executable's folder decides portable mode. public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData); @@ -41,14 +50,9 @@ public sealed class AppPaths public static AppPaths Resolve(string applicationDirectory, string localAppData) => Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots()); - internal static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyList syncRoots) - { - var portable = PortableMode.IsEnabled(applicationDirectory); - var root = Path.GetFullPath(portable - ? Path.Combine(applicationDirectory, PortableMode.DataFolderName) - : Path.Combine(localAppData, ProductFolderName)); - return new AppPaths(root, portable, OneDriveFolders.Containing(root, syncRoots)); - } + /// Paths for an executable in , checked against . + public static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyCollection syncRoots) => + new(DataLocation.Choose(applicationDirectory, PortableMode.IsEnabled(applicationDirectory), localAppData, syncRoots)); /// Creates the data, logs, cache and thumbnails folders. /// The data root lies inside a OneDrive-synced folder. diff --git a/src/Titano.Core.Windows/Shell/OneDriveFolders.cs b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs index b37a5a67..3b9ce98a 100644 --- a/src/Titano.Core.Windows/Shell/OneDriveFolders.cs +++ b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs @@ -1,4 +1,6 @@ +using System.Security; using Microsoft.Win32; +using Titano.Core.IO; namespace Titano.Core.Windows.Shell; @@ -10,34 +12,34 @@ public static class OneDriveFolders /// /// Sync roots from the OneDrive environment variables and HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder, - /// as full paths without a trailing separator, distinct (case-insensitive). + /// as full paths without a trailing separator, distinct (case-insensitive). An account key that cannot be read is + /// skipped: the programs start all the same. /// public static IReadOnlyList SyncRoots() { var roots = new List(); foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable)); - using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey); - if (accounts is not null) + try { - foreach (var name in accounts.GetSubKeyNames()) + using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey); + if (accounts is not null) { - using var account = accounts.OpenSubKey(name); - Add(roots, account?.GetValue("UserFolder") as string); + foreach (var name in accounts.GetSubKeyNames()) + { + using var account = accounts.OpenSubKey(name); + Add(roots, account?.GetValue("UserFolder") as string); + } } } + catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException) + { + // The environment variables name the usual roots. + } return roots; } /// The sync root that contains , or null. Both are expected to be full paths. - public static string? Containing(string path, IEnumerable syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root)); - - /// True when equals or lies below it (whole path segments, case-insensitive). - internal static bool IsUnder(string path, string root) - { - var trimmedRoot = root.TrimEnd('\\', '/'); - if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false; - return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/'; - } + public static string? Containing(string path, IEnumerable syncRoots) => DataLocation.SyncRootOf(path, syncRoots); private static void Add(List roots, string? candidate) { diff --git a/src/Titano.Core.Windows/Shell/PortableMode.cs b/src/Titano.Core.Windows/Shell/PortableMode.cs index 2c438a37..c8f48f1c 100644 --- a/src/Titano.Core.Windows/Shell/PortableMode.cs +++ b/src/Titano.Core.Windows/Shell/PortableMode.cs @@ -1,10 +1,12 @@ +using Titano.Core.IO; + namespace Titano.Core.Windows.Shell; /// Portable mode (BRIEF §6.2): a portable.txt next to the executable keeps all data under .\data\. public static class PortableMode { public const string MarkerFileName = "portable.txt"; - public const string DataFolderName = "data"; + public const string DataFolderName = DataLocation.PortableFolderName; public static bool IsEnabled(string applicationDirectory) => File.Exists(Path.Combine(applicationDirectory, MarkerFileName)); } diff --git a/src/Titano.Core/IO/DataLocation.cs b/src/Titano.Core/IO/DataLocation.cs new file mode 100644 index 00000000..d097d59f --- /dev/null +++ b/src/Titano.Core/IO/DataLocation.cs @@ -0,0 +1,52 @@ +namespace Titano.Core.IO; + +/// +/// Where the desktop client keeps its data (BRIEF §6.2): the per-user folder (%LOCALAPPDATA%\Titano), or +/// .\data next to the executable of a portable copy (a portable.txt beside it). SQLite corrupts inside +/// synchronised folders, so a portable copy in a folder OneDrive synchronises (a OneDrive folder, or a Desktop or +/// Documents folder moved into one) keeps its data in the per-user folder instead, and +/// says so, to tell the user. Paths are full paths; a folder lies in a sync root when its whole leading segments are +/// that root's, ignoring case as Windows does. +/// +/// The data folder. +/// The copy is portable, also when its data had to go to the per-user folder. +/// The sync root that contains itself; null when the data is safe there. +/// The sync root a portable copy runs from, whose data went to the per-user folder instead; null otherwise. +public sealed record DataLocation(string Root, bool IsPortable, string? SyncedFolder, string? PortableSyncRoot) +{ + /// The data folder's name under the user's local application data. + public const string ProductFolderName = "Titano"; + + /// The data folder's name next to a portable copy's executable. + public const string PortableFolderName = "data"; + + /// + /// The data folder of a copy in ( when it has a + /// portable.txt), given the user's local application data and the OneDrive sync roots. + /// + public static DataLocation Choose(string applicationDirectory, bool portable, string localAppData, IReadOnlyCollection syncRoots) + { + ArgumentNullException.ThrowIfNull(applicationDirectory); + ArgumentNullException.ThrowIfNull(localAppData); + ArgumentNullException.ThrowIfNull(syncRoots); + var perUser = Path.GetFullPath(Path.Combine(localAppData, ProductFolderName)); + if (!portable) return new DataLocation(perUser, false, SyncRootOf(perUser, syncRoots), null); + var beside = Path.GetFullPath(Path.Combine(applicationDirectory, PortableFolderName)); + return SyncRootOf(beside, syncRoots) is { } synced + ? new DataLocation(perUser, true, SyncRootOf(perUser, syncRoots), synced) + : new DataLocation(beside, true, null, null); + } + + /// The sync root that contains , or null. + public static string? SyncRootOf(string path, IEnumerable syncRoots) => syncRoots.FirstOrDefault(root => IsUnder(path, root)); + + /// True when equals or lies below it (whole path segments, case-insensitive). + public static bool IsUnder(string path, string root) + { + ArgumentNullException.ThrowIfNull(path); + ArgumentNullException.ThrowIfNull(root); + var trimmedRoot = root.TrimEnd('\\', '/'); + if (trimmedRoot.Length == 0 || !path.StartsWith(trimmedRoot, StringComparison.OrdinalIgnoreCase)) return false; + return path.Length == trimmedRoot.Length || path[trimmedRoot.Length] is '\\' or '/'; + } +} diff --git a/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs b/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs index 993a0fdb..46ec0cb6 100644 --- a/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs +++ b/src/Titano.Uploader/Infrastructure/UploaderEnvironment.cs @@ -4,7 +4,8 @@ namespace Titano.Uploader.Infrastructure; /// /// Where the uploader keeps its files: %LOCALAPPDATA%\Titano (shared with the client), or .\data next -/// to the executable when portable.txt exists — the same rule as the desktop client. +/// to the executable when portable.txt exists — the desktop client's rule, except that the client never keeps +/// its SQLite index in a folder OneDrive synchronises; the Uploader's JSON files, written atomically, stay there. /// public sealed class UploaderEnvironment { diff --git a/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs b/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs new file mode 100644 index 00000000..771e2d94 --- /dev/null +++ b/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs @@ -0,0 +1,34 @@ +using System.IO; +using Titano.App.Infrastructure; +using Titano.Core.Windows.Shell; +using Titano.Testing; + +namespace Titano.App.Tests.Infrastructure; + +/// BRIEF §6.2: the client's data folder, which is never inside a folder OneDrive synchronises. +public sealed class AppEnvironmentTests(TestContext context) +{ + [Test] + public void APortableCopyInOneDriveKeepsItsDataInTheUserFolderAndSaysSo() + { + var oneDrive = context.CreateTempDirectory("onedrive"); + var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Titano")).FullName; + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + var local = context.CreateTempDirectory("local"); + + var environment = AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive])); + + Assert.Equal(Path.Combine(local, "Titano", "titano.db"), environment.DatabasePath); + Assert.True(environment.IsPortable, "still a portable copy: updates fetch the portable zip, no sign-in entry"); + Assert.Equal(oneDrive, environment.SyncedFolder); + Assert.True(Directory.Exists(environment.LogDirectory)); + Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder"); + + // Elsewhere (a USB stick) a portable copy keeps its data beside it. + var stick = context.CreateTempDirectory("stick"); + File.WriteAllText(Path.Combine(stick, PortableMode.MarkerFileName), ""); + var beside = AppEnvironment.From(AppPaths.Resolve(stick, local, [oneDrive])); + Assert.Equal(Path.Combine(stick, "data"), beside.DataDirectory); + Assert.Null(beside.SyncedFolder); + } +} diff --git a/tests/Titano.Core.Tests/Foundation/DataLocationTests.cs b/tests/Titano.Core.Tests/Foundation/DataLocationTests.cs new file mode 100644 index 00000000..958858dd --- /dev/null +++ b/tests/Titano.Core.Tests/Foundation/DataLocationTests.cs @@ -0,0 +1,68 @@ +using Titano.Core.IO; +using Titano.Testing; + +namespace Titano.Core.Tests.Foundation; + +/// BRIEF §6.2: where the client keeps its index, and never inside a folder OneDrive synchronises. +public sealed class DataLocationTests(TestContext context) +{ + [Test] + public void AnInstalledCopyUsesThePerUserFolderAndAPortableOneItsOwn() + { + var app = context.CreateTempDirectory("app"); + var local = context.CreateTempDirectory("local"); + + var installed = DataLocation.Choose(app, portable: false, local, []); + Assert.Equal(new DataLocation(Path.Combine(local, "Titano"), false, null, null), installed); + + var portable = DataLocation.Choose(app, portable: true, local, []); + Assert.Equal(new DataLocation(Path.Combine(app, "data"), true, null, null), portable); + } + + [Test] + public void APortableCopyInASynchronisedFolderKeepsItsDataInThePerUserFolder() + { + // A portable copy unpacked on a Desktop that OneDrive's folder backup moved into the sync root. + var oneDrive = context.CreateTempDirectory("onedrive"); + var app = Path.Combine(oneDrive, "Desktop", "Titano"); + var local = context.CreateTempDirectory("local"); + + var location = DataLocation.Choose(app, portable: true, local, [Path.Combine(context.CreateTempDirectory("other"), "OneDrive"), oneDrive]); + + Assert.Equal(Path.Combine(local, "Titano"), location.Root); + Assert.True(location.IsPortable, "still a portable copy (updates, no sign-in entry)"); + Assert.Equal(oneDrive, location.PortableSyncRoot); + Assert.Null(location.SyncedFolder); + + // A sync root that only shares the start of the name is another folder. + var beside = DataLocation.Choose(oneDrive + "Backup", portable: true, local, [oneDrive]); + Assert.Equal(new DataLocation(Path.Combine(oneDrive + "Backup", "data"), true, null, null), beside); + } + + [Test] + public void APerUserFolderInsideASyncRootIsReported() + { + var oneDrive = context.CreateTempDirectory("onedrive"); + var local = Path.Combine(oneDrive, "AppData", "Local"); + + var installed = DataLocation.Choose(context.CreateTempDirectory("app"), portable: false, local, [oneDrive]); + Assert.Equal(oneDrive, installed.SyncedFolder); + + var portable = DataLocation.Choose(Path.Combine(oneDrive, "Titano"), portable: true, local, [oneDrive]); + Assert.Equal<(string, string?, string?)>((Path.Combine(local, "Titano"), oneDrive, oneDrive), (portable.Root, portable.SyncedFolder, portable.PortableSyncRoot)); + } + + [Test] + public void SyncRootMatchingIsSegmentWiseAndIgnoresCase() + { + var root = Path.Combine(context.CreateTempDirectory(), "OneDrive"); + Assert.True(DataLocation.IsUnder(root, root)); + Assert.True(DataLocation.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar)); + Assert.True(DataLocation.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root)); + Assert.True(DataLocation.IsUnder(@"C:\Users\ada\OneDrive\Desktop\Titano\data", @"c:\users\ada\onedrive"), "Windows paths on any platform"); + Assert.False(DataLocation.IsUnder(root + "Backup", root)); + Assert.False(DataLocation.IsUnder(root, string.Empty)); + Assert.Null(DataLocation.SyncRootOf(root + "Backup", [root])); + Assert.Equal(root, DataLocation.SyncRootOf(Path.Combine(root, "Documents"), ["", root])); + } +} diff --git a/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs b/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs index 3be36314..d70366f8 100644 --- a/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs +++ b/tests/Titano.Core.Windows.Tests/Shell/AppPathsTests.cs @@ -17,6 +17,7 @@ public sealed class AppPathsTests(TestContext context) Assert.Equal(Path.Combine(app, "data"), paths.DataRoot); Assert.Equal(Path.Combine(app, "data", "titano.db"), paths.DatabasePath); Assert.False(paths.IsInSyncedFolder); + Assert.Null(paths.PortableSyncRoot); paths.CreateDirectories(); Assert.True(Directory.Exists(paths.LogsDirectory)); @@ -37,13 +38,31 @@ public sealed class AppPathsTests(TestContext context) } [Test] - public void DataInsideOneDriveIsReportedAndRefused() + public void APortableCopyInOneDriveKeepsItsDataInLocalAppData() { var oneDrive = context.CreateTempDirectory("onedrive"); var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Tools", "Titano")).FullName; File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + var local = context.CreateTempDirectory("local"); - var paths = AppPaths.Resolve(app, context.CreateTempDirectory("local"), [oneDrive]); + var paths = AppPaths.Resolve(app, local, [oneDrive]); + Assert.True(paths.IsPortable); + Assert.Equal(Path.Combine(local, "Titano"), paths.DataRoot); + Assert.Equal(oneDrive, paths.PortableSyncRoot); + Assert.False(paths.IsInSyncedFolder); + paths.CreateDirectories(); + Assert.True(Directory.Exists(paths.LogsDirectory)); + Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder"); + } + + [Test] + public void DataInsideOneDriveIsReportedAndRefused() + { + // Local application data inside a sync root: nowhere is safe, so nothing is created. + var oneDrive = context.CreateTempDirectory("onedrive"); + var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName; + + var paths = AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive]); Assert.True(paths.IsInSyncedFolder); Assert.Equal(oneDrive, paths.SyncedFolder); Assert.Throws(paths.CreateDirectories); @@ -54,10 +73,7 @@ public sealed class AppPathsTests(TestContext context) public void SyncRootMatchingIsSegmentWise() { var root = Path.Combine(context.CreateTempDirectory(), "OneDrive"); - Assert.True(OneDriveFolders.IsUnder(root, root)); - Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "Pictures"), root + Path.DirectorySeparatorChar)); - Assert.True(OneDriveFolders.IsUnder(Path.Combine(root, "x").ToUpperInvariant(), root)); - Assert.False(OneDriveFolders.IsUnder(root + "Backup", root)); + Assert.Equal(root, OneDriveFolders.Containing(Path.Combine(root, "Pictures"), [root])); Assert.Null(OneDriveFolders.Containing(root + "Backup", [root])); } @@ -68,8 +84,10 @@ public sealed class AppPathsTests(TestContext context) var app = context.CreateTempDirectory("app"); File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); var paths = AppPaths.Resolve(app, KnownFolders.LocalAppData); + var roots = OneDriveFolders.SyncRoots(); Assert.True(paths.IsPortable); - Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, OneDriveFolders.SyncRoots()), paths.SyncedFolder); - Assert.True(OneDriveFolders.SyncRoots().All(Path.IsPathFullyQualified)); + Assert.Equal(OneDriveFolders.Containing(Path.Combine(app, PortableMode.DataFolderName), roots), paths.PortableSyncRoot); + Assert.Equal(OneDriveFolders.Containing(paths.DataRoot, roots), paths.SyncedFolder); + Assert.True(roots.All(Path.IsPathFullyQualified)); } } diff --git a/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs b/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs new file mode 100644 index 00000000..cd0c9bd6 --- /dev/null +++ b/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs @@ -0,0 +1,39 @@ +using Titano.Core.Windows.Shell; +using Titano.Testing; + +namespace Titano.Core.Windows.Tests.Shell; + +/// The OneDrive folders of the user as Windows reports them. Serial: a test sets a process environment variable. +[Serial] +public sealed class OneDriveFoldersTests(TestContext context) +{ + private const string Variable = "OneDriveCommercial"; + + [Test] + [WindowsOnly] + public void APortableCopyInTheUsersOneDriveKeepsItsDataInLocalAppData() + { + var oneDrive = context.CreateTempDirectory("onedrive"); + var previous = Environment.GetEnvironmentVariable(Variable); + Environment.SetEnvironmentVariable(Variable, oneDrive); + try + { + Assert.Contains(OneDriveFolders.SyncRoots(), root => string.Equals(root, Path.TrimEndingDirectorySeparator(oneDrive), StringComparison.OrdinalIgnoreCase)); + // A Desktop that OneDrive's folder backup moved into the sync root, with a portable copy unpacked on it. + var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Titano")).FullName; + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + var local = context.CreateTempDirectory("local"); + + var paths = AppPaths.Resolve(app, local); + + Assert.True(paths.IsPortable); + Assert.Equal(Path.Combine(local, AppPaths.ProductFolderName), paths.DataRoot); + Assert.NotNull(paths.PortableSyncRoot); + Assert.False(paths.IsInSyncedFolder); + } + finally + { + Environment.SetEnvironmentVariable(Variable, previous); + } + } +} From d2e547f9d274a81a2a8005e602ce06a9eb2d5e4e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:02:43 +0000 Subject: [PATCH 4/8] fix(settings): archive rows keep offline sizes, edit no stray archive and keep edits made while a folder opens MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - While the open archive's archive.json cannot be read, the rows show the index's templates and proxy size and the thumbnail size stays this PC's: the stand-in 320 no longer replaces the default of new archives. Settings › Archive loads through RefreshSettingsAsync, so opening it also brings the index up to a change made elsewhere. - With no archive folder the rows edit only this PC's defaults, never the first archive of the index. - An Archive row edited (or Reset section) while the archive at a just-chosen folder is opening waits for it and goes to that archive (or stays a default when the folder holds none), instead of being undone when it opens. - A portable copy whose data had to leave its OneDrive folder says so at start, with Open on the data folder. - Opening Settings re-reads Start with Windows, which Task Manager may have changed meanwhile. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Settings.resx | 1 + i18n/it/Settings.it.resx | 1 + src/Titano.App/Sections/SettingsViewModel.cs | 111 +++++++++++++----- .../Settings/SettingsScreenSmokeTests.cs | 45 +++++++ 4 files changed, 127 insertions(+), 31 deletions(-) diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx index 12316821..4df33790 100644 --- a/i18n/en/Settings.resx +++ b/i18n/en/Settings.resx @@ -8,6 +8,7 @@ Index backed up Back up now Data folder + Data kept outside OneDrivelong Diagnostics Diagnostics bundle saved Save the diagnostics bundle to diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx index 487c29f2..f61c0972 100644 --- a/i18n/it/Settings.it.resx +++ b/i18n/it/Settings.it.resx @@ -8,6 +8,7 @@ Copia dell'indice salvata Salva una copia Cartella dati + Dati tenuti fuori da OneDrive Diagnostica Pacchetto diagnostico salvato Salva il pacchetto in diff --git a/src/Titano.App/Sections/SettingsViewModel.cs b/src/Titano.App/Sections/SettingsViewModel.cs index bdd1ae23..f899372e 100644 --- a/src/Titano.App/Sections/SettingsViewModel.cs +++ b/src/Titano.App/Sections/SettingsViewModel.cs @@ -45,6 +45,12 @@ public sealed class SettingsViewModel : SectionViewModel private bool _isTesting; private CancellationTokenSource? _selfTest; private Archive? _archive; + + /// + /// The open of the archive at the folder chosen last (), with the archive it found + /// there: edits of the Archive rows made meanwhile wait for it (). + /// + private Task _retarget = Task.FromResult(null); private bool _isDetectingFormats; private IReadOnlyList _backups = []; private BackupOption? _selectedBackup; @@ -82,7 +88,7 @@ public sealed class SettingsViewModel : SectionViewModel _s.LastArchivePath = v.Length == 0 ? null : Path.GetFullPath(v); Save(); UpdateArchiveFree(); - _ = RetargetArchiveAsync(); + _retarget = RetargetArchiveAsync(); }, () => Loc.L("Tooltips.Settings.ArchiveRoot")); FolderTemplate = new EditableField(_s.FolderTemplate, v => NamingPreview.Validate(v, isFolder: true), v => { @@ -770,7 +776,8 @@ public sealed class SettingsViewModel : SectionViewModel /// /// Loads what needs the services (certificates, cache usage, the open archive's settings), follows the server session, - /// applies "Background priority" while Titano is in front and says how a restore staged before this start went. + /// applies "Background priority" while Titano is in front and says how a restore staged before this start went, and + /// where the data of a portable copy in a OneDrive folder went. /// public void Attach() { @@ -798,6 +805,10 @@ public sealed class SettingsViewModel : SectionViewModel Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true); break; } + // BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead. + if (Shell.Services.Environment.SyncedFolder is not null) + Shell.Notify(Loc.L("Settings.Advanced.DataOutsideOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"), + Loc.L("Tooltips.Settings.OpenDataFolder"), () => ShellActions.Reveal(DataFolder)); Startup.Refresh(); } @@ -868,33 +879,39 @@ public sealed class SettingsViewModel : SectionViewModel /// /// Takes the archive and server values other screens set (opening an archive, connecting), unless the field holds an - /// edit not committed yet. + /// edit not committed yet, and the sign-in entry as Task Manager may have left it. /// private void ReloadShared() { if (!ArchiveRoot.IsDirty) ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty); if (!DefaultServer.IsDirty) DefaultServer.Load(ServerAddress.Display(_s.ServerUrl)); + OnPropertyChanged(nameof(StartWithWindows)); UpdateArchiveFree(); _ = LoadArchiveAsync(); if (_page == SettingsPage.Advanced) LoadBackups(); } /// - /// Shows the open archive's own templates, proxy size and thumbnail size (its archive.json; the index's while it is - /// offline) unless a field holds an edit; they also become the defaults of new archives. The open archive is the one - /// at the archive folder of this PC, never another one of the index: with none registered there, the rows edit only - /// this PC's defaults. + /// Shows the open archive's own templates, proxy size and thumbnail size unless a field holds an edit; they also become + /// the defaults of new archives. They come from its archive.json, which also brings the index up to a change another + /// process sharing the archive made, so imports follow it too. While the file cannot be read (offline), the templates + /// and proxy size are the index's and the thumbnail size stays this PC's: only the file knows the archive's. The open + /// archive is the one at the archive folder of this PC, never another one of the index: with no folder, or none + /// registered there, the rows edit only this PC's defaults. Returns that archive (null for none). /// - private async Task LoadArchiveAsync() + private async Task LoadArchiveAsync() { - if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return; + if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return null; + Archive? archive = null; try { var registered = await db.Archives.ListAsync(); - var archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : CurrentArchive.Pick(registered, null); + archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : null; _archive = archive; - if (archive is null) return; - var settings = await Task.Run(() => archives.GetSettingsAsync(archive.Id)); + if (archive is null) return null; + var settings = await Task.Run(() => archives.RefreshSettingsAsync(archive.Id)) + ?? new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate }, + new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy { LongEdge = _s.ThumbnailLongEdge }); if (!FolderTemplate.IsDirty) FolderTemplate.Load(settings.Templates.Folder); if (!FileTemplate.IsDirty) FileTemplate.Load(settings.Templates.File); var changed = _s.FolderTemplate != settings.Templates.Folder || _s.FileTemplate != settings.Templates.File @@ -915,20 +932,41 @@ public sealed class SettingsViewModel : SectionViewModel { Log.Warning("settings", "The open archive's settings could not be read", ex); } + return archive; + } + + /// + /// The archive an Archive row edits, as the folder was when the row was edited (, the + /// latest folder change then): the open one, or, while the archive at that folder is still opening, the one found + /// there once it has (null for none), so the edit is neither lost nor sent to a folder chosen later. + /// + private async Task ArchiveAtFolderAsync(Task retarget) + { + if (retarget.IsCompleted) return _archive; + // Its failures were told already; only the archive it found matters here. + await ((Task)retarget).ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext | ConfigureAwaitOptions.SuppressThrowing); + return retarget.IsCompletedSuccessfully ? retarget.Result : null; } /// /// Writes one Archive row into the open archive's archive.json and index through the archive engine (BRIEF §7). When - /// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again. + /// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again. An edit made + /// while the archive at a folder just chosen is opening waits for it, then goes to that archive (or stays this PC's + /// default when there is none), instead of being lost. /// private async Task UpdateArchiveAsync(Func edit) { - if (_archive is not { } archive || Shell.Services.Archives is not { } archives) return; + var retarget = _retarget; + var waited = !retarget.IsCompleted; + if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return; try { var updated = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit)); // The archive folder may have changed meanwhile: the rows then belong to another archive. if (_archive?.Id == updated.Id) _archive = updated; + // The open showed the archive's values over the edit: unless another folder was chosen since, the rows (and + // this PC's defaults) take what it holds now. + if (waited && _retarget == retarget) await LoadArchiveAsync(); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException or DatabaseException) @@ -950,9 +988,9 @@ public sealed class SettingsViewModel : SectionViewModel /// /// The archive folder changed: an archive already there is registered as at start (relinked when it moved) and given /// its rescan, and the rows show its settings; any other folder leaves them with this PC's defaults for new archives. - /// Later edits never reach the archive shown before. + /// Later edits never reach the archive shown before. Returns the archive found there (null for none). /// - private async Task RetargetArchiveAsync() + private async Task RetargetArchiveAsync() { _archive = null; if (_s.LastArchivePath is { } root && Shell.Services.Archives is { } archives) @@ -968,7 +1006,7 @@ public sealed class SettingsViewModel : SectionViewModel Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true); } } - await LoadArchiveAsync(); + return await LoadArchiveAsync(); } /// @@ -1306,19 +1344,8 @@ public sealed class SettingsViewModel : SectionViewModel UiLanguage.Apply(null); break; case SettingsPage.Archive: - // The rows are the open archive's own: resetting them changes it for everyone sharing it, so only when confirmed. - var open = _archive; - if (open is not null && !ConfirmArchiveReset(open)) return; - _s.FolderTemplate = defaults.FolderTemplate; - _s.FileTemplate = defaults.FileTemplate; - _s.ProxyLongEdge = defaults.ProxyLongEdge; - _s.ThumbnailLongEdge = defaults.ThumbnailLongEdge; - _s.ScanIntervalMinutes = defaults.ScanIntervalMinutes; - FolderTemplate.Load(_s.FolderTemplate); - FileTemplate.Load(_s.FileTemplate); - UpdatePreview(); - if (open is not null) _ = PushArchiveSettingsAsync(); - break; + _ = ResetArchiveAsync(defaults); + return; case SettingsPage.Import: _s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes; _s.ImportMinimumFrames = defaults.ImportMinimumFrames; @@ -1367,6 +1394,28 @@ public sealed class SettingsViewModel : SectionViewModel Shell.Server.Refresh(); } + /// + /// Archive › Reset section. The rows are the open archive's own: resetting them changes it for everyone sharing it, so + /// only when confirmed. The archive at a folder just chosen is opened first, so the question names it and the reset + /// reaches it instead of being undone when it opens. + /// + private async Task ResetArchiveAsync(AppSettings defaults) + { + var open = await ArchiveAtFolderAsync(_retarget); + if (open is not null && !ConfirmArchiveReset(open)) return; + _s.FolderTemplate = defaults.FolderTemplate; + _s.FileTemplate = defaults.FileTemplate; + _s.ProxyLongEdge = defaults.ProxyLongEdge; + _s.ThumbnailLongEdge = defaults.ThumbnailLongEdge; + _s.ScanIntervalMinutes = defaults.ScanIntervalMinutes; + FolderTemplate.Load(_s.FolderTemplate); + FileTemplate.Load(_s.FileTemplate); + UpdatePreview(); + Save(); + OnAllPropertiesChanged(); + if (open is not null) await PushArchiveSettingsAsync(); + } + private void LoadImportFields() { SessionGap.Load(_s.ImportSessionGapMinutes.ToString(CultureInfo.CurrentCulture)); @@ -1484,7 +1533,7 @@ public sealed class SettingsViewModel : SectionViewModel ApplyAll(imported); // Settings of a PC never rewrite the shared archive.json: the imported templates and sizes are the defaults of new // archives, and the rows show the own settings of the archive at the (possibly imported) archive folder. - _ = RetargetArchiveAsync(); + _retarget = RetargetArchiveAsync(); Shell.Notify(Loc.L("Settings.Import.Done")); } diff --git a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs index ebe92133..8d2a3408 100644 --- a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs @@ -169,6 +169,51 @@ public sealed class SettingsScreenSmokeTests installs[0].Command.Execute(null); }); + [Test] + public Task ArchiveRowsEditOnlyTheArchiveAtTheFolderAndKeepEditsMadeWhileItOpens() => ScreenHost.RunAsync(async () => + { + await using var app = await ScreenSmokeTests.SampleApp.StartAsync(); + var shell = app.Shell; + await app.Sample.FillAsync(); + var settings = shell.Settings; + var db = shell.Services.Database!; + var archive = Assert.NotNull(await Titano.App.Archiving.CurrentArchive.FindAsync(db, null)); + var manifestPath = new Titano.Core.Archiving.ArchivePaths(archive.RootPath).ManifestPath; + static Titano.Core.Archiving.ArchiveManifest Read(string path) => Titano.Core.Archiving.ManifestStore.ReadArchive(path); + shell.Navigate(SectionKey.Settings); + settings.Page = SettingsPage.Archive; + + // No archive folder: a template edit is this PC's default only, never the first archive of the index. + settings.ArchiveRoot.Text = string.Empty; + Assert.True(settings.ArchiveRoot.Commit()); + settings.FolderTemplate.Text = "{camera}/{date}"; + Assert.True(settings.FolderTemplate.Commit()); + + // The archive's folder is chosen and a template edited at once, while that archive is still opening: the edit + // reaches its archive.json instead of being undone when it opens, and the row shows it. + settings.ArchiveRoot.Text = archive.RootPath; + Assert.True(settings.ArchiveRoot.Commit()); + settings.FileTemplate.Text = "{date}_{n:0000}"; + Assert.True(settings.FileTemplate.Commit()); + await WaitAsync(() => Read(manifestPath).LayoutTemplates.File == "{date}_{n:0000}", "the edit reached the archive that was opening"); + await WaitAsync(() => settings.FileTemplate.Text == "{date}_{n:0000}" && shell.Services.Settings.FileTemplate == "{date}_{n:0000}", "the row shows it"); + Assert.NotEqual("{camera}/{date}", Read(manifestPath).LayoutTemplates.Folder); + + // Offline, only archive.json knows the thumbnail size: this PC's stays instead of becoming the default. + Titano.Core.Archiving.ManifestStore.WriteArchive(manifestPath, Read(manifestPath) with { ThumbnailPolicy = new Titano.Core.Archiving.ThumbnailPolicy { LongEdge = 480 } }); + shell.Navigate(SectionKey.Library); + shell.Navigate(SectionKey.Settings); + await WaitAsync(() => shell.Services.Settings.ThumbnailLongEdge == 480, "the archive's thumbnail size is shown"); + var row = Assert.NotNull(await db.Archives.GetAsync(archive.Id)); + await db.Archives.UpsertAsync(row with { ProxyLongEdge = 2560 }); + System.IO.File.Move(manifestPath, manifestPath + ".away"); + shell.Navigate(SectionKey.Library); + shell.Navigate(SectionKey.Settings); + await WaitAsync(() => shell.Services.Settings.ProxyLongEdge == 2560, "the index's proxy size is shown while offline"); + Assert.Equal(480, shell.Services.Settings.ThumbnailLongEdge); + Assert.Equal(480, settings.SelectedThumbnailSize.Value); + }); + [Test] public Task TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () => { From bf2183764f760cc222f6e5936bc67e049f5a475f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:33:45 +0000 Subject: [PATCH 5/8] fix(settings): an archive row edit reaches the folder it was made for A retarget now returns the archive registered at its own folder, not at the folder current when it finishes, so an edit made while folder A opens no longer lands in the archive of a folder B chosen right after. The rows and _archive follow only the latest folder; Reset section pushes to the archive it asked about and reloads the rows when the folder changed. A newer sidecar met while opening no longer faults the retarget silently: it is reported like any open failure. The smoke test now waits for the empty-folder retarget before editing, so the archives[0] fallback would fail it, and covers the two-folder race. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.App/Sections/SettingsViewModel.cs | 60 +++++++++++++------ .../Settings/SettingsScreenSmokeTests.cs | 27 ++++++++- 2 files changed, 69 insertions(+), 18 deletions(-) diff --git a/src/Titano.App/Sections/SettingsViewModel.cs b/src/Titano.App/Sections/SettingsViewModel.cs index f899372e..b041255d 100644 --- a/src/Titano.App/Sections/SettingsViewModel.cs +++ b/src/Titano.App/Sections/SettingsViewModel.cs @@ -313,6 +313,9 @@ public sealed class SettingsViewModel : SectionViewModel /// Where "Start with Windows" is kept (the Run key); screenshots, tests and portable copies keep it in memory. internal IStartWithWindows Startup { get; set; } + /// The latest archive folder change: done once the rows show what the folder holds (tests wait for it). + internal Task ArchiveRetarget => _retarget; + /// A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row. public bool ShowsStartup => !Shell.Services.Environment.IsPortable; @@ -899,19 +902,28 @@ public sealed class SettingsViewModel : SectionViewModel /// archive is the one at the archive folder of this PC, never another one of the index: with no folder, or none /// registered there, the rows edit only this PC's defaults. Returns that archive (null for none). /// - private async Task LoadArchiveAsync() + private Task LoadArchiveAsync() => LoadArchiveAsync(_s.LastArchivePath); + + /// + /// for the archive folder , which a folder change may have + /// replaced meanwhile: the rows are then left to the folder chosen since, and the archive registered at + /// is still returned, so edits made for that folder reach it. + /// + private async Task LoadArchiveAsync(string? root) { if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return null; Archive? archive = null; try { var registered = await db.Archives.ListAsync(); - archive = _s.LastArchivePath is { Length: > 0 } root ? CurrentArchive.At(registered, root) : null; + archive = root is { Length: > 0 } ? CurrentArchive.At(registered, root) : null; + if (!IsArchiveFolder(root)) return archive; _archive = archive; if (archive is null) return null; var settings = await Task.Run(() => archives.RefreshSettingsAsync(archive.Id)) ?? new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate }, new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy { LongEdge = _s.ThumbnailLongEdge }); + if (!IsArchiveFolder(root)) return archive; if (!FolderTemplate.IsDirty) FolderTemplate.Load(settings.Templates.Folder); if (!FileTemplate.IsDirty) FileTemplate.Load(settings.Templates.File); var changed = _s.FolderTemplate != settings.Templates.Folder || _s.FileTemplate != settings.Templates.File @@ -935,14 +947,18 @@ public sealed class SettingsViewModel : SectionViewModel return archive; } + /// Whether is still this PC's archive folder (the one the rows show). + private bool IsArchiveFolder(string? root) => string.Equals(root, _s.LastArchivePath, StringComparison.Ordinal); + /// /// The archive an Archive row edits, as the folder was when the row was edited (, the - /// latest folder change then): the open one, or, while the archive at that folder is still opening, the one found - /// there once it has (null for none), so the edit is neither lost nor sent to a folder chosen later. + /// latest folder change then): the open one, or, while the archive at that folder is still opening or once another + /// folder has been chosen, the one found there (null for none), so the edit is neither lost nor sent to a folder + /// chosen later. /// private async Task ArchiveAtFolderAsync(Task retarget) { - if (retarget.IsCompleted) return _archive; + if (retarget.IsCompleted && retarget == _retarget) return _archive; // Its failures were told already; only the archive it found matters here. await ((Task)retarget).ConfigureAwait(ConfigureAwaitOptions.ContinueOnCapturedContext | ConfigureAwaitOptions.SuppressThrowing); return retarget.IsCompletedSuccessfully ? retarget.Result : null; @@ -952,11 +968,12 @@ public sealed class SettingsViewModel : SectionViewModel /// Writes one Archive row into the open archive's archive.json and index through the archive engine (BRIEF §7). When /// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again. An edit made /// while the archive at a folder just chosen is opening waits for it, then goes to that archive (or stays this PC's - /// default when there is none), instead of being lost. + /// default when there is none), instead of being lost. is the folder change the edit was + /// made after, the latest one by default. /// - private async Task UpdateArchiveAsync(Func edit) + private async Task UpdateArchiveAsync(Func edit, Task? retarget = null) { - var retarget = _retarget; + retarget ??= _retarget; var waited = !retarget.IsCompleted; if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return; try @@ -977,36 +994,42 @@ public sealed class SettingsViewModel : SectionViewModel } } - /// Every archive row into the open archive: Archive › Reset section, after the user confirmed it for that archive. - private Task PushArchiveSettingsAsync() => UpdateArchiveAsync(a => a with + /// + /// Every archive row into the archive found after : Archive › Reset section, after the user + /// confirmed it for that archive. + /// + private Task PushArchiveSettingsAsync(Task retarget) => UpdateArchiveAsync(a => a with { Templates = a.Templates with { Folder = _s.FolderTemplate, File = _s.FileTemplate }, Proxies = a.Proxies with { LongEdge = _s.ProxyLongEdge }, Thumbnails = a.Thumbnails with { LongEdge = _s.ThumbnailLongEdge }, - }); + }, retarget); /// /// The archive folder changed: an archive already there is registered as at start (relinked when it moved) and given /// its rescan, and the rows show its settings; any other folder leaves them with this PC's defaults for new archives. - /// Later edits never reach the archive shown before. Returns the archive found there (null for none). + /// Later edits never reach the archive shown before. Returns the archive registered at that folder (null for none), + /// even when another folder has been chosen since: edits made for this one go there. /// private async Task RetargetArchiveAsync() { _archive = null; - if (_s.LastArchivePath is { } root && Shell.Services.Archives is { } archives) + var root = _s.LastArchivePath; + if (root is not null && Shell.Services.Archives is { } archives) { try { var opened = await Task.Run(async () => File.Exists(new ArchivePaths(root).ManifestPath) ? await archives.OpenAsync(root) : null); if (opened is not null) await Shell.Services.QueueScanAsync(opened, full: false); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or DatabaseException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException + or DatabaseException) { Log.Warning("settings", $"The archive at {root} could not be opened", ex); Shell.Notify(Loc.L("Errors.Archive.Open"), ArchiveActions.Cause(ex), isError: true); } } - return await LoadArchiveAsync(); + return await LoadArchiveAsync(root); } /// @@ -1401,7 +1424,8 @@ public sealed class SettingsViewModel : SectionViewModel /// private async Task ResetArchiveAsync(AppSettings defaults) { - var open = await ArchiveAtFolderAsync(_retarget); + var retarget = _retarget; + var open = await ArchiveAtFolderAsync(retarget); if (open is not null && !ConfirmArchiveReset(open)) return; _s.FolderTemplate = defaults.FolderTemplate; _s.FileTemplate = defaults.FileTemplate; @@ -1413,7 +1437,9 @@ public sealed class SettingsViewModel : SectionViewModel UpdatePreview(); Save(); OnAllPropertiesChanged(); - if (open is not null) await PushArchiveSettingsAsync(); + if (open is not null) await PushArchiveSettingsAsync(retarget); + // Another folder was chosen while this one's archive opened: the rows show what that folder's archive holds again. + if (retarget != _retarget) await LoadArchiveAsync(); } private void LoadImportFields() diff --git a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs index 8d2a3408..7215198c 100644 --- a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs @@ -183,11 +183,14 @@ public sealed class SettingsScreenSmokeTests shell.Navigate(SectionKey.Settings); settings.Page = SettingsPage.Archive; - // No archive folder: a template edit is this PC's default only, never the first archive of the index. + // No archive folder: a template edit is this PC's default only, never the first archive of the index. The edit is + // made once the rows follow the empty folder, so it cannot wait for anything that would hide a write. settings.ArchiveRoot.Text = string.Empty; Assert.True(settings.ArchiveRoot.Commit()); + await settings.ArchiveRetarget; settings.FolderTemplate.Text = "{camera}/{date}"; Assert.True(settings.FolderTemplate.Commit()); + Assert.Equal("{camera}/{date}", shell.Services.Settings.FolderTemplate); // The archive's folder is chosen and a template edited at once, while that archive is still opening: the edit // reaches its archive.json instead of being undone when it opens, and the row shows it. @@ -199,6 +202,28 @@ public sealed class SettingsScreenSmokeTests await WaitAsync(() => settings.FileTemplate.Text == "{date}_{n:0000}" && shell.Services.Settings.FileTemplate == "{date}_{n:0000}", "the row shows it"); Assert.NotEqual("{camera}/{date}", Read(manifestPath).LayoutTemplates.Folder); + // An edit made before a second folder change, while the first folder's archive is still opening, goes to that + // archive: never to the archive at the folder chosen after it. + var otherRoot = System.IO.Path.Combine(shell.Services.Environment.DataDirectory, "other-archive"); + await shell.Services.Archives!.CreateAsync(otherRoot, "Other"); + var otherManifestPath = new Titano.Core.Archiving.ArchivePaths(otherRoot).ManifestPath; + settings.ArchiveRoot.Text = otherRoot; + Assert.True(settings.ArchiveRoot.Commit()); + await settings.ArchiveRetarget; + settings.ArchiveRoot.Text = archive.RootPath; + Assert.True(settings.ArchiveRoot.Commit()); + settings.FileTemplate.Text = "{date}-{n:0000}"; + Assert.True(settings.FileTemplate.Commit()); + settings.ArchiveRoot.Text = otherRoot; + Assert.True(settings.ArchiveRoot.Commit()); + await WaitAsync(() => Read(manifestPath).LayoutTemplates.File == "{date}-{n:0000}", "the edit reached the archive of the folder it was made for"); + await settings.ArchiveRetarget; + Assert.NotEqual("{date}-{n:0000}", Read(otherManifestPath).LayoutTemplates.File); + Assert.Equal(Read(otherManifestPath).LayoutTemplates.File, settings.FileTemplate.Text); + settings.ArchiveRoot.Text = archive.RootPath; + Assert.True(settings.ArchiveRoot.Commit()); + await settings.ArchiveRetarget; + // Offline, only archive.json knows the thumbnail size: this PC's stays instead of becoming the default. Titano.Core.Archiving.ManifestStore.WriteArchive(manifestPath, Read(manifestPath) with { ThumbnailPolicy = new Titano.Core.Archiving.ThumbnailPolicy { LongEdge = 480 } }); shell.Navigate(SectionKey.Library); From c68590920f1c0093a23d705ddc5550a8230fd731 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:33:56 +0000 Subject: [PATCH 6/8] fix(archive): the admin form reads archive.json; a poll never undoes an admin's edit GET /api/v1/archive/settings refreshes the served archive from archive.json first, so the admin form (which saves every field) starts from a desktop's change made since the last poll instead of writing the old templates back. ServerArchive.RefreshAsync replaces the served archive only when the refresh registered a change, and only through a compare-and-swap against the archive it read, so a poll racing an admin's PUT no longer puts the pre-edit row back for ten minutes. RefreshSettingsAsync now ignores an archive.json a newer Titano wrote, as documented, instead of registering what this version reads of it. AppServicesTests now points the folder at an archive the index does not list first, and checks that the archive no longer chosen gets no scan. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Data/Archiving/ArchiveService.cs | 27 ++++++++++++----- src/Titano.Server/Api/ArchiveEndpoints.cs | 4 ++- src/Titano.Server/Storage/ArchivePolling.cs | 3 +- src/Titano.Server/Storage/ServerArchive.cs | 23 +++++++++++++++ .../Infrastructure/AppServicesTests.cs | 29 ++++++++++++++----- .../Archiving/ArchiveSettingsTests.cs | 9 ++++++ .../Storage/ArchiveModuleTests.cs | 23 +++++++++++++-- 7 files changed, 98 insertions(+), 20 deletions(-) diff --git a/src/Titano.Data/Archiving/ArchiveService.cs b/src/Titano.Data/Archiving/ArchiveService.cs index ddd1fce3..be8b1150 100644 --- a/src/Titano.Data/Archiving/ArchiveService.cs +++ b/src/Titano.Data/Archiving/ArchiveService.cs @@ -163,15 +163,15 @@ public sealed class ArchiveService : IJobHandlerProvider { var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false); if (TryReadManifest(archive) is not { } manifest) return null; - if (manifest.Name != archive.Name || manifest.LayoutTemplates.Folder != archive.FolderTemplate || manifest.LayoutTemplates.File != archive.FileTemplate - || manifest.ProxyPolicy.LongEdge != archive.ProxyLongEdge) + var settings = ArchiveSettings.Of(manifest); + if (!settings.IsRegisteredIn(archive)) { // Read without the settings lease, as at open: an edit made meanwhile writes its own row, and the next refresh // settles a file that changes again. await RegisterAsync(new ArchivePaths(archive.RootPath), manifest, cancellationToken).ConfigureAwait(false); Log.Info("archive", $"Settings of {archive.RootPath} changed elsewhere: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}"); } - return ArchiveSettings.Of(manifest); + return settings; } /// @@ -339,7 +339,10 @@ public sealed class ArchiveService : IJobHandlerProvider return archive; } - /// The archive's archive.json; null (logged) while it cannot be read or when it belongs to another archive. + /// + /// The archive's archive.json; null (logged) while it cannot be read, when a newer Titano wrote it (this one + /// would drop what it does not know) or when it belongs to another archive. + /// private static ArchiveManifest? TryReadManifest(Archive archive) { var paths = new ArchivePaths(archive.RootPath); @@ -347,10 +350,12 @@ public sealed class ArchiveService : IJobHandlerProvider { if (!File.Exists(paths.ManifestPath)) return null; var manifest = ManifestStore.ReadArchive(paths.ManifestPath); - if (manifest.Id == archive.Id) return manifest; - Log.Warning("archive", $"{paths.ManifestPath} belongs to archive {manifest.Id}, not {archive.Id}; the index's settings are used"); + if (manifest.SchemaVersion > ArchiveManifest.CurrentSchemaVersion) + Log.Warning("archive", $"{paths.ManifestPath} has schema version {manifest.SchemaVersion}, newer than this Titano's; the index's settings are used"); + else if (manifest.Id == archive.Id) return manifest; + else Log.Warning("archive", $"{paths.ManifestPath} belongs to archive {manifest.Id}, not {archive.Id}; the index's settings are used"); } - catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or NewerFormatException) + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) { Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex); } @@ -381,6 +386,14 @@ public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, Pro public static ArchiveSettings Of(ArchiveManifest manifest) => new(manifest.Name, manifest.LayoutTemplates, manifest.ProxyPolicy, manifest.ThumbnailPolicy); + /// Whether the index row holds these settings (all it keeps: not the thumbnail policy). + public bool IsRegisteredIn(Archive archive) + { + ArgumentNullException.ThrowIfNull(archive); + return Name == archive.Name && Templates.Folder == archive.FolderTemplate && Templates.File == archive.FileTemplate + && Proxies.LongEdge == archive.ProxyLongEdge; + } + /// The first invalid field by its API name (name, folderTemplate, fileTemplate, /// proxyLongEdge, thumbnailLongEdge); null when every field is valid. public string? Problem() diff --git a/src/Titano.Server/Api/ArchiveEndpoints.cs b/src/Titano.Server/Api/ArchiveEndpoints.cs index 953df725..f3b62057 100644 --- a/src/Titano.Server/Api/ArchiveEndpoints.cs +++ b/src/Titano.Server/Api/ArchiveEndpoints.cs @@ -19,7 +19,9 @@ public static class ArchiveEndpoints public static void Map(RouteGroupBuilder api) { var archive = api.MapGroup("/archive").Requires(Permissions.ManageArchive); - archive.MapGet("/settings", (ServerArchive a) => Results.Json(Settings(a.Current), ProtocolJson.Default.ArchiveSettingsDto)); + // The form saves every field: it starts from what archive.json holds now, also a desktop's change since the last poll. + archive.MapGet("/settings", async (HttpContext c, ServerArchive a, TitanoDatabase db, [FromServices] ArchiveService? archives) => + Results.Json(Settings(archives is null ? a.Current : await a.RefreshAsync(archives, db, c.RequestAborted)), ProtocolJson.Default.ArchiveSettingsDto)); archive.MapPut("/settings", UpdateAsync); archive.MapGet("/stats", async (HttpContext c, TitanoDatabase db, ServerArchive a) => Results.Json(await StatsAsync(db, a, c.RequestAborted), ProtocolJson.Default.ArchiveStatsDto)); diff --git a/src/Titano.Server/Storage/ArchivePolling.cs b/src/Titano.Server/Storage/ArchivePolling.cs index 739d6451..32a0d3ff 100644 --- a/src/Titano.Server/Storage/ArchivePolling.cs +++ b/src/Titano.Server/Storage/ArchivePolling.cs @@ -28,8 +28,7 @@ public sealed class ArchivePolling(TitanoDatabase db, ServerArchive archive, Arc if (!jobs.CanRun(JobKind.Scan)) return null; var current = archive.Current; if (ArchiveService.GetAvailability(current) != ArchiveAvailability.Online) return null; - if (await archives.RefreshSettingsAsync(current.Id, cancellationToken) is not null && await db.Archives.GetAsync(current.Id, cancellationToken) is { } row) - archive.Current = current = row; + current = await archive.RefreshAsync(archives, db, cancellationToken); foreach (var kind in new[] { JobKind.Scan, JobKind.Rebuild }) { foreach (var state in Pending) diff --git a/src/Titano.Server/Storage/ServerArchive.cs b/src/Titano.Server/Storage/ServerArchive.cs index f6ca64b6..8565acb7 100644 --- a/src/Titano.Server/Storage/ServerArchive.cs +++ b/src/Titano.Server/Storage/ServerArchive.cs @@ -19,6 +19,29 @@ public sealed class ServerArchive(Archive archive) set => _current = value; } + /// + /// Serves unless is no longer , the archive + /// it was read from: an edit an administrator saved meanwhile is never undone. False when it was not replaced. + /// + public bool TryReplace(Archive expected, Archive value) => ReferenceEquals(Interlocked.CompareExchange(ref _current, value, expected), expected); + + /// + /// once it and the index row hold the settings another writer sharing the archive (a desktop) + /// put into its archive.json (): uploads, the polling and the admin + /// panel, whose form saves every field, never work from older ones. Unchanged while the file cannot be read. + /// + public async Task RefreshAsync(ArchiveService archives, TitanoDatabase db, CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(archives); + ArgumentNullException.ThrowIfNull(db); + var current = Current; + // Only a change the refresh registered is served, and never over an edit an administrator saved since the read above. + if (await archives.RefreshSettingsAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } settings && !settings.IsRegisteredIn(current) + && await db.Archives.GetAsync(current.Id, cancellationToken).ConfigureAwait(false) is { } row) + TryReplace(current, row); + return Current; + } + public Guid Id => _current.Id; public string Root => _current.RootPath; diff --git a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs index 187a40b0..f8ade358 100644 --- a/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs +++ b/tests/Titano.App.Tests/Infrastructure/AppServicesTests.cs @@ -74,17 +74,30 @@ public sealed class AppServicesTests Assert.Equal(TimeSpan.FromMinutes(30), services.PollingPeriod); // The first-run dialog creates an archive: the next rescan is of it. - await services.ArchiveSetup.CreateAsync(Path.Combine(environment.DataDirectory, "first")); - Assert.Equal("first", (await services.RescanAsync())?.Name); + var firstRoot = Path.Combine(environment.DataDirectory, "first"); + await services.ArchiveSetup.CreateAsync(firstRoot); + var first = Assert.NotNull(await services.RescanAsync()); + Assert.Equal("first", first.Name); - // Settings › Archive moves to another archive: the next rescan is of that one, no longer of the first. - var second = Path.Combine(environment.DataDirectory, "second"); - await new ArchiveService(services.Database!).CreateAsync(second, "Second"); - settings.LastArchivePath = second; + // Settings › Archive moves to another archive, which the index lists after the first one: the next rescan + // is of the archive at the folder, no longer of the first one. + var other = Path.Combine(environment.DataDirectory, "zeta"); + await new ArchiveService(services.Database!).CreateAsync(other, "zeta"); + Assert.Equal("first", (await services.Database!.Archives.ListAsync())[0].Name); + async Task ScansOfAsync(Guid archiveId) => + (await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items.Count(j => j.TargetIds.Contains(archiveId)); + var scansOfFirst = await ScansOfAsync(first.Id); + settings.LastArchivePath = other; services.SaveSettings(); var rescanned = Assert.NotNull(await services.RescanAsync()); - Assert.Equal("Second", rescanned.Name); - Assert.Contains((await services.Database!.Jobs.ListAsync(null, JobKind.Scan)).Items, j => j.TargetIds.Contains(rescanned.Id)); + Assert.Equal("zeta", rescanned.Name); + Assert.True(await ScansOfAsync(rescanned.Id) > 0, "the archive at the folder is rescanned"); + Assert.Equal(scansOfFirst, await ScansOfAsync(first.Id)); + + // And back: the folder decides, whatever the order of the index. + settings.LastArchivePath = firstRoot; + services.SaveSettings(); + Assert.Equal(first.Id, (await services.RescanAsync())?.Id); } finally { diff --git a/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs b/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs index fe5ab3bb..ea057f04 100644 --- a/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs +++ b/tests/Titano.Data.Tests/Archiving/ArchiveSettingsTests.cs @@ -143,6 +143,15 @@ public sealed class ArchiveSettingsTests(TestContext context) Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); Assert.Equal("{year}/{camera}", (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!.FolderTemplate); + // A newer Titano rewrote the file: what this one reads of it is neither shown nor registered. + ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { Name = "Newer", LayoutTemplates = manifest.LayoutTemplates with { Folder = "{camera}" } }); + var newer = JsonNode.Parse(await File.ReadAllTextAsync(fx.Paths.ManifestPath, fx.Ct))!; + newer["schemaVersion"] = ArchiveManifest.CurrentSchemaVersion + 1; + await File.WriteAllTextAsync(fx.Paths.ManifestPath, newer.ToJsonString(), fx.Ct); + Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); + var kept = (await fx.Db.Archives.GetAsync(fx.Archive.Id, fx.Ct))!; + Assert.Equal(("Shared", "{year}/{camera}"), (kept.Name, kept.FolderTemplate)); + // The folder now holds another archive: its settings are neither shown nor registered as this one's. ManifestStore.WriteArchive(fx.Paths.ManifestPath, manifest with { Id = Guid.CreateVersion7(), Name = "Other" }); Assert.Null(await fx.Service.RefreshSettingsAsync(fx.Archive.Id, fx.Ct)); diff --git a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs index 68520d42..24c2ae65 100644 --- a/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs +++ b/tests/Titano.Server.Tests/Storage/ArchiveModuleTests.cs @@ -103,10 +103,16 @@ public sealed class ArchiveModuleTests(TestContext context) } [Test] - public async Task SettingsADesktopChangedInArchiveJsonReachTheServerAtTheNextPoll() + public async Task SettingsADesktopChangedInArchiveJsonReachUploadsAndTheAdminPanel() { await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register); var archive = server.Services.GetRequiredService(); + var polling = server.Services.GetRequiredService(); + // Nothing changed: the served archive (the one an administrator's edit put there) is not replaced by a row read again. + var served = archive.Current; + await polling.PollAsync(context.Cancellation); + Assert.True(ReferenceEquals(served, archive.Current), "a poll that registered nothing keeps the served archive"); + // A desktop sharing the archive changed its folder template and proxy size in archive.json. var path = new ArchivePaths(archive.Root).ManifestPath; var manifest = ManifestStore.ReadArchive(path); @@ -116,12 +122,25 @@ public sealed class ArchiveModuleTests(TestContext context) ProxyPolicy = manifest.ProxyPolicy with { LongEdge = 2560 }, }); - await server.Services.GetRequiredService().PollAsync(context.Cancellation); + await polling.PollAsync(context.Cancellation); // Uploads (the index row) and the admin panel (the served archive) follow it. Assert.Equal(("{camera}/{date}", 2560), (archive.Current.FolderTemplate, archive.Current.ProxyLongEdge)); var row = Assert.NotNull(await server.Database.Archives.GetAsync(archive.Id, context.Cancellation)); Assert.Equal(("{camera}/{date}", 2560), (row.FolderTemplate, row.ProxyLongEdge)); + + // The admin panel opens before the next poll: its form, which saves every field, starts from the desktop's change. + ManifestStore.WriteArchive(path, ManifestStore.ReadArchive(path) with { LayoutTemplates = manifest.LayoutTemplates with { Folder = "{year}/{camera}" } }); + var admin = await server.AdminAsync(); + using (var read = await admin.GetAsync("/api/v1/archive/settings")) + Assert.Equal("{year}/{camera}", (await read.ReadAsync(ProtocolJson.Default.ArchiveSettingsDto)).FolderTemplate); + Assert.Equal("{year}/{camera}", archive.Current.FolderTemplate); + + // A refresh that read the archive before an administrator saved an edit never puts it back over that edit. + var before = archive.Current; + archive.Current = before with { Name = "Edited" }; + Assert.False(archive.TryReplace(before, before with { Name = "Stale" }), "the edit saved meanwhile stays"); + Assert.Equal("Edited", archive.Current.Name); } private static async Task UntilIndexedAsync(TestServer server, Guid archiveId, string folder) From 760695727679ae0fd64b89fae16a91382e67964b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:34:05 +0000 Subject: [PATCH 7/8] fix(app): warn about a synced data folder and name a portable copy's earlier data AppEnvironment now carries AppPaths.SyncedFolder: when the per-user data folder itself lies in a OneDrive sync root, Titano still starts (nowhere is safer), logs it and shows the error toast "Data inside OneDrive" with Open, instead of the false "Data kept outside OneDrive". The latter now needs PortableSyncRoot (renamed from the old SyncedFolder meaning). A portable copy now in a OneDrive folder whose .\data still holds an index or settings.json gets that folder named in the log and in a toast ("Earlier data unused", with Open). Nothing is moved or deleted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- i18n/en/Settings.resx | 2 + i18n/en/Tooltips.resx | 2 + i18n/it/Settings.it.resx | 2 + i18n/it/Tooltips.it.resx | 2 + src/Titano.App/App.xaml.cs | 4 +- .../Infrastructure/AppEnvironment.cs | 26 +++++++--- src/Titano.App/Sections/SettingsViewModel.cs | 12 ++++- src/Titano.Core.Windows/Shell/AppPaths.cs | 26 ++++++++-- .../Infrastructure/AppEnvironmentTests.cs | 50 ++++++++++++++++++- 9 files changed, 111 insertions(+), 15 deletions(-) diff --git a/i18n/en/Settings.resx b/i18n/en/Settings.resx index 4df33790..d183a3f6 100644 --- a/i18n/en/Settings.resx +++ b/i18n/en/Settings.resx @@ -8,10 +8,12 @@ Index backed up Back up now Data folder + Data inside OneDrive Data kept outside OneDrivelong Diagnostics Diagnostics bundle saved Save the diagnostics bundle to + Earlier data unused Export bundle Logs No backups yet diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index 65d67fdd..ffd83e9b 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -528,10 +528,12 @@ Delete the cache contents now Delete spilled frames and cached thumbnails; asks first Database, settings, logs and caches of this PC + Open the data folder in Explorer. OneDrive synchronises it, which can damage the index: exclude it from syncing New cards and folders queue a deep analysis of what they import, in the background; each card can change it Sequences a scan finds (adopted folders, new sidecars) also get a deep analysis, in the background Server Titano connects to at start; changing it signs out · Enter applies, Esc reverts Zip the logs, a system and codec report, settings and recent failed jobs into a folder you choose; passwords, tokens and photos are left out + Open the data this portable copy kept beside it before it ran from OneDrive. Titano no longer uses it and leaves it as it is Save every setting as JSON, without the session token File name of each frame, for example {date}_{time}_{n:0000}; the extension is added · Enter applies, Esc reverts Archive folders, for example {year}/{date} {camera}; a slash starts a subfolder · Enter applies, Esc reverts diff --git a/i18n/it/Settings.it.resx b/i18n/it/Settings.it.resx index f61c0972..f171f9e0 100644 --- a/i18n/it/Settings.it.resx +++ b/i18n/it/Settings.it.resx @@ -8,10 +8,12 @@ Copia dell'indice salvata Salva una copia Cartella dati + Dati dentro OneDrive Dati tenuti fuori da OneDrive Diagnostica Pacchetto diagnostico salvato Salva il pacchetto in + Dati precedenti inutilizzati Esporta pacchetto Log Ancora nessuna copia diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index 91f31e25..78e9ea04 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -528,10 +528,12 @@ Elimina adesso il contenuto della cache Elimina fotogrammi temporanei e miniature in cache; prima chiede conferma Database, impostazioni, log e cache di questo PC + Apri la cartella dati in Esplora file. OneDrive la sincronizza e così può danneggiare l'indice: escludila dalla sincronizzazione Schede e cartelle nuove accodano l'analisi profonda di ciò che importano, in background; ogni scheda può cambiarlo Anche le sequenze trovate da una scansione (cartelle adottate, nuovi sidecar) ricevono l'analisi profonda, in background Server a cui Titano si connette all'avvio; cambiarlo chiude l'accesso · Invio applica, Esc annulla Comprime log, rapporto su sistema e codec, impostazioni e attività fallite di recente in una cartella a tua scelta; password, token e foto restano fuori + Apri i dati che questa copia portatile teneva accanto a sé prima di trovarsi in OneDrive. Titano non li usa più e li lascia com'erano Salva tutte le impostazioni in JSON, senza il token di sessione Nome del file di ogni fotogramma, ad esempio {date}_{time}_{n:0000}; l'estensione viene aggiunta · Invio applica, Esc annulla Cartelle dell'archivio, ad esempio {year}/{date} {camera}; la barra crea una sottocartella · Invio applica, Esc annulla diff --git a/src/Titano.App/App.xaml.cs b/src/Titano.App/App.xaml.cs index 9da130e6..2125e10f 100644 --- a/src/Titano.App/App.xaml.cs +++ b/src/Titano.App/App.xaml.cs @@ -46,7 +46,9 @@ public partial class App : Application Log.SetSink(capture ? new TeeLogSink(_log, new StderrLogSink()) : _log); Log.Info("app", $"Titano {AppServices.VersionText} starting; data at {Environment.DataDirectory}"); // Settings tells the user once the window is up. - if (Environment.SyncedFolder is { } synced) Log.Warning("app", $"This portable copy runs in the OneDrive folder {synced}: its data is kept outside it"); + if (Environment.PortableSyncRoot is { } portableIn) Log.Warning("app", $"This portable copy runs in the OneDrive folder {portableIn}: its data is kept outside it"); + if (Environment.EarlierPortableData is { } earlier) Log.Warning("app", $"The data this portable copy kept in {earlier} before is left there and no longer used"); + if (Environment.SyncedFolder is { } synced) Log.Warning("app", $"The data folder lies in the OneDrive folder {synced}: synchronisation may damage the index"); var projectFile = capture ? null : ProjectFileArgument(e.Args); if (!capture) diff --git a/src/Titano.App/Infrastructure/AppEnvironment.cs b/src/Titano.App/Infrastructure/AppEnvironment.cs index 06c60555..83a2cbc1 100644 --- a/src/Titano.App/Infrastructure/AppEnvironment.cs +++ b/src/Titano.App/Infrastructure/AppEnvironment.cs @@ -7,16 +7,20 @@ namespace Titano.App.Infrastructure; /// Where the client keeps its data (BRIEF §6.2, ): %LOCALAPPDATA%\Titano, or .\data /// next to the executable when portable.txt exists. Never inside a folder OneDrive synchronises (SQLite corrupts /// there): a portable copy in one keeps its data in %LOCALAPPDATA%\Titano, and Settings tells the user so -/// (). +/// (, ). When that folder itself lies in one, nowhere +/// is safe: Titano starts all the same and Settings warns (). /// public sealed class AppEnvironment { - private AppEnvironment(string dataDirectory, bool portable, bool isCapture, string? syncedFolder = null) + private AppEnvironment(string dataDirectory, bool portable, bool isCapture, string? syncedFolder = null, string? portableSyncRoot = null, + string? earlierPortableData = null) { DataDirectory = dataDirectory; IsPortable = portable; IsCapture = isCapture; SyncedFolder = syncedFolder; + PortableSyncRoot = portableSyncRoot; + EarlierPortableData = earlierPortableData; Directory.CreateDirectory(DataDirectory); Directory.CreateDirectory(LogDirectory); Directory.CreateDirectory(CacheDirectory); @@ -28,20 +32,30 @@ public sealed class AppEnvironment /// A throw-away environment for --capture: nothing of the user's data is read or written. public bool IsCapture { get; } - /// The OneDrive folder this portable copy runs from; its data is in %LOCALAPPDATA%\Titano instead of .\data. Null otherwise. + /// The OneDrive folder itself lies in, where the index may be damaged; null when it is safe. public string? SyncedFolder { get; } + /// The OneDrive folder this portable copy runs from; its data is in %LOCALAPPDATA%\Titano instead of .\data. Null otherwise. + public string? PortableSyncRoot { get; } + + /// The .\data folder this portable copy used before it ran from OneDrive, left as it was; null when there is none. + public string? EarlierPortableData { get; } + public string LogDirectory => Path.Combine(DataDirectory, "logs"); public string CacheDirectory => Path.Combine(DataDirectory, "cache"); public string BackupDirectory => Path.Combine(DataDirectory, "backups"); - public string DatabasePath => Path.Combine(DataDirectory, "titano.db"); - public string SettingsPath => Path.Combine(DataDirectory, "settings.json"); + public string DatabasePath => Path.Combine(DataDirectory, AppPaths.DatabaseFileName); + public string SettingsPath => Path.Combine(DataDirectory, AppPaths.SettingsFileName); /// The environment of this process: its executable's folder and the user's OneDrive folders decide. public static AppEnvironment Detect() => From(AppPaths.Resolve()); /// The environment at (its folders are created). - public static AppEnvironment From(AppPaths paths) => new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.PortableSyncRoot); + public static AppEnvironment From(AppPaths paths) + { + ArgumentNullException.ThrowIfNull(paths); + return new(paths.DataRoot, paths.IsPortable, isCapture: false, paths.SyncedFolder, paths.PortableSyncRoot, paths.EarlierPortableData); + } /// A fresh temporary data folder for screenshots and smoke tests; delete it with . public static AppEnvironment ForCapture() => diff --git a/src/Titano.App/Sections/SettingsViewModel.cs b/src/Titano.App/Sections/SettingsViewModel.cs index b041255d..72fbc458 100644 --- a/src/Titano.App/Sections/SettingsViewModel.cs +++ b/src/Titano.App/Sections/SettingsViewModel.cs @@ -808,10 +808,18 @@ public sealed class SettingsViewModel : SectionViewModel Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true); break; } - // BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead. - if (Shell.Services.Environment.SyncedFolder is not null) + // BRIEF §6.2: a portable copy in a folder OneDrive synchronises keeps its data in this user's folder instead, and + // leaves the data it kept beside it before where it is. Only a user folder that is itself synchronised is unsafe. + var environment = Shell.Services.Environment; + if (environment.SyncedFolder is not null) + Shell.Notify(Loc.L("Settings.Advanced.DataInOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"), + Loc.L("Tooltips.Settings.DataInOneDrive"), () => ShellActions.Reveal(DataFolder), isError: true); + else if (environment.PortableSyncRoot is not null) Shell.Notify(Loc.L("Settings.Advanced.DataOutsideOneDrive"), Formatting.LeftToRight(DataFolder), Loc.L("Common.Open"), Loc.L("Tooltips.Settings.OpenDataFolder"), () => ShellActions.Reveal(DataFolder)); + if (environment.EarlierPortableData is { } earlier) + Shell.Notify(Loc.L("Settings.Advanced.EarlierData"), Formatting.LeftToRight(earlier), Loc.L("Common.Open"), + Loc.L("Tooltips.Settings.EarlierData"), () => ShellActions.Reveal(earlier)); Startup.Refresh(); } diff --git a/src/Titano.Core.Windows/Shell/AppPaths.cs b/src/Titano.Core.Windows/Shell/AppPaths.cs index 7bd02b74..91279f78 100644 --- a/src/Titano.Core.Windows/Shell/AppPaths.cs +++ b/src/Titano.Core.Windows/Shell/AppPaths.cs @@ -6,20 +6,22 @@ namespace Titano.Core.Windows.Shell; /// Where the desktop programs keep their data (BRIEF §6.2, ): %LOCALAPPDATA%\Titano, or /// .\data next to the executable in portable mode. SQLite corrupts inside synchronised folders, so a portable /// copy in a OneDrive folder keeps its data in %LOCALAPPDATA%\Titano instead ( -/// names that folder to tell the user), and a data root still under OneDrive is reported by -/// and refused by . +/// names that folder to tell the user, the data it kept there before), and a data +/// root still under OneDrive is reported by and refused by . /// public sealed class AppPaths { public const string ProductFolderName = DataLocation.ProductFolderName; public const string DatabaseFileName = "titano.db"; + public const string SettingsFileName = "settings.json"; - private AppPaths(DataLocation location) + private AppPaths(DataLocation location, string? earlierPortableData) { DataRoot = location.Root; IsPortable = location.IsPortable; SyncedFolder = location.SyncedFolder; PortableSyncRoot = location.PortableSyncRoot; + EarlierPortableData = earlierPortableData; } /// A portable copy, also when its data had to go to %LOCALAPPDATA%\Titano. @@ -43,6 +45,12 @@ public sealed class AppPaths /// The OneDrive sync root a portable copy runs from, whose data is in %LOCALAPPDATA%\Titano instead; null otherwise. public string? PortableSyncRoot { get; } + /// + /// The .\data folder of a portable copy now in a OneDrive folder when it still holds the index or the settings + /// of an earlier start: nothing moves or deletes it, and the user is told where it is. Null otherwise. + /// + public string? EarlierPortableData { get; } + /// Paths for this process: the executable's folder decides portable mode. public static AppPaths Resolve() => Resolve(AppContext.BaseDirectory, KnownFolders.LocalAppData); @@ -51,8 +59,16 @@ public sealed class AppPaths Resolve(applicationDirectory, localAppData, OneDriveFolders.SyncRoots()); /// Paths for an executable in , checked against . - public static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyCollection syncRoots) => - new(DataLocation.Choose(applicationDirectory, PortableMode.IsEnabled(applicationDirectory), localAppData, syncRoots)); + public static AppPaths Resolve(string applicationDirectory, string localAppData, IReadOnlyCollection syncRoots) + { + var location = DataLocation.Choose(applicationDirectory, PortableMode.IsEnabled(applicationDirectory), localAppData, syncRoots); + var beside = Path.GetFullPath(Path.Combine(applicationDirectory, PortableMode.DataFolderName)); + var earlier = location.PortableSyncRoot is not null + && (File.Exists(Path.Combine(beside, DatabaseFileName)) || File.Exists(Path.Combine(beside, SettingsFileName))) + ? beside + : null; + return new AppPaths(location, earlier); + } /// Creates the data, logs, cache and thumbnails folders. /// The data root lies inside a OneDrive-synced folder. diff --git a/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs b/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs index 771e2d94..a50b4cf6 100644 --- a/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs +++ b/tests/Titano.App.Tests/Infrastructure/AppEnvironmentTests.cs @@ -20,7 +20,9 @@ public sealed class AppEnvironmentTests(TestContext context) Assert.Equal(Path.Combine(local, "Titano", "titano.db"), environment.DatabasePath); Assert.True(environment.IsPortable, "still a portable copy: updates fetch the portable zip, no sign-in entry"); - Assert.Equal(oneDrive, environment.SyncedFolder); + Assert.Equal(oneDrive, environment.PortableSyncRoot); + Assert.Null(environment.SyncedFolder); + Assert.Null(environment.EarlierPortableData); Assert.True(Directory.Exists(environment.LogDirectory)); Assert.False(Directory.Exists(Path.Combine(app, "data")), "nothing is written into the synchronised folder"); @@ -29,6 +31,52 @@ public sealed class AppEnvironmentTests(TestContext context) File.WriteAllText(Path.Combine(stick, PortableMode.MarkerFileName), ""); var beside = AppEnvironment.From(AppPaths.Resolve(stick, local, [oneDrive])); Assert.Equal(Path.Combine(stick, "data"), beside.DataDirectory); + Assert.Null(beside.PortableSyncRoot); Assert.Null(beside.SyncedFolder); } + + [Test] + public void TheDataAPortableCopyKeptInOneDriveBeforeIsNamedAndLeftAlone() + { + var oneDrive = context.CreateTempDirectory("onedrive"); + var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Documents", "Titano")).FullName; + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + // An earlier version kept its index and settings beside the program. + var earlier = Directory.CreateDirectory(Path.Combine(app, "data")).FullName; + File.WriteAllText(Path.Combine(earlier, "settings.json"), "{}"); + File.WriteAllBytes(Path.Combine(earlier, "titano.db"), [1, 2, 3]); + var local = context.CreateTempDirectory("local"); + + var environment = AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive])); + + Assert.Equal(earlier, environment.EarlierPortableData); + Assert.Equal(Path.Combine(local, "Titano"), environment.DataDirectory); + Assert.SequenceEqual(new byte[] { 1, 2, 3 }, File.ReadAllBytes(Path.Combine(earlier, "titano.db"))); + Assert.Equal("{}", File.ReadAllText(Path.Combine(earlier, "settings.json"))); + + // A data folder with neither (logs only) holds nothing the user would miss. + File.Delete(Path.Combine(earlier, "settings.json")); + File.Delete(Path.Combine(earlier, "titano.db")); + Directory.CreateDirectory(Path.Combine(earlier, "logs")); + Assert.Null(AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive])).EarlierPortableData); + } + + [Test] + public void AUserFolderOneDriveSynchronisesIsReportedNotHidden() + { + // Nowhere is safe: Titano starts all the same, and the folder that is synchronised is named for the warning. + var oneDrive = context.CreateTempDirectory("onedrive"); + var local = Directory.CreateDirectory(Path.Combine(oneDrive, "AppData", "Local")).FullName; + + var installed = AppEnvironment.From(AppPaths.Resolve(context.CreateTempDirectory("app"), local, [oneDrive])); + Assert.Equal(oneDrive, installed.SyncedFolder); + Assert.Null(installed.PortableSyncRoot); + Assert.True(Directory.Exists(installed.LogDirectory)); + + // A portable copy in that OneDrive has nowhere safe either: its data is not said to be kept outside it. + var app = Directory.CreateDirectory(Path.Combine(oneDrive, "Desktop", "Titano")).FullName; + File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), ""); + var portable = AppEnvironment.From(AppPaths.Resolve(app, local, [oneDrive])); + Assert.Equal<(string?, string?)>((oneDrive, oneDrive), (portable.SyncedFolder, portable.PortableSyncRoot)); + } } From fe4a9eacc42cd02d6359080b37b2582f7c7f79ba Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 12 Oct 2026 16:34:12 +0000 Subject: [PATCH 8/8] fix(uploader): Start with Windows shows what Task Manager left when the settings open The Uploader runs for the whole sign-in session and read its sign-in entry only at start, so an entry Task Manager turned off meanwhile still showed as ticked. Opening the settings panel now reads it again. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC --- src/Titano.Uploader/DesignTime/SampleData.cs | 9 ++++-- src/Titano.Uploader/Shell/MainViewModel.cs | 8 +++++- .../Uploader/UploaderScreenSmokeTests.cs | 28 +++++++++++++++++++ 3 files changed, 41 insertions(+), 4 deletions(-) diff --git a/src/Titano.Uploader/DesignTime/SampleData.cs b/src/Titano.Uploader/DesignTime/SampleData.cs index 3d2d80a3..f432af07 100644 --- a/src/Titano.Uploader/DesignTime/SampleData.cs +++ b/src/Titano.Uploader/DesignTime/SampleData.cs @@ -41,13 +41,16 @@ public sealed class SampleData ], }; - /// A view model over in-memory sample services; settings changes are discarded. - public MainViewModel CreateViewModel() + /// + /// A view model over in-memory sample services; settings changes are discarded. stands for + /// the sign-in entry (an in-memory one, on, by default). + /// + public MainViewModel CreateViewModel(IStartupRegistration? startup = null) { var memory = new ProcessedFileMemory(); _session.BandwidthLimit = Settings.BandwidthLimit; _vm = new MainViewModel(new UploaderServices( - Settings, () => { }, _session, _queue, new SampleEngine(_queue), new SampleStartup(), new UploaderDialogs(), + Settings, () => { }, _session, _queue, new SampleEngine(_queue), startup ?? new SampleStartup(), new UploaderDialogs(), new WatchFolderService(memory, _queue.ContainsPath), memory, string.Empty)); foreach (var w in _vm.WatchFolders) w.IsAvailable = true; // A disconnected drive: its chip shows the hollow ring and wraps to a second line. diff --git a/src/Titano.Uploader/Shell/MainViewModel.cs b/src/Titano.Uploader/Shell/MainViewModel.cs index 8e217c1e..0f66906d 100644 --- a/src/Titano.Uploader/Shell/MainViewModel.cs +++ b/src/Titano.Uploader/Shell/MainViewModel.cs @@ -156,7 +156,13 @@ public sealed class MainViewModel : LocalizedViewModel public bool IsSettingsOpen { get => _isSettingsOpen; - set => Set(ref _isSettingsOpen, value); + set + { + if (!Set(ref _isSettingsOpen, value) || !value) return; + // The Uploader runs for the whole session: Task Manager may have turned its sign-in entry off meanwhile. + _startWithWindows = _s.Startup.IsEnabled; + OnPropertyChanged(nameof(StartWithWindows)); + } } // ---------------- Target ---------------- diff --git a/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs b/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs index 19e25822..2dd42775 100644 --- a/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs +++ b/tests/Titano.App.Tests/Uploader/UploaderScreenSmokeTests.cs @@ -125,6 +125,34 @@ public sealed class UploaderScreenSmokeTests } }); + [Test] + public Task StartWithWindowsShowsWhatTaskManagerLeftWhenTheSettingsOpen() => ScreenHost.RunAsync(() => + { + UiLanguage.Apply("en"); + var startup = new SignInEntry { IsEnabled = true }; + var vm = new SampleData().CreateViewModel(startup); + Assert.True(vm.StartWithWindows); + + // The Uploader runs for the whole session: Task Manager turns its entry off meanwhile, and the box follows when + // the settings open. + startup.IsEnabled = false; + var changed = new List(); + vm.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + vm.OpenSettingsCommand.Execute(null); + Assert.False(vm.StartWithWindows, "shown as Task Manager left it"); + Assert.Contains(nameof(MainViewModel.StartWithWindows), changed); + vm.CloseSettingsCommand.Execute(null); + return Task.CompletedTask; + }); + + /// A sign-in entry another program (Task Manager) can turn off. + private sealed class SignInEntry : Titano.Uploader.Infrastructure.IStartupRegistration + { + public bool IsEnabled { get; set; } + + public void SetEnabled(bool enabled) => IsEnabled = enabled; + } + /// A on , shown off screen like --capture. private sealed class UploaderScreen : IDisposable {