fix(app): import gates, partial results and plan editing after review

- a card that leaves needs a new check; formatting re-lists the card and refuses
  one that changed since its check; files that are not photos are named in the
  format confirmation
- an import never stays stuck in Running; Retry never resumes an older job
- server imports list refused files and keep what was uploaded when stopped
- the archive result matches each copy to its job's record and shows the job's
  own error per file
- refreshing devices keeps typed titles and choices; titles lock while copying
- three destination names, merge and split of sessions, camera profiles shared
  by the cards of a camera, photo counts and a new-card toast
- disabled controls say why; keyboard focus follows the nickname field and
  Show plan (Esc closes it); label column fits longer languages
- capture states for insertion, running, failed and a new card

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-03 10:44:22 +00:00
1 parent 5aa5edab57
commit 29c82eba5c
27 files changed
+1286 -285

No files matched your search

@@ -71,16 +71,32 @@ public sealed class ImportChoicesTests
}
[Test]
public void ACardWithoutSettingsTakesTheLastSavedProfileOfItsCamera()
public void ACardFollowsItsCameraProfileWhenItJoinedItOrHasNoSettingsYet()
{
var older = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 20 }, daysAgo: 30);
var newer = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 90 }, daysAgo: 2);
var other = Card("SONY", "ILCE-7M4", new CardProfile { SessionGapMinutes = 5 }, daysAgo: 1);
var unsaved = Card("Canon", "Canon EOS R5", null, daysAgo: 0);
Assert.Equal(90, CameraProfiles.Find("Canon", "Canon EOS R5", [older, newer, other, unsaved])!.SessionGapMinutes);
Assert.Null(CameraProfiles.Find("Canon", "Canon EOS R6", [older, newer, other]));
Assert.Null(CameraProfiles.Find("Canon", null, [older, newer]));
Assert.Null(CameraProfiles.Find("Canon", "Canon EOS R5", [unsaved]), "only saved settings are shared");
var shared = new CardProfile { SessionGapMinutes = 90 };
var defaults = new CardProfile { SessionGapMinutes = 45 };
var own = Card("Canon", "Canon EOS R5", new CardProfile { SessionGapMinutes = 20 }, daysAgo: 30);
var fresh = Card("Canon", "Canon EOS R5", null, daysAgo: 0);
var camera = new CameraProfile("Canon", "Canon EOS R5", shared, []);
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(fresh, camera, defaults), "a new card of a known camera needs no setup");
Assert.Equal(new ResolvedProfile(defaults, false), CameraProfiles.Resolve(fresh, null, defaults));
Assert.Equal(20, CameraProfiles.Resolve(own, camera, defaults).Profile.SessionGapMinutes, "a card with its own settings keeps them");
Assert.False(CameraProfiles.Resolve(own, camera, defaults).FollowsCamera);
Assert.Equal(new ResolvedProfile(shared, true), CameraProfiles.Resolve(own, camera.With(own.Id), defaults), "a card that joined follows the shared rules");
var joined = camera.With(own.Id).With(own.Id).With(fresh.Id);
Assert.SequenceEqual([own.Id, fresh.Id], joined.Cards);
Assert.SequenceEqual([fresh.Id], joined.Without(own.Id).Cards);
}
[Test]
public void SplitsAndMergesTravelToThePlanner()
{
var options = new ImportChoices().ToOptions(null, new HashSet<string> { "DCIM/100CANON/IMG_0005.CR2" }, new HashSet<string> { "DCIM/100CANON/IMG_0009.CR2" });
Assert.True(options.SplitBefore.Contains("DCIM/100CANON/IMG_0005.CR2"));
Assert.True(options.MergeAt.Contains("DCIM/100CANON/IMG_0009.CR2"));
Assert.Empty(new ImportChoices().ToOptions().SplitBefore);
}
private static MediaCard Card(string make, string model, CardProfile? profile, int daysAgo) => new()
@@ -33,7 +33,7 @@ public sealed class ImportFlowTests(TestContext context)
var plan = await destination.PlanAsync(card, choices.ToOptions(), media.Id, null, context.Cancellation);
Assert.Equal(3, plan.Sessions.Count);
Assert.Equal(30, plan.CopyCount);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, null, null, plan.FileCount);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, null, null, null);
Assert.False(before.CanCheck, "no import, no erase");
Assert.False(before.CanDelete);
Assert.False(before.CanFormat);
@@ -41,32 +41,54 @@ public sealed class ImportFlowTests(TestContext context)
var unverified = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
Assert.Empty(unverified.ToDelete);
Job queued;
await using (var engine = new JobEngine(db, archives.CreateJobHandlers(),
new JobEngineOptions { Workers = 1, WorkerId = "test", PollInterval = TimeSpan.FromMilliseconds(50), CheckpointInterval = TimeSpan.FromMilliseconds(50) }))
{
await engine.StartAsync(context.Cancellation);
var job = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation);
await WaitDoneAsync(db, job.Id);
queued = await engine.EnqueueAsync(ArchiveJobs.Import(archive, plan, media.Id, choices.VerifyCopies), cancellationToken: context.Cancellation);
await WaitDoneAsync(db, queued.Id);
}
var outcome = await ImportOutcome.CheckAsync(plan, choices.VerifyCopies,
async (item, ct) => (await db.Frames.FindBySizeAndCaptureAsync(archive.Id, item.Size, item.CapturedAt, ct)).Count > 0, context.Cancellation);
// The verification result comes from the job's own records: every planned copy has its frame.
var job = (await db.Jobs.GetAsync(queued.Id, context.Cancellation))!;
var outcome = await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, media.Id, choices.VerifyCopies, context.Cancellation);
Assert.Equal(30, outcome.Copied);
Assert.True(outcome.IsComplete);
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, plan.FileCount);
Assert.Equal(30, (await ArchiveImportCheck.CheckAsync(db, archive.Id, plan, job, null, choices.VerifyCopies, context.Cancellation)).Copied,
"a folder source, without import history, finds its frames in the sessions' sequences");
var afterImport = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
Assert.True(afterImport.CanCheck);
Assert.False(afterImport.CanDelete, "the dry run must come first");
Assert.Equal(Loc.L("Import.Blocked.NoDryRun"), afterImport.DeleteBlocker);
var snapshot = CardSnapshot.Take(card, Volume.Identity);
var erase = await archives.PlanCardEraseAsync(archive.Id, media.Id, card, null, context.Cancellation);
var ready = afterImport with { Erase = erase };
var ready = afterImport with { Erase = erase, Card = snapshot };
Assert.True(ready.CanDelete);
Assert.True(ready.CanFormat);
Assert.Equal(30, ready.DeleteCount);
Assert.Equal("30 verified on the card · " + Infrastructure.Formatting.Bytes(ready.DeleteBytes), ready.EraseText);
Assert.False((ready with { Card = null }).CanDelete, "the dry run lists the card too");
Assert.True(snapshot.IsUnchanged(CardSnapshot.Take(card, Volume.Identity)));
Assert.False(snapshot.IsUnchanged(CardSnapshot.Take(card, "another card")), "another card with the same files is not the checked card");
// A video is not a photo: it never blocks formatting but is named as never imported.
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"), [1, 2, 3]);
var withVideo = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
Assert.True(withVideo.CanFormat);
Assert.SequenceEqual(["DCIM/100CANON/MVI_0031.MP4"], withVideo.NotImported);
Assert.Equal("30 verified on the card · " + Infrastructure.Formatting.Bytes(ready.DeleteBytes) + " · 1 other file not imported", withVideo.EraseText);
Assert.False(snapshot.IsUnchanged(withVideo.Card!), "a file added since the check changes the card");
File.Delete(Path.Combine(card, "DCIM", "100CANON", "MVI_0031.MP4"));
// A photo added to the card after the import is not verified: formatting would lose it.
Assert.False((ready with { CardPhotos = 31 }).CanFormat);
File.WriteAllBytes(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"), Jpeg(Start.AddDays(2), 31));
var withPhoto = ready with { Card = CardSnapshot.Take(card, Volume.Identity) };
Assert.False(withPhoto.CanFormat);
Assert.Equal(Loc.L("Import.Blocked.NotAllVerified"), withPhoto.FormatBlocker);
Assert.True(withPhoto.CanDelete, "the verified photos may still be deleted");
File.Delete(Path.Combine(card, "DCIM", "100CANON", "IMG_0031.JPG"));
Assert.False((ready with { Outcome = outcome with { Verified = false } }).CanFormat);
Assert.False((ready with { Destination = ImportDestinationKind.Folder }).CanDelete);
Assert.False((ready with { IsInserted = false }).CanDelete);
@@ -101,22 +123,47 @@ public sealed class ImportFlowTests(TestContext context)
new FolderImportSink(target), verify: true, null, context.Cancellation);
Assert.Equal(0, again.Copied);
Assert.Equal(16, again.Duplicates);
Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, 16).CanCheck);
Assert.False(new CardActions(ImportDestinationKind.Folder, false, true, true, outcome, null, null).CanCheck);
}
[Test]
public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrived()
public async Task TheIndexCheckReportsPlannedCopiesThatNeverArrivedWithTheJobsOwnError()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4), action: ImportAction.SkipImported)));
var outcome = await ImportOutcome.CheckAsync(plan, true, (item, _) => Task.FromResult(!item.SourcePath.EndsWith("0002.CR2", StringComparison.Ordinal)),
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4), action: ImportAction.SkipImported),
Item(4, Start.AddSeconds(6))));
var errors = ImportOutcome.JobErrors("18:02:11 Not copied: DCIM/100CANON/IMG_0002.CR2 (Disk full)\n18:02:12 Imported 1, skipped 1, failed 1");
var outcome = await ImportOutcome.CheckAsync(plan, true,
(item, _) => Task.FromResult(item.SourcePath.EndsWith("0001.CR2", StringComparison.Ordinal) ? CommitCheck.Copied : CommitCheck.Missing), errors,
context.Cancellation);
Assert.Equal(1, outcome.Copied);
Assert.Equal(1, outcome.Skipped);
Assert.Equal("DCIM/100CANON/IMG_0002.CR2", outcome.Failures.Single().SourcePath);
Assert.Equal(2, outcome.Failures.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0002.CR2", "Disk full"), outcome.Failures[0]);
Assert.Equal(Loc.L("Import.Result.NotCommitted"), outcome.Failures[1].Message, "no log line for it: not committed");
Assert.False(outcome.IsComplete);
}
[Test]
public void AnAbortedRunCountsWhatTheDestinationCommittedAndFailsTheRest()
{
Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
var plan = Plan(null, null, Session(1, "f", Item(1, Start), Item(2, Start.AddSeconds(2)), Item(3, Start.AddSeconds(4)), Item(4, Start.AddSeconds(6),
action: ImportAction.SkipImported)));
var items = plan.Sessions[0].Items;
var report = new ImportSinkReport();
report.Committed[items[1].SourcePath] = new SinkCommit(Guid.NewGuid(), items[1].FileName, Duplicate: false);
report.Rejected[items[0].SourcePath] = "Hash mismatch";
var results = new[] { new ImportItemResult(plan.Sessions[0], items[0], ImportItemStatus.Copied, "a", new SinkCommit(null, items[0].FileName, false), null) };
var outcome = ImportOutcome.From(plan, results, verified: true, report, stopped: "Connection lost");
Assert.Equal(1, outcome.Copied, "committed in the batch the abort interrupted");
Assert.Equal(1, outcome.Skipped);
Assert.SequenceEqual(
[new ImportFailure(items[0].SourcePath, "Hash mismatch"), new ImportFailure(items[2].SourcePath, "Connection lost")],
outcome.Failures);
}
private async Task WaitDoneAsync(TitanoDatabase db, Guid jobId)
{
var until = DateTime.UtcNow.AddSeconds(60);
@@ -125,12 +125,46 @@ public sealed class ImportPlansTests
}
[Test]
public void TheNamePreviewIsTheFirstCopiedFile()
public void TheNamePreviewShowsTheFirstThreeCopiedFiles()
{
var plan = ThreeSessions();
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestination(plan, ImportDestinationKind.Archive));
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestination(plan, ImportDestinationKind.Server));
var names = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive);
Assert.Equal(3, names.Count);
Assert.Equal("2026/2026-09-28 Canon EOS R5/" + plan.Sessions[0].Items[0].FileName, names[0]);
Assert.Equal("→ " + names[0] + " · " + plan.Sessions[0].Items[1].FileName + " · " + plan.Sessions[0].Items[2].FileName, ImportPlans.NamePreview(names));
Assert.Equal(plan.Sessions[0].Items[0].FileName, ImportPlans.FirstDestinations(plan, ImportDestinationKind.Server)[0]);
// A name in another folder keeps its folder.
var across = ImportPlans.FirstDestinations(plan, ImportDestinationKind.Archive, 5);
Assert.Equal(5, across.Count);
Assert.True(ImportPlans.NamePreview(across).EndsWith(" · " + across[4], StringComparison.Ordinal), "the third session's folder is shown");
var nothing = ImportPlans.WithDuplicates(Plan(null, null, Session(1, "x", Item(1, Start, action: ImportAction.SkipImported))), DuplicatePolicy.Skip);
Assert.Null(ImportPlans.FirstDestination(nothing, ImportDestinationKind.Archive));
Assert.Empty(ImportPlans.FirstDestinations(nothing, ImportDestinationKind.Archive));
Assert.Equal(string.Empty, ImportPlans.NamePreview([]));
}
[Test]
public void ASessionMergesOnlyIntoTheEarlierSessionOfTheSameCameraAndFormat()
{
var plan = ThreeSessions();
var rows = ImportPlans.Sessions(plan, ImportDestinationKind.Archive, new HashSet<string>());
Assert.Null(rows[0].MergesInto);
Assert.Equal(1, rows[1].MergesInto);
Assert.Equal(2, rows[2].MergesInto);
Assert.Equal("DCIM/100CANON/IMG_0005.CR2", rows[1].FirstPath);
var otherBody = plan with { Sessions = [plan.Sessions[0], plan.Sessions[1] with { CameraSerial = "9999" }, plan.Sessions[2]] };
var split = ImportPlans.Sessions(otherBody, ImportDestinationKind.Archive, new HashSet<string>());
Assert.Null(split[1].MergesInto, "another camera body never merges");
Assert.Equal(1, split[2].MergesInto, "the earlier session of the same body, skipping the other camera");
}
[Test]
public void ShowPlanOffersASplitOnEveryPhotoButTheFirstOfItsSession()
{
var details = ImportPlans.Details(ThreeSessions(), ImportDestinationKind.Archive, verify: true);
Assert.False(details.Rows[0].CanSplit, "a session heading");
Assert.False(details.Rows[1].CanSplit, "the first photo already starts the session");
Assert.True(details.Rows[2].CanSplit);
}
}
@@ -22,12 +22,19 @@ public sealed class SampleCardsTests(TestContext context)
var devices = new SampleDeviceMonitor();
await SampleCards.InsertAsync(db, devices, context.CreateTempDirectory("data"));
var pool = CardPool.Build(devices.Devices, await db.MediaCards.ListAsync(context.Cancellation), null);
Assert.SequenceEqual(new[] { SourceKind.Card, SourceKind.Drive, SourceKind.Card }, pool.Select(s => s.Kind));
var contents = devices.Devices.Where(d => d.HasDcim).ToDictionary(d => d.Identity, d => CardContents.Read(d.Root));
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("GoPro 12", pool[2].Title);
Assert.False(pool[2].IsInserted);
Assert.Equal("Canon EOS R5 · 50 photos", pool[0].ToastText);
Assert.Contains("50 photos", pool[0].Subtitle);
Assert.Equal("SONY", pool[1].Title);
Assert.False(pool[1].IsKnown);
Assert.Equal("12 photos · not yet known to Titano", pool[1].ToastText[(pool[1].ToastText.IndexOf(" · ", StringComparison.Ordinal) + 3)..],
"the camera of its first photo, its photos, and that it is new");
Assert.Equal("GoPro 12", pool[3].Title);
Assert.False(pool[3].IsInserted);
var card = pool[0].Card!;
Assert.Equal(new DateTimeOffset(2026, 9, 21, 19, 40, 0, TimeSpan.Zero), (await db.MediaCards.ListImportsAsync(card.Id, 1, context.Cancellation))[0].ImportedAt);
@@ -38,9 +45,9 @@ public sealed class SampleCardsTests(TestContext context)
Assert.Equal("Canon EOS R5", plan.Sessions[0].CameraModel);
var outcome = SampleCards.Outcome(plan);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, plan.FileCount);
var before = new CardActions(ImportDestinationKind.Archive, true, true, true, outcome, null, null);
Assert.False(before.CanDelete, "no dry run yet");
var actions = before with { Erase = SampleCards.Erase(plan) };
var actions = before with { Erase = SampleCards.Erase(plan), Card = CardSnapshot.Take(pool[0].Root!, pool[0].Key) };
Assert.True(actions.CanDelete);
Assert.Equal(49, actions.DeleteCount);
Assert.Equal(1, actions.KeptCount);
@@ -64,16 +64,37 @@ public sealed class ServerImportSinkTests(TestContext context)
}
[Test]
public async Task AHashTheServerRejectsStopsTheImport()
public async Task AFileTheServerRefusesIsListedAndTheImportGoesOn()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096) { Corrupt = true };
var server = new FakeUploadServer(chunkSize: 4096) { CorruptFile = "IMG_0003.JPG" };
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var error = await Assert.ThrowsAsync<TitanoApiException>(() => LocalImport.RunAsync(plan, new ServerImportSink(client, staging), true, null, context.Cancellation));
Assert.Equal(HttpStatusCode.UnprocessableEntity, error.Status);
Assert.Empty(server.Committed);
var sink = new ServerImportSink(client, staging);
var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report);
Assert.Equal(7, outcome.Copied);
Assert.Equal(7, server.Committed.Count);
Assert.Equal(new ImportFailure("DCIM/100CANON/IMG_0003.JPG", "Hash mismatch"), outcome.Failures.Single());
Assert.Empty(Directory.EnumerateFileSystemEntries(staging));
}
[Test]
public async Task ALostSignInStopsTheImportAndKeepsWhatWasUploaded()
{
var card = Card(context.CreateTempDirectory("card"), 8, Start);
var staging = context.CreateTempDirectory("staging");
var server = new FakeUploadServer(chunkSize: 4096) { SignedOutAfter = 3 };
using var client = new TitanoClient(new Uri("https://nas.local:8443/"), new CertificatePinning([]), "tests", server) { Token = "t" };
var plan = await new UnindexedDestination(ImportDestinationKind.Server, staging).PlanAsync(card, new ImportChoices().ToOptions(), null, null, context.Cancellation);
var sink = new ServerImportSink(client, staging);
var outcome = await LocalImport.RunAsync(plan, sink, true, null, context.Cancellation, sink.Report);
Assert.Equal(3, outcome.Copied, "the uploads the server committed before the sign-in was lost");
Assert.Equal(5, outcome.Failures.Count);
Assert.Equal("Sign in again", outcome.Failures[0].Message, "the server's sentence");
Assert.False(outcome.IsComplete);
}
[Test]
@@ -103,8 +124,11 @@ public sealed class ServerImportSinkTests(TestContext context)
public Dictionary<Guid, string> Titles { get; } = [];
public int ChunkCount { get; private set; }
/// <summary>Flip a byte of every received chunk (a damaged transfer).</summary>
public bool Corrupt { get; init; }
/// <summary>Flip a byte of every chunk of this file (a damaged transfer).</summary>
public string? CorruptFile { get; init; }
/// <summary>Answer 401 to new uploads once this many were committed (the sign-in expired).</summary>
public int? SignedOutAfter { get; init; }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
@@ -112,6 +136,8 @@ public sealed class ServerImportSinkTests(TestContext context)
if (request.Method == HttpMethod.Post && path is ["api", "v1", "uploads"])
{
var start = (await request.Content!.ReadFromJsonAsync(ProtocolJson.Default.StartUploadRequest, cancellationToken))!;
if (Committed.Count >= SignedOutAfter)
return Json(new ApiError("unauthorized", "Sign in again"), ProtocolJson.Default.ApiError, HttpStatusCode.Unauthorized);
if (_frames.TryGetValue(start.Sha256, out var existing))
return Json(new StartUploadResponse(null, chunkSize, [], true, existing), ProtocolJson.Default.StartUploadResponse);
var upload = new Upload(Guid.NewGuid(), start.FileName, start.Size, start.Sha256, start.SessionKey ?? "user");
@@ -122,7 +148,7 @@ public sealed class ServerImportSinkTests(TestContext context)
{
var upload = _open[Guid.Parse(id)];
var bytes = await request.Content!.ReadAsByteArrayAsync(cancellationToken);
if (Corrupt) bytes[0] ^= 0xFF;
if (upload.FileName == CorruptFile) bytes[0] ^= 0xFF;
upload.Parts[int.Parse(n, System.Globalization.CultureInfo.InvariantCulture)] = bytes;
ChunkCount++;
return Json(new ChunkReceived(int.Parse(n, System.Globalization.CultureInfo.InvariantCulture), [.. upload.Parts.Keys]), ProtocolJson.Default.ChunkReceived);