diff --git a/deploy/releases-repo/README.md b/deploy/releases-repo/README.md
index 4f3ff4aa..b132fe83 100644
--- a/deploy/releases-repo/README.md
+++ b/deploy/releases-repo/README.md
@@ -128,11 +128,17 @@ accounts and read by other users; when other users can change an existing archiv
Run `Titano.Server.exe` in a console, or install it as a Windows service from an administrator prompt with
`Titano.Server.exe --install-service` (remove it with `--uninstall-service`). The service runs as LocalSystem, so it
registers only from a copy inside `Program Files` that only administrators can change: install for *All users*, or
-unpack the zip into a folder under `Program Files`. A console run that was not elevated creates the data folder as your
-own account, and the service then refuses it. Either delete the folder (with SQLite this also deletes the server's
-database and its accounts), or, before you start the service, give the folder and everything in it to Administrators
-and reset its permissions from an administrator prompt: `takeown /F "C:\ProgramData\Titano Server" /A /R`, then
-`icacls "C:\ProgramData\Titano Server" /reset /T`. The server makes the folder private again at its next start.
+unpack the zip into a folder under `Program Files`. A console run that was not elevated creates the data folder as the
+account that ran it, and the service then refuses the folder and names that account (`… belongs to PC\name …`).
+Either delete the folder (with SQLite this also deletes the server's database and its accounts), or give the folder
+and everything in it to Administrators and take that account's access to it away, from a Command Prompt run as
+administrator: `takeown /F "C:\ProgramData\Titano Server" /A /R`, then
+`icacls "C:\ProgramData\Titano Server" /remove:g "PC\name" /T`, with the account the refusal names in place of
+`PC\name` (`dir /q C:\ProgramData` also shows it, as the folder's owner, until `takeown` runs). When you ran the
+console yourself and the prompt runs as you, that account is `"%USERDOMAIN%\%USERNAME%"`. Then start the service. No
+other account gains access at any step, and afterwards only SYSTEM and Administrators have it, to the TLS key and
+`initial-admin-password.txt` too. Do not reset the folder's permissions (`icacls /reset`): everything in it would then
+inherit those of `C:\ProgramData`, which let every user read it.
## Translations
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index 63684cc3..38b11209 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -349,8 +349,8 @@ One line per decision: date · decision · alternative · reason.
| 2026-10-12 | When another process sharing the archive (a server's admin panel, another PC) changes archive.json, this index catches up when Settings › Archive loads it, before each rescan (desktop and server) and when the server's admin panel opens its archive form. Name, templates and proxy size are registered again from the file without the settings lease. A file that cannot be read, was written by a newer Titano, or belongs to another archive leaves the row alone. The server serves the re-read archive only when the refresh registered a change, and never over an administrator's edit saved since it read the archive (compare-and-swap). | Read the templates from archive.json at every import and upload; refresh only at start | Imports, uploads and the admin panel use the index row, and the admin form saves every field: a stale row lasts only until the next refresh, and an edit made meanwhile registers its own row. |
| 2026-10-12 | While the open archive's archive.json cannot be read, Settings › Archive shows the index's templates and proxy size and keeps this PC's thumbnail size, which the index does not store. | Show and save the default thumbnail policy | The stand-in 320 replaced the user's default for new archives whenever the archive was offline. |
| 2026-10-12 | An Archive row edited (or Reset section) while the archive at a just-chosen folder is opening waits for that open. The edit then goes to the archive registered at that folder, or stays this PC's default when the folder holds none. An edit made before a later folder change still goes to the folder it was made for, and the rows show the archive at the folder chosen last. | Disable the Archive rows while the folder opens | The edit is neither lost silently nor written into another archive's shared archive.json. Nothing is disabled under the user's typing, where a field losing focus would commit anyway. |
-| 2026-10-12 | Start with Windows (client and Uploader) shows as on only while Task Manager has not turned the entry off, i.e. its StartupApproved\Run value does not have an odd first byte. The client reads it again when Settings is shown, the Uploader when its settings panel opens. Ticking the box deletes that value, unticking deletes it with the Run value, and re-pointing the command after a rename keeps it. The uninstaller removes only the Run value; a marker left behind is inert. | Read only the Run value; write 0x02 instead of deleting the marker | Task Manager keeps the Run value when it disables an entry, so the box stayed ticked and could not turn the entry back on. With no marker, Windows runs the entry. |
-| 2026-10-12 | A portable copy whose .\data would lie in a folder OneDrive synchronises keeps its data in %LOCALAPPDATA%\Titano. Sync roots come from the OneDrive environment variables and HKCU\Software\Microsoft\OneDrive\Accounts, matched by whole path segments, ignoring case. The copy otherwise stays portable (portable-zip updates, no sign-in entry) and shows a toast at every start (Data kept outside OneDrive, with Open). It then shares the data folder and the single instance with an installed copy of the same user. The Uploader keeps .\data, since its files are JSON written atomically. Other sync tools are not detected. | Refuse to start; a separate per-copy folder under %LOCALAPPDATA%\Titano | BRIEF §6.2 forbids synchronised folders and names the per-user folder as the location. A copy that refused to start would leave the user with nothing. |
+| 2026-10-12 | Start with Windows (client and Uploader) shows as on only while Task Manager has not turned the entry off, i.e. its StartupApproved\Run value does not have an odd first byte. The client reads it again when Settings is shown, the Uploader when its settings panel opens. Ticking the box deletes that value, unticking deletes it with the Run value, and re-pointing the command after a rename keeps it. Setup removes the value together with the Run value when it removes the entry (see the Task Manager state row below). | Read only the Run value; write 0x02 instead of deleting the marker | Task Manager keeps the Run value when it disables an entry, so the box stayed ticked and could not turn the entry back on. With no marker, Windows runs the entry. |
+| 2026-10-12 | (Partly superseded by the SyncEngines mount point row below: sync roots also come from HKCU\Software\SyncEngines\Providers\OneDrive\*\MountPoint.) A portable copy whose .\data would lie in a folder OneDrive synchronises keeps its data in %LOCALAPPDATA%\Titano. Sync roots come from the OneDrive environment variables and HKCU\Software\Microsoft\OneDrive\Accounts, matched by whole path segments, ignoring case. The copy otherwise stays portable (portable-zip updates, no sign-in entry) and shows a toast at every start (Data kept outside OneDrive, with Open). It then shares the data folder and the single instance with an installed copy of the same user. The Uploader keeps .\data, since its files are JSON written atomically. Other sync tools are not detected. | Refuse to start; a separate per-copy folder under %LOCALAPPDATA%\Titano | BRIEF §6.2 forbids synchronised folders and names the per-user folder as the location. A copy that refused to start would leave the user with nothing. |
| 2026-10-12 | The .\data a portable copy now in a OneDrive folder used before (a titano.db or settings.json in it) is left as it is: the log and a toast at every start (Earlier data unused, with Open) name it. Nothing is copied, moved or deleted. | Move or copy it into %LOCALAPPDATA%\Titano at start | Moving an index is a destructive operation (dry-run plan, hash verification, explicit user action), and the per-user folder may already hold an installed copy's index; the user decides which to keep. |
| 2026-10-12 | When %LOCALAPPDATA%\Titano itself lies in a OneDrive sync root, the client starts all the same, logs a warning and shows an error toast at every start (Data inside OneDrive, with Open; its tooltip says to exclude the folder from syncing) instead of Data kept outside OneDrive. AppPaths.CreateDirectories, which refuses such a folder, stays unused by the client. | Refuse to start | BRIEF §6.2 names no safer place than the per-user folder; a client that does not start leaves the user nothing, while the warning lets them fix the sync setup. |
| 2026-10-12 | A photo an import could not copy shows one catalog sentence beside it on the Import screen and in the import job's log (`ImportExecutor.FailureText`: the executor's own checks, a full destination, access denied, else 'The photo could not be read or copied.'). So does a card file the plan cannot read ('Cannot read {0}: {1}'). The photos a stopped folder or server import never reached show the stop's cause (`ImportFailures.Stop`: the server's own sentence, not answering, untrusted certificate, card gone, destination full or not writable), and a failed index check reads `Archive.Failed.Index`. The system's text goes to the application log only. | Keep `ex.Message` beside each photo, or move it into each line's tooltip | BRIEF §0.2 rules 5–6, as for toasts (2026-10-12): framework and OS messages are technical English under a translated screen, and each failure is already logged with its exception. |
@@ -358,7 +358,7 @@ One line per decision: date · decision · alternative · reason.
| 2026-10-12 | Picking another archive, or the shown archive leaving the index, also clears the previous archive's tiles, charts, last scan, recent runs and rail badge, and its read state, until the new archive is read. Picking the first archive again before that read ends does not count it as read either | Keep them until the read ends and clear them only when it fails; a loading state drawn over the old figures | Probing an offline NAS takes seconds and a failed read never replaces anything, so the old figures stood under the new archive's name. An empty overview is the simplest honest state. |
| 2026-10-12 | A finished render is announced once, by whoever claims it first (`JobsViewModel.ClaimRenderToast`). The Jobs screen yields while the open editor still follows the render (`EditorViewModel.FollowsRender`). That editor announces it with the output and Show in folder. Without them, it still announces it when the sequence cannot be read again or when it closed in between. A render no editor follows is announced by the Jobs screen | The Jobs screen stays silent whenever an editor has the sequence open; first come, first served | The editor only announced renders it saw running, and only after reading the sequence again, so a failed read or an unfollowed render got no completion toast, against the job-ending rule (2026-10-12). The order of the Jobs flush and the editor's callback is not fixed, so 'first' alone could lose the output file. |
| 2026-10-12 | Open on a job that worked on several sequences (toast, Windows notification, Jobs row) shows the Library with every one of them selected under the mass actions bar. Search and filters are cleared when they hide one, and pages are read until each is listed. A job over more sequences than a Library page (200, e.g. Rebuild proxies over an archive) opens the Library as it is | Open the first in the editor; lead to the Jobs screen; a Library filter by job; select every target of any job | One editor holds one sequence. The selection is what the job was started from and its results show on the cards; it needs no new filter chip or strings. Looking up, paging through and selecting a whole archive would hold the UI thread for seconds. |
-| 2026-10-12 | When the Windows service fails to start or stop, it writes the reason to the Application event log as source `TitanoServer` (advapi32 `ReportEventW`; event 1 start, event 2 stop) as well as to stderr. The reason comes first (the refused entry), then the exception. The source is not registered with a message file. The Windows README says where to look. It also says how to fix a data folder created by an unelevated console run: delete it (with SQLite, the database goes with it), or `takeown /A /R` and `icacls /reset /T` it from an administrator prompt, after which the server makes it private again. | Register the source at `--install-service` with .NET Framework's EventLogMessages.dll; `System.Diagnostics.EventLog`; a log file outside the data folder; re-own only the folder | A service has no console, and the data folder refusal comes before the log file exists (the log folder may itself be the refused entry), so the SCM recorded only error 1064. Event Viewer shows an unregistered source's text whole, after a 'description not found' line. Nothing is written to the registry, so setup's uninstall has nothing more to clean up, and nothing depends on a message DLL being present or extracted from the single-file build. The server checks the owner of every entry, and the TLS key and password file keep a protected DACL granting the console user, so the folder alone is not enough. |
+| 2026-10-12 | (Partly superseded by the console-run data folder recovery row below: `takeown /A /R`, then `icacls /remove:g` of the account the console ran as, never `/reset`.) When the Windows service fails to start or stop, it writes the reason to the Application event log as source `TitanoServer` (advapi32 `ReportEventW`; event 1 start, event 2 stop) as well as to stderr. The reason comes first (the refused entry), then the exception. The source is not registered with a message file. The Windows README says where to look. It also says how to fix a data folder created by an unelevated console run: delete it (with SQLite, the database goes with it), or `takeown /A /R` and `icacls /reset /T` it from an administrator prompt, after which the server makes it private again. | Register the source at `--install-service` with .NET Framework's EventLogMessages.dll; `System.Diagnostics.EventLog`; a log file outside the data folder; re-own only the folder | A service has no console, and the data folder refusal comes before the log file exists (the log folder may itself be the refused entry), so the SCM recorded only error 1064. Event Viewer shows an unregistered source's text whole, after a 'description not found' line. Nothing is written to the registry, so setup's uninstall has nothing more to clean up, and nothing depends on a message DLL being present or extracted from the single-file build. The server checks the owner of every entry, and the TLS key and password file keep a protected DACL granting the console user, so the folder alone is not enough. |
| 2026-10-12 | Deployment guidance (compose comments, releases README, Unraid template) lists the reverse proxy container's own fixed address in `TITANO_TRUSTED_PROXIES`: a fixed IP on a user-defined network shared with Titano, reached on that network rather than through a published port. It warns never to list a subnet, the network gateway or Docker's default bridge. For a proxy on the Docker host itself, Titano runs with `network_mode: host` and the proxy reaches it over loopback. This replaces 'its address or subnet' in the trusted-proxies row above. | Keep recommending the shared network's subnet; make the server refuse gateway addresses | Docker's userland proxy relays IPv6 clients and the host's own connections to published ports from the gateway. On Unraid's default bridge the subnet also covers every other container. Trusting a subnet would let any of them set X-Forwarded-For/Proto again. The server cannot tell a gateway from a proxy, so the guidance has to carry the rule. |
| 2026-10-12 | Sign-in entry move: on an upgrade, setup moves the client's or the Uploader's sign-in entry that starts a program the upgrade removes. The entry then starts the program of the same component in the new payload (its shortcut target), with the same options and value name. The entry is removed only when that component is no longer installed. Uninstall removes the entries of the programs its log lists, as before. | Delete the entry and let the client follow it (impossible: nothing is left to follow); remove the client's follow and drop rename support | Setup runs while the programs are closed and knows both the removed and the new program. So the rename case of the Startup row ('rewritten only when an update renamed the program') survives the upgrade, and Task Manager's on/off state stays with the unchanged value name. The client's own follow remains for an entry setup did not move. |
| 2026-10-12 | Setup removes a sign-in entry's Task Manager state (`StartupApproved\Run` value of the same name) together with the entry; an entry an upgrade moves to a renamed program keeps it. | Leave the value (Windows ignores it without a Run value) | Uninstall leaves nothing of the entry behind, and an entry the user turned off stays off after an upgrade that renames its program. |
diff --git a/i18n/en/Import.resx b/i18n/en/Import.resx
index 4ded1106..950a7ddf 100644
--- a/i18n/en/Import.resx
+++ b/i18n/en/Import.resx
@@ -105,6 +105,8 @@
{0:N0} verified on the card
{0:N0} verified on the card
Titano may not write to the destination.long
+ Titano may not write to this PC's cache folder.long
+ The drive of this PC's cache folder is full.long
{0} is write-protected or holds protected photos.long; {0} card name
A photo or its archive copy could not be read.long
The destination is full.long
diff --git a/i18n/it/Import.it.resx b/i18n/it/Import.it.resx
index aa9a3724..5770f72f 100644
--- a/i18n/it/Import.it.resx
+++ b/i18n/it/Import.it.resx
@@ -103,6 +103,8 @@
{0:N0} verificata sulla scheda
{0:N0} verificate sulla scheda
Titano non può scrivere nella destinazione.
+ Titano non può scrivere nella cartella cache di questo PC.
+ Il disco della cartella cache di questo PC è pieno.
{0}: la scheda è protetta da scrittura o contiene foto protette.
Impossibile leggere una foto o la sua copia nell'archivio.
La destinazione è piena.
diff --git a/src/Titano.App/Import/ImportDestinations.cs b/src/Titano.App/Import/ImportDestinations.cs
index 89136bd1..0070f684 100644
--- a/src/Titano.App/Import/ImportDestinations.cs
+++ b/src/Titano.App/Import/ImportDestinations.cs
@@ -233,7 +233,7 @@ public static class LocalImport
catch (Exception ex) when (!cancellationToken.IsCancellationRequested && Stops(ex))
{
Log.Warning("import", $"Import into {plan.DestinationRoot} stopped", ex);
- stopped = ImportFailures.Stop(ex, source);
+ stopped = ImportFailures.Stop(ex, source, sink.StagesOnThisPc);
}
return ImportOutcome.From(plan, results, verify, report, stopped);
}
diff --git a/src/Titano.App/Import/ImportFailures.cs b/src/Titano.App/Import/ImportFailures.cs
index b1308733..50f4120c 100644
--- a/src/Titano.App/Import/ImportFailures.cs
+++ b/src/Titano.App/Import/ImportFailures.cs
@@ -1,5 +1,6 @@
using System.IO;
using System.Net.Http;
+using System.Text.RegularExpressions;
using Titano.App.Shell;
using Titano.Core.Archiving;
using Titano.Core.Import;
@@ -20,6 +21,13 @@ public static class ImportFailures
private const int HandleDiskFull = unchecked((int)0x80070027);
private const int WriteProtect = unchecked((int)0x80070013);
+ /// The sentences an archive import job fails with when the archive's engine stops it itself.
+ private static readonly string[] EngineSentences =
+ [
+ "Archive.Error.Offline", "Archive.Error.ReadOnly", "Archive.Error.Busy", "Archive.Error.NewerFormat", "Archive.Error.SourceGone",
+ "Archive.Error.DuplicateLost",
+ ];
+
/// The card or folder as the Devices list names it.
public static string Import(Exception ex, string source) => ex switch
{
@@ -33,14 +41,26 @@ public static class ImportFailures
///
/// Why the photos an import into a folder or the server never reached were not copied ():
/// the card left, the destination is full or refuses writing, or the server answered with its own sentence, does
- /// not answer (a timeout too) or is no longer trusted.
+ /// not answer (a timeout too) or is no longer trusted. When the sink stages on this PC (,
+ /// the server's), a full disk or a refused write is this PC's cache folder's: the server answers for its own space.
///
- public static string Stop(Exception ex, string source) => ex switch
+ public static string Stop(Exception ex, string source, bool stagesOnThisPc = false) => ex switch
{
TitanoApiException or HttpRequestException or UntrustedCertificateException or OperationCanceledException => ErrorText.ForServer(ex),
+ IOException { HResult: DiskFull or HandleDiskFull } when stagesOnThisPc => Loc.L("Import.Failed.CacheFull"),
+ UnauthorizedAccessException when stagesOnThisPc => Loc.L("Import.Failed.CacheAccess"),
_ => Import(ex, source),
};
+ ///
+ /// What a failed archive import job says, from the text the job engine kept of what stopped it: the engine's own
+ /// sentence (archive offline, read-only or busy, a newer format, the card gone, a photo it could not add) in the
+ /// language shown now, else 'The import stopped before the end.' Framework, database and system text goes to the
+ /// tooltip and the logs only.
+ ///
+ public static string Job(string? error) =>
+ error is { Length: > 0 } && EngineSentences.Any(key => IsSentence(key, error)) ? error : Loc.L("Import.Failed.Other");
+
/// Why the card or folder could not be planned.
public static string Plan(Exception ex, string source) => ex switch
{
@@ -70,6 +90,14 @@ public static class ImportFailures
_ => Loc.L("Errors.Unexpected"),
};
+ /// Whether is the sentence of , whatever its arguments.
+ private static bool IsSentence(string key, string text)
+ {
+ const string Argument = "\u0001";
+ var pattern = Regex.Escape(Loc.L(key, Argument, Argument)).Replace(Argument, ".+", StringComparison.Ordinal);
+ return Regex.IsMatch(text, "^" + pattern + "$", RegexOptions.CultureInvariant | RegexOptions.Singleline);
+ }
+
private static bool CardGone(Exception ex, string root) =>
ex is DirectoryNotFoundException or DriveNotFoundException or ImportSourceUnavailableException || !Directory.Exists(root);
}
diff --git a/src/Titano.App/Import/ServerImportSink.cs b/src/Titano.App/Import/ServerImportSink.cs
index 311c34fe..7df1138d 100644
--- a/src/Titano.App/Import/ServerImportSink.cs
+++ b/src/Titano.App/Import/ServerImportSink.cs
@@ -24,6 +24,9 @@ public sealed class ServerImportSink(TitanoClient client, string stagingDirector
public string StagingDirectory { get; } = stagingDirectory;
+ /// The copies wait in this PC's cache folder until they are uploaded: the server's space is its quota.
+ public bool StagesOnThisPc => true;
+
/// Every file committed or refused so far, by card path; pass it to .
public ImportSinkReport Report { get; } = new();
diff --git a/src/Titano.App/Sections/ImportViewModel.cs b/src/Titano.App/Sections/ImportViewModel.cs
index fcc45e58..effed0ef 100644
--- a/src/Titano.App/Sections/ImportViewModel.cs
+++ b/src/Titano.App/Sections/ImportViewModel.cs
@@ -1279,8 +1279,9 @@ public sealed class ImportViewModel : SectionViewModel
await QueueDeepAnalysisAsync(plan);
break;
case JobState.Failed:
- // The engine wrote the job's error (a localized sentence for the archive's own failures); the full text stays in the tooltip.
- Fail(job.Error ?? Loc.L("Import.Failed.Other"), job.Error);
+ // The engine kept the text of what stopped the job: the archive's own failures are localized sentences, anything
+ // else reads as the catalog's and its text stays in the tooltip.
+ Fail(ImportFailures.Job(job.Error), job.Error);
break;
case JobState.Cancelled:
_jobId = null;
diff --git a/src/Titano.App/Sections/SettingsViewModel.cs b/src/Titano.App/Sections/SettingsViewModel.cs
index 72fbc458..cb43a7fc 100644
--- a/src/Titano.App/Sections/SettingsViewModel.cs
+++ b/src/Titano.App/Sections/SettingsViewModel.cs
@@ -51,6 +51,9 @@ public sealed class SettingsViewModel : SectionViewModel
/// there: edits of the Archive rows made meanwhile wait for it ().
///
private Task _retarget = Task.FromResult(null);
+
+ /// Drops a read of the open archive's settings that may have missed an edit being written meanwhile.
+ private readonly ArchiveReadGate _archiveReads = new();
private bool _isDetectingFormats;
private IReadOnlyList _backups = [];
private BackupOption? _selectedBackup;
@@ -316,6 +319,9 @@ public sealed class SettingsViewModel : SectionViewModel
/// The latest archive folder change: done once the rows show what the folder holds (tests wait for it).
internal Task ArchiveRetarget => _retarget;
+ /// The read of the open archive's settings when Settings was last shown: done once the rows show them (tests wait for it).
+ internal Task ArchiveReload { get; private set; } = Task.CompletedTask;
+
/// A portable copy leaves nothing in the registry (BRIEF §6.2): it offers no Startup row.
public bool ShowsStartup => !Shell.Services.Environment.IsPortable;
@@ -898,7 +904,7 @@ public sealed class SettingsViewModel : SectionViewModel
if (!DefaultServer.IsDirty) DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
OnPropertyChanged(nameof(StartWithWindows));
UpdateArchiveFree();
- _ = LoadArchiveAsync();
+ ArchiveReload = LoadArchiveAsync();
if (_page == SettingsPage.Advanced) LoadBackups();
}
@@ -923,15 +929,24 @@ public sealed class SettingsViewModel : SectionViewModel
Archive? archive = null;
try
{
- var registered = await db.Archives.ListAsync();
- 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))
+ ArchiveSettings settings;
+ while (true)
+ {
+ var read = _archiveReads.BeginRead();
+ var registered = await db.Archives.ListAsync();
+ archive = root is { Length: > 0 } ? CurrentArchive.At(registered, root) : null;
+ if (!IsArchiveFolder(root)) return archive;
+ _archive = archive;
+ if (archive is null) return null;
+ 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 (!IsArchiveFolder(root)) return archive;
+ // A read that overlapped an edit being written may have missed it: it is not shown, and the rows are read
+ // again once no edit is being written (ArchiveReadGate), so this is done only when they show the archive.
+ if (_archiveReads.IsCurrent(read)) break;
+ await _archiveReads.WrittenAsync();
+ }
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
@@ -984,6 +999,8 @@ public sealed class SettingsViewModel : SectionViewModel
retarget ??= _retarget;
var waited = !retarget.IsCompleted;
if (await ArchiveAtFolderAsync(retarget) is not { } archive || Shell.Services.Archives is not { } archives) return;
+ bool reload;
+ _archiveReads.BeginWrite();
try
{
var updated = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
@@ -991,15 +1008,22 @@ public sealed class SettingsViewModel : SectionViewModel
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();
+ reload = waited && _retarget == retarget;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or NewerFormatException
or DatabaseException)
{
Log.Warning("settings", "The archive settings were not saved", ex);
Shell.Notify(Loc.L("Settings.Archive.NotSaved"), ArchiveActions.Cause(ex), isError: true);
- await LoadArchiveAsync();
+ reload = true;
}
+ finally
+ {
+ // A read of the archive's settings this write overlapped was not shown: it reads again once no edit is written.
+ _archiveReads.EndWrite();
+ }
+ // Only once the write ended: a read begun while it is written waits for that end.
+ if (reload) await LoadArchiveAsync();
}
///
diff --git a/src/Titano.App/Settings/ArchiveReadGate.cs b/src/Titano.App/Settings/ArchiveReadGate.cs
new file mode 100644
index 00000000..8be3cabf
--- /dev/null
+++ b/src/Titano.App/Settings/ArchiveReadGate.cs
@@ -0,0 +1,52 @@
+namespace Titano.App.Settings;
+
+///
+/// Orders Settings › Archive's reads of the open archive's settings (its archive.json and index row) against the edits
+/// written into them. A read that overlapped a write may hold the file as it was before the edit (a share waking up
+/// answers late, and reads take no settings lease): showing it would undo the edit on the rows and in this PC's defaults
+/// while the archive keeps it. Such a read is not shown (): its reader waits until no edit is being
+/// written () and reads again, so a read is done only once the rows show what the archive holds.
+/// Used from the interface thread only.
+///
+public sealed class ArchiveReadGate
+{
+ /// The token of a read begun while an edit was being written: never current.
+ private const int Overlapped = -1;
+
+ private int _begun;
+ private int _writing;
+ private TaskCompletionSource? _written;
+
+ /// An edit starts being written into the archive.
+ public void BeginWrite()
+ {
+ _begun++;
+ _writing++;
+ }
+
+ /// The edit was written, or failed. When it was the last one being written, the reads waiting for it go on.
+ public void EndWrite()
+ {
+ if (_writing == 0) throw new InvalidOperationException("No edit is being written.");
+ if (--_writing > 0) return;
+ var written = _written;
+ _written = null;
+ written?.SetResult();
+ }
+
+ /// A read starts; its token tells which edits it may have missed.
+ public int BeginRead() => _writing > 0 ? Overlapped : _begun;
+
+ ///
+ /// Whether what a read begun with found may be shown: no edit was being written when it began
+ /// and none began since. When it may not, its reader awaits and reads again.
+ ///
+ public bool IsCurrent(int token) => token == _begun;
+
+ ///
+ /// Done once no edit is being written: at once when none is, else when the last one ends. Its continuations run after
+ /// returns, never inside it.
+ ///
+ public Task WrittenAsync() =>
+ _writing == 0 ? Task.CompletedTask : (_written ??= new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously)).Task;
+}
diff --git a/src/Titano.Core.Windows/Shell/OneDriveFolders.cs b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs
index 3b9ce98a..f4e116da 100644
--- a/src/Titano.Core.Windows/Shell/OneDriveFolders.cs
+++ b/src/Titano.Core.Windows/Shell/OneDriveFolders.cs
@@ -4,43 +4,62 @@ using Titano.Core.IO;
namespace Titano.Core.Windows.Shell;
-/// Folders synchronised by OneDrive for the current user (personal and work/school accounts).
+///
+/// Folders synchronised by OneDrive for the current user: personal and work/school accounts, and the SharePoint and Teams
+/// libraries synced with their Sync button.
+///
public static class OneDriveFolders
{
private const string AccountsKey = @"Software\Microsoft\OneDrive\Accounts";
+
+ ///
+ /// The sync engines' registry, which Office reads to find synchronised files: one subkey per folder OneDrive
+ /// synchronises ("Personal", each work or school account, and each library synced with its Sync button, which lies
+ /// beside the account's folder, not in it), its local folder in MountPoint.
+ ///
+ private const string MountPointsKey = @"Software\SyncEngines\Providers\OneDrive";
+
private static readonly string[] EnvironmentVariables = ["OneDrive", "OneDriveConsumer", "OneDriveCommercial"];
///
- /// Sync roots from the OneDrive environment variables and HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder,
- /// 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.
+ /// Sync roots from the OneDrive environment variables, HKCU\Software\Microsoft\OneDrive\Accounts\*\UserFolder
+ /// and HKCU\Software\SyncEngines\Providers\OneDrive\*\MountPoint, as full paths without a trailing separator,
+ /// distinct (case-insensitive). A key that cannot be read is skipped: the programs start all the same.
///
- public static IReadOnlyList SyncRoots()
+ public static IReadOnlyList SyncRoots() => SyncRoots(Registry.CurrentUser);
+
+ /// with the registry keys read under instead of the current user's hive.
+ public static IReadOnlyList SyncRoots(RegistryKey user)
{
var roots = new List();
foreach (var variable in EnvironmentVariables) Add(roots, Environment.GetEnvironmentVariable(variable));
- try
- {
- using var accounts = Registry.CurrentUser.OpenSubKey(AccountsKey);
- if (accounts is not null)
- {
- 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.
- }
+ AddFolders(roots, user, AccountsKey, "UserFolder");
+ AddFolders(roots, user, MountPointsKey, "MountPoint");
return roots;
}
/// The sync root that contains , or null. Both are expected to be full paths.
public static string? Containing(string path, IEnumerable syncRoots) => DataLocation.SyncRootOf(path, syncRoots);
+ /// Adds the folder that value of each subkey of names.
+ private static void AddFolders(List roots, RegistryKey user, string keyPath, string valueName)
+ {
+ try
+ {
+ using var parent = user.OpenSubKey(keyPath);
+ if (parent is null) return;
+ foreach (var name in parent.GetSubKeyNames())
+ {
+ using var entry = parent.OpenSubKey(name);
+ Add(roots, entry?.GetValue(valueName) as string);
+ }
+ }
+ catch (Exception ex) when (ex is SecurityException or IOException or UnauthorizedAccessException)
+ {
+ // The environment variables and the other key name the usual roots.
+ }
+ }
+
private static void Add(List roots, string? candidate)
{
if (string.IsNullOrWhiteSpace(candidate) || !Path.IsPathFullyQualified(candidate)) return;
diff --git a/src/Titano.Core/Import/ImportExecutor.cs b/src/Titano.Core/Import/ImportExecutor.cs
index 5a7f166e..5833a75d 100644
--- a/src/Titano.Core/Import/ImportExecutor.cs
+++ b/src/Titano.Core/Import/ImportExecutor.cs
@@ -27,6 +27,12 @@ public interface IImportSink
/// Folder for verified copies, on the destination volume so commits are renames.
string StagingDirectory { get; }
+ ///
+ /// True when lies on this PC rather than at the destination (a server import stages its
+ /// copies in this PC's cache folder): a full disk or a refused write while staging then concerns this PC.
+ ///
+ bool StagesOnThisPc => false;
+
/// Moves staged files of one session into place; returns one result per file, in order. Files it does
/// not move stay where they are and the executor deletes them.
Task> CommitAsync(PlannedSession session, IReadOnlyList files, CancellationToken cancellationToken);
@@ -138,7 +144,7 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
}
Log.Warning("import", $"Copy of {item.SourcePath} failed", ex);
failed++;
- results.Add(new ImportItemResult(session, item, ImportItemStatus.Failed, null, null, FailureText(ex)));
+ results.Add(new ImportItemResult(session, item, ImportItemStatus.Failed, null, null, FailureText(ex, sink.StagesOnThisPc)));
}
}
await FlushAsync().ConfigureAwait(false);
@@ -148,13 +154,14 @@ public sealed class ImportExecutor(ImportPlan plan, IImportSink sink)
///
/// Why one photo was not copied, as one localized sentence (BRIEF §0.2 rule 6): the Import screen lists it beside the
/// photo and the import job writes it to its log. The executor's own checks say what they found; the operating
- /// system's text, technical English, goes to the application log only.
+ /// system's text, technical English, goes to the application log only. A full disk is the staging folder's: the
+ /// destination's, or this PC's when the sink stages there ().
///
- internal static string FailureText(Exception ex) => ex switch
+ internal static string FailureText(Exception ex, bool stagesOnThisPc = false) => ex switch
{
// Already one localized sentence each.
ImportSourceChangedException or CopyVerificationException => ex.Message,
- IOException { HResult: DiskFull or HandleDiskFull } => Loc.L("Import.Failed.Full"),
+ IOException { HResult: DiskFull or HandleDiskFull } => Loc.L(stagesOnThisPc ? "Import.Failed.CacheFull" : "Import.Failed.Full"),
UnauthorizedAccessException => Loc.L("Import.Failed.PhotoAccess"),
_ => Loc.L("Import.Failed.Photo"),
};
diff --git a/src/Titano.Server/Api/FileEndpoints.cs b/src/Titano.Server/Api/FileEndpoints.cs
index e1cb76f1..8408e277 100644
--- a/src/Titano.Server/Api/FileEndpoints.cs
+++ b/src/Titano.Server/Api/FileEndpoints.cs
@@ -1,5 +1,5 @@
using System.Globalization;
-using Microsoft.AspNetCore.Http.Features;
+using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.AspNetCore.Mvc;
using Titano.Core.Archiving;
using Titano.Core.Imaging.Decoders;
@@ -29,7 +29,7 @@ public static class FileEndpoints
api.MapGet("/frames/{id:guid}/proxy", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Proxy, db, a, l))
.Requires(Permissions.Read | Permissions.RenderNode);
// Made by clients that edit and by render nodes, which decode what the server cannot.
- api.MapPut("/frames/{id:guid}/proxy", StoreProxyAsync).Requires(Permissions.Edit | Permissions.RenderNode);
+ api.MapPut("/frames/{id:guid}/proxy", StoreProxyAsync).Requires(Permissions.Edit | Permissions.RenderNode).WithMetadata(new ProxyBodyLimit());
api.MapGet("/frames/{id:guid}/thumb", (HttpContext c, Guid id, TitanoDatabase db, ServerArchive a, IFrameAssetLocator l) => AssetAsync(c, id, FrameAsset.Thumbnail, db, a, l))
.Requires(Permissions.Read);
api.MapGet("/renders/{id:guid}/file", RenderAsync).Requires(Permissions.Read);
@@ -74,9 +74,8 @@ public static class FileEndpoints
// A proxy replaces the server's own of an original it decodes, which renders and remote views would then show.
if (!ServerProxies.CannotDecode(frame.Format) || (frame.Flags & (FrameFlags.Missing | FrameFlags.Corrupt)) != 0)
return ApiErrors.Result(context, StatusCodes.Status422UnprocessableEntity, "proxy_not_wanted");
+ // Routing raised Kestrel's limit to this size (ProxyBodyLimit); reading past it answers 413.
if (context.Request.ContentLength is > ArchiveImages.MaxProxyBytes) return ApiErrors.Result(context, StatusCodes.Status413PayloadTooLarge, "too_large");
- // Proxies are larger than the JSON bodies Kestrel is limited to; reading past this answers 413.
- if (context.Features.Get() is { IsReadOnly: false } limit) limit.MaxRequestBodySize = ArchiveImages.MaxProxyBytes;
using var body = new MemoryStream();
await context.Request.Body.CopyToAsync(body, ct);
@@ -114,4 +113,15 @@ public static class FileEndpoints
return FileResponses.Serve(context, file, 0, file.Length, FileResponses.ContentTypeOf(file.Name), Immutable, etag, file.Name)
?? ApiErrors.NotFound(context, "file_missing");
}
+
+ ///
+ /// The proxy route's body limit (), applied by routing as it selects the
+ /// endpoint, before authentication can answer 401 or 403 and before the handler answers 404 or 422 with the proxy
+ /// unread. Kestrel drains an unread body only within the limit; above it, it closes the connection and the client sees
+ /// a network error instead of the answer (as for chunks, ).
+ ///
+ private sealed class ProxyBodyLimit : IRequestSizeLimitMetadata
+ {
+ public long? MaxRequestBodySize => ArchiveImages.MaxProxyBytes;
+ }
}
diff --git a/src/Titano.Server/Api/UploadEndpoints.cs b/src/Titano.Server/Api/UploadEndpoints.cs
index 3e62ee29..f59c33fe 100644
--- a/src/Titano.Server/Api/UploadEndpoints.cs
+++ b/src/Titano.Server/Api/UploadEndpoints.cs
@@ -57,9 +57,10 @@ public static class UploadEndpoints
}
///
- /// Chunks are the only large request bodies; every other endpoint keeps Kestrel's small default limit. Routing raises
- /// it for this route (), and the service keeps it at least at the chunk size of this upload
- /// (fixed when it started) and of this server, so a body left unread by any answer can still be drained.
+ /// Chunks and proxies () are the only large request bodies; every other endpoint keeps
+ /// Kestrel's small default limit. Routing raises it for this route (), and the service
+ /// keeps it at least at the chunk size of this upload (fixed when it started) and of this server, so a body left
+ /// unread by any answer can still be drained.
///
private static async Task ChunkAsync(HttpContext context, Caller caller, Guid id, int index, UploadService service)
{
diff --git a/tests/Titano.App.Tests/Import/ImportFailuresTests.cs b/tests/Titano.App.Tests/Import/ImportFailuresTests.cs
index 8c1d5094..f22761a4 100644
--- a/tests/Titano.App.Tests/Import/ImportFailuresTests.cs
+++ b/tests/Titano.App.Tests/Import/ImportFailuresTests.cs
@@ -49,6 +49,47 @@ public sealed class ImportFailuresTests
Assert.Equal(Loc.L("Server.Error.Untrusted"), ImportFailures.Stop(new UntrustedCertificateException("AB:CD"), Card));
}
+ [Test]
+ public void AServerImportStoppedOnThisPcNamesItsCacheFolderNotTheServer()
+ {
+ // The server import stages its copies in this PC's cache folder; the server answers for its own space and rights.
+ const string Card = "EOS R5 · card A";
+ using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests");
+ var staging = Path.Combine(Path.GetTempPath(), "titano-server-import");
+ Assert.True(((IImportSink)new ServerImportSink(client, staging)).StagesOnThisPc);
+ Assert.Equal("The drive of this PC's cache folder is full.",
+ ImportFailures.Stop(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), Card, stagesOnThisPc: true));
+ Assert.Equal("Titano may not write to this PC's cache folder.",
+ ImportFailures.Stop(new UnauthorizedAccessException(@"Access to the path 'C:\Users\me\AppData\Local\Titano\cache\server-import' is denied."), Card,
+ stagesOnThisPc: true));
+ Assert.Equal("EOS R5 · card A is no longer available.", ImportFailures.Stop(new ImportSourceUnavailableException(@"E:\"), Card, stagesOnThisPc: true));
+ Assert.Equal("The import stopped before the end.", ImportFailures.Stop(new IOException("The specified network name is no longer available."), Card, stagesOnThisPc: true));
+ Assert.Equal(Loc.L("Server.Error.Unreachable"), ImportFailures.Stop(new HttpRequestException("No such host is known."), Card, stagesOnThisPc: true));
+ }
+
+ [Test]
+ public void AFailedImportJobShowsOnlyTheArchivesOwnSentences()
+ {
+ // The job engine keeps the text of what stopped the job: the archive's own failures are already catalog sentences.
+ Assert.Equal("The archive D:\\Shoots is offline.", ImportFailures.Job(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.Offline).Message));
+ Assert.Equal("The archive D:\\Shoots is read-only.", ImportFailures.Job(new ArchiveOfflineException(@"D:\Shoots", ArchiveAvailability.ReadOnly).Message));
+ Assert.Equal("The card or folder E:\\ is no longer available.", ImportFailures.Job(new ImportSourceUnavailableException(@"E:\").Message));
+ var busy = new LeaseUnavailableException("settings", new LeaseRecord("t", "Titano Server (nas)", "nas", 42, DateTimeOffset.UnixEpoch, DateTimeOffset.UnixEpoch));
+ Assert.Equal(busy.Message, ImportFailures.Job(busy.Message));
+ var newer = new NewerFormatException(Path.Combine(Path.GetTempPath(), "archive.json"), 3);
+ Assert.Equal("archive.json was written by a newer Titano (format 3).", ImportFailures.Job(newer.Message));
+ Assert.Equal("IMG_0001.CR3 could not be added to the sequence.", ImportFailures.Job(Loc.L("Archive.Error.DuplicateLost", "IMG_0001.CR3")));
+
+ // A database, framework or system text reads as the catalog's sentence; the tooltip keeps it.
+ Assert.Equal("The import stopped before the end.", ImportFailures.Job("database is locked: no write lock within 30 s"));
+ Assert.Equal("The import stopped before the end.",
+ ImportFailures.Job(@"The process cannot access the file 'D:\Shoots\2026\IMG_0001.CR3' because it is being used by another process."));
+ Assert.Equal("The import stopped before the end.", ImportFailures.Job("There is not enough space on the disk. : 'D:\\Shoots\\.titano\\journal'"));
+ Assert.Equal("The import stopped before the end.", ImportFailures.Job($"Sequence {Guid.Empty} is not indexed."));
+ Assert.Equal("The import stopped before the end.", ImportFailures.Job(null));
+ Assert.Equal("The import stopped before the end.", ImportFailures.Job(string.Empty));
+ }
+
[Test]
public void APlanningFailureNamesTheSource()
{
diff --git a/tests/Titano.App.Tests/Settings/ArchiveReadGateTests.cs b/tests/Titano.App.Tests/Settings/ArchiveReadGateTests.cs
new file mode 100644
index 00000000..c7ab69aa
--- /dev/null
+++ b/tests/Titano.App.Tests/Settings/ArchiveReadGateTests.cs
@@ -0,0 +1,93 @@
+using Titano.App.Settings;
+using Titano.Testing;
+
+namespace Titano.App.Tests.Settings;
+
+///
+/// Settings › Archive never shows a read of the archive's settings that overlapped an edit being written: on a slow share
+/// that read can hold archive.json as it was before the edit, and would undo the edit on the rows and in this PC's
+/// defaults while the archive keeps it. Its reader waits for the edits instead and reads again, so the read is done only
+/// once the rows show what the archive holds.
+///
+public sealed class ArchiveReadGateTests
+{
+ [Test]
+ public void AReadWithNoEditMeanwhileIsShown()
+ {
+ var gate = new ArchiveReadGate();
+ Assert.True(gate.IsCurrent(gate.BeginRead()));
+ Assert.True(gate.WrittenAsync().IsCompleted, "no edit is being written");
+
+ // An edit written and ended before the read began is in the file it reads.
+ gate.BeginWrite();
+ gate.EndWrite();
+ Assert.True(gate.IsCurrent(gate.BeginRead()));
+ Assert.True(gate.WrittenAsync().IsCompleted);
+ }
+
+ [Test]
+ public void AReadThatAnEditOverlapsWaitsForTheEditAndReadsAgain()
+ {
+ // Settings is shown and reads archive.json; the user commits a template before the read answers.
+ var gate = new ArchiveReadGate();
+ var read = gate.BeginRead();
+ gate.BeginWrite();
+ Assert.False(gate.IsCurrent(read), "the read may hold the file before the edit");
+ var written = gate.WrittenAsync();
+ Assert.False(written.IsCompleted, "the edit is still being written");
+ gate.EndWrite();
+ Assert.True(written.IsCompleted, "the reader reads again once the edit is written");
+ Assert.True(gate.IsCurrent(gate.BeginRead()));
+
+ // The edit began and ended while the read was out: the reader reads again at once.
+ read = gate.BeginRead();
+ gate.BeginWrite();
+ gate.EndWrite();
+ Assert.False(gate.IsCurrent(read));
+ Assert.True(gate.WrittenAsync().IsCompleted);
+ Assert.True(gate.IsCurrent(gate.BeginRead()));
+ }
+
+ [Test]
+ public void AReadBegunWhileAnEditIsWrittenIsNeverShown()
+ {
+ // The rows are read again (a folder change, the screen shown) while an edit is still being written.
+ var gate = new ArchiveReadGate();
+ gate.BeginWrite();
+ var read = gate.BeginRead();
+ Assert.False(gate.IsCurrent(read));
+ var written = gate.WrittenAsync();
+ gate.EndWrite();
+ Assert.False(gate.IsCurrent(read), "it began before the edit was written");
+ Assert.True(written.IsCompleted);
+ Assert.True(gate.IsCurrent(gate.BeginRead()));
+ }
+
+ [Test]
+ public async Task AReaderGoesOnOnlyOnceTheLastOfSeveralEditsIsWrittenAndNeverInsideIt()
+ {
+ // A proxy size and a thumbnail size picked one after the other, both overlapping a read.
+ var gate = new ArchiveReadGate();
+ var read = gate.BeginRead();
+ gate.BeginWrite();
+ gate.BeginWrite();
+ Assert.False(gate.IsCurrent(read));
+ var written = gate.WrittenAsync();
+ Assert.Same(written, gate.WrittenAsync());
+ gate.EndWrite();
+ Assert.False(written.IsCompleted, "another edit is still being written");
+
+ // The reader goes on once the last edit ends, never inside its EndWrite: the writer finishes first.
+ var thread = Environment.CurrentManagedThreadId;
+ var ending = false;
+ var inside = written.ContinueWith(_ => ending && Environment.CurrentManagedThreadId == thread, CancellationToken.None,
+ TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
+ ending = true;
+ gate.EndWrite();
+ ending = false;
+ Assert.True(written.IsCompleted);
+ Assert.False(await inside, "the reader did not go on inside EndWrite");
+ Assert.True(gate.IsCurrent(gate.BeginRead()));
+ Assert.Throws(() => gate.EndWrite());
+ }
+}
diff --git a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs
index 7215198c..34ca3119 100644
--- a/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs
+++ b/tests/Titano.App.Tests/Settings/SettingsScreenSmokeTests.cs
@@ -217,9 +217,12 @@ public sealed class SettingsScreenSmokeTests
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");
+ // The folder change is done only once the rows show that folder's archive, also when its read overlapped the
+ // edit written into the first archive: that read waits for the edit and reads again instead of leaving the rows.
await settings.ArchiveRetarget;
Assert.NotEqual("{date}-{n:0000}", Read(otherManifestPath).LayoutTemplates.File);
Assert.Equal(Read(otherManifestPath).LayoutTemplates.File, settings.FileTemplate.Text);
+ Assert.Equal(Read(otherManifestPath).LayoutTemplates.File, shell.Services.Settings.FileTemplate);
settings.ArchiveRoot.Text = archive.RootPath;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
@@ -239,6 +242,56 @@ public sealed class SettingsScreenSmokeTests
Assert.Equal(480, settings.SelectedThumbnailSize.Value);
});
+ [Test]
+ public Task AnArchiveRowEditedWhileSettingsReadsTheArchiveIsNotUndoneByThatRead() => ScreenHost.RunAsync(async () =>
+ {
+ await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
+ var shell = app.Shell;
+ await app.Sample.FillAsync();
+ var settings = shell.Settings;
+ var archive = Assert.NotNull(await Titano.App.Archiving.CurrentArchive.FindAsync(shell.Services.Database!, null));
+ var paths = new Titano.Core.Archiving.ArchivePaths(archive.RootPath);
+ static Titano.Core.Archiving.ArchiveManifest Read(string path) => Titano.Core.Archiving.ManifestStore.ReadArchive(path);
+ shell.Navigate(SectionKey.Settings);
+ settings.Page = SettingsPage.Archive;
+ settings.ArchiveRoot.Text = archive.RootPath;
+ Assert.True(settings.ArchiveRoot.Commit());
+ await settings.ArchiveRetarget;
+ var before = Read(paths.ManifestPath).LayoutTemplates.File;
+ const string edited = "{camera}_{n:00000}";
+ Assert.NotEqual(edited, before);
+ Assert.Equal(before, settings.FileTemplate.Text);
+
+ // Another PC holds the archive's settings, so the edit waits to be written. Settings is shown again just before
+ // the edit is committed: its read of archive.json answers meanwhile, with the file from before the edit.
+ var lease = Assert.NotNull(Titano.Core.Archiving.LeaseFile.TryAcquire(paths.LocksDirectory, "archive-settings", "other-pc"));
+ Task reload;
+ try
+ {
+ shell.Navigate(SectionKey.Library);
+ shell.Navigate(SectionKey.Settings);
+ reload = settings.ArchiveReload;
+ Assert.False(reload.IsCompleted, "the read is in flight");
+ settings.FileTemplate.Text = edited;
+ Assert.True(settings.FileTemplate.Commit());
+ await Task.WhenAny(reload, Task.Delay(1500));
+ Assert.False(reload.IsCompleted, "the read waits for the edit it overlapped");
+ Assert.Equal(edited, settings.FileTemplate.Text);
+ Assert.Equal(edited, shell.Services.Settings.FileTemplate);
+ Assert.Equal(before, Read(paths.ManifestPath).LayoutTemplates.File);
+ }
+ finally
+ {
+ lease.Dispose();
+ }
+
+ // Once the edit is written, the read is made again and shows it.
+ await reload.WaitAsync(TimeSpan.FromSeconds(20));
+ Assert.Equal(edited, Read(paths.ManifestPath).LayoutTemplates.File);
+ Assert.Equal(edited, settings.FileTemplate.Text);
+ Assert.Equal(edited, shell.Services.Settings.FileTemplate);
+ });
+
[Test]
public Task TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () =>
{
diff --git a/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs b/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs
index 1d1c2d39..7dbbf13b 100644
--- a/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs
+++ b/tests/Titano.Core.Tests/Import/ImportExecutorTests.cs
@@ -174,6 +174,13 @@ public sealed class ImportExecutorTests(TestContext context)
Assert.Equal(Loc.L("Import.Failed.PhotoAccess"), ImportExecutor.FailureText(new UnauthorizedAccessException(@"Access to the path 'E:\DCIM\IMG_0001.CR3' is denied.")));
Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new IOException("The semaphore timeout period has expired.")));
Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new FileNotFoundException(@"Could not find file 'E:\DCIM\IMG_0001.CR3'.")));
+ // A sink that stages its copies on this PC (a server import, in the cache folder): a full disk there is this PC's.
+ Assert.Equal(Loc.L("Import.Failed.CacheFull"),
+ ImportExecutor.FailureText(new IOException("There is not enough space on the disk.", unchecked((int)0x80070070)), stagesOnThisPc: true));
+ Assert.Equal(Loc.L("Import.Failed.CacheFull"), ImportExecutor.FailureText(new IOException("The disk is full.", unchecked((int)0x80070027)), stagesOnThisPc: true));
+ Assert.Equal(Loc.L("Import.Failed.PhotoAccess"), ImportExecutor.FailureText(new UnauthorizedAccessException("Access denied."), stagesOnThisPc: true));
+ Assert.Equal(Loc.L("Import.Failed.Photo"), ImportExecutor.FailureText(new IOException("The semaphore timeout period has expired."), stagesOnThisPc: true));
+ Assert.False(((IImportSink)new FolderImportSink(Path.GetTempPath())).StagesOnThisPc, "a folder import stages inside the destination");
// The executor's own checks are one sentence each already.
Assert.Equal(Loc.L("Archive.Error.CopyMismatch", "IMG_0001.CR3"), ImportExecutor.FailureText(new CopyVerificationException("/staging/IMG_0001.CR3")));
Assert.Equal(Loc.L("Archive.Error.SourceChanged", "DCIM/IMG_0001.CR3"), ImportExecutor.FailureText(new ImportSourceChangedException("DCIM/IMG_0001.CR3")));
diff --git a/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs b/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs
index cd0c9bd6..8cac13c1 100644
--- a/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs
+++ b/tests/Titano.Core.Windows.Tests/Shell/OneDriveFoldersTests.cs
@@ -1,9 +1,13 @@
+using Microsoft.Win32;
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.
+///
+/// The OneDrive folders of the user as Windows reports them, from its environment and registry (a scratch key in tests).
+/// Serial: a test sets a process environment variable.
+///
[Serial]
public sealed class OneDriveFoldersTests(TestContext context)
{
@@ -36,4 +40,47 @@ public sealed class OneDriveFoldersTests(TestContext context)
Environment.SetEnvironmentVariable(Variable, previous);
}
}
+
+ [Test]
+ [WindowsOnly]
+ public void ALibrarySyncedBesideTheAccountsFolderIsASyncRootToo()
+ {
+ // A scratch hive of its own: the user's OneDrive settings are never read or touched.
+ var hive = @"Software\Titano.OneDriveTests." + Guid.NewGuid().ToString("N");
+ try
+ {
+ var profile = context.CreateTempDirectory("profile");
+ var account = Path.Combine(profile, "OneDrive - Contoso");
+ // The Sync button of a SharePoint or Teams library puts it in %USERPROFILE%\, not in the account's folder.
+ var library = Path.Combine(profile, "Contoso", "Team Site - Documents");
+ using var user = Registry.CurrentUser.CreateSubKey(hive, writable: true);
+ using (var business = user.CreateSubKey(@"Software\Microsoft\OneDrive\Accounts\Business1")) business.SetValue("UserFolder", account);
+ using (var engine = user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\Business1")) engine.SetValue("MountPoint", account);
+ using (var site = user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\8c2f0b1e7d6a4f3e9b5c2d1a0e9f8b7c+1")) site.SetValue("MountPoint", library + @"\");
+ // Entries without a full path name nothing.
+ using (var relative = user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\Relative")) relative.SetValue("MountPoint", @"Contoso\Elsewhere");
+ using (user.CreateSubKey(@"Software\SyncEngines\Providers\OneDrive\Empty")) { }
+
+ var roots = OneDriveFolders.SyncRoots(user);
+
+ Assert.Equal(1, roots.Count(r => string.Equals(r, account, StringComparison.OrdinalIgnoreCase)), "the account's folder once");
+ Assert.Contains(roots, r => string.Equals(r, library, StringComparison.OrdinalIgnoreCase));
+ Assert.False(roots.Any(r => r.EndsWith("Elsewhere", StringComparison.OrdinalIgnoreCase)), "a relative mount point is ignored");
+
+ // A portable copy unpacked in that library keeps its data in %LOCALAPPDATA%\Titano.
+ var app = Directory.CreateDirectory(Path.Combine(library, "Tools", "Titano")).FullName;
+ File.WriteAllText(Path.Combine(app, PortableMode.MarkerFileName), "");
+ var local = context.CreateTempDirectory("local");
+
+ var paths = AppPaths.Resolve(app, local, roots);
+
+ Assert.True(paths.IsPortable);
+ Assert.Equal(Path.Combine(local, AppPaths.ProductFolderName), paths.DataRoot);
+ Assert.True(string.Equals(library, paths.PortableSyncRoot, StringComparison.OrdinalIgnoreCase), $"sync root {paths.PortableSyncRoot}");
+ }
+ finally
+ {
+ Registry.CurrentUser.DeleteSubKeyTree(hive, throwOnMissingSubKey: false);
+ }
+ }
}
diff --git a/tests/Titano.Server.Tests/Storage/ProxyUploadTests.cs b/tests/Titano.Server.Tests/Storage/ProxyUploadTests.cs
index 90cddd9d..86e963d6 100644
--- a/tests/Titano.Server.Tests/Storage/ProxyUploadTests.cs
+++ b/tests/Titano.Server.Tests/Storage/ProxyUploadTests.cs
@@ -164,6 +164,36 @@ public sealed class ProxyUploadTests(TestContext context)
await refused.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_not_wanted");
}
+ [Test]
+ public async Task AnswersThatLeaveALargeProxyUnreadReachTheClient()
+ {
+ // A full-size proxy is far above the 1 MiB other requests may send: more than the connection buffers while the
+ // server reads nothing.
+ await using var server = await TestServer.StartAsync(context, services: ArchiveModule.Register);
+ var (editor, _, _) = await server.UserAsync("alberto", "editor");
+ var heif = await Uploads.UploadAsync(editor, Heif(1), "IMG_0001.HEIC", sessionKey: "roof");
+ var jpeg = await Uploads.UploadAsync(editor, Proxy(new DateTime(2026, 9, 28, 18, 2, 12)), "IMG_0002.JPG", sessionKey: "roof");
+ var large = Uploads.Photo(24 * 1024 * 1024, 7);
+
+ // The handler answers before reading the body: a frame deleted since the manifest, and one the server decodes itself.
+ using (var missing = await PutAsync(editor, Guid.CreateVersion7(), large))
+ Assert.Equal("frame", (await missing.ExpectErrorAsync(HttpStatusCode.NotFound, "not_found")).Details);
+ using (var unwanted = await PutAsync(editor, jpeg.FrameId, large))
+ await unwanted.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "proxy_not_wanted");
+ // A body that may be the proxy is read whole, past the 1 MiB, before it is judged.
+ using (var invalid = await PutAsync(editor, heif.FrameId, large))
+ await invalid.ExpectErrorAsync(HttpStatusCode.UnprocessableEntity, "invalid_proxy");
+
+ // Authentication answers before the endpoint runs: an account that lost the Edit role, and a session signed out meanwhile.
+ var (viewer, _, _) = await server.UserAsync("vera", "viewer");
+ using (var forbidden = await PutAsync(viewer, heif.FrameId, large))
+ await forbidden.ExpectErrorAsync(HttpStatusCode.Forbidden, "forbidden");
+ using (var logout = await editor.PostAsync("/api/v1/auth/logout", null))
+ await logout.ExpectAsync(HttpStatusCode.NoContent);
+ using var revoked = await PutAsync(editor, heif.FrameId, large);
+ await revoked.ExpectErrorAsync(HttpStatusCode.Unauthorized, "unauthorized");
+ }
+
/// A HEIF file as far as signature sniffing goes (an ftyp box naming heic), with no pixels the server can read.
private static byte[] Heif(int seed) => [0, 0, 0, 24, .. "ftypheic"u8, 0, 0, 0, 0, .. "mif1heic"u8, .. Uploads.Photo(2000, seed)];