feat: work board, no usage data, archive folder tree, deploy guide (owner review 4 + owner review 1 phase 6) (#62)
CI / Build and test (push) Successful in 10m37s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 9s
Release / Build, test and publish (push) Successful in 16m19s
CI / PostgreSQL 16 integration (push) Successful in 10m19s
CI / PostgreSQL 17 integration (push) Successful in 11m27s
CI / Docker image (push) Successful in 57s
Release / Server image (push) Successful in 1m34s

Owner review 4 and owner review 1 phase 6.

- Work board in Videos (desktop and admin panel): Published and Workspace lanes (#29).
- Anonymous usage counts removed: Chronos sends nothing about its use (#30).
- The archive's whole folder tree is created inside any archive root, on the server and the desktop (#31).
- Video cards start with the preset; sizes keep number and unit together (#28).
- Deploy guide docs/deploy (Docker, Unraid, desktop), BRIEF §24, original documentation in docs/reference/original (#22).

Closes #22 #28 #29 #30 #31

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 #62.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-11-06 18:46:22 +01:00
1 parent 728ffa35cb
commit 0075065884
304 files changed
+6892 -325

No files matched your search

@@ -45,8 +45,8 @@ public sealed class ArchiveLanguageTests
var tree = ArchiveTree.Build(Main, ArchiveAvailability.Online, [harbour]);
var year = new ArchiveTreeRowViewModel(tree.Root.Children[0], ArchiveAvailability.Online, _ => { });
var sequence = new ArchiveTreeRowViewModel(tree.Root.Children[0].Children[0], ArchiveAvailability.Online, _ => { });
Assert.Equal("Construction cam · weekly · 3,600 photos · 72 GB", sequence.RowToolTip);
Assert.Equal("2026 · 1 sequence · 72 GB · Right arrow opens the year, Left arrow closes it", year.RowToolTip);
Assert.Equal("Construction cam · weekly · 3,600 photos · 72\u00A0GB", sequence.RowToolTip);
Assert.Equal("2026 · 1 sequence · 72\u00A0GB · Right arrow opens the year, Left arrow closes it", year.RowToolTip);
try
{
Loc.SetCulture(CultureInfo.GetCultureInfo("he"));
@@ -45,8 +45,8 @@ public sealed class ArchiveLogicTests
Assert.Equal("ChronosArchive", tree.Root.Title);
Assert.SequenceEqual(new[] { "2026", "2025", "Undated" }, tree.Root.Children.Select(n => n.Title));
Assert.SequenceEqual(new[] { "Harbour", "Comet" }, tree.Root.Children[0].Children.Select(n => n.Title));
Assert.Equal("3,600 photos · 72 GB", tree.Root.Children[0].Children[0].Detail);
Assert.Equal("2 sequences · 72 GB", tree.Root.Children[0].Detail);
Assert.Equal("3,600 photos · 72\u00A0GB", tree.Root.Children[0].Children[0].Detail);
Assert.Equal("2 sequences · 72\u00A0GB", tree.Root.Children[0].Detail);
// Collapsed years show only themselves; expanding one reveals its sequences.
Assert.Equal(4, tree.Visible().Count);
@@ -137,7 +137,7 @@ public sealed class ArchiveLogicTests
var stats = Stats();
var years = ArchiveFigures.StorageByYear(stats);
Assert.SequenceEqual(new[] { "2024", "2026" }, years.Select(b => b.Label));
Assert.Equal("2.1 TB", years[1].ValueText);
Assert.Equal("2.1\u00A0TB", years[1].ValueText);
var cameras = ArchiveFigures.ByCamera(stats);
Assert.Equal(ArchiveFigures.TopCameras + 1, cameras.Count);
@@ -176,7 +176,7 @@ public sealed class ArchiveLogicTests
var tiles = ArchiveFigures.Tiles(Stats());
Assert.Equal(5, tiles.Count);
Assert.Equal("10,000", tiles[0].Value);
Assert.Equal("9.4 TB", tiles[2].Value);
Assert.Equal("9.4\u00A0TB", tiles[2].Value);
Assert.Equal("6", tiles[3].Value);
Assert.Equal("cameras · 8 formats", tiles[3].Caption);
Assert.Equal(Formatting.LeftToRight("2024 – 2026"), tiles[4].Value, "a year range keeps its order in right-to-left text");
@@ -42,10 +42,10 @@ public sealed class CardPoolTests
Assert.Equal("New card", pool[0].StateText);
Assert.Equal("EOS R5 · card A", pool[1].Title);
Assert.Equal("Known card", pool[1].StateText);
Assert.Equal("128 GB · 96.2 GB used", pool[1].Subtitle);
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[1].IdentityText);
Assert.Equal("128\u00A0GB · 96.2\u00A0GB used", pool[1].Subtitle);
Assert.Equal("128\u00A0GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[1].IdentityText);
Assert.Equal(SourceKind.Drive, pool[2].Kind);
Assert.Equal("no DCIM · 1.8 TB free", pool[2].Subtitle);
Assert.Equal("no DCIM · 1.8\u00A0TB free", pool[2].Subtitle);
Assert.False(pool[3].IsInserted);
Assert.Null(pool[3].Root);
Assert.Equal("Canon EOS R5 · not inserted", pool[3].Subtitle);
@@ -72,8 +72,8 @@ public sealed class CardPoolTests
public void TheEntryTooltipCarriesTheStateAndTheWholeSubtitle()
{
var pool = CardPool.Build([CardA, Usb], [Known(CardA, "EOS R5 · card A", DateTimeOffset.UtcNow)], @"D:\Shoots\2026");
Assert.Equal("Known card · 128 GB · 96.2 GB used", pool[0].ToolTip);
Assert.Equal("no DCIM · 1.8 TB free", pool[1].ToolTip);
Assert.Equal("Known card · 128\u00A0GB · 96.2\u00A0GB used", pool[0].ToolTip);
Assert.Equal("no DCIM · 1.8\u00A0TB free", pool[1].ToolTip);
Assert.Equal(@"Folder · D:\Shoots\2026", pool[2].ToolTip);
}
@@ -40,11 +40,11 @@ public sealed class ImportPlansTests
Assert.Equal(80_000_000L, totals.FreeAfter);
Assert.True(totals.HasEnoughSpace);
Assert.Equal(TimeSpan.FromSeconds(3), totals.Estimate);
Assert.Equal("3 sessions · 7 photos · 120 MB · about 3 s", totals.Text);
Assert.Equal("3 sessions · 7 photos · 120 MB", totals.SummaryText);
Assert.Equal("3 sessions · 7 photos · 120\u00A0MB · about 3 s", totals.Text);
Assert.Equal("3 sessions · 7 photos · 120\u00A0MB", totals.SummaryText);
Assert.Equal("1 duplicate", totals.DuplicatesText);
Assert.Equal("Import 5 photos", totals.ImportText);
Assert.Equal("80 MB free after import", totals.SpaceText);
Assert.Equal("80\u00A0MB free after import", totals.SpaceText);
}
[Test]
@@ -52,7 +52,7 @@ public sealed class ImportPlansTests
{
var totals = ImportPlans.Totals(ThreeSessions(available: 100_000_000), verify: false);
Assert.False(totals.HasEnoughSpace);
Assert.Equal("20 MB missing", totals.SpaceText);
Assert.Equal("20\u00A0MB missing", totals.SpaceText);
Assert.Equal(string.Empty, ImportPlans.Totals(ThreeSessions(available: null), verify: false).SpaceText);
Assert.Equal(TimeSpan.FromSeconds(2), ImportPlans.Totals(ThreeSessions(), verify: false).Estimate);
}
@@ -105,7 +105,7 @@ public sealed class ImportPlansTests
Assert.Equal("Adds to · 2026/2026-09-29 Canon EOS R5", rows[1].TargetText);
Assert.Equal("2026-09-28 Canon EOS R5", rows[0].DefaultTitle);
Assert.Equal("Canon EOS R5", rows[0].CameraText);
Assert.Equal("96 MB", rows[0].SizeText);
Assert.Equal("96\u00A0MB", rows[0].SizeText);
Assert.Contains("6:02", rows[0].TimeText);
Assert.Equal("Server", ImportPlans.Sessions(plan, ImportDestinationKind.Server, new HashSet<string>())[0].TargetText);
}
@@ -140,7 +140,7 @@ public sealed class ImportPlansTests
Assert.True(details.Rows.Single(r => r.Source.EndsWith("0007.CR2", StringComparison.Ordinal)).IsSkipped);
Assert.Equal(3, details.Conflicts.Count);
Assert.Contains("IMG_0099.CR2", details.Conflicts[0]);
Assert.Equal("7 files · copy 5 (120 MB) · 1 imported before · 1 duplicate", details.TotalsText);
Assert.Equal("7 files · copy 5 (120\u00A0MB) · 1 imported before · 1 duplicate", details.TotalsText);
var folder = ImportPlans.Details(plan, ImportDestinationKind.Folder, verify: true);
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, folder.Rows[1].Destination);
@@ -26,7 +26,7 @@ public sealed class SampleCardsTests(TestContext context)
var pool = CardPool.Build(devices.Devices, await db.MediaCards.ListAsync(context.Cancellation), null, contents);
Assert.SequenceEqual(new[] { SourceKind.Card, SourceKind.Card, SourceKind.Drive, SourceKind.Card }, pool.Select(s => s.Kind));
Assert.Equal("EOS R5 · card A", pool[0].Title);
Assert.Equal("128 GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[0].IdentityText);
Assert.Equal("128\u00A0GB · serial 3F2A-9C11 · Canon EOS R5 #0431", pool[0].IdentityText);
Assert.Equal("Canon EOS R5 · 50 photos", pool[0].ToastText);
Assert.Contains("50 photos", pool[0].Subtitle);
Assert.Equal("SONY", pool[1].Title);
@@ -172,7 +172,7 @@ public sealed class JobListModelTests
Assert.Equal("Render · Harbour sunset · 2,232 / 3,600 · 11.3 fps · 2 min left", JobText.Bar(running));
Assert.Equal("2 min", JobText.Left(running, 0));
// Imports and verifies count bytes; scans count folders; frame jobs read in fps (owner review 1).
Assert.Equal("118 B/s", JobText.Speed(JobKind.Import, 118));
Assert.Equal("118\u00A0B/s", JobText.Speed(JobKind.Import, 118));
Assert.Equal(JobText.Speed(JobKind.Verify, 57_000_000), Loc.L("Jobs.Speed.Bytes", Formatting.Bytes(57_000_000)));
Assert.Equal("4/s", JobText.Speed(JobKind.Scan, 4));
Assert.Equal("1.7 fps", JobText.Speed(JobKind.Proxies, 1.7));
@@ -305,6 +305,20 @@ public sealed class SettingsLogicTests
Assert.Equal((640, 30, 3.5, true), (copy.ThumbnailLongEdge, copy.ScanIntervalMinutes, copy.NightBrightnessPercent, copy.DeepAnalysisAfterScan));
}
[Test]
public void AnOldSettingsFileWithUsageCountsStillLoads()
{
// Chronos sends nothing about its use (owner review 4, R2): the setting is gone, and a file that still carries it loads
// with its other values and is saved without it.
Assert.Null(typeof(AppSettings).GetProperty("AnonymousUsageCounts"));
var path = Path.Combine(_context.CreateTempDirectory("settings"), "settings.json");
File.WriteAllText(path, """{ "Theme": "Light", "AnonymousUsageCounts": true, "OsNotifications": false }""");
var loaded = AppSettings.Load(path);
Assert.Equal((Chronos.Ui.Theming.AppTheme.Light, false), (loaded.Theme, loaded.OsNotifications));
loaded.Save(path);
Assert.False(File.ReadAllText(path).Contains("AnonymousUsageCounts", StringComparison.Ordinal), "saved without the removed member");
}
[Test]
public void BackgroundPriorityRaisesTheInterfaceOnlyInFront()
{
@@ -565,7 +579,7 @@ public sealed class SettingsLogicTests
pending.SetResult(new WorkspaceUsage(MediaBytes: 9_000_000_000, TotalBytes: 12_400_000_000, TrashBytes: 1_200_000_000, TrashItems: 3));
await measuring;
Assert.False(rows.IsMeasuring);
Assert.Equal(("12.4 GB used", "3 items, 1.2 GB"), (rows.UsageText, rows.TrashText));
Assert.Equal(("12.4\u00A0GB used", "3 items, 1.2\u00A0GB"), (rows.UsageText, rows.TrashText));
Assert.True(rows.HasUsageText);
Assert.True(rows.HasTrash);
Assert.True(rows.EmptyTrashCommand.CanExecute(null));
@@ -573,13 +587,13 @@ public sealed class SettingsLogicTests
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 4_000, 0, 0));
await rows.MeasureAsync();
Assert.Equal(("4 KB used", "Nothing in trash"), (rows.UsageText, rows.TrashText));
Assert.Equal(("4\u00A0KB used", "Nothing in trash"), (rows.UsageText, rows.TrashText));
Assert.False(rows.HasTrash);
Assert.False(rows.EmptyTrashCommand.CanExecute(null));
Assert.Equal(Loc.L("Tooltips.Settings.Workspace.EmptyTrash.Disabled"), rows.EmptyTrashToolTip);
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 1_000, 2_000, 1));
await rows.MeasureAsync();
Assert.Equal("1 item, 2 KB", rows.TrashText);
Assert.Equal("1 item, 2\u00A0KB", rows.TrashText);
}
[Test]
@@ -600,7 +614,7 @@ public sealed class SettingsLogicTests
Assert.True(firstToken.IsCancellationRequested, "the older measure is told to stop");
first.SetResult(new WorkspaceUsage(0, 9_000_000_000, 0, 5));
await older;
Assert.Equal(("2 MB used", false, false), (rows.UsageText, rows.HasTrash, rows.IsMeasuring));
Assert.Equal(("2\u00A0MB used", false, false), (rows.UsageText, rows.HasTrash, rows.IsMeasuring));
workspace.Measure = _ => Task.FromException<WorkspaceUsage>(new IOException("the drive went away"));
await rows.MeasureAsync();
@@ -631,9 +645,9 @@ public sealed class SettingsLogicTests
Assert.Equal((Loc.L("Settings.Workspace.TrashPlan.Action"), Loc.L("Tooltips.Settings.Workspace.TrashPlan.Action"), Loc.L("Tooltips.Settings.Workspace.TrashPlan.Keep")),
(request.ActionText, request.ActionToolTip, request.SafeToolTip));
var lines = request.Detail!.Split(Environment.NewLine);
Assert.Equal(("Entries: 8", "Size: 36 MB"), (lines[0], lines[1]));
Assert.Equal(("Entries: 8", "Size: 36\u00A0MB"), (lines[0], lines[1]));
// The newest entries are named, the rest counted.
Assert.Equal(Loc.L("Settings.Workspace.TrashPlan.Item", items[7].Name, "8 MB", Formatting.Date(items[7].Trashed)), lines[2]);
Assert.Equal(Loc.L("Settings.Workspace.TrashPlan.Item", items[7].Name, "8\u00A0MB", Formatting.Date(items[7].Trashed)), lines[2]);
Assert.Equal(2 + DeletePlansListed + 1, lines.Length);
Assert.Equal(Loc.Plural("Archive.Delete.More", 2), lines[^1]);
@@ -642,7 +656,7 @@ public sealed class SettingsLogicTests
workspace.Measure = _ => Task.FromResult(new WorkspaceUsage(0, 14_000_000, 0, 0));
await rows.EmptyTrashAsync();
Assert.Same(plan, Assert.Contains(workspace.Emptied, _ => true));
Assert.Equal((Loc.L("Settings.Workspace.TrashEmptied"), "36 MB", false), Assert.Contains(workspace.Notices, _ => true));
Assert.Equal((Loc.L("Settings.Workspace.TrashEmptied"), "36\u00A0MB", false), Assert.Contains(workspace.Notices, _ => true));
Assert.Equal("Nothing in trash", rows.TrashText);
// An empty trash asks nothing.
@@ -666,7 +680,7 @@ public sealed class SettingsLogicTests
var (_, rows, _) = WorkspaceRows(workspace);
await rows.EmptyTrashAsync();
Assert.Equal((Loc.L("Settings.Workspace.TrashNotEmptied"), Loc.L("Errors.Workspace.TrashChanged"), true), Assert.Contains(workspace.Notices, _ => true));
Assert.Equal("1 item, 1 KB", rows.TrashText);
Assert.Equal("1 item, 1\u00A0KB", rows.TrashText);
workspace.Notices.Clear();
workspace.Empty = _ => throw new UnauthorizedAccessException("denied");
@@ -302,6 +302,55 @@ public sealed class SettingsScreenSmokeTests
Assert.Equal(edited, shell.Services.Settings.FileTemplate);
});
[Test]
public Task AFolderTypedAsTheArchiveFolderBecomesAnArchiveOnlyWhenTheUserConfirms() => ScreenHost.RunAsync(async () =>
{
// Rc.14 review: the folder may be half-typed or one of the user's own; nothing is written there unasked.
var dialogs = new AnsweringDialogs();
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(dialogs: dialogs);
var shell = app.Shell;
var settings = shell.Settings;
shell.Navigate(SectionKey.Settings);
settings.Page = SettingsPage.Archive;
var mine = System.IO.Path.Combine(shell.Services.Environment.DataDirectory, "my-photos");
System.IO.Directory.CreateDirectory(mine);
var manifest = new Chronos.Core.Archiving.ArchivePaths(mine).ManifestPath;
settings.ArchiveRoot.Text = mine;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
Assert.Count(1, dialogs.Asked);
Assert.Equal(mine, dialogs.Asked[0].Detail);
Assert.False(System.IO.File.Exists(manifest), "declined: the folder stays as it was");
Assert.Empty(System.IO.Directory.EnumerateFileSystemEntries(mine));
Assert.Equal(mine, shell.Services.Settings.LastArchivePath);
dialogs.Answer = true;
settings.ArchiveRoot.Text = string.Empty;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
settings.ArchiveRoot.Text = mine;
Assert.True(settings.ArchiveRoot.Commit());
await settings.ArchiveRetarget;
Assert.Count(2, dialogs.Asked);
Assert.True(System.IO.File.Exists(manifest), "confirmed: the folder is an archive");
});
/// <summary>Dialogs that record each confirmation and give <see cref="Answer"/>.</summary>
private sealed class AnsweringDialogs : IAppDialogs
{
public bool Answer { get; set; }
public List<ConfirmRequest> Asked { get; } = [];
public string? PickFolder(string title, string? initialFolder = null) => null;
public string? PickJsonFile(string title) => null;
public bool Confirm(ConfirmRequest request)
{
Asked.Add(request);
return Answer;
}
public bool SignIn(string server, string? username, Func<string, string, Task<string?>> signIn) => false;
}
[Test]
public Task TheFirstRunDialogKeepsTheKeyboardInside() => ScreenHost.RunAsync(async () =>
{
@@ -8,11 +8,14 @@ using Chronos.App.Settings;
using Chronos.App.Shell;
using Chronos.App.Tests.Windows;
using Chronos.App.Videos;
using Chronos.App.Workspace;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Core.Project;
using Chronos.Core.Windows.Shell;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Videos;
using Chronos.Data.Workspaces;
using Chronos.Protocol;
using Chronos.Testing;
using Chronos.Ui.Controls;
@@ -24,7 +27,7 @@ namespace Chronos.App.Tests.Videos;
/// The Videos library's sources (owner review 1, R9; decision 20): this PC's, the server's and the workspace's renders
/// merged by render id, the filters and the orders, the videos folder's checks, the player's fallback, and the copy's toast.
/// </summary>
public sealed class VideoSourcesTests
public sealed class VideoSourcesTests(TestContext context)
{
private static readonly Guid Harbour = Guid.CreateVersion7();
private static readonly Guid Comet = Guid.CreateVersion7();
@@ -200,6 +203,112 @@ public sealed class VideoSourcesTests
}
}
[Test]
public void TheBoardPutsEachRenderInTheLaneOfWhereItIs()
{
var local = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 100);
var remote = Server(Guid.CreateVersion7(), Comet, "Comet", 300);
var unsent = Unsent(Guid.CreateVersion7(), Comet);
// Sent from the workspace to this PC's archive: the archive's entry under Published, its file still in exports/ under Workspace.
var sent = Unsent(local.Id, Harbour) with { IsUnsent = false, IsWorkspaceSent = true, Created = local.Created, Title = "Harbour sunset" };
Assert.Equal(VideoLane.Published, VideoBoard.LaneOf(local));
Assert.Equal(VideoLane.Published, VideoBoard.LaneOf(remote));
Assert.Equal(VideoLane.Workspace, VideoBoard.LaneOf(unsent));
Assert.Equal(VideoLane.Workspace, VideoBoard.LaneOf(sent));
// The list has one row per render: the sent one is the archive's.
var merged = VideoSources.Merge([local], [remote], [unsent, sent]);
Assert.SequenceEqual([local.Id, remote.Id, unsent.Id], merged.Select(e => e.Id));
Assert.False(merged.Any(e => e.IsWorkspaceSent));
// Newest first in each lane whatever the list's order; the list's filters narrow both lanes.
var (published, workspace) = VideoBoard.Split(merged, [sent], new VideoFilter { Sort = VideoSorts.Title });
Assert.SequenceEqual([local.Id, remote.Id], published.Select(e => e.Id));
Assert.SequenceEqual([unsent.Id, sent.Id], workspace.Select(e => e.Id));
Assert.True(workspace[1].IsWorkspaceSent);
var harbour = VideoBoard.Split(merged, [sent], new VideoFilter { SequenceId = Harbour });
Assert.SequenceEqual([local.Id], harbour.Published.Select(e => e.Id));
Assert.SequenceEqual([sent.Id], harbour.Workspace.Select(e => e.Id));
Assert.Empty(VideoBoard.Split(merged, [sent], new VideoFilter { Text = "instagram" }).Published);
// This PC holds a sent render's file; it is not the server's, nor waiting to be sent.
Assert.True(new VideoFilter { Source = VideoSourceFilter.Local }.Matches(sent));
Assert.False(new VideoFilter { Source = VideoSourceFilter.NotSent }.Matches(sent));
Assert.False(new VideoFilter { Source = VideoSourceFilter.Server }.Matches(sent));
// Its chip says it was sent, worded for its project's home.
Assert.Contains(VideoText.States(sent), s => s.Text == Loc.L("Videos.State.Sent") && s.ToolTip == Loc.L("Tooltips.Videos.Sent"));
Assert.Contains(VideoText.States(sent with { WorkspaceServerHome = true }), s => s.ToolTip == Loc.L("Tooltips.Videos.Sent.Server"));
Assert.Equal(Loc.L("Tooltips.Videos.SentRow"), new VideoRowViewModel(sent).ToolTip);
Assert.False(new VideoRowViewModel(sent).CanSend);
Assert.True(new VideoRowViewModel(unsent).CanSend);
}
[Test]
public void AWorkspaceLedgerEntryReadsAsSentOrNot()
{
var home = new BundleHome(BundleHome.ArchiveKind, Harbour);
var project = new WorkspaceEntry(Guid.CreateVersion7(), Harbour, "Social cut", false, home, "Harbour sunset", true, DateTimeOffset.UtcNow);
var render = new WorkspaceRenderEntry(Guid.CreateVersion7(), Guid.CreateVersion7(), "harbour.mp4", new string('a', 64), 1_000, "Instagram", "h264", 1080, 1920, 30, 12,
project.ProjectId, null, null, DateTimeOffset.UtcNow);
var pending = VideoSources.FromWorkspace(render, project, @"C:\ws\exports\harbour.mp4", exists: true);
Assert.True(pending is { IsUnsent: true, IsWorkspaceSent: false, Missing: false, ProjectName: "Social cut" });
var sent = VideoSources.FromWorkspace(render.AsSent(DateTimeOffset.UtcNow), project, @"C:\ws\exports\harbour.mp4", exists: true);
Assert.True(sent is { IsUnsent: false, IsWorkspaceSent: true, HasLocalFile: true });
Assert.Equal(VideoLane.Workspace, VideoBoard.LaneOf(sent));
// A failed send waits to be sent again.
Assert.True(VideoSources.FromWorkspace(render.AsFailed("no"), project, @"C:\ws\exports\harbour.mp4", exists: false) is { IsUnsent: true, Missing: true });
}
[Test]
public void ASentRenderWhoseFileLeftTheWorkspaceIsNotListedAsMissing()
{
// Rc.14 review: its home holds it, and the home's entry stands for it; only a render not sent yet can be missing.
var store = new WorkspaceStore(context.CreateTempDirectory("ledger"));
var home = new BundleHome(BundleHome.ArchiveKind, Harbour);
var project = new WorkspaceEntry(Guid.CreateVersion7(), Harbour, "Social cut", false, home, "Harbour sunset", true, DateTimeOffset.UtcNow);
var folder = store.Project(project.ProjectId);
Directory.CreateDirectory(folder.ExportsDirectory);
WorkspaceRenderEntry Render(string file) => new(Guid.CreateVersion7(), Guid.CreateVersion7(), file, new string('a', 64), 8, "Instagram", "h264", 1080, 1920, 30, 12,
project.ProjectId, null, null, DateTimeOffset.UtcNow);
File.WriteAllText(folder.ExportFile("kept.mp4"), "rendered");
var kept = Render("kept.mp4").AsSent(DateTimeOffset.UtcNow);
var gone = Render("gone.mp4").AsSent(DateTimeOffset.UtcNow);
var lost = Render("lost.mp4");
folder.WriteRenders(WorkspaceRenders.Empty.With(kept).With(gone).With(lost));
var entries = VideoSources.ReadWorkspace(store, [project]);
Assert.Count(2, entries);
Assert.True(entries.Single(e => e.Id == kept.RenderId) is { IsWorkspaceSent: true, Missing: false });
Assert.True(entries.Single(e => e.Id == lost.RenderId) is { IsUnsent: true, Missing: true }, "a render not sent yet whose file is gone is missing");
Assert.False(entries.Any(e => e.Id == gone.RenderId));
}
[Test]
public void ACardStartsWithItsPresetAndKeepsSizesWhole()
{
var video = Local(Guid.CreateVersion7(), Harbour, "Harbour sunset", 100) with { PresetName = "4K archive", Codec = "hevc", DurationSeconds = 41, Bytes = 1_400_000_000 };
// Issue #28: "4K archive · HEVC · 0:41 · 1.4 GB", the number and its unit held together by a no-break space.
var size = Formatting.Bytes(video.Bytes);
Assert.True(size.Contains('\u00A0', StringComparison.Ordinal) && !size.Contains(' ', StringComparison.Ordinal), size);
Assert.Equal(string.Join(Loc.Separator, "4K archive", "HEVC", VideoText.Duration(video), size), VideoText.Card(video));
Assert.Equal(VideoText.Card(video), new VideoRowViewModel(video).CardText);
var still = video with { Kind = RenderKind.Still, PresetName = "Frame 512", Codec = null, DurationSeconds = 0, Bytes = 3_400_000 };
Assert.Equal(string.Join(Loc.Separator, "Frame 512", Formatting.Bytes(still.Bytes)), VideoText.Card(still), "no codec, no duration");
Assert.False(Formatting.Bytes(999).Contains(' ', StringComparison.Ordinal));
// A Board card names the project and its version when known.
Assert.Equal(string.Empty, VideoText.Project(video));
Assert.Equal("Social cut", VideoText.Project(video with { ProjectName = "Social cut" }));
Assert.Equal("Social cut" + Loc.Separator + Loc.L("Videos.Version", "3"), VideoText.Project(video with { ProjectName = "Social cut", ProjectVersionNumber = 3 }));
var row = new VideoRowViewModel(video with { ProjectName = "Social cut", ProjectVersionNumber = 3 });
Assert.True(row.HasProject);
Assert.Equal(Loc.L("Videos.Kind.One.Video") + Loc.Separator + row.DateText, row.BoardFactsText);
Assert.Equal(3, VideoSources.FromServer(new VideoDto(Guid.CreateVersion7(), Comet, "4K", "h264", 1, 1, 1, 1, 1, DateTimeOffset.UtcNow, "nas", null, null, null,
RenderKind.Video, "Comet", null, "Social cut", 3, VideoStates.Ok, [])).ProjectVersionNumber);
}
[Test]
public void ACopyToTheVideosFolderEndsWithAToast()
{
@@ -505,6 +614,105 @@ public sealed class VideosSectionTests(TestContext context)
Assert.True(shell.Settings.OpenVideosFolderCommand.CanExecute(null));
});
[Test]
public Task TheBoardShowsPublishedAndWorkspaceLanes() => WithSectionAsync(async (shell, section, library, _) =>
{
var folder = context.CreateTempDirectory("videos-board");
var unsentFile = Path.Combine(folder, "comet-instagram.mp4");
var sentFile = Path.Combine(folder, "harbour-4k.mp4");
File.WriteAllBytes(unsentFile, [1]);
File.WriteAllBytes(sentFile, [1]);
var project = Guid.CreateVersion7();
var unsent = new VideoEntry
{
Id = Guid.CreateVersion7(),
SequenceId = library.Items[1].Render.SequenceId,
Title = "Comet",
PresetName = "Instagram",
Codec = "h264",
Bytes = 10,
Created = DateTimeOffset.UtcNow,
Kind = RenderKind.Video,
FileName = "comet-instagram.mp4",
LocalPath = unsentFile,
IsUnsent = true,
WorkspaceProjectId = project,
ProjectName = "Social cut",
};
// The archive's first render, sent from the workspace, its file still in exports/.
var archived = library.Items[0].Render;
var sent = unsent with
{
Id = archived.Id,
SequenceId = archived.SequenceId,
Title = "Harbour sunset",
PresetName = archived.PresetName,
Created = archived.Created,
FileName = "harbour-4k.mp4",
LocalPath = sentFile,
IsUnsent = false,
IsWorkspaceSent = true,
};
section.WorkspaceRenders = _ => Task.FromResult<IReadOnlyList<VideoEntry>>([unsent, sent]);
await section.RefreshAsync();
// The list and the cards: one row per render, the sent one being the archive's.
Assert.Equal(library.Items.Count + 1, section.Rows.Count);
Assert.Equal(sent.Id, Assert.NotNull(section.SentEntries.SingleOrDefault()).Id);
Assert.False(section.IsBoard);
// The Board: kept for the next run, Published beside Workspace, newest first, a count per lane.
section.LayoutIndex = 2;
Assert.True(section.IsBoard);
Assert.Equal(LibraryLayout.Board, shell.Services.Settings.VideosLayout);
Assert.Equal(2, new VideosViewModel(shell).LayoutIndex, "a new section opens on the Board");
Assert.SequenceEqual(library.Items.OrderByDescending(i => i.Render.Created).Select(i => i.Render.Id), section.PublishedRows.Select(r => r.Entry.Id));
Assert.SequenceEqual([unsent.Id, sent.Id], section.WorkspaceRows.Select(r => r.Entry.Id));
Assert.Equal((Formatting.Count(3), Formatting.Count(2)), (section.PublishedCountText, section.WorkspaceCountText));
Assert.Same(section.Rows.Single(r => r.Entry.Id == unsent.Id), section.WorkspaceRows[0]);
var sentRow = section.WorkspaceRows[1];
Assert.True(sentRow.Entry.IsWorkspaceSent);
Assert.False(ReferenceEquals(section.Rows.Single(r => r.Entry.Id == sent.Id), sentRow), "a row of its own beside the archive's");
// The sent row's actions: Play, Show in folder and Open in Edit (its home is this PC's archive); no copy, delete or send.
Assert.True(section.PlayCommand.CanExecute(sentRow));
Assert.True(section.ShowInFolderCommand.CanExecute(sentRow));
Assert.True(section.OpenInEditCommand.CanExecute(sentRow));
Assert.False(section.SendCommand.CanExecute(sentRow));
Assert.Equal(Loc.L("Tooltips.Videos.SentRow"), section.CopyBlocker([sentRow]));
Assert.Equal(Loc.L("Tooltips.Videos.SentRow"), section.DeleteBlocker([sentRow]));
Assert.True(section.SendCommand.CanExecute(section.WorkspaceRows[0]), "the unsent one sends");
// Selected on the Board, it is part of the selection; off the Board, it is let go.
sentRow.IsSelected = true;
Assert.True(section.HasSelection);
Assert.Contains(sentRow, section.SelectedRows);
Assert.Equal(Loc.L("Videos.Selected", Formatting.Count(1)), section.SelectionText);
section.LayoutIndex = 0;
Assert.False(sentRow.IsSelected);
Assert.False(section.HasSelection);
section.LayoutIndex = 2;
// The list's filters narrow both lanes; none kept is the section's empty state.
section.SearchText = "instagram";
Assert.SequenceEqual([unsent.Id], section.WorkspaceRows.Select(r => r.Entry.Id));
Assert.Empty(section.PublishedRows);
Assert.True(section.IsPublishedEmpty, "the lane says it is empty");
section.SearchText = "no such video";
Assert.True(section.IsNoMatch);
Assert.False(section.IsPublishedEmpty || section.IsWorkspaceEmpty, "one empty state, not three");
section.SearchText = string.Empty;
// Laid out: both lanes' headings and cards, with the card's line starting with the preset (issue #28).
var view = new VideosView { DataContext = section };
Layout(view, 1400);
var texts = Descendants(view).OfType<System.Windows.Controls.TextBlock>().Where(t => t.ActualWidth > 0).Select(t => t.Text).ToList();
Assert.Contains(Loc.L("Videos.Lane.Published"), texts);
Assert.Contains(Loc.L("Videos.Lane.Workspace"), texts);
Assert.Contains(sentRow.CardText, texts);
Assert.True(sentRow.CardText.StartsWith(sent.PresetName + Loc.Separator, StringComparison.Ordinal), sentRow.CardText);
});
private static void Layout(System.Windows.FrameworkElement view, double width = 1200)
{
view.Measure(new System.Windows.Size(width, 800));
@@ -409,15 +409,16 @@ public sealed class ShellNotificationTests
});
[Test]
public Task GeneralSettingsHoldStartupAndNotificationsButNoConsent() => ScreenHost.RunAsync(async () =>
public Task GeneralSettingsHoldStartupAndNotificationsAndNoUsageCounts() => ScreenHost.RunAsync(async () =>
{
// Monetization (BRIEF §21) ships disabled: the default build offers no usage counts consent.
// Monetization (BRIEF §21) ships disabled.
Assert.False(ProductFeatures.AdsEnabled);
// Chronos sends nothing about its use (owner review 4, R2): the first run asks no consent.
await using var app = await ScreenSmokeTests.SampleApp.StartAsync(firstRun: true);
var shell = app.Shell;
await app.ExpectAsync<WelcomeView>("welcome");
Assert.False(app.FindAll<CheckBox>().Any(c => c.IsVisible && Equals(c.Content, Loc.L("Settings.General.UsageCounts"))), "no consent on the first-run dialog");
Assert.False(app.FindAll<CheckBox>().Any(c => c.IsVisible), "no consent on the first-run dialog");
shell.CompleteWelcome();
var settings = shell.Settings;
@@ -427,7 +428,7 @@ public sealed class ShellNotificationTests
settings.Page = SettingsPage.General;
await app.ExpectAsync<SettingsView>("settings-general");
var boxes = app.FindAll<CheckBox>().Where(c => c.IsVisible).ToList();
Assert.False(boxes.Any(c => Equals(c.Content, Loc.L("Settings.General.UsageCounts"))), "no consent in Settings");
Assert.Equal(2, boxes.Count);
var start = boxes.Single(c => Equals(c.Content, Loc.L("Settings.General.StartWithWindows")));
Assert.Equal(Loc.L("Tooltips.Settings.StartWithWindows"), start.ToolTip);
var notify = boxes.Single(c => Equals(c.Content, Loc.L("Settings.General.OsNotifications")));
@@ -444,11 +445,11 @@ public sealed class ShellNotificationTests
// Reset section also returned the language to the system's.
UiLanguage.Apply("en");
// The search finds General by its new rows, not by the hidden consent.
// The search finds General by its rows, not by the removed usage counts.
settings.SearchText = Loc.L("Settings.General.Startup");
Assert.Contains(settings.VisiblePages, p => p.Page == SettingsPage.General);
settings.SearchText = Loc.L("Settings.General.Usage");
Assert.False(settings.VisiblePages.Any(p => p.Page == SettingsPage.General), "the hidden consent does not match");
settings.SearchText = "Usage counts";
Assert.False(settings.VisiblePages.Any(p => p.Page == SettingsPage.General), "no usage counts row");
settings.SearchText = string.Empty;
});
@@ -131,10 +131,13 @@ public sealed class WorkspaceHostTests(TestContext context)
Assert.Equal(at, mine.WorkspaceOpened[project]);
// Import takes another PC's preferences and keeps this PC's projects.
var theirs = new AppSettings { WorkspaceSizeLimitGb = 40, WorkspaceFolder = @"E:\Elsewhere" };
var theirs = new AppSettings { WorkspaceSizeLimitGb = 40, WorkspaceFolder = @"E:\Elsewhere", LastArchivePath = @"D:\Photos" };
theirs.WorkspaceOpened[Guid.CreateVersion7()] = at.AddDays(-3);
mine.LastArchivePath = @"F:\Chronos";
var imported = mine.KeepLocalIn(AppSettings.Parse(theirs.ToJson())!);
Assert.Equal((40, @"D:\Fast\Workspace"), (imported.WorkspaceSizeLimitGb, imported.WorkspaceFolder));
// Another PC's archive folder can name one of this PC's own folders: this PC's stays.
Assert.Equal(@"F:\Chronos", imported.LastArchivePath);
Assert.Equal(at, imported.WorkspaceOpened.Values.Single());
Assert.Count(1, imported.WorkspaceOpened);
}
@@ -0,0 +1,180 @@
using System.Security.AccessControl;
using System.Security.Principal;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Testing;
namespace Chronos.Core.Tests.Archiving;
[Category("archive")]
public sealed class ArchiveStructureTests(TestContext context)
{
private ArchivePaths NewArchive() => new(context.CreateTempDirectory("structure"));
[Test]
public void AnEmptyFolderGetsTheWholeLayout()
{
var archive = NewArchive();
var report = ArchiveStructure.Ensure(archive);
Assert.True(report.IsComplete);
Assert.Null(report.Message);
foreach (var folder in ArchiveStructure.Folders(archive)) Assert.True(Directory.Exists(folder), folder);
Assert.SequenceEqual(ArchiveStructure.Folders(archive).Skip(1), report.Created);
Assert.Empty(ArchiveStructure.Missing(archive));
string[] expected = [".chronos", ".chronos/locks", ".chronos/journal", ".chronos/staging", ".chronos/trash", ".chronos/trash/photos", ".chronos/trash/videos"];
Assert.SequenceEqual(expected, report.Created.Select(archive.ToRelative));
}
[Test]
public void AMissingRootIsCreatedOnlyForANewArchive()
{
var parent = context.CreateTempDirectory("parent");
var archive = new ArchivePaths(Path.Combine(parent, "Archive"));
var refused = ArchiveStructure.Ensure(archive);
Assert.Equal(ArchiveStructureProblem.Unavailable, refused.Problem);
Assert.Equal(archive.Root, refused.Folder);
Assert.False(Directory.Exists(archive.Root), "an archive that is not there is never made up");
var created = ArchiveStructure.Ensure(archive, createRoot: true);
Assert.True(created.IsComplete);
Assert.Equal(archive.Root, created.Created[0]);
Assert.Empty(ArchiveStructure.Missing(archive));
}
[Test]
public void AnExistingLayoutAndItsFilesAreLeftAsTheyAre()
{
var archive = NewArchive();
Assert.True(ArchiveStructure.Ensure(archive).IsComplete);
// Files where an archive keeps them, and the user's own: none may change, nor their times.
string[] files =
[
archive.ManifestPath,
Path.Combine(archive.TrashPhotosDirectory, "entry.json"),
Path.Combine(archive.StagingDirectory, "copy.tmp"),
Path.Combine(archive.Root, "2026", "Harbour", "originals", "IMG_0001.JPG"),
Path.Combine(archive.Root, "notes.txt"),
];
var written = new DateTime(2026, 1, 2, 3, 4, 5, DateTimeKind.Utc);
for (var i = 0; i < files.Length; i++)
{
Directory.CreateDirectory(Path.GetDirectoryName(files[i])!);
File.WriteAllBytes(files[i], [(byte)i, 1, 2, 3]);
File.SetLastWriteTimeUtc(files[i], written);
}
var folders = Directory.GetDirectories(archive.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal).ToList();
var again = ArchiveStructure.Ensure(archive);
Assert.True(again.IsComplete);
Assert.Empty(again.Created);
for (var i = 0; i < files.Length; i++)
{
Assert.BytesEqual([(byte)i, 1, 2, 3], File.ReadAllBytes(files[i]));
Assert.Equal(written, File.GetLastWriteTimeUtc(files[i]));
}
Assert.SequenceEqual(folders, Directory.GetDirectories(archive.Root, "*", SearchOption.AllDirectories).Order(StringComparer.Ordinal));
}
[Test]
public void OnlyTheMissingFoldersAreCreated()
{
var archive = NewArchive();
Directory.CreateDirectory(archive.LocksDirectory);
File.WriteAllText(Path.Combine(archive.LocksDirectory, "lease"), "held");
var report = ArchiveStructure.Ensure(archive);
Assert.True(report.IsComplete);
Assert.False(report.Created.Contains(archive.MetaDirectory) || report.Created.Contains(archive.LocksDirectory));
Assert.True(report.Created.Contains(archive.TrashVideosDirectory));
Assert.Equal("held", File.ReadAllText(Path.Combine(archive.LocksDirectory, "lease")));
}
[Test]
public void AFileWhereAFolderBelongsIsReportedNotReplaced()
{
var archive = NewArchive();
Directory.CreateDirectory(archive.MetaDirectory);
File.WriteAllText(archive.TrashDirectory, "mine");
var report = ArchiveStructure.Ensure(archive);
Assert.Equal(ArchiveStructureProblem.Failed, report.Problem);
Assert.Equal(archive.TrashDirectory, report.Folder);
Assert.Equal("mine", File.ReadAllText(archive.TrashDirectory));
Assert.True(Directory.Exists(archive.StagingDirectory), "the folders before it are made");
Assert.Equal(Loc.L("Archive.Structure.Failed", archive.TrashDirectory), report.Message);
Assert.Equal(report.Message, new ArchiveStructureException(report).Message);
}
[Test]
public void EachFailureSaysWhy()
{
var archive = NewArchive();
(Exception Thrown, ArchiveStructureProblem Expected, string Key)[] cases =
[
(new UnauthorizedAccessException("denied"), ArchiveStructureProblem.Denied, "Archive.Structure.Denied"),
(new IOException("write protected", unchecked((int)0x80070013)), ArchiveStructureProblem.ReadOnly, "Archive.Structure.ReadOnly"),
(new IOException("not ready", unchecked((int)0x80070015)), ArchiveStructureProblem.Unavailable, "Archive.Structure.Unavailable"),
(new DirectoryNotFoundException("gone"), ArchiveStructureProblem.Unavailable, "Archive.Structure.Unavailable"),
(new IOException("disk full", unchecked((int)0x80070070)), ArchiveStructureProblem.Failed, "Archive.Structure.Failed"),
];
foreach (var (thrown, expected, key) in cases)
{
var report = ArchiveStructure.Ensure(archive, createDirectory: _ => throw thrown);
Assert.Equal(expected, report.Problem);
Assert.Equal(archive.MetaDirectory, report.Folder);
Assert.Equal(thrown.Message, report.Detail);
Assert.Empty(report.Created);
Assert.Equal(Loc.L(key, archive.MetaDirectory), report.Message);
}
Assert.False(Directory.Exists(archive.MetaDirectory));
if (!OperatingSystem.IsWindows())
Assert.Equal(ArchiveStructureProblem.ReadOnly, ArchiveStructure.Classify(new IOException("read-only file system", 30)));
}
[Test]
public void AFolderChronosMayNotWriteReportsTheError()
{
var archive = NewArchive();
if (OperatingSystem.IsWindows())
{
var info = new DirectoryInfo(archive.Root);
var me = WindowsIdentity.GetCurrent().User!;
var deny = new FileSystemAccessRule(me, FileSystemRights.CreateDirectories | FileSystemRights.CreateFiles, AccessControlType.Deny);
var security = info.GetAccessControl();
security.AddAccessRule(deny);
info.SetAccessControl(security);
try
{
var report = ArchiveStructure.Ensure(archive);
Assert.Equal(ArchiveStructureProblem.Denied, report.Problem);
Assert.Equal(archive.MetaDirectory, report.Folder);
Assert.False(Directory.Exists(archive.MetaDirectory));
}
finally
{
security.RemoveAccessRule(deny);
info.SetAccessControl(security);
}
return;
}
File.SetUnixFileMode(archive.Root, UnixFileMode.UserRead | UnixFileMode.UserExecute);
try
{
var report = ArchiveStructure.Ensure(archive);
// An account that ignores permissions (root in a CI container) writes anyway; the cases above cover the mapping.
if (report.IsComplete) Assert.Inconclusive("this account writes into read-only folders");
Assert.Equal(ArchiveStructureProblem.Denied, report.Problem);
Assert.Equal(archive.MetaDirectory, report.Folder);
}
finally
{
File.SetUnixFileMode(archive.Root, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute);
}
}
}
@@ -0,0 +1,64 @@
using Chronos.Core.Archiving;
using Chronos.Data.Archiving;
using Chronos.Testing;
namespace Chronos.Data.Tests.Archiving;
/// <summary>Every archive the service creates, adopts or opens holds its whole layout (BRIEF §7, owner request 2026-11-06).</summary>
[Category("archive")]
public sealed class ArchiveStructureServiceTests(TestContext context)
{
[Test]
public async Task ANewArchiveGetsItsWholeLayout()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
var service = new ArchiveService(db);
var root = Path.Combine(context.CreateTempDirectory("new"), "Chronos", "Archive");
var archive = await service.AdoptAsync(root, "Fresh", context.Cancellation);
var paths = new ArchivePaths(archive.RootPath);
Assert.FileExists(paths.ManifestPath);
Assert.Empty(ArchiveStructure.Missing(paths));
Assert.True(Directory.Exists(paths.TrashPhotosDirectory) && Directory.Exists(paths.TrashVideosDirectory));
}
[Test]
public async Task OpeningAnArchiveMakesTheFoldersItLacksAndTouchesNothingElse()
{
await using var fx = await ArchiveFixture.CreateAsync(context);
var paths = fx.Paths;
var kept = Path.Combine(paths.StagingDirectory, "copy.tmp");
File.WriteAllText(kept, "staged");
var manifest = File.ReadAllBytes(paths.ManifestPath);
// An archive an older Chronos or a copy left without its trash, journal and locks.
Directory.Delete(paths.TrashDirectory, recursive: true);
Directory.Delete(paths.JournalDirectory);
Directory.Delete(paths.LocksDirectory, recursive: true);
await fx.Service.OpenAsync(paths.Root, fx.Ct);
Assert.Empty(ArchiveStructure.Missing(paths));
Assert.Equal("staged", File.ReadAllText(kept));
Assert.BytesEqual(manifest, File.ReadAllBytes(paths.ManifestPath));
}
[Test]
public async Task AnArchiveThatCannotBeLaidOutIsNotCreated()
{
await using var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation);
var service = new ArchiveService(db);
var root = context.CreateTempDirectory("blocked");
// A file where the archive's metadata folder belongs: it stays, and the archive is refused with the reason.
var meta = new ArchivePaths(root).MetaDirectory;
File.WriteAllText(meta, "not a folder");
var error = await Assert.ThrowsAsync<ArchiveStructureException>(() => service.CreateAsync(root, "Blocked", cancellationToken: context.Cancellation));
Assert.Equal(ArchiveStructureProblem.Failed, error.Report.Problem);
Assert.Equal(meta, error.Report.Folder);
Assert.Equal(error.Report.Message, error.Message);
Assert.Equal("not a folder", File.ReadAllText(meta));
Assert.Empty(await db.Archives.ListAsync(context.Cancellation));
}
}
@@ -105,7 +105,7 @@ public abstract class FrameTrashTests(TestContext context) : DatabaseTest(contex
Assert.SequenceEqual([frames[1].Id, frames[3].Id], plan.Frames.Select(f => f.Id));
Assert.Equal(frames[1].Size + frames[3].Size, plan.Bytes);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.False(Directory.Exists(FrameTrash.Directory(fx.Paths)), "a dry run moves nothing");
Assert.False(Directory.EnumerateFileSystemEntries(FrameTrash.Directory(fx.Paths)).Any(), "a dry run moves nothing");
foreach (var frame in frames) Assert.FileExists(fx.Paths.FromRelative(frame.RelativePath));
}
@@ -26,6 +26,11 @@ public abstract class SequenceTrashTests(TestContext context) : DatabaseTest(con
return sequences;
}
/// <summary>What the trash holds besides its photos and videos areas, which every archive has (empty here).</summary>
private static IEnumerable<string> TrashContents(ArchivePaths paths) =>
Directory.EnumerateFileSystemEntries(paths.TrashDirectory, "*", SearchOption.AllDirectories)
.Where(e => e != paths.TrashPhotosDirectory && e != paths.TrashVideosDirectory);
private static (int Files, long Bytes) OnDisk(string folder)
{
var files = new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories).ToList();
@@ -109,7 +114,7 @@ public abstract class SequenceTrashTests(TestContext context) : DatabaseTest(con
Assert.Equal(6, plan.Frames);
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.True(Directory.Exists(folder), "a dry run moves nothing");
Assert.False(Directory.Exists(SequenceTrash.TrashDirectory(fx.Paths)));
Assert.Empty(TrashContents(fx.Paths));
}
[Test]
@@ -166,7 +171,7 @@ public abstract class SequenceTrashTests(TestContext context) : DatabaseTest(con
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.Equal(render.OutputPath, (await fx.Db.Renders.ListBySequenceAsync(victim.Id)).Single().OutputPath);
Assert.Empty(await fx.Service.ListTrashAsync(fx.Archive.Id, fx.Ct));
Assert.Empty(Directory.EnumerateFileSystemEntries(SequenceTrash.TrashDirectory(fx.Paths)));
Assert.Empty(TrashContents(fx.Paths));
Assert.Equal(0, (await fx.ScanAsync()).Indexed);
// Deleted again: the trash takes it again under the same name.
@@ -360,7 +365,7 @@ public abstract class SequenceTrashTests(TestContext context) : DatabaseTest(con
Assert.True(Directory.Exists(folder), "the folder is back where it was");
Assert.Equal(before, await Photos.DumpIndexAsync(fx.Db, fx.Archive.Id));
Assert.Empty(Directory.EnumerateFileSystemEntries(SequenceTrash.TrashDirectory(fx.Paths)));
Assert.Empty(TrashContents(fx.Paths));
await HealSequencesAsync(fx, "DELETE");
Assert.Count(1, await fx.Service.DeleteAsync(await fx.Service.PlanDeleteAsync([victim.Id], null, fx.Ct), null, null, fx.Ct));
}
@@ -48,12 +48,16 @@ public sealed partial class AdminVideosTests(TestContext context)
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
var calls = ApiCall().Matches(page).Select(m => (Method: m.Groups[1].Value, Target: m.Groups[2].Value)).ToList();
Assert.True(calls.Count >= 4, string.Join(", ", calls));
// Reads the list, the server's videos folder and a filtered sequence's title; writes only the videos' delete and copy:
// no settings, no project, no render, no job of its own.
// Reads the list, the server's videos folder, its name (the board's lanes) and a filtered sequence's title; writes only
// the videos' delete and copy: no settings, no project, no render, no job of its own.
foreach (var (method, target) in calls)
{
Assert.True(method is "get" or "post", $"api.{method}({target}");
if (method == "get") Assert.True(target is "listQuery(" or @"""/api/v1/server/settings""" or "`/api/v1/sequences/${encodeURIComponent(id)}`", target);
if (method == "get")
{
Assert.True(target is "listQuery(" or @"""/api/v1/server/settings""" or @"""/api/v1/server/info""" or "`/api/v1/sequences/${encodeURIComponent(id)}`",
target);
}
else Assert.True(target is @"""/api/v1/videos/copy""" or @"""/api/v1/videos/delete""", target);
}
Assert.Contains("return `/api/v1/videos?${p}`;", page);
@@ -103,6 +107,39 @@ public sealed partial class AdminVideosTests(TestContext context)
Assert.Equal("missing", VideoStates.Missing);
}
[Test]
public async Task TheBoardShowsPublishedAndWorkspaceLanes()
{
await using var server = await TestServer.StartAsync(context);
var page = await server.Client.GetStringAsync("/admin/pages/videos.js");
// A third view beside cards and list, kept like them; its icon is the panel's.
Assert.Contains(@"data-view=""board"" aria-pressed=""${view === ""board""}"" data-i18n-title=""Admin.Videos.View.Board.Tip""", page);
Assert.Contains(@"return stored === ""list"" || stored === ""board"" ? stored : ""cards"";", page);
Assert.Contains(" board: `<svg", await server.Client.GetStringAsync("/admin/icons.js"));
// Two lanes, newest first whatever the order chosen: the board reads the server newest first, with Order off and
// saying why (rc.14 review: re-sorting the page read in another order left the newest out). Published counts the
// server's total; Workspace holds the renders a PC's workspace sent here (a project named, produced by a machine
// other than this server), marked Sent, counted among those read ("+" while more can be read).
Assert.Contains(@"return view === ""board"" ? ""newest"" : filters.sort;", page);
Assert.Contains(@"if (sortShown() !== ""newest"") p.set(""sort"", sortShown());", page);
Assert.Contains(@"sort.disabled = view === ""board"";", page);
Assert.Contains(@"""Admin.Videos.Sort.Board.Tip""", page);
Assert.Contains(@"return lane(""Published"", rows, false, formatNumber(total ?? rows.length))", page);
Assert.Contains(@"+ lane(""Workspace"", sent, true, `${formatNumber(sent.length)}${cursor ? ""+"" : """"}`);", page);
// A Shift range runs along the lane picked in, as its cards are shown.
Assert.Contains(@"order: (el) => view === ""board"" && el?.closest("".board-lane"")", page);
Assert.Contains("if (shift) selection.range(key, order(el));", await server.Client.GetStringAsync("/admin/pages/library/shared.js"));
// Sizes keep their number and unit together, as the desktop's (issue #28).
Assert.Contains(@"format(value)} ${units[unit]}`;", await server.Client.GetStringAsync("/admin/ui.js"));
Assert.Contains("export function boardLane(v, serverName)", page);
Assert.Contains(@"return v.projectId && producer && producer !== String(serverName ?? """") ? ""workspace"" : ""published"";", page);
Assert.Contains(@"${workspace ? sentChip(v) : """"}${stateChips(v)}", page);
// The server's name comes from its public info, the name its own renders carry.
Assert.Contains(@"api.get(""/api/v1/server/info"").then((info) => {", page);
var css = await server.Client.GetStringAsync("/admin/admin.css");
Assert.Contains(".seq-items.board { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr));", css);
}
[Test]
public async Task TheVideosStringsAreInEnglishAndItalian()
{
@@ -117,7 +154,8 @@ public sealed partial class AdminVideosTests(TestContext context)
// The keys the pages build from a value.
keys.AddRange(VideoSorts.All.Select(s => $"Admin.Videos.Sort.{char.ToUpperInvariant(s[0])}{s[1..]}"));
keys.AddRange(["Admin.Videos.Kind.Video", "Admin.Videos.Kind.Still", "Admin.Videos.Kind.Sequence", "Admin.Trash.Kind.Videos", "Admin.Nav.Videos", "Admin.Nav.Videos.Tip",
"Admin.Settings.VideosPath", "Admin.Settings.VideosPath.Tip", "Admin.Job.Kind.VideoCopy"]);
"Admin.Settings.VideosPath", "Admin.Settings.VideosPath.Tip", "Admin.Job.Kind.VideoCopy", "Admin.Videos.Lane.Published", "Admin.Videos.Lane.Published.Tip",
"Admin.Videos.Lane.Workspace", "Admin.Videos.Lane.Workspace.Tip"]);
keys.AddRange(Regex.Matches(trash + sequence, @"""(Admin\.(?:Trash\.[A-Za-z]*Video[A-Za-z]*|Videos\.[A-Za-z.]+)(?:\.[A-Za-z]+)*)""").Select(m => m.Groups[1].Value));
Assert.Contains("Admin.Trash.RestoredVideo", keys);
Assert.Contains("Admin.Videos.AllVideos.Tip", keys);
@@ -0,0 +1,119 @@
using System.Net;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Chronos.Core.Archiving;
using Chronos.Data;
using Chronos.Data.Archiving;
using Chronos.Protocol;
using Chronos.Server.Storage;
using Chronos.Testing;
namespace Chronos.Server.Tests.Hosting;
/// <summary>The server lays out its archive folder whole at start (owner request 2026-11-06) and says when it cannot.</summary>
[Category("server")]
public sealed class ArchiveStructureStartupTests(TestContext context)
{
[Test]
public async Task StartingTheServerLaysOutTheArchiveFolder()
{
await using var server = await TestServer.StartAsync(context);
var paths = new ArchivePaths(server.Options.ArchivePath);
Assert.FileExists(paths.ManifestPath);
Assert.Empty(ArchiveStructure.Missing(paths));
Assert.True(Assert.NotNull(server.Services.GetRequiredService<ServerArchive>().Structure).IsComplete);
var health = Assert.NotNull(await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus));
Assert.Equal("ok", health.Checks["archive"]);
}
[Test]
public async Task AnArchiveMissingFoldersGetsThemAtStart()
{
var root = Path.Combine(context.CreateTempDirectory("existing"), "archive");
await using (var db = await ChronosDatabase.OpenAsync(DatabaseOptions.Sqlite(Path.Combine(context.CreateTempDirectory("db"), "chronos.db")), context.Cancellation))
await new ArchiveService(db).CreateAsync(root, "Older", cancellationToken: context.Cancellation);
var paths = new ArchivePaths(root);
Directory.Delete(paths.TrashDirectory, recursive: true);
Directory.Delete(paths.StagingDirectory);
var notes = Path.Combine(root, "notes.txt");
File.WriteAllText(notes, "mine");
await using var server = await TestServer.StartAsync(context, o => o.ArchivePath = root);
Assert.Empty(ArchiveStructure.Missing(paths));
Assert.Equal("mine", File.ReadAllText(notes));
}
[Test]
public async Task TheDashboardWarnsWhileAFolderCannotBeCreated()
{
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
var paths = new ArchivePaths(server.Options.ArchivePath);
Directory.Delete(paths.TrashVideosDirectory);
File.WriteAllText(paths.TrashVideosDirectory, "in the way");
var warned = await DashboardAsync(admin);
var problem = Assert.NotNull(warned.ArchiveProblem);
Assert.Equal(("failed", paths.TrashVideosDirectory), (problem.Code, problem.Folder));
var health = Assert.NotNull(await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus));
Assert.Equal(("ok", "incomplete"), (health.Status, health.Checks["archive"]));
Assert.Equal("in the way", File.ReadAllText(paths.TrashVideosDirectory));
// Once the file is out of the way, the next look at the dashboard makes the folder and the warning goes.
File.Delete(paths.TrashVideosDirectory);
Assert.Null((await DashboardAsync(admin)).ArchiveProblem);
Assert.True(Directory.Exists(paths.TrashVideosDirectory));
health = Assert.NotNull(await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus));
Assert.Equal("ok", health.Checks["archive"]);
}
[Test]
public async Task HealthSeesAFixOnTheHostWithoutTheDashboard()
{
await using var server = await TestServer.StartAsync(context);
var archive = server.Services.GetRequiredService<ServerArchive>();
var paths = new ArchivePaths(server.Options.ArchivePath);
Directory.Delete(paths.TrashVideosDirectory);
File.WriteAllText(paths.TrashVideosDirectory, "in the way");
archive.HealthRecheck = TimeSpan.Zero;
var health = Assert.NotNull(await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus));
Assert.Equal("incomplete", health.Checks["archive"]);
File.Delete(paths.TrashVideosDirectory);
health = Assert.NotNull(await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus));
Assert.Equal("ok", health.Checks["archive"]);
Assert.True(Directory.Exists(paths.TrashVideosDirectory));
}
[Test]
public async Task ARootThatLostItsArchiveJsonGetsNoFolders()
{
// Rc.14 review: an unmounted disk leaves an empty mount point; nothing is written onto the disk beneath it.
await using var server = await TestServer.StartAsync(context);
var admin = await server.AdminAsync();
var paths = new ArchivePaths(server.Options.ArchivePath);
var manifest = File.ReadAllBytes(paths.ManifestPath);
File.Delete(paths.ManifestPath);
Directory.Delete(paths.TrashDirectory, recursive: true);
var problem = Assert.NotNull((await DashboardAsync(admin)).ArchiveProblem);
Assert.Equal("unavailable", problem.Code);
Assert.False(Directory.Exists(paths.TrashDirectory), "nothing created");
var health = Assert.NotNull(await server.Client.GetFromJsonAsync("/health", ProtocolJson.Default.HealthStatus));
Assert.Equal("missing", health.Checks["archive"]);
// The disk is back: the next look completes the layout.
File.WriteAllBytes(paths.ManifestPath, manifest);
Assert.Null((await DashboardAsync(admin)).ArchiveProblem);
Assert.Empty(ArchiveStructure.Missing(paths));
}
private static async Task<DashboardDto> DashboardAsync(HttpClient admin)
{
using var response = await admin.GetAsync("/api/v1/server/dashboard");
await response.ExpectAsync(HttpStatusCode.OK);
return await response.ReadAsync(ProtocolJson.Default.DashboardDto);
}
}
@@ -52,6 +52,24 @@ public sealed partial class LoggingTests(TestContext context)
Assert.Equal((LogLevel.Debug, LogLevel.Warning, Chronos.Core.Diagnostics.LogLevel.Debug), (logging.FileLevel, logging.ConsoleLevel, CoreLog.MinimumLevel));
}
[Test]
public void AValueOutOfRangeIsNamedByItsVariable()
{
// Rc.14 review: the start's message named the setting's property, which the deploy guide never mentions.
ServerOptions Load(params (string Name, string Value)[] variables)
{
var environment = new Dictionary<string, string?> { ["CHRONOS_DATA_PATH"] = context.CreateTempDirectory("ranges"), ["CHRONOS_DB"] = "postgres" };
foreach (var (name, value) in variables) environment[name] = value;
return ServerOptions.Load(environment);
}
var logs = Assert.Throws<InvalidOperationException>(() => Load(("CHRONOS_LOG_MAX_FILE_MB", "50"), ("CHRONOS_LOG_MAX_TOTAL_MB", "10")).Validate());
Assert.True(logs.Message.StartsWith("CHRONOS_LOG_MAX_TOTAL_MB is out of range", StringComparison.Ordinal), logs.Message);
var port = Assert.Throws<InvalidOperationException>(() => Load(("CHRONOS_HTTP_PORT", "70000")).Validate());
Assert.Contains("CHRONOS_HTTP_PORT", port.Message);
// Parallelism alone is held to its range instead.
Assert.Equal(ServerOptions.MaxParallelism, Load(("CHRONOS_PARALLELISM", "128")).Parallelism);
}
[Test]
public async Task TheFileLevelChangesWhileTheServerRuns()
{
Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 KiB

After

Width:  |  Height:  |  Size: 213 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 213 KiB

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 210 KiB

After

Width:  |  Height:  |  Size: 210 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 216 KiB

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 214 KiB

After

Width:  |  Height:  |  Size: 214 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 226 KiB

After

Width:  |  Height:  |  Size: 226 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 223 KiB

After

Width:  |  Height:  |  Size: 223 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 60 KiB

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 65 KiB

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 61 KiB

After

Width:  |  Height:  |  Size: 61 KiB