refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,92 @@
using System.Globalization;
using System.IO;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>The confirmation of Delete in the Library and the Archive manager: the engine's dry run behind a typed confirmation (DESIGN §4).</summary>
public sealed class DeletePlansTests
{
private static Sequence Sequence(string title, int frames) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = title,
Folder = "2026/" + title,
FrameCount = frames,
};
private static DeleteStep Step(string title, int frames, int files, long bytes) =>
new(Sequence(title, frames), $".chronos/trash/{Guid.CreateVersion7():N}", files, bytes);
[Test]
public void ThePlanAsksToTypeHowManySequencesMove()
{
var plan = new DeletePlan(
[Step("Harbour sunset", 3_600, 3_640, 96_200_000_000), Step("Comet over the ridge", 1_005, 1_020, 21_000_000_000)],
[new BlockedDelete(Sequence("Fog lifting", 980), DeleteBlock.Busy)]);
var request = Assert.NotNull(DeletePlans.Request(plan));
Assert.True(request.IsDestructive, "the action is outlined, never primary");
Assert.Equal("2", request.TypedConfirmation);
Assert.Equal(Loc.L("Archive.Delete.Type", "2"), request.TypedPrompt);
Assert.Equal(Loc.Plural("Archive.Delete.Heading", 2), request.Heading);
Assert.Equal(Loc.L("Archive.Delete.Message", Loc.Plural("Shell.Status.Photos", 4_605), Loc.Plural("Archive.Delete.Files", 4_660),
Formatting.Bytes(117_200_000_000)), request.Message);
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(3, lines.Length);
Assert.Equal(Loc.L("Archive.Delete.Line", "Harbour sunset", Loc.Plural("Shell.Status.Photos", 3_600), Formatting.Bytes(96_200_000_000)), lines[0]);
Assert.Equal(Loc.L("Archive.Delete.Blocked", "Fog lifting", Loc.L("Archive.Delete.Reason.Busy")), lines[2]);
Assert.Equal(Loc.L("Archive.Delete.Keep"), request.SafeText);
Assert.Equal(Loc.Plural("Tooltips.Archive.DeleteAction", 2), request.ActionToolTip);
}
[Test]
public void LongPlansAreCountedAndEmptyOnesAskNothing()
{
var many = Enumerable.Range(1, DeletePlans.ListedLines + 3).Select(i => Step("Sequence " + i.ToString(CultureInfo.InvariantCulture), 10, 10, 1_000)).ToList();
var request = Assert.NotNull(DeletePlans.Request(new DeletePlan(many, [])));
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(DeletePlans.ListedLines + 1, lines.Length);
Assert.Equal(Loc.Plural("Archive.Delete.More", 3), lines[^1]);
Assert.Equal((DeletePlans.ListedLines + 3).ToString(CultureInfo.InvariantCulture), request.TypedConfirmation);
var blocked = new DeletePlan([], [new BlockedDelete(Sequence("Root", 2), DeleteBlock.ArchiveRoot)]);
Assert.Null(DeletePlans.Request(blocked), "nothing can move: no confirmation");
Assert.SequenceEqual([Loc.L("Archive.Delete.Blocked", "Root", Loc.L("Archive.Delete.Reason.ArchiveRoot"))], DeletePlans.Blocked(blocked, 8));
foreach (var reason in Enum.GetValues<DeleteBlock>())
Assert.NotEqual("Archive.Delete.Reason." + reason, Loc.L("Archive.Delete.Reason." + reason), "every reason has words");
}
[Test]
public void TheConfirmationStaysShortEnoughForASmallScreen()
{
var steps = Enumerable.Range(1, 20).Select(i => Step("Sequence " + i.ToString(CultureInfo.InvariantCulture), 10, 10, 1_000)).ToList();
var blocked = Enumerable.Range(1, 9).Select(i => new BlockedDelete(Sequence("Busy " + i.ToString(CultureInfo.InvariantCulture), 5), DeleteBlock.Busy)).ToList();
var request = Assert.NotNull(DeletePlans.Request(new DeletePlan(steps, blocked)));
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(DeletePlans.ListedLines + 1 + DeletePlans.BlockedLines + 1, lines.Length, "named lines plus one count for each part");
Assert.Equal(Loc.Plural("Archive.Delete.More", 14), lines[DeletePlans.ListedLines]);
Assert.Equal(Loc.Plural("Archive.Delete.More", 6), lines[^1]);
Assert.False(request.IsDetailMonospaced, "names read in the UI font, not the fingerprint font");
}
[Test]
public void ARefusedDeleteOrRestoreSaysWhyInOneSentence()
{
Assert.Equal(Loc.L("Archive.Error.StalePlan"), ArchiveFailures.Cause(new StaleDeletePlanException(Guid.NewGuid())));
Assert.Equal(Loc.L("Archive.Error.InLibrary", "Harbour sunset"), ArchiveFailures.Cause(new SequenceInLibraryException(Guid.NewGuid(), "Harbour sunset")));
Assert.Equal(Loc.L("Archive.Error.NewerFormat", "sequence.json", 9), ArchiveFailures.Cause(new NewerFormatException("/a/2026/x/.chronos/sequence.json", 9)));
Assert.Equal(Loc.L("Archive.Failed.Files"), ArchiveFailures.Cause(new DirectoryNotFoundException("/a/.chronos/trash/0123 is not in the trash")),
"the engine's own words stay in the log");
}
}
@@ -0,0 +1,45 @@
using Chronos.App.Library;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>"Export list as CSV" (BRIEF §12.2): RFC 4180 rows that spreadsheets read as data, never as formulas.</summary>
public sealed class LibraryCsvTests
{
[Test]
public void RowsAreQuotedInvariantAndSafe()
{
var harbour = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = "Harbour, \"golden\" hour",
Folder = "2026/2026-09-28 Canon EOS R5",
CameraMake = "Canon",
CameraModel = "Canon EOS R5",
FirstCapture = new DateTime(2026, 9, 28, 18, 2, 11),
LastCapture = new DateTime(2026, 9, 28, 20, 2, 9),
FrameCount = 3_600,
TotalBytes = 96_200_000_000,
Tags = ["sunset", "harbour"],
};
var formula = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Folder = string.Empty,
Title = "=HYPERLINK(\"x\")",
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
var lines = LibraryCsv.Write([harbour, formula]).Split("\r\n");
Assert.Equal("title,first_capture,last_capture,camera_make,camera_model,frames,bytes,folder,tags,origin", lines[0]);
Assert.Equal("\"Harbour, \"\"golden\"\" hour\",2026-09-28 18:02:11,2026-09-28 20:02:09,Canon,Canon EOS R5,3600,96200000000,"
+ "2026/2026-09-28 Canon EOS R5,sunset;harbour,local", lines[1]);
Assert.Equal("\"'=HYPERLINK(\"\"x\"\")\",,,,,0,0,,,server", lines[2]);
Assert.Equal(string.Empty, lines[3], "every row ends with CRLF");
}
}
@@ -0,0 +1,74 @@
using Chronos.App.Library;
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>Mixed mode (BRIEF §4.4): the server's sequences without a copy here count in the Year and Camera choices and the timeline.</summary>
public sealed class LibraryFacetsTests
{
private static readonly ArchiveStats Local = new(3, 6_000, 60_000, [new YearBucket(2026, 3, 6_000, 60_000)],
[new MonthBucket(2026, 9, 2, 5_000), new MonthBucket(2026, 2, 1, 1_000)],
[new CameraBucket("Canon", "Canon EOS R5", 2, 5_000, 50_000), new CameraBucket("NIKON CORPORATION", "NIKON Z 8", 1, 1_000, 10_000)], [],
new ArchiveHealth(0, 0, 0, 0, 0, 0, 0));
private static Sequence Remote(DateTime? first, string? make, string? model, int frames) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Title = "Remote",
Folder = string.Empty,
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
FirstCapture = first,
CameraMake = make,
CameraModel = model,
FrameCount = frames,
TotalBytes = frames * 10L,
};
[Test]
public void RemoteCardsJoinTheYearsMonthsAndCameras()
{
Sequence[] remote =
[
Remote(new DateTime(2024, 5, 3), "SONY", "ILCE-7M4", 2_000),
Remote(new DateTime(2026, 9, 20), "Canon", "Canon EOS R5", 500),
Remote(null, null, null, 10),
];
var stats = LibraryFacets.Of(Local, remote, OriginFilter.Any);
Assert.SequenceEqual([2024, 2026], stats.ByYear.Select(y => y.Year));
Assert.Equal(new YearBucket(2024, 1, 2_000, 20_000), stats.ByYear[0]);
Assert.Equal(new YearBucket(2026, 4, 6_500, 65_000), stats.ByYear[1]);
Assert.SequenceEqual([(2024, 5), (2026, 2), (2026, 9)], stats.ByMonth.Select(m => (m.Year, m.Month)));
Assert.Equal(new MonthBucket(2026, 9, 3, 5_500), stats.ByMonth[2]);
Assert.Equal(3, stats.ByCamera.Single(c => c.Model == "Canon EOS R5").Sequences);
Assert.Equal(1, stats.ByCamera.Single(c => c.Model == "ILCE-7M4").Sequences);
Assert.Equal(1, stats.ByCamera.Single(c => c.Model is null).Sequences, "a card without camera counts under none");
Assert.Equal(Local.Sequences, stats.Sequences, "the totals stay the index's own");
var timeline = LibraryTimeline.From(stats, new DateTime(2026, 10, 6));
Assert.SequenceEqual([2026, 2025, 2024], timeline.Years, "a year only the server has gets its band");
Assert.Equal(2_000.0, timeline.Bands[2].Values[4]);
}
[Test]
public void TheOriginFilterDecidesWhoCounts()
{
Sequence[] remote = [Remote(new DateTime(2024, 5, 3), "SONY", "ILCE-7M4", 2_000)];
var local = LibraryFacets.Of(Local, remote, OriginFilter.Local);
Assert.SequenceEqual([2026], local.ByYear.Select(y => y.Year), "on this PC: the index alone");
Assert.False(local.ByCamera.Any(c => c.Model == "ILCE-7M4"));
var server = LibraryFacets.Of(Local, remote, OriginFilter.Server);
Assert.SequenceEqual([2024], server.ByYear.Select(y => y.Year), "only on server: the remote cards alone");
Assert.SequenceEqual(["ILCE-7M4"], server.ByCamera.Select(c => c.Model));
Assert.SequenceEqual([(2024, 5)], server.ByMonth.Select(m => (m.Year, m.Month)));
Assert.SequenceEqual(Local.ByYear, LibraryFacets.Of(Local, [], OriginFilter.Any).ByYear, "signed out, nothing changes");
}
}
@@ -0,0 +1,58 @@
using Chronos.App.Library;
using Chronos.Core.Model;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>The Status choices of Main.html (analysed, proxies, rendered, synced): the index's query and the same test in memory agree.</summary>
public sealed class LibraryFilterTests
{
private static Sequence Sequence(int rendered, SyncState sync, SequenceStatus status = SequenceStatus.None) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Folder = "2026/x",
RenderedCount = rendered,
SyncState = sync,
Status = status,
};
[Test]
public void RenderedAndSyncedAskTheIndexForRendersAndSyncStates()
{
Assert.Equal(true, new LibraryFilter { Status = StatusFilter.Rendered }.ToQuery(50, null).Rendered);
Assert.Equal(false, new LibraryFilter { Status = StatusFilter.NotRendered }.ToQuery(50, null).Rendered);
Assert.Null(new LibraryFilter { Status = StatusFilter.Analysed }.ToQuery(50, null).Rendered);
Assert.SequenceEqual([SyncState.InSync, SyncState.LocalAhead], new LibraryFilter { Status = StatusFilter.Synced }.ToQuery(50, null).SyncStates!);
Assert.Null(new LibraryFilter { Status = StatusFilter.Rendered }.ToQuery(50, null).SyncStates);
var (with, without) = LibraryFilter.Flags(StatusFilter.NotRendered);
Assert.Equal(SequenceStatus.None, with | without, "renders are counted, not flagged");
}
[Test]
public void TheSameChoicesMatchInMemory()
{
var rendered = Sequence(2, SyncState.InSync, SequenceStatus.AnalyzedLight);
var bare = Sequence(0, SyncState.LocalOnly);
var ahead = Sequence(0, SyncState.ServerAhead);
Assert.True(LibraryFilter.MatchesStatus(rendered, StatusFilter.Rendered));
Assert.False(LibraryFilter.MatchesStatus(bare, StatusFilter.Rendered));
Assert.True(LibraryFilter.MatchesStatus(bare, StatusFilter.NotRendered));
Assert.True(LibraryFilter.MatchesStatus(rendered, StatusFilter.Synced));
Assert.False(LibraryFilter.MatchesStatus(ahead, StatusFilter.Synced), "the server is ahead: not synced");
Assert.True(LibraryFilter.MatchesStatus(rendered, StatusFilter.Analysed));
Assert.True(LibraryFilter.MatchesStatus(bare, StatusFilter.Any));
Assert.False(new LibraryFilter { Status = StatusFilter.NotRendered }.Matches(rendered));
}
[Test]
public void TheBriefsExampleViewCanBeSaved()
{
var filter = new LibraryFilter { Status = StatusFilter.NotRendered, Text = "night" };
var view = SavedView.Of(Guid.CreateVersion7(), "Night, 4K, not rendered", filter);
Assert.Equal(StatusFilter.NotRendered, view.Status);
Assert.True(view.Matches(filter));
Assert.Equal(filter.Status, view.ToFilter().Status);
}
}
@@ -0,0 +1,180 @@
using Chronos.App.Library;
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
public sealed class LibraryPagerTests
{
[Test]
public async Task PagesFollowTheCursorUntilTheEnd()
{
var source = new FakeSource(450);
var pager = new LibraryPager(source.FetchAsync, pageSize: 200);
var first = Assert.NotNull(await pager.ResetAsync(new LibraryFilter()));
Assert.True(first.IsFirst);
Assert.Equal(200, first.Items.Count);
Assert.True(pager.HasMore);
Assert.Null(source.Queries[0].Cursor);
var second = Assert.NotNull(await pager.LoadMoreAsync());
Assert.False(second.IsFirst);
Assert.Equal(200, second.Items.Count);
Assert.Equal("200", source.Queries[1].Cursor);
var third = Assert.NotNull(await pager.LoadMoreAsync());
Assert.Equal(50, third.Items.Count);
Assert.False(third.HasMore);
Assert.False(pager.HasMore);
Assert.Equal(450, pager.Loaded);
Assert.Null(await pager.LoadMoreAsync());
Assert.Equal(3, source.Queries.Count);
var ids = first.Items.Concat(second.Items).Concat(third.Items).Select(s => s.Id).ToList();
Assert.Equal(450, ids.Distinct().Count());
}
[Test]
public async Task FilterAndSortReachTheQuery()
{
var source = new FakeSource(10);
var pager = new LibraryPager(source.FetchAsync, pageSize: 50);
await pager.ResetAsync(new LibraryFilter
{
Text = " harbour ",
Year = 2026,
Camera = "Canon EOS R5",
Status = StatusFilter.NotAnalysed,
Tag = "sunset",
Sort = SequenceSort.Title,
});
var q = source.Queries.Single();
Assert.Equal("harbour", q.Text);
Assert.Equal(2026, q.Year);
Assert.Equal("Canon EOS R5", q.Camera);
Assert.Equal("sunset", q.Tag);
Assert.Equal(SequenceStatus.None, q.WithStatus);
Assert.Equal(SequenceStatus.AnalyzedLight, q.WithoutStatus);
Assert.Equal(SequenceSort.Title, q.Sort);
Assert.Equal(50, q.Limit);
}
[Test]
public async Task AResetDropsThePageOfTheOldFilter()
{
var source = new FakeSource(1000) { Gate = new TaskCompletionSource() };
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
var stale = pager.ResetAsync(new LibraryFilter { Text = "old" });
source.Gate = null;
var fresh = await pager.ResetAsync(new LibraryFilter { Text = "new" });
Assert.NotNull(fresh);
Assert.Equal(2, fresh!.Generation);
// The first request was cancelled; even if its data had arrived it must not be applied.
Assert.Null(await stale);
Assert.True(source.Cancelled > 0);
Assert.Equal("new", pager.Filter.Text);
}
[Test]
public async Task ASupersededResultIsDroppedEvenWithoutCancellation()
{
var gate = new TaskCompletionSource();
var source = new FakeSource(1000) { Gate = gate, IgnoreCancellation = true };
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
var stale = pager.ResetAsync(new LibraryFilter { Text = "old" });
source.Gate = null;
var fresh = await pager.ResetAsync(new LibraryFilter { Text = "new" });
gate.SetResult();
Assert.Null(await stale);
Assert.Equal(100, fresh!.Items.Count);
Assert.Equal(100, pager.Loaded);
}
[Test]
public async Task OnlyOnePageLoadsAtATime()
{
var source = new FakeSource(1000);
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
await pager.ResetAsync(new LibraryFilter());
source.Gate = new TaskCompletionSource();
var a = pager.LoadMoreAsync();
var b = pager.LoadMoreAsync();
Assert.True(pager.IsLoading);
Assert.Null(await b);
source.Gate.SetResult();
Assert.Equal(100, (await a)!.Items.Count);
Assert.Equal(2, source.Queries.Count);
}
[Test]
public async Task AFailedPageStopsScrollLoadingUntilTheNextReset()
{
var source = new FakeSource(1000);
var pager = new LibraryPager(source.FetchAsync, pageSize: 100);
await pager.ResetAsync(new LibraryFilter());
source.Fail = true;
await Assert.ThrowsAsync<InvalidOperationException>(() => pager.LoadMoreAsync());
Assert.False(pager.HasMore);
Assert.Null(await pager.LoadMoreAsync());
source.Fail = false;
Assert.NotNull(await pager.ResetAsync(new LibraryFilter()));
Assert.True(pager.HasMore);
}
[Test]
public void StatusChoicesMapToFlags()
{
Assert.Equal((SequenceStatus.AnalyzedLight, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Analysed));
Assert.Equal((SequenceStatus.None, SequenceStatus.ProxiesBuilt), LibraryFilter.Flags(StatusFilter.NoProxies));
Assert.Equal((SequenceStatus.Verified, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Verified));
Assert.Equal((SequenceStatus.HasWarnings, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Warnings));
Assert.Equal((SequenceStatus.None, SequenceStatus.None), LibraryFilter.Flags(StatusFilter.Any));
Assert.True(new LibraryFilter { Sort = SequenceSort.Size }.IsUnfiltered);
Assert.False(new LibraryFilter { Text = "x" }.IsUnfiltered);
Assert.False(new LibraryFilter { Status = StatusFilter.Proxies }.IsUnfiltered);
var cleared = new LibraryFilter { Text = "x", Year = 2020, Sort = SequenceSort.Oldest }.Cleared();
Assert.True(cleared.IsUnfiltered);
Assert.Equal(SequenceSort.Oldest, cleared.Sort);
Assert.Null(new LibraryFilter { Text = " " }.ToQuery(10, null).Text);
}
/// <summary>An in-memory library: cursors are offsets, optionally held back by a gate.</summary>
private sealed class FakeSource(int count)
{
private readonly Guid _archive = Guid.CreateVersion7();
public List<SequenceQuery> Queries { get; } = [];
public TaskCompletionSource? Gate { get; set; }
public bool IgnoreCancellation { get; init; }
public bool Fail { get; set; }
public int Cancelled { get; private set; }
public async Task<Page<Sequence>> FetchAsync(SequenceQuery query, CancellationToken ct)
{
Queries.Add(query);
if (Gate is { } gate)
{
try
{
await gate.Task.WaitAsync(IgnoreCancellation ? CancellationToken.None : ct);
}
catch (OperationCanceledException)
{
Cancelled++;
throw;
}
}
if (Fail) throw new InvalidOperationException("database gone");
var start = query.Cursor is null ? 0 : int.Parse(query.Cursor, System.Globalization.CultureInfo.InvariantCulture);
var items = Enumerable.Range(start, Math.Max(0, Math.Min(query.Limit, count - start)))
.Select(i => new Sequence { Id = Guid.CreateVersion7(), ArchiveId = _archive, Folder = "s" + i, Title = "S" + i })
.ToList();
var next = start + items.Count < count ? (start + items.Count).ToString(System.Globalization.CultureInfo.InvariantCulture) : null;
return new Page<Sequence>(items, next);
}
}
}
@@ -0,0 +1,244 @@
using System.Collections.Specialized;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using Chronos.App.Archiving;
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.App.Sections;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Testing;
using Chronos.Ui.Controls;
using Chronos.Ui.Visuals;
namespace Chronos.App.Tests.Library;
/// <summary>
/// The Library's new states of <c>--capture</c> (<see cref="LibraryScenes"/>) on the sample index while signed in to the
/// sample server, rendered in both themes in the real main window: the timeline, a selection with the whole mass actions
/// bar and its delete dry run, the server's sequences as remote cards, saved views and Save view, and the archive's trash.
/// </summary>
[WindowsOnly]
[Serial]
[Timeout(300_000)]
public sealed class LibraryScreenSmokeTests
{
[Test]
public Task EveryLibrarySceneRendersInBothThemes() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
await app.Shell.Services.Server.RestoreAsync();
await app.Shell.Services.Sync.RefreshAsync();
var library = app.Shell.Library;
await LibraryScenes.ShowAsync(app.Shell, "timeline");
Assert.True(library.IsTimeline, "the timeline shows its bands");
Assert.True(library.IsGrid, "the cards stay under the bands");
Assert.Equal(2, library.TimelineBands.Count, "one band per year, 2026 and 2025, the server's sequences included");
Assert.True(library.TimelineBand >= 0 && library.TimelineSlot >= 0, "the chosen month is outlined");
Assert.True(library.IsYearFiltered, "a month narrows the Library to its year");
await app.ExpectAsync<LibraryView>("library-timeline", waitForThumbnails: true);
var bands = Assert.NotNull(app.FindAll<TimelineBands>().FirstOrDefault(t => t.IsVisible && t.ActualHeight > 0), "the bands are drawn");
Assert.True(bands.Focusable, "the keyboard reaches the months");
// Without the mouse: Enter on the month under the keyboard narrows the Library to its year.
library.ClearFiltersCommand.Execute(null);
await library.RefreshAsync();
Assert.Equal(-1, library.TimelineBand);
bands.Focus();
Press(bands, Key.Enter);
await library.RefreshAsync();
Assert.True(library.TimelineBand >= 0 && library.TimelineSlot >= 0, "Enter chose a month");
Assert.True(library.IsYearFiltered, "the year filter follows the band");
await LibraryScenes.ShowAsync(app.Shell, "mass");
Assert.Equal(LibraryScenes.MassSelection, library.SelectionCount);
await app.ExpectAsync<LibraryView>("library-mass", waitForThumbnails: true);
foreach (var command in new[] { library.AnalyseCommand, library.ProxiesCommand, library.VerifyCommand, library.TagCommand, library.MoveCommand,
library.ExportListCommand, library.DeleteCommand })
Assert.True(ButtonFor(app, command).IsEnabled, "the bar's archive actions work on sequences of this PC");
Assert.True(library.CanRate);
var request = Assert.NotNull(await LibraryScenes.DeleteRequestAsync(app.Shell), "the dry run moves something");
Assert.True(request.IsDestructive);
Assert.NotNull(request.TypedConfirmation);
var dialog = new ConfirmDialog(request) { WindowStartupLocation = WindowStartupLocation.Manual, Left = -20000, Top = -20000, ShowActivated = false };
dialog.Show();
try
{
dialog.UpdateLayout();
var action = Find<Button>(dialog).Single(b => Equals(b.Content, request.ActionText));
Assert.False(action.IsEnabled, "Delete waits for the typed confirmation");
Find<TextBox>(dialog).Single(t => t.IsVisible).Text = request.TypedConfirmation;
Assert.True(action.IsEnabled, "typing the count enables Delete");
}
finally
{
dialog.Close();
}
// The sample dialogs cancel every confirmation: the delete dialog closes and nothing moves.
var selected = library.SelectedItems().Select(i => i.Id).ToList();
Assert.False(await library.DeleteAsync(selected));
Assert.Null(library.Dialog, "the delete dialog closes once it is answered");
foreach (var id in selected) Assert.NotNull(await app.Services.Database!.Sequences.GetAsync(id));
var first = library.Items.First(i => i.IsSelected);
Assert.True(library.AnalyseItemCommand.CanExecute(first) && library.RenderItemCommand.CanExecute(first), "the quick actions run on this PC's engine");
await LibraryScenes.ShowAsync(app.Shell, "remote");
Assert.True(library.ShowsOrigin, "signed in, the origin filter shows");
Assert.Equal(2, library.Items.Count, "the two sequences only on the sample server");
Assert.True(library.Items.All(i => i.IsRemote));
Assert.True(library.IsSingleSelection);
Assert.False(library.DeleteCommand.CanExecute(null), "a remote card has nothing here to delete");
Assert.True(library.DownloadCommand.CanExecute(null), "its originals can come here");
Assert.False(library.RevealCommand.CanExecute(null), "a remote card has no folder here");
Assert.Equal(Loc.L("Library.Blocked.ServerOnly"), library.RevealToolTip);
await app.ExpectAsync<LibraryView>("library-remote");
Assert.True(library.Years.Count > 1, "the server's years are choices too");
library.ClearFiltersCommand.Execute(null);
await library.RefreshAsync();
Assert.True(library.HasViews, "the sample saved two views");
library.ViewChoices.Single(v => v.Label == "Nikon Z 8").Command.Execute(null);
await library.RefreshAsync();
Assert.True(library.IsViewActive);
Assert.True(library.Items.Count > 0 && library.Items.All(i => i.Sequence.CameraModel == "NIKON Z 8"));
await LibraryScenes.ShowAsync(app.Shell, "viewname");
var naming = Assert.NotNull(library.Dialog as ViewNameDialogViewModel, "Save view asks a name");
Assert.True(naming.SaveCommand.CanExecute(null), "the status filter's label is a free name");
Assert.False(library.IsContentEnabled, "the screen behind a dialog takes no input");
await app.ExpectAsync<LibraryView>("library-viewname");
naming.CloseCommand.Execute(null);
Assert.Null(library.Dialog);
await ArchiveScenes.ShowAsync(app.Shell, "trash");
var trash = Assert.NotNull(app.Shell.Archive.Dialog as TrashDialogViewModel, "Maintenance › Trash… opens the trash");
Assert.Equal(2, trash.Rows.Count, "the sample's deleted sequences");
Assert.True(trash.HasRows);
await app.ExpectAsync<ArchiveView>("archive-trash-sample");
trash.CloseCommand.Execute(null);
});
[Test]
public Task ADeletedSequenceComesBackFromTheArchiveTrash() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
await LibraryScenes.ShowAsync(app.Shell, "mass");
var db = app.Services.Database!;
var archives = app.Services.Archives!;
// What Delete runs once confirmed: the movable part of the selection goes to the archive's trash.
var plan = await archives.PlanDeleteAsync([.. app.Shell.Library.SelectedItems().Select(i => i.Id)]);
var moved = Assert.NotNull(plan.Steps.FirstOrDefault(), "the selection holds a sequence no job works on").Sequence;
Assert.NotEmpty(plan.Blocked);
await archives.DeleteAsync(plan);
Assert.Null(await db.Sequences.GetAsync(moved.Id));
app.Shell.Navigate(SectionKey.Archive);
await app.Shell.Archive.LoadAsync();
Assert.True(app.Shell.Archive.DeleteSetCommand.CanExecute(null), "the mass operations bar offers Delete…");
await app.Shell.Archive.OpenTrashAsync();
var trash = Assert.NotNull(app.Shell.Archive.Dialog as TrashDialogViewModel);
var row = trash.Rows.Single();
Assert.Equal(moved.Id, row.Entry.SequenceId);
await app.ExpectAsync<ArchiveView>("archive-trash");
row.RestoreCommand.Execute(null);
for (var i = 0; i < 100 && await db.Sequences.GetAsync(moved.Id) is null; i++) await Task.Delay(50);
var restored = Assert.NotNull(await db.Sequences.GetAsync(moved.Id), "Restore brings the sequence back into the index");
Assert.Equal(moved.Folder, restored.Folder);
Assert.True(trash.IsEmpty);
trash.CloseCommand.Execute(null);
});
/// <summary>A language switch makes the timeline's month readouts again, as it does the filters (BRIEF §16).</summary>
[Test]
public Task TheTimelineReadoutsFollowALanguageSwitch() => ScreenHost.RunAsync(async () =>
{
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
await app.Shell.Services.Server.RestoreAsync();
await app.Shell.Services.Sync.RefreshAsync();
var library = app.Shell.Library;
await LibraryScenes.ShowAsync(app.Shell, "timeline");
var english = Readout(library);
try
{
UiLanguage.Apply("it");
var italian = Readout(library);
Assert.NotEqual(english, italian, "the month readouts follow the language");
}
finally
{
UiLanguage.Apply("en");
}
Assert.Equal(english, Readout(library), "and come back with it");
static string Readout(LibraryViewModel library) => library.TimelineBands[0].ToolTips!.First(t => !string.IsNullOrEmpty(t))!;
});
/// <summary>
/// A remote card's Analyse posted to a server whose certificate changed since sign-in: the pin refuses it before
/// anything is sent, and the error toast says so (it used to escape the action unreported).
/// </summary>
[Test]
public Task APostRefusedByThePinnedCertificateSaysSo() => ScreenHost.RunAsync(async () =>
{
using var server = new UntrustedTlsEndpoint();
await using var app = await ScreenSmokeTests.SampleApp.StartAsync();
await app.Sample.FillAsync();
app.Services.Settings.ServerUrl = server.Address.ToString();
await app.Shell.Services.Server.RestoreAsync();
var actions = new LibraryActions(app.Shell);
Assert.True(actions.CanPost, "signed in to the endpoint (the sample's own certificate was trusted at sign-in)");
var toasts = new List<Toast>();
NotifyCollectionChangedEventHandler collect = (_, e) => toasts.AddRange(e.NewItems?.OfType<Toast>() ?? []);
app.Shell.PendingToasts.CollectionChanged += collect;
try
{
var remote = new Sequence
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Folder = "Harbour",
Title = "Harbour sunset",
Origin = SequenceOrigin.Server,
SyncState = SyncState.RemoteOnly,
};
await actions.AnalyseAsync([remote]);
}
finally
{
app.Shell.PendingToasts.CollectionChanged -= collect;
}
var toast = Assert.Contains(toasts, t => t.Title == Loc.L("Library.Post.Failed"));
Assert.Equal(Loc.L("Server.Error.Untrusted"), toast.Message);
Assert.True(toast.IsError);
});
private static void Press(UIElement target, Key key) =>
target.RaiseEvent(new KeyEventArgs(Keyboard.PrimaryDevice, PresentationSource.FromVisual(target)!, 0, key) { RoutedEvent = Keyboard.KeyDownEvent });
private static Button ButtonFor(ScreenSmokeTests.SampleApp app, ICommand command) =>
Assert.NotNull(app.FindAll<Button>().FirstOrDefault(b => ReferenceEquals(b.Command, command) && b.IsVisible), "a visible button bound to the command");
private static List<T> Find<T>(DependencyObject root)
where T : DependencyObject
{
var found = new List<T>();
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match) found.Add(match);
found.AddRange(Find<T>(child));
}
return found;
}
}
@@ -0,0 +1,71 @@
using Chronos.App.Library;
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>The Library's timeline: year bands of photos per month and the way from a month to the grid (BRIEF §12.2).</summary>
public sealed class LibraryTimelineTests
{
private static ArchiveStats Stats(params MonthBucket[] months) => new(0, 0, 0, [], months, [], [], new ArchiveHealth(0, 0, 0, 0, 0, 0, 0));
[Test]
public void BandsRunFromTheNewestYearWithEveryYearBetween()
{
var timeline = LibraryTimeline.From(Stats(new MonthBucket(2023, 3, 1, 400), new MonthBucket(2026, 9, 2, 5_000), new MonthBucket(2026, 1, 1, 120)),
new DateTime(2026, 10, 3));
Assert.SequenceEqual([2026, 2025, 2024, 2023], timeline.Years);
Assert.SequenceEqual(["2026", "2025", "2024", "2023"], timeline.Bands.Select(b => b.Label));
var newest = timeline.Bands[0].Values;
Assert.Equal(120.0, newest[0]);
Assert.Equal(5_000.0, newest[8]);
Assert.Equal(0.0, newest[9], "October has passed its first days: an empty month, not a future one");
Assert.True(double.IsNaN(newest[10]), "months to come carry no density");
Assert.Equal(400.0, timeline.Bands[3].Values[2]);
Assert.True(timeline.Bands[1].Values.All(v => v == 0), "a year without photos still has its band");
}
[Test]
public void AnEmptyLibraryHasNoBands()
{
var timeline = LibraryTimeline.From(Stats(), new DateTime(2026, 10, 3));
Assert.Empty(timeline.Bands);
Assert.Null(timeline.MonthAt(0, 0));
Assert.Equal((-1, -1), timeline.SlotOf(2026, 1));
}
[Test]
public void SlotsAndMonthsMapBothWays()
{
var timeline = LibraryTimeline.From(Stats(new MonthBucket(2025, 6, 1, 10), new MonthBucket(2026, 2, 1, 10)), new DateTime(2026, 10, 3));
Assert.Equal((2026, 1), timeline.MonthAt(0, 0));
Assert.Equal((2025, 12), timeline.MonthAt(1, 11));
Assert.Null(timeline.MonthAt(2, 0));
Assert.Null(timeline.MonthAt(0, 12));
Assert.Null(timeline.MonthAt(-1, 3));
Assert.Equal((1, 5), timeline.SlotOf(2025, 6));
Assert.Equal((-1, -1), timeline.SlotOf(2024, 6));
Assert.Equal((-1, -1), timeline.SlotOf(2026, 13));
}
[Test]
public void TheFirstSequenceOfAMonthIsFoundInListOrder()
{
Sequence At(int year, int month, int day) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.Empty,
Folder = "f",
FirstCapture = new DateTime(year, month, day, 18, 0, 0),
};
List<Sequence> newestFirst = [At(2026, 9, 28), At(2026, 9, 2), At(2026, 7, 14), new() { Id = Guid.CreateVersion7(), ArchiveId = Guid.Empty, Folder = "g" }];
Assert.Equal(0, LibraryTimeline.FirstOfMonth(newestFirst, 2026, 9));
Assert.Equal(2, LibraryTimeline.FirstOfMonth(newestFirst, 2026, 7));
Assert.Equal(-1, LibraryTimeline.FirstOfMonth(newestFirst, 2026, 8));
Assert.Equal(-1, LibraryTimeline.FirstOfMonth([], 2026, 9));
}
}
@@ -0,0 +1,148 @@
using Chronos.App.Library;
using Chronos.App.Server;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Sync;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>Which selected sequences each button of the mass actions bar works on, and why a button is off (BRIEF §12.2, DESIGN §4).</summary>
public sealed class MassActionsTests
{
private const string Server = "https://nas.local:8443";
private static readonly SyncRights Editor = SyncRights.Of((long)RolePermissions.Default(UserRole.Editor));
private static readonly SyncRights Viewer = SyncRights.Of((long)RolePermissions.Default(UserRole.Viewer));
private static readonly Guid MainArchive = Guid.CreateVersion7();
private static readonly SelectionContext Offline = new(HasEngine: true, IsSignedIn: false, default);
private static readonly SelectionContext SignedIn = new(HasEngine: true, IsSignedIn: true, Editor);
private static Sequence Local(string title, Guid? archive = null) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = archive ?? MainArchive,
Title = title,
Folder = "2026/" + title,
FrameCount = 120,
};
private static SyncLink Link(Sequence sequence) => new() { Server = Server, RemoteId = Guid.CreateVersion7(), Title = sequence.DisplayTitle };
private static SelectedSequence Remote(string title)
{
var link = new SyncLink { Server = Server, RemoteId = Guid.CreateVersion7(), Title = title, FrameCount = 300 };
var card = RemoteCards.FromLink(link);
return new SelectedSequence(card, new SyncEntry(null, link, SyncStatus.RemoteOnly));
}
private static SelectedSequence Linked(string title, SyncStatus status, Func<SyncLink, SyncLink>? change = null)
{
var local = Local(title);
var link = Link(local);
return new SelectedSequence(local, new SyncEntry(local, change?.Invoke(link) ?? link, status));
}
private static SelectedSequence Only(string title) => new(Local(title), null);
[Test]
public void NothingRunsWithoutASelectionOrAnIndexButTheListExport()
{
foreach (var action in Enum.GetValues<MassAction>())
Assert.Equal(Loc.L("Library.Blocked.NoSelection"), MassActions.Blocker(action, [], SignedIn));
SelectedSequence[] one = [Only("Harbour sunset")];
var noIndex = new SelectionContext(HasEngine: false, IsSignedIn: false, default);
Assert.Equal(Loc.L("Library.Blocked.NoIndex"), MassActions.Blocker(MassAction.Analyse, one, noIndex));
Assert.Equal(Loc.L("Library.Blocked.NoIndex"), MassActions.Blocker(MassAction.Delete, one, noIndex));
Assert.Null(MassActions.Blocker(MassAction.ExportList, one, noIndex), "a CSV needs only the rows on screen");
}
[Test]
public void ArchiveActionsWorkOnTheSequencesOfThisPc()
{
var harbour = Only("Harbour sunset");
var remote = Remote("Sunrise over Superga");
SelectedSequence[] mixed = [harbour, remote];
foreach (var action in new[] { MassAction.Analyse, MassAction.Proxies, MassAction.Verify, MassAction.Tag, MassAction.Rate, MassAction.Move, MassAction.Delete })
{
Assert.Null(MassActions.Blocker(action, mixed, SignedIn), action.ToString());
Assert.SequenceEqual([harbour], MassActions.Targets(action, mixed, SignedIn), action.ToString());
Assert.Equal(Loc.L("Library.Blocked.ServerOnly"), MassActions.Blocker(action, [remote], SignedIn));
}
Assert.SequenceEqual(mixed, MassActions.Targets(MassAction.ExportList, mixed, SignedIn), "the CSV lists remote cards too");
Assert.Equal(Loc.Plural("Tooltips.Library.Mass.Delete", 1), MassActions.ToolTip(MassAction.Delete, 1));
}
[Test]
public void MoveStaysInsideOneArchive()
{
SelectedSequence[] two = [Only("Harbour sunset"), new(Local("Aurora", Guid.CreateVersion7()), null)];
Assert.Equal(Loc.L("Library.Blocked.Archives"), MassActions.Blocker(MassAction.Move, two, Offline));
Assert.Null(MassActions.Blocker(MassAction.Delete, two, Offline), "the trash of each archive takes its own sequences");
}
[Test]
public void TransfersNeedASessionAndTheRight()
{
SelectedSequence[] one = [Only("Harbour sunset")];
Assert.Equal(Loc.L("Library.Blocked.NotConnected"), MassActions.Blocker(MassAction.Upload, one, Offline));
Assert.Equal(Loc.L("Library.Blocked.NotConnected"), MassActions.Blocker(MassAction.Download, one, Offline));
Assert.Equal(Loc.L("Library.Blocked.NoUploadRight"), MassActions.Blocker(MassAction.Upload, one, SignedIn with { Rights = Viewer }));
Assert.Equal(Loc.L("Library.Blocked.NoDownloadRight"), MassActions.Blocker(MassAction.Download, one, SignedIn with { Rights = Viewer }));
Assert.Null(MassActions.Blocker(MassAction.Upload, one, SignedIn), "a sequence only here uploads before the table compares it");
Assert.Equal(Loc.L("Library.Blocked.NothingToDownload"), MassActions.Blocker(MassAction.Download, one, SignedIn));
}
[Test]
public void EachTransferTakesWhatItsSyncRowOffers()
{
var only = Only("Harbour sunset");
var ahead = Linked("Comet over the ridge", SyncStatus.LocalAhead, l => l with { MissingRemote = 4 });
var renders = Linked("Star trails", SyncStatus.InSync, l => l with { ExportsToSend = 1, ExportsToGet = 2 });
var same = Linked("Aurora, Tromsø", SyncStatus.InSync);
var behind = Linked("Fog lifting", SyncStatus.ServerAhead, l => l with { MissingLocal = 12 });
var remote = Remote("Sunrise over Superga");
SelectedSequence[] all = [only, ahead, renders, same, behind, remote];
Assert.SequenceEqual([only, ahead, renders], MassActions.Targets(MassAction.Upload, all, SignedIn));
Assert.Equal(SyncAction.Upload, MassActions.UploadStep(only, Editor));
Assert.Equal(SyncAction.Upload, MassActions.UploadStep(ahead, Editor));
Assert.Equal(SyncAction.SendExports, MassActions.UploadStep(renders, Editor));
Assert.Null(MassActions.UploadStep(same, Editor));
Assert.Null(MassActions.UploadStep(remote, Editor), "a remote card has nothing here to send");
Assert.SequenceEqual([renders, behind, remote], MassActions.Targets(MassAction.Download, all, SignedIn));
Assert.Equal(SyncAction.GetExports, MassActions.DownloadStep(renders, Editor));
Assert.Equal(SyncAction.DownloadOriginals, MassActions.DownloadStep(behind, Editor));
Assert.Equal(SyncAction.DownloadOriginals, MassActions.DownloadStep(remote, Editor));
Assert.Null(MassActions.DownloadStep(only, Editor));
Assert.Equal(Loc.L("Library.Blocked.NothingToUpload"), MassActions.Blocker(MassAction.Upload, [same, remote], SignedIn));
}
[Test]
public void TheCardsSyncDoesTheFirstThingItsRowOffers()
{
Assert.Null(MassActions.QuickSync(Only("Harbour sunset"), Offline, out var why));
Assert.Equal(Loc.L("Library.Blocked.NotConnected"), why);
Assert.Equal(SyncAction.Upload, MassActions.QuickSync(Only("Harbour sunset"), SignedIn, out why));
Assert.Null(why);
Assert.Null(MassActions.QuickSync(Only("Harbour sunset"), SignedIn with { Rights = Viewer }, out why));
Assert.Equal(Loc.L("Library.Blocked.NoUploadRight"), why);
Assert.Equal(SyncAction.DownloadOriginals, MassActions.QuickSync(Remote("Sunrise over Superga"), SignedIn, out _));
Assert.Equal(SyncAction.SyncSettings, MassActions.QuickSync(Linked("Holy grail", SyncStatus.ServerAhead), SignedIn, out _));
Assert.Equal(SyncAction.KeepMine, MassActions.QuickSync(Linked("Holy grail", SyncStatus.Conflict), SignedIn, out _), "a conflict goes to the Server screen");
Assert.Null(MassActions.QuickSync(Linked("Aurora, Tromsø", SyncStatus.InSync), SignedIn, out why));
Assert.Equal(Loc.L("Library.Blocked.InSync"), why);
var moving = Linked("Comet over the ridge", SyncStatus.LocalAhead);
var transferring = moving with { Sync = moving.Sync! with { Transfer = new Job { Id = Guid.CreateVersion7(), Kind = JobKind.UploadCommit, State = JobState.Running } } };
Assert.Null(MassActions.QuickSync(transferring, SignedIn, out why));
Assert.Equal(Loc.L("Library.Blocked.Transferring"), why);
}
}
@@ -0,0 +1,136 @@
using Chronos.App.Infrastructure;
using Chronos.App.Library;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Repositories;
using Chronos.Data.Sync;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Library;
/// <summary>Server sequences without a copy here as Library cards, and their place among the index's pages (BRIEF §4.4).</summary>
public sealed class RemoteCardsTests
{
private const string Server = "https://nas.local:8443";
private static SyncLink Link(string title, int frames = 100) => new() { Server = Server, RemoteId = Guid.CreateVersion7(), Title = title, FrameCount = frames };
private static Sequence Card(string title, DateTime? first, string? camera = null, params string[] tags) =>
RemoteCards.FromLink(Link(title)) with { FirstCapture = first, CameraModel = camera, Tags = tags };
private static Sequence Local(string title, DateTime? first) => new()
{
Id = Guid.CreateVersion7(),
ArchiveId = Guid.CreateVersion7(),
Title = title,
Folder = title,
FirstCapture = first,
};
[Test]
public void OnlyServerSequencesWithoutALocalCopyBecomeCards()
{
var harbour = new Sequence { Id = Guid.CreateVersion7(), ArchiveId = Guid.CreateVersion7(), Folder = "harbour", Title = "Harbour sunset" };
var sunrise = Link("Sunrise over Superga", 2_880) with { TotalBytes = 60_000_000_000, RemoteStatus = SequenceStatus.ProxiesBuilt, RenderCount = 1 };
var lake = Link("Lake Como storm");
SyncEntry[] table =
[
new(harbour, Link("Harbour sunset"), SyncStatus.InSync),
new(harbour with { Id = Guid.CreateVersion7() }, null, SyncStatus.LocalOnly),
new(null, sunrise, SyncStatus.RemoteOnly),
new(null, lake, SyncStatus.ProxiesOnly),
];
var cards = RemoteCards.Build(table, null);
Assert.SequenceEqual([sunrise.RemoteId, lake.RemoteId], cards.Select(c => c.Id));
var card = cards[0];
Assert.Equal("Sunrise over Superga", card.DisplayTitle);
Assert.Equal(2_880, card.FrameCount);
Assert.Equal(60_000_000_000, card.TotalBytes);
Assert.Equal(SequenceStatus.ProxiesBuilt, card.Status);
Assert.Equal(1, card.RenderedCount);
Assert.Equal(SequenceOrigin.Server, card.Origin);
Assert.Equal(SyncState.RemoteOnly, card.SyncState);
Assert.Equal(Guid.Empty, card.ArchiveId, "a remote card belongs to no archive of this PC");
}
[Test]
public void TheServersListingFillsInTheDetails()
{
var link = Link("Sunrise");
var dto = new SequenceDto(link.RemoteId, "Sunrise over Superga", "Sunrise over Superga", "2026/2026-07-02 Sony ILCE-7M4", "Sony", "ILCE-7M4", null,
new DateTime(2026, 7, 2, 5, 40, 0), new DateTime(2026, 7, 2, 7, 16, 0), 2_880, 2.0, 60_000_000_000, (int)SequenceStatus.ProxiesBuilt, 1, null,
["sunrise"], 4, null, 3, 2, 0, null, DateTimeOffset.UtcNow);
var card = RemoteCards.Build([new SyncEntry(null, link, SyncStatus.RemoteOnly)], new Dictionary<Guid, SequenceDto> { [dto.Id] = dto }).Single();
Assert.Equal("Sunrise over Superga", card.DisplayTitle);
Assert.Equal("ILCE-7M4", card.CameraModel);
Assert.Equal(new DateTime(2026, 7, 2, 5, 40, 0), card.FirstCapture);
Assert.SequenceEqual(["sunrise"], card.Tags);
Assert.Equal(4, card.Rating);
Assert.Equal(SyncState.RemoteOnly, card.SyncState);
}
[Test]
public void PreviewOnlyFramesShowAChipWithTheirCount()
{
// A server sequence of CR3s it reads only through their previews (BRIEF §8.2 tier 2).
var link = Link("Aurora");
var dto = new SequenceDto(link.RemoteId, "Aurora", "Aurora", "2026/2026-02-20 Nikon Z 8", "NIKON CORPORATION", "NIKON Z 8", null,
new DateTime(2026, 2, 20, 21, 0, 0), new DateTime(2026, 2, 21, 1, 8, 0), 1_860, 8.0, 50_000_000_000, (int)SequenceStatus.AnalyzedLight, 0, null,
[], 0, null, 1, 1, 0, null, DateTimeOffset.UtcNow, PreviewOnlyCount: 1_860);
var card = RemoteCards.Build([new SyncEntry(null, link, SyncStatus.RemoteOnly)], new Dictionary<Guid, SequenceDto> { [dto.Id] = dto }).Single();
Assert.Equal(1_860, card.PreviewOnlyCount);
Assert.Equal(1_860, RemoteCards.ToSequence(dto).PreviewOnlyCount);
var chip = SequenceItem.BuildStatuses(card, analysing: false).Single(s => s.Kind == StatusKind.PreviewOnly);
Assert.Equal(Formatting.Count(1_860), chip.Text);
Assert.Equal(Loc.Plural("Tooltips.Library.Status.PreviewOnly", 1_860), chip.ToolTip);
Assert.NotEqual(Loc.Plural("Tooltips.Library.Status.PreviewOnly", 1), chip.ToolTip, "plural forms");
Assert.False(SequenceItem.BuildStatuses(card with { PreviewOnlyCount = 0 }, analysing: false).Any(s => s.Kind == StatusKind.PreviewOnly), "no chip without them");
}
[Test]
public void CardsSortAmongThePagesAndFollowTheFilter()
{
var merge = new RemoteMerge();
var september = Card("Comet", new DateTime(2026, 9, 20), "ILCE-7M4", "stars");
var july = Card("Sunrise", new DateTime(2026, 7, 2), "ILCE-7M4");
var undated = Card("Unknown", null);
var otherYear = Card("Old", new DateTime(2024, 5, 1));
merge.Reset(new LibraryFilter(), [july, undated, september, otherYear]);
Assert.Equal(4, merge.Pending);
// Newest first: each page takes the cards that sort before its last row, the last page the rest.
var first = merge.Merge([Local("A", new DateTime(2026, 9, 28)), Local("B", new DateTime(2026, 8, 1))], last: false);
Assert.SequenceEqual(["A", "Comet", "B"], first.Select(s => s.DisplayTitle));
var second = merge.Merge([Local("C", new DateTime(2025, 1, 1))], last: false);
Assert.SequenceEqual(["Sunrise", "C"], second.Select(s => s.DisplayTitle));
var last = merge.Merge([Local("D", new DateTime(2023, 1, 1))], last: true);
Assert.SequenceEqual(["Old", "D", "Unknown"], last.Select(s => s.DisplayTitle), "undated cards come last");
Assert.Equal(0, merge.Pending);
merge.Reset(new LibraryFilter { Year = 2026, Text = "sun" }, [july, september, otherYear]);
Assert.SequenceEqual(["Sunrise"], merge.Merge([], last: true).Select(s => s.DisplayTitle));
merge.Reset(new LibraryFilter { Tag = "stars" }, [july, september]);
Assert.SequenceEqual(["Comet"], merge.Merge([], last: true).Select(s => s.DisplayTitle));
merge.Reset(new LibraryFilter { Origin = OriginFilter.Local }, [july, september]);
Assert.Equal(0, merge.Pending, "on this PC only: no remote card");
merge.Reset(new LibraryFilter { Status = StatusFilter.Analysed }, [july]);
Assert.Equal(0, merge.Pending, "a remote card not analysed does not pass the status filter");
}
[Test]
public void FiltersCompareLikeTheIndex()
{
var byTitle = new LibraryFilter { Sort = SequenceSort.Title };
Assert.True(byTitle.Compare(Local("aurora", null), Local("Comet", null)) < 0, "titles ignore case");
var bySize = new LibraryFilter { Sort = SequenceSort.Size };
Assert.True(bySize.Compare(Local("big", null) with { TotalBytes = 10 }, Local("small", null) with { TotalBytes = 1 }) < 0, "largest first");
var oldest = new LibraryFilter { Sort = SequenceSort.Oldest };
Assert.True(oldest.Compare(Local("a", new DateTime(2020, 1, 1)), Local("b", new DateTime(2021, 1, 1))) < 0);
Assert.True(oldest.Compare(Local("a", null), Local("b", new DateTime(2021, 1, 1))) > 0, "undated last");
}
}
@@ -0,0 +1,82 @@
using System.IO;
using Chronos.App.Library;
using Chronos.Core.Localization;
using Chronos.Data;
using Chronos.Data.Repositories;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
/// <summary>Saved views of the Library (BRIEF §12.2): a name for filters and sort, kept as app-scope settings rows.</summary>
public sealed class SavedViewTests(TestContext context)
{
private static readonly LibraryFilter Night = new()
{
Text = " night ",
Year = 2026,
Camera = "ILCE-7M4",
Status = StatusFilter.NotAnalysed,
Tag = "stars",
Origin = OriginFilter.Local,
Sort = SequenceSort.Size,
};
[Test]
public void AViewKeepsFiltersAndSortAndRecognisesThem()
{
var view = SavedView.Of(Guid.CreateVersion7(), " Night, 4K, not analysed ", Night);
Assert.Equal("Night, 4K, not analysed", view.Name);
Assert.Equal("night", view.Text);
Assert.Equal(Night with { Text = "night" }, view.ToFilter());
Assert.True(view.Matches(Night));
Assert.True(view.Matches(Night with { Text = "NIGHT" }), "the search compares trimmed and ignoring case");
Assert.False(view.Matches(Night with { Sort = SequenceSort.Newest }), "the sort is part of the view");
Assert.False(view.Matches(Night with { Origin = OriginFilter.Any }));
Assert.False(view.Matches(Night with { Tag = null }));
var blank = SavedView.Of(Guid.CreateVersion7(), "All", new LibraryFilter { Text = " " });
Assert.Null(blank.Text);
Assert.True(blank.Matches(new LibraryFilter()));
}
[Test]
public void NamesAreShortUniqueAndPrintable()
{
string[] others = ["Night", "Holy grail"];
Assert.Equal(Loc.L("Library.Views.Error.Empty"), SavedView.Validate(" ", others));
Assert.Equal(Loc.L("Library.Views.Error.Long", SavedView.MaxName), SavedView.Validate(new string('a', SavedView.MaxName + 1), others));
Assert.Equal(Loc.L("Library.Views.Error.Long", SavedView.MaxName), SavedView.Validate("Night\tsky", others));
Assert.Equal(Loc.L("Library.Views.Error.Taken"), SavedView.Validate(" night ", others));
Assert.Null(SavedView.Validate("Night, 4K", others));
Assert.Null(SavedView.Validate(new string('a', SavedView.MaxName), others));
}
[Test]
public async Task ViewsRoundTripThroughTheSettingsTable()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
var store = new SavedViewStore(db.Settings);
Assert.Empty(await store.ListAsync());
var night = SavedView.Of(Guid.CreateVersion7(), "Night", Night);
var grail = SavedView.Of(Guid.CreateVersion7(), "holy grail", new LibraryFilter { Tag = "holy grail", Sort = SequenceSort.Oldest });
await store.SaveAsync(night);
await store.SaveAsync(grail);
// Other app settings and a damaged row live next to the views and are not views.
await db.Settings.SetJsonAsync(SettingScope.App, null, "library.layout", "2");
await db.Settings.SetJsonAsync(SettingScope.App, null, "library.view.broken", "\"not a view\"");
var listed = await store.ListAsync();
Assert.SequenceEqual(["holy grail", "Night"], listed.Select(v => v.Name), "by name, ignoring case");
Assert.Equal(night, listed[1]);
Assert.Equal(grail, listed[0]);
await store.SaveAsync(night with { Name = "Night sky" });
Assert.SequenceEqual(["holy grail", "Night sky"], (await store.ListAsync()).Select(v => v.Name), "a rename keeps one row");
Assert.True(await store.DeleteAsync(grail.Id));
Assert.False(await store.DeleteAsync(grail.Id));
Assert.Equal(night.Id, (await store.ListAsync()).Single().Id);
}
}
@@ -0,0 +1,169 @@
using System.Collections.Concurrent;
using System.IO;
using Chronos.App.Library;
using Chronos.Testing;
namespace Chronos.App.Tests.Library;
public sealed class ThumbnailCacheTests
{
private static readonly TimeSpan Wait = TimeSpan.FromSeconds(10);
[Test]
public async Task LeastRecentlyUsedEntriesAreEvicted()
{
var loads = new ConcurrentBag<int>();
using var cache = new ThumbnailCache<int, string>(3, (k, _) =>
{
loads.Add(k);
return Task.FromResult<string?>("img" + k);
});
Assert.Equal("img1", await cache.GetAsync(1, CancellationToken.None));
await cache.GetAsync(2, CancellationToken.None);
await cache.GetAsync(3, CancellationToken.None);
Assert.True(cache.TryGet(1, out _)); // 1 becomes the most recent
await cache.GetAsync(4, CancellationToken.None); // evicts 2
Assert.Equal(3, cache.Count);
Assert.False(cache.TryGet(2, out _));
Assert.True(cache.TryGet(1, out var one));
Assert.Equal("img1", one);
Assert.True(cache.TryGet(3, out _));
Assert.True(cache.TryGet(4, out _));
await cache.GetAsync(1, CancellationToken.None);
Assert.Equal(4, loads.Count); // the cached key was not decoded again
cache.Capacity = 1;
Assert.Equal(1, cache.Count);
Assert.True(cache.TryGet(1, out _));
}
[Test]
public async Task MissingThumbnailsAreCachedButFailuresAreNot()
{
var calls = 0;
using var cache = new ThumbnailCache<int, string>(8, (k, _) =>
{
Interlocked.Increment(ref calls);
return k == 13 ? throw new IOException("unreadable") : Task.FromResult<string?>(null);
});
Assert.Null(await cache.GetAsync(1, CancellationToken.None));
Assert.Null(await cache.GetAsync(1, CancellationToken.None));
Assert.True(cache.TryGet(1, out var none));
Assert.Null(none);
await Assert.ThrowsAsync<IOException>(() => cache.GetAsync(13, CancellationToken.None));
await Assert.ThrowsAsync<IOException>(() => cache.GetAsync(13, CancellationToken.None));
Assert.Equal(3, calls);
Assert.Equal(0, cache.PendingLoads);
}
[Test]
public async Task ConcurrentRequestsShareOneLoad()
{
var release = new TaskCompletionSource();
var calls = 0;
using var cache = new ThumbnailCache<int, string>(8, async (k, ct) =>
{
Interlocked.Increment(ref calls);
await release.Task.WaitAsync(ct);
return "img" + k;
});
var a = cache.GetAsync(7, CancellationToken.None);
var b = cache.GetAsync(7, CancellationToken.None);
release.SetResult();
Assert.Equal("img7", await a.WaitAsync(Wait));
Assert.Equal("img7", await b.WaitAsync(Wait));
Assert.Equal(1, calls);
}
[Test]
public async Task ALoadStopsWhenEveryRequestIsCancelled()
{
var started = new TaskCompletionSource();
var observed = new TaskCompletionSource();
using var cache = new ThumbnailCache<int, string>(8, async (_, ct) =>
{
started.TrySetResult();
try
{
await Task.Delay(Timeout.Infinite, ct);
}
catch (OperationCanceledException)
{
observed.TrySetResult();
throw;
}
return "never";
});
using var first = new CancellationTokenSource();
using var second = new CancellationTokenSource();
var a = cache.GetAsync(5, first.Token);
var b = cache.GetAsync(5, second.Token);
await started.Task.WaitAsync(Wait);
first.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => a);
Assert.False(observed.Task.IsCompleted, "the load must continue while another card still waits");
Assert.Equal(1, cache.PendingLoads);
second.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => b);
await observed.Task.WaitAsync(Wait);
Assert.Equal(0, cache.PendingLoads);
Assert.False(cache.TryGet(5, out _));
}
[Test]
public async Task ALoadAfterACancelledOneStartsFresh()
{
var attempts = 0;
var blocked = true;
using var cache = new ThumbnailCache<int, string>(8, async (k, ct) =>
{
Interlocked.Increment(ref attempts);
if (Volatile.Read(ref blocked)) await Task.Delay(Timeout.Infinite, ct);
return "img" + k;
});
using var scrolledAway = new CancellationTokenSource();
var first = cache.GetAsync(9, scrolledAway.Token);
scrolledAway.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => first);
Volatile.Write(ref blocked, false);
Assert.Equal("img9", await cache.GetAsync(9, CancellationToken.None).WaitAsync(Wait));
// The cancelled load may have stopped before it reached the decoder.
Assert.InRange(Volatile.Read(ref attempts), 1, 2);
Assert.Equal(0, cache.PendingLoads);
}
[Test]
public async Task LoadsRunConcurrentlyUpToTheLimit()
{
var running = 0;
var peak = 0;
var gate = new TaskCompletionSource();
using var cache = new ThumbnailCache<int, string>(64, async (k, ct) =>
{
var now = Interlocked.Increment(ref running);
InterlockedMax(ref peak, now);
await gate.Task.WaitAsync(ct);
Interlocked.Decrement(ref running);
return "img" + k;
}, maxConcurrentLoads: 2);
var tasks = Enumerable.Range(0, 10).Select(i => cache.GetAsync(i, CancellationToken.None)).ToList();
await Task.Delay(100);
Assert.LessOrEqual(Volatile.Read(ref running), 2);
gate.SetResult();
await Task.WhenAll(tasks).WaitAsync(Wait);
Assert.LessOrEqual(peak, 2);
Assert.Equal(10, cache.Count);
}
private static void InterlockedMax(ref int target, int value)
{
int current;
while ((current = Volatile.Read(ref target)) < value && Interlocked.CompareExchange(ref target, value, current) != current)
{
}
}
}
@@ -0,0 +1,78 @@
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace Chronos.App.Tests.Library;
/// <summary>
/// A TLS endpoint on loopback with a self-signed certificate no client trusted (a server whose certificate changed since
/// sign-in): the client's pinning refuses every handshake, so nothing is ever sent.
/// </summary>
internal sealed class UntrustedTlsEndpoint : IDisposable
{
private readonly TcpListener _listener = new(IPAddress.Loopback, 0);
private readonly X509Certificate2 _certificate;
private readonly CancellationTokenSource _stop = new();
private readonly Task _accepting;
public UntrustedTlsEndpoint()
{
using var key = RSA.Create(2048);
var request = new CertificateRequest("CN=127.0.0.1", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1));
// Schannel serves only a certificate whose key it can open: a PKCS #12 round trip gives it one.
_certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pkcs12), null);
_listener.Start();
_accepting = Task.Run(AcceptAsync);
}
public Uri Address => new($"https://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/");
public void Dispose()
{
_stop.Cancel();
_listener.Stop();
try
{
_accepting.Wait(TimeSpan.FromSeconds(5));
}
catch (AggregateException)
{
// The loop ends with the listener; how it ended does not matter.
}
_certificate.Dispose();
_stop.Dispose();
}
private async Task AcceptAsync()
{
while (!_stop.IsCancellationRequested)
{
TcpClient client;
try
{
client = await _listener.AcceptTcpClientAsync(_stop.Token);
}
catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException)
{
return;
}
using (client)
{
try
{
await using var tls = new SslStream(client.GetStream());
await tls.AuthenticateAsServerAsync(new SslServerAuthenticationOptions { ServerCertificate = _certificate }, _stop.Token);
}
catch (Exception ex) when (ex is AuthenticationException or IOException or OperationCanceledException or SocketException)
{
// The client refused the certificate: the handshake ends here, as intended.
}
}
}
}
}