From 1c2c6633f957cf73c25e1b6144a484a0328f7759 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:12:40 -0800 Subject: [PATCH 01/10] Companions: clean up appended-form temp files; Reorganize moves them with their photo MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Edit preservation B-2, items 1 and 2. - TransferExecutor's temp-file pattern now accepts one second extension before the UUID, so a crash mid-copy of `…_007.jpg.xmp` no longer leaves `…_007.jpg.xmp..tmp` behind. The UUID and .tmp requirements are unchanged. - ReorganizeExecutor.parseFileBucket buckets `..xmp|.aae` with its photo instead of counting it unrecognized. The move goes through the existing receipted, no-overwrite path. Co-Authored-By: Claude Fable 5.2 --- .../ChronoframeCore/ReorganizeExecutor.swift | 9 +- .../ChronoframeCore/TransferExecutor.swift | 2 +- ...ronoframeCoreReorganizeExecutorTests.swift | 83 +++++++++++++++++++ ...ameCoreTransferExecutorBehaviorTests.swift | 34 ++++++++ 4 files changed, 126 insertions(+), 2 deletions(-) diff --git a/ui/Sources/ChronoframeCore/ReorganizeExecutor.swift b/ui/Sources/ChronoframeCore/ReorganizeExecutor.swift index 9a587bdd..e42bedc5 100644 --- a/ui/Sources/ChronoframeCore/ReorganizeExecutor.swift +++ b/ui/Sources/ChronoframeCore/ReorganizeExecutor.swift @@ -581,7 +581,14 @@ public struct ReorganizeExecutor: Sendable { /// - `YYYY-MM-DD_NNN.ext` (or wider sequence) — dated bucket /// - `Unknown_NNN.ext` — unknown-date bucket private func parseFileBucket(filename: String) -> (bucket: String, isUnknown: Bool)? { - let stem = (filename as NSString).deletingPathExtension + var stem = (filename as NSString).deletingPathExtension + + // Appended-form companion (`..xmp`): bucket it + // with its photo by dropping the photo's extension as well. + if MediaLibraryRules.isCompanionFile(path: filename), + MediaLibraryRules.isSupportedMediaFile(path: stem) { + stem = (stem as NSString).deletingPathExtension + } // Unknown_ prefix if stem.hasPrefix(namingRules.unknownFilenamePrefix) { diff --git a/ui/Sources/ChronoframeCore/TransferExecutor.swift b/ui/Sources/ChronoframeCore/TransferExecutor.swift index 71646115..2c317606 100644 --- a/ui/Sources/ChronoframeCore/TransferExecutor.swift +++ b/ui/Sources/ChronoframeCore/TransferExecutor.swift @@ -212,7 +212,7 @@ public struct TransferExecutor: Sendable { // Matches Chronoframe's own .tmp files only. Update both sides if the // filename convention changes. private static let chronoframeTmpPattern: NSRegularExpression? = try? NSRegularExpression( - pattern: #"^(?:\d{4}-\d{2}-\d{2}|Unknown)_\d+(?:_collision_\d+)?\.[a-zA-Z0-9]+(?:\.[0-9a-fA-F-]{36})?\.tmp$"# + pattern: #"^(?:\d{4}-\d{2}-\d{2}|Unknown)_\d+(?:_collision_\d+)?\.[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+(?=\.[0-9a-fA-F-]{36}\.tmp$))?(?:\.[0-9a-fA-F-]{36})?\.tmp$"# ) public var fileHasher: FileIdentityHasher diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreReorganizeExecutorTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreReorganizeExecutorTests.swift index 83ca3961..97642ad1 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreReorganizeExecutorTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreReorganizeExecutorTests.swift @@ -242,6 +242,89 @@ final class ChronoframeCoreReorganizeExecutorTests: XCTestCase { XCTAssertEqual(plan.unrecognizedCount, 2) } + /// Appended-form companions (`2024-04-08_001.jpg.xmp`, `Unknown_002.heic.aae`) + /// bucket with their photo instead of being counted as unrecognized. + func testPlanBucketsAppendedFormCompanionWithItsPhoto() throws { + try writeFile(at: ["2024-04-08_001.jpg"]) + try writeFile(at: ["2024-04-08_001.jpg.xmp"]) + try writeFile(at: ["Unknown_002.heic"]) + try writeFile(at: ["Unknown_002.heic.AAE"]) + + let plan = try ReorganizeExecutor().plan( + destinationRoot: temporaryDirectoryURL, + targetStructure: .yyyyMMDD + ) + + XCTAssertEqual(plan.unrecognizedCount, 0) + let destinations = Dictionary( + uniqueKeysWithValues: plan.moves.map { (URL(fileURLWithPath: $0.sourcePath).lastPathComponent, $0.destinationPath) } + ) + XCTAssertEqual( + destinations["2024-04-08_001.jpg.xmp"], + temporaryDirectoryURL.appendingPathComponent("2024/04/08/2024-04-08_001.jpg.xmp").standardizedFileURL.path + ) + XCTAssertEqual( + URL(fileURLWithPath: destinations["2024-04-08_001.jpg.xmp"] ?? "").deletingLastPathComponent().path, + URL(fileURLWithPath: destinations["2024-04-08_001.jpg"] ?? "").deletingLastPathComponent().path + ) + XCTAssertEqual( + destinations["Unknown_002.heic.AAE"], + temporaryDirectoryURL.appendingPathComponent("Unknown_Date/Unknown_002.heic.AAE").standardizedFileURL.path + ) + } + + /// The companion extension strip is narrow: a companion extension on a + /// name that is not `..` stays + /// unrecognized, and a non-companion double extension is untouched. + func testPlanKeepsLookalikeCompanionNamesUnrecognized() throws { + try writeFile(at: ["2024-04-08_001.notes.xmp"]) + try writeFile(at: ["2024-04-08_001.jpg.txt"]) + try writeFile(at: ["2024-04-08_notes.jpg.xmp"]) + try writeFile(at: ["IMG_1234.jpg.xmp"]) + + let plan = try ReorganizeExecutor().plan( + destinationRoot: temporaryDirectoryURL, + targetStructure: .yyyyMMDD + ) + + XCTAssertEqual(plan.moves.count, 0) + XCTAssertEqual(plan.unrecognizedCount, 4) + } + + // AGENTS-INVARIANT: 4 + /// An appended-form companion travels with its photo, and an existing file + /// at the companion's new name is never overwritten. + func testExecuteMovesAppendedFormCompanionAndNeverOverwritesExistingOne() throws { + let photo = try writeFile(at: ["2024-04-08_001.jpg"]) + let companion = try writeFile(at: ["2024-04-08_001.jpg.xmp"]) + let secondPhoto = try writeFile(at: ["2024-04-09_001.jpg"]) + let secondCompanion = try writeFile(at: ["2024-04-09_001.jpg.xmp"]) + let blocker = try writeFile(at: ["2024", "04", "09", "2024-04-09_001.jpg.xmp"]) + try Data("occupant".utf8).write(to: blocker) + + let plan = try ReorganizeExecutor().plan( + destinationRoot: temporaryDirectoryURL, + targetStructure: .yyyyMMDD + ) + let result = try ReorganizeExecutor().execute(plan: plan) + + XCTAssertEqual(result.failedCount, 0) + XCTAssertFalse(FileManager.default.fileExists(atPath: photo.path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: companion.path)) + XCTAssertTrue(FileManager.default.fileExists( + atPath: temporaryDirectoryURL.appendingPathComponent("2024/04/08/2024-04-08_001.jpg").path + )) + XCTAssertTrue(FileManager.default.fileExists( + atPath: temporaryDirectoryURL.appendingPathComponent("2024/04/08/2024-04-08_001.jpg.xmp").path + )) + + // Occupied companion destination: skipped, source kept, occupant intact. + XCTAssertFalse(FileManager.default.fileExists(atPath: secondPhoto.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: secondCompanion.path)) + XCTAssertEqual(try Data(contentsOf: blocker), Data("occupant".utf8)) + XCTAssertEqual(result.skippedCount, 1) + } + func testPlanRoutesUnknownDateFilesUnderUnknownDateBucket() throws { try writeFile(at: ["Unknown_Date", "Unknown_001.jpg"]) diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreTransferExecutorBehaviorTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreTransferExecutorBehaviorTests.swift index f6a93fad..a2bf91b1 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreTransferExecutorBehaviorTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreTransferExecutorBehaviorTests.swift @@ -383,6 +383,40 @@ final class ChronoframeCoreTransferExecutorBehaviorTests: XCTestCase { XCTAssertTrue(FileManager.default.fileExists(atPath: foreignEditorAutosave.path)) } + /// Appended-form companions (`photo.jpg.xmp`) are copied through a temp + /// named `..tmp`, so an interrupted copy leaves + /// `2024-03-01_007.jpg.xmp..tmp`. Cleanup must remove it, and still + /// leave user files that only look similar. + func testCleanupTemporaryFilesRemovesAppendedCompanionOrphanButKeepsLookalikes() throws { + let destinationRoot = temporaryDirectoryURL.appendingPathComponent("companion-orphans", isDirectory: true) + let dayDirectory = destinationRoot.appendingPathComponent("2024/03/01", isDirectory: true) + try FileManager.default.createDirectory(at: dayDirectory, withIntermediateDirectories: true) + + let uuid = "8F3A2C1D-8F3A-2C1D-8F3A-2C1D8F3A2C1D" + let appendedOrphan = dayDirectory.appendingPathComponent("2024-03-01_007.jpg.xmp.\(uuid).tmp") + let unknownAppendedOrphan = destinationRoot.appendingPathComponent("Unknown_003.heic.aae.\(uuid).tmp") + let collisionAppendedOrphan = dayDirectory.appendingPathComponent("2024-03-01_008_collision_1.jpg.xmp.\(uuid).tmp") + let noUUIDLookalike = dayDirectory.appendingPathComponent("2024-03-01_007.jpg.xmp.tmp") + let notAUUIDLookalike = dayDirectory.appendingPathComponent("2024-03-01_007.jpg.xmp.backup.tmp") + let threeExtensionLookalike = dayDirectory.appendingPathComponent("2024-03-01_007.jpg.xmp.aae.\(uuid).tmp") + let foreignAppendedScratch = dayDirectory.appendingPathComponent("render.final.cache.\(uuid).tmp") + + let kept = [noUUIDLookalike, notAUUIDLookalike, threeExtensionLookalike, foreignAppendedScratch] + for url in [appendedOrphan, unknownAppendedOrphan, collisionAppendedOrphan] + kept { + try Data("payload".utf8).write(to: url) + } + + let cleaned = TransferExecutor().cleanupTemporaryFiles(at: destinationRoot) + + XCTAssertEqual(cleaned, 3) + XCTAssertFalse(FileManager.default.fileExists(atPath: appendedOrphan.path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: unknownAppendedOrphan.path)) + XCTAssertFalse(FileManager.default.fileExists(atPath: collisionAppendedOrphan.path)) + for url in kept { + XCTAssertTrue(FileManager.default.fileExists(atPath: url.path), "\(url.lastPathComponent) must survive cleanup") + } + } + // MARK: - PersistentRunLogger rotation /// When the existing log is past the configured size cap, opening must From 5379edf723c5a18fcfc9af797a7e6e15b641bcd5 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:15:48 -0800 Subject: [PATCH 02/10] Dedupe review: panes show the decision the plan will make Edit preservation B-3. The list, detail and Quick Review panes fell back to Delete for any member with no explicit decision, so a protected edited variant (INV-31) could read "Suggested for removal" while the plan kept it. They now read one shared DedupeDecisions.effectiveDecision, the rule keepersForCluster already used. In a group the planner will not auto-select, members with no decision now show Keep, which is what the plan does. What reaches the Trash is unchanged. Co-Authored-By: Claude Fable 5.2 --- .../Views/Deduplicate/ClusterDetailPane.swift | 8 +-- .../Views/Deduplicate/ClusterListPane.swift | 2 +- .../Views/Deduplicate/RapidTriageView.swift | 12 ++-- .../Stores/DeduplicateSessionStore.swift | 27 ++++--- .../DeduplicateSessionStoreTests.swift | 72 +++++++++++++++++++ 5 files changed, 103 insertions(+), 18 deletions(-) diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterDetailPane.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterDetailPane.swift index 6a8949f8..94458740 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterDetailPane.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterDetailPane.swift @@ -299,7 +299,7 @@ struct ClusterDetailPane: View { private func comparisonPane(member: PhotoCandidate, role: ComparisonRole, cluster: DuplicateCluster) -> some View { let isFocused = member.path == focusedMemberPath - let decision = sessionStore.decisions.byPath[member.path] ?? (isSuggestedKeeper(member, in: cluster) ? .keep : .delete) + let decision = sessionStore.decisions.effectiveDecision(for: member, in: cluster) return Button { focusedMemberPath = member.path } label: { @@ -387,7 +387,7 @@ struct ClusterDetailPane: View { .accessibilityValue(member.map { selectedMember in DeduplicateAccessibilityText.photoPreviewDetail( member: selectedMember, - decision: sessionStore.decisions.byPath[selectedMember.path] ?? (isSuggestedKeeper(selectedMember, in: cluster) ? .keep : .delete), + decision: sessionStore.decisions.effectiveDecision(for: selectedMember, in: cluster), isSuggestedKeeper: isSuggestedKeeper(selectedMember, in: cluster), confidence: cluster.annotation?.confidence, keeperReason: cluster.annotation?.keeperReason @@ -599,7 +599,7 @@ struct ClusterDetailPane: View { } private func decisionControls(for member: PhotoCandidate, cluster: DuplicateCluster) -> some View { - let current = sessionStore.decisions.byPath[member.path] ?? (isSuggestedKeeper(member, in: cluster) ? .keep : .delete) + let current = sessionStore.decisions.effectiveDecision(for: member, in: cluster) return Picker("Decision", selection: Binding( get: { current }, set: { newValue in sessionStore.setDecision(newValue, forPath: member.path) } @@ -615,7 +615,7 @@ struct ClusterDetailPane: View { } private func memberThumb(member: PhotoCandidate, cluster: DuplicateCluster, thumbnailSize: CGFloat) -> some View { - let decision = sessionStore.decisions.byPath[member.path] ?? (isSuggestedKeeper(member, in: cluster) ? .keep : .delete) + let decision = sessionStore.decisions.effectiveDecision(for: member, in: cluster) let isFocused = member.path == focusedMemberPath return Button { focusedMemberPath = member.path diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterListPane.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterListPane.swift index fcb01e7d..66c7fa04 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterListPane.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/ClusterListPane.swift @@ -388,7 +388,7 @@ private struct ClusterRow: View { } private func decisionFor(_ member: PhotoCandidate) -> DedupeDecision { - decisions.byPath[member.path] ?? (isSuggestedKeeper(member) ? .keep : .delete) + decisions.effectiveDecision(for: member, in: cluster) } private var hasWarnings: Bool { diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift index 943044ad..1d71176b 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift @@ -207,20 +207,22 @@ struct RapidTriageView: View { HStack(spacing: 6) { ForEach(cluster.members) { member in let isKeeper = cluster.suggestedKeeperIDs.prefix(1).contains(member.id) - let glyph: DedupeDecisionGlyph = isKeeper ? .keep : .delete + // What Accept will store (a protected edited variant is kept). + let isKept = sessionStore.suggestedDecision(for: member, in: cluster) == .keep + let glyph: DedupeDecisionGlyph = isKept ? .keep : .delete // Triage shows the cluster's *suggestion* — nothing is // committed until the user accepts/skips — so the label is // phrased as a suggestion, not a final keep/delete decision. - let suggestionLabel = isKeeper ? "Suggested keeper" : "Suggested for removal" + let suggestionLabel = isKept ? "Suggested keeper" : "Suggested for removal" DedupeThumbnailView( path: member.path, size: CGSize(width: 56, height: 56), loader: thumbnailLoader ) - .opacity(isKeeper ? 1.0 : 0.6) + .opacity(isKept ? 1.0 : 0.6) .overlay( RoundedRectangle(cornerRadius: 4, style: .continuous) - .stroke(isKeeper ? DesignTokens.ColorSystem.statusSuccess : Color.clear, lineWidth: 2) + .stroke(isKept ? DesignTokens.ColorSystem.statusSuccess : Color.clear, lineWidth: 2) ) // Non-color cue: a glyph badge so the suggested keeper is // distinguishable without relying on the green stroke. @@ -228,7 +230,7 @@ struct RapidTriageView: View { Image(systemName: glyph.symbolName) .font(.system(size: 14)) .foregroundStyle( - isKeeper ? DesignTokens.ColorSystem.statusSuccess : DesignTokens.ColorSystem.inkMuted, + isKept ? DesignTokens.ColorSystem.statusSuccess : DesignTokens.ColorSystem.inkMuted, Color.white ) .padding(2) diff --git a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift index 1a90e574..9845eb2b 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift @@ -884,6 +884,11 @@ public final class DeduplicateSessionStore: ObservableObject { ) } + /// The decision "Accept" will store for `member`; Quick Review shows this. + public func suggestedDecision(for member: PhotoCandidate, in cluster: DuplicateCluster) -> DedupeDecision { + suggestedDecisions(for: [cluster]).byPath[member.path] ?? .keep + } + private func automaticDecisions(for clusters: [DuplicateCluster]) -> DedupeDecisions { guard let configuration = lastScanConfiguration else { return DedupeDecisions(byPath: [:]) @@ -900,16 +905,22 @@ extension DedupeDecisions { /// falling back to the cluster's suggested keepers for any member with /// no explicit decision. public func keepersForCluster(_ cluster: DuplicateCluster) -> [String] { + cluster.members.compactMap { member in + effectiveDecision(for: member, in: cluster) == .keep ? member.path : nil + } + } + + /// What the plan does with `member`: its explicit decision, else the + /// planner's default. Review panes use this for any member with no + /// explicit decision so the screen never contradicts the plan. + public func effectiveDecision(for member: PhotoCandidate, in cluster: DuplicateCluster) -> DedupeDecision { let suggestedKeepers = Set(cluster.suggestedKeeperIDs.prefix(1)) let autoSelectable = DeduplicationPlanner.isAutomaticCommitEligible(cluster) - return cluster.members.compactMap { member in - // INV-31: without an explicit decision a protected variant is Keep. - let decision = byPath[member.path] - ?? (autoSelectable && !member.isProtectedEditedVariant - ? (suggestedKeepers.contains(member.id) ? .keep : .delete) - : .keep) - return decision == .keep ? member.path : nil - } + // INV-31: without an explicit decision a protected variant is Keep. + return byPath[member.path] + ?? (autoSelectable && !member.isProtectedEditedVariant + ? (suggestedKeepers.contains(member.id) ? .keep : .delete) + : .keep) } } diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift index fa4ae531..04dd2c4c 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift @@ -879,6 +879,78 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.currentDeletionPlan().pathsToDelete, ["/dest/x.jpg"]) } + // Review-pane fallback (BLOCKED B-3): with no explicit decision the panes + // must show what the planner will do, never "Suggested for removal" for a + // protected edited variant. + // AGENTS-INVARIANT: 31 + @MainActor + func testEffectiveDecisionForProtectedVariantWithNoExplicitDecisionIsKeep() async throws { + let fixture = editedVariantStoreCluster() + let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [fixture.cluster])) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + _ = await waitForCondition { store.status == .readyToReview } + let cluster = store.clusters[0] + let byPath = Dictionary(uniqueKeysWithValues: cluster.members.map { ($0.path, $0) }) + + // Reset the review: no explicit decisions at all. + store.decisions = DedupeDecisions() + + XCTAssertEqual(store.decisions.effectiveDecision(for: byPath[fixture.variantPath]!, in: cluster), .keep) + XCTAssertEqual(store.decisions.effectiveDecision(for: byPath["/dest/x.jpg"]!, in: cluster), .delete) + XCTAssertEqual(store.decisions.effectiveDecision(for: byPath["/dest/other.jpg"]!, in: cluster), .keep) + + // The screen and the plan agree: only the file shown as Delete is trashed. + XCTAssertEqual(store.currentDeletionPlan().pathsToDelete, ["/dest/x.jpg"]) + + // An explicit decision always wins over the fallback. + store.setDecision(.delete, forPath: fixture.variantPath) + XCTAssertEqual(store.decisions.effectiveDecision(for: byPath[fixture.variantPath]!, in: cluster), .delete) + } + + // AGENTS-INVARIANT: 31 + @MainActor + func testEffectiveDecisionInReviewOnlyClusterMatchesPlannerKeep() async throws { + // A cluster the planner will not auto-select (medium confidence): with + // no explicit decision every member is kept, so none may read Delete. + let keeper = PhotoCandidate(path: "/dest/a.jpg", size: 100, modificationTime: 0, qualityScore: 0.9) + let other = PhotoCandidate(path: "/dest/b.jpg", size: 50, modificationTime: 0, qualityScore: 0.4) + let cluster = DuplicateCluster( + kind: .nearDuplicate, + members: [keeper, other], + suggestedKeeperIDs: [keeper.path], + bytesIfPruned: 50, + annotation: ClusterAnnotation(confidence: .medium, matchReason: MatchReason(kind: .exactDuplicate)) + ) + let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [cluster])) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + _ = await waitForCondition { store.status == .readyToReview } + store.decisions = DedupeDecisions() + + XCTAssertEqual(store.decisions.effectiveDecision(for: keeper, in: cluster), .keep) + XCTAssertEqual(store.decisions.effectiveDecision(for: other, in: cluster), .keep) + XCTAssertEqual(store.currentDeletionPlan().count, 0) + } + + // AGENTS-INVARIANT: 31 + @MainActor + func testSuggestedDecisionForTriageKeepsProtectedVariant() async throws { + let fixture = editedVariantStoreCluster() + let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [fixture.cluster])) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + _ = await waitForCondition { store.status == .readyToReview } + let cluster = store.clusters[0] + let byPath = Dictionary(uniqueKeysWithValues: cluster.members.map { ($0.path, $0) }) + + // What Quick Review shows must be what Accept stores. + XCTAssertEqual(store.suggestedDecision(for: byPath[fixture.variantPath]!, in: cluster), .keep) + XCTAssertEqual(store.suggestedDecision(for: byPath["/dest/x.jpg"]!, in: cluster), .delete) + XCTAssertEqual(store.suggestedDecision(for: byPath["/dest/other.jpg"]!, in: cluster), .keep) + store.acceptSuggestionsForCluster(cluster) + for member in cluster.members { + XCTAssertEqual(store.decisions.byPath[member.path], store.suggestedDecision(for: member, in: cluster)) + } + } + // MARK: - reviewedClusters / reviewedDeletionPlan / commitReviewed /// A cluster is reviewed when every member has an explicit decision in From ca58b4e6972d3fe1c9aafa11472eafc0df80f25c Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:31:15 -0800 Subject: [PATCH 03/10] Unlock sheet: Return takes the free action; Shortcut uses the stored layout - When the unlock sheet offers a free copy or free removal, that button is the Return-key default. Buy is the default only when nothing free is offered. UnlockSheetModel.defaultAction decides; the view reads it. - The Organize Folder Shortcut hard-coded Year/Month/Day. It now reads the folder layout from PreferencesStore, so a Shortcut run and the app write the same layout into a library. Co-Authored-By: Claude Fable 5.2 --- .../AppIntents/OrganizeFolderIntent.swift | 28 +++-- .../Views/Purchase/UnlockSheet.swift | 10 +- .../Services/UnlockPresentation.swift | 20 ++++ .../UnlockPresentationTests.swift | 102 ++++++++++++++++++ ...ganizeFolderIntentConfigurationTests.swift | 77 +++++++++++++ 5 files changed, 230 insertions(+), 7 deletions(-) create mode 100644 ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift diff --git a/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift b/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift index 900a9f82..6ad65258 100644 --- a/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift +++ b/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift @@ -100,12 +100,15 @@ public struct OrganizeFolderIntent: AppIntent { "Successfully organized folder. Transferred \(copiedCount == 1 ? "1 file" : "\(copiedCount) files")." } + /// The run this intent performs. The layout is the person's own, read through + /// `PreferencesStore`, so a Shortcut run lands in the same library layout as the app. @MainActor - public func perform() async throws -> some IntentResult & ReturnsValue { - let sourcePath = sourceFolder.path - let destinationPath = destinationFolder.path - - let config = RunConfiguration( + static func makeConfiguration( + sourcePath: String, + destinationPath: String, + preferences: PreferencesStore + ) -> RunConfiguration { + RunConfiguration( mode: .transfer, sourcePath: sourcePath, destinationPath: destinationPath, @@ -113,7 +116,20 @@ public struct OrganizeFolderIntent: AppIntent { verifyCopies: true, parallelTransferEnabled: true, workerCount: 8, - folderStructure: .default + folderStructure: preferences.folderStructure + ) + } + + @MainActor + public func perform() async throws -> some IntentResult & ReturnsValue { + let sourcePath = sourceFolder.path + let destinationPath = destinationFolder.path + + // Built from `PreferencesStore` directly: a Shortcut can run before `AppState` exists. + let config = Self.makeConfiguration( + sourcePath: sourcePath, + destinationPath: destinationPath, + preferences: PreferencesStore() ) let sourceStart = sourceFolder.startAccessingSecurityScopedResource() diff --git a/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift b/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift index 95fff7b2..b5c0b862 100644 --- a/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift +++ b/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift @@ -73,6 +73,12 @@ struct UnlockSheet: View { } } + /// Whether Return presses this action. Decided by the model so that only + /// the action the sheet leads with ever carries the default shortcut. + private func isDefault(_ action: UnlockSheetAction) -> Bool { + model.defaultAction == action + } + /// The one-line purchase terms the model chose for this refusal, if any. var termsLine: String? { model.purchaseTermsLine } @@ -166,7 +172,7 @@ struct UnlockSheet: View { Text("\(displayName) · \(displayPrice)") .fixedSize(horizontal: false, vertical: true) } - .keyboardShortcut(.defaultAction) + .keyboardShortcut(isDefault(action) ? .defaultAction : nil) .disabled(model.isBusy) .accessibilityIdentifier("unlockSheet.buy") @@ -240,6 +246,7 @@ struct UnlockSheet: View { Button(PluralPhrases.copyTheseFiles(fileCount)) { onRunFreeTestBatch() } + .keyboardShortcut(isDefault(action) ? .defaultAction : nil) .disabled(!model.isBatchEnabled) .accessibilityIdentifier("unlockSheet.runBatch") } @@ -259,6 +266,7 @@ struct UnlockSheet: View { Button(DeduplicateFooterCopy.freeBatchCommitTitle(fileCount: fileCount)) { onRunFreeDedupeBatch() } + .keyboardShortcut(isDefault(action) ? .defaultAction : nil) .disabled(!model.isBatchEnabled) .accessibilityIdentifier("unlockSheet.runDedupeBatch") } diff --git a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift index 6470ad8a..d5400006 100644 --- a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift +++ b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift @@ -78,6 +78,26 @@ public struct UnlockSheetModel: Equatable, Sendable { self.purchaseTermsLine = purchaseTermsLine } + /// The action the Return key presses: the one the sheet leads with. + /// + /// A free copy or free removal on offer is that action, wherever it sits in + /// `actions` — the view draws it above the button row. Return must never + /// open the purchase prompt when the sheet is offering something free first. + /// Buy is the default only when it is the lead action. Restore, Try Again + /// and Not Now are never the default. Busy does not change this: the view + /// disables the default along with its other buttons. + public var defaultAction: UnlockSheetAction? { + actions.first { + switch $0 { + case .runFreeTestBatch, .runFreeDedupeBatch: return true + default: return false + } + } ?? actions.first { + if case .buy = $0 { return true } + return false + } + } + /// Build the sheet's contents. /// /// - Parameters: diff --git a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift index 9083835a..f873ad43 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift @@ -446,4 +446,106 @@ final class UnlockPresentationTests: XCTestCase { XCTAssertTrue(model(refusal: spent(), product: product, isRestoring: true).isBusy) XCTAssertFalse(model(refusal: spent(), product: product).isBusy) } + + // MARK: - The Return key + + private func dedupeModel( + product: StoreProductInfo?, + isLoadingProduct: Bool = false, + isPurchasing: Bool = false + ) -> UnlockSheetModel { + UnlockSheetModel.make( + refusal: dedupeSpent(), + product: product, + isLoadingProduct: isLoadingProduct, + isPurchasing: isPurchasing, + isRestoring: false, + offeredDedupeBatch: (fileCount: 3, deferredCount: 37) + ) + } + + /// Return must do what the sheet leads with. A free copy on offer is that; + /// Return opening the StoreKit prompt instead is an App Review risk. + func testReturnTakesTheFreeMonthCopyNotTheBuy() { + let requested = requestedModel(product: product) + XCTAssertEqual(requested.defaultAction, .runFreeTestBatch(fileCount: 3, deferredCount: 897)) + + // A suggested (not requested) batch is still the free action on screen. + let suggested = requestedModel( + product: product, + batch: FreeTestBatch(included: requestedMonthBatch().included, deferredCount: 897, monthKey: "2026-10") + ) + XCTAssertEqual(suggested.defaultAction, .runFreeTestBatch(fileCount: 3, deferredCount: 897)) + + // While the price loads, or when it failed, the free copy is still the default. + XCTAssertEqual( + requestedModel(product: nil, isLoadingProduct: true).defaultAction, + .runFreeTestBatch(fileCount: 3, deferredCount: 897) + ) + XCTAssertEqual( + requestedModel(product: nil).defaultAction, + .runFreeTestBatch(fileCount: 3, deferredCount: 897) + ) + } + + func testReturnTakesTheFreeDedupeBatchNotTheBuy() { + XCTAssertEqual( + dedupeModel(product: product).defaultAction, + .runFreeDedupeBatch(fileCount: 3, deferredCount: 37) + ) + XCTAssertEqual( + dedupeModel(product: nil, isLoadingProduct: true).defaultAction, + .runFreeDedupeBatch(fileCount: 3, deferredCount: 37) + ) + } + + func testReturnBuysOnlyWhenNoFreeActionIsOffered() { + let buy = UnlockSheetAction.buy(displayName: product.displayName, displayPrice: "£14.99") + XCTAssertEqual(model(refusal: spent(), product: product).defaultAction, buy) + XCTAssertEqual( + UnlockSheetModel.make( + product: product, isLoadingProduct: false, isPurchasing: false, isRestoring: false + ).defaultAction, + buy + ) + } + + /// Nothing the sheet has no business defaulting gets a default: Restore, + /// Try Again and Not Now are never what Return should press. + func testReturnNeverDefaultsToRestoreRetryOrDismiss() { + XCTAssertNil(model(refusal: .purchaseUnconfirmed(TrialRefusal(meter: .organize, requested: 1, remaining: 0)), + product: product).defaultAction) + XCTAssertNil(model(refusal: spent(), product: nil).defaultAction, "load failed: Try Again is not the default") + XCTAssertNil(model(refusal: spent(), product: nil, isLoadingProduct: true).defaultAction) + } + + /// Busy changes what is disabled, not which action leads: the default stays + /// where it is and the view disables it, so Return cannot fire mid-purchase. + func testBusyDoesNotMoveTheDefault() { + let buy = UnlockSheetAction.buy(displayName: product.displayName, displayPrice: "£14.99") + let buying = model(refusal: spent(), product: product, isPurchasing: true) + XCTAssertEqual(buying.defaultAction, buy) + XCTAssertTrue(buying.isBusy) + + let dedupeBusy = dedupeModel(product: product, isPurchasing: true) + XCTAssertEqual(dedupeBusy.defaultAction, .runFreeDedupeBatch(fileCount: 3, deferredCount: 37)) + XCTAssertTrue(dedupeBusy.isBusy) + XCTAssertFalse(dedupeBusy.isBatchEnabled) + } + + /// The default is always one of the sheet's own actions, so exactly one + /// button can carry it. + func testTheDefaultIsAlwaysOneOfTheOfferedActionsAndOnlyOne() { + let models = [ + requestedModel(product: product), + requestedModel(product: nil), + dedupeModel(product: product), + model(refusal: spent(), product: product), + model(refusal: spent(), product: nil), + ] + for model in models { + guard let action = model.defaultAction else { continue } + XCTAssertEqual(model.actions.filter { $0 == action }.count, 1, "\(model.actions)") + } + } } diff --git a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift new file mode 100644 index 00000000..3342c80b --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift @@ -0,0 +1,77 @@ +import Foundation +import XCTest +@testable import ChronoframeApp +@testable import ChronoframeAppCore +@testable import ChronoframeCore + +/// The Organize Folder Shortcut must write the layout the person's library +/// already uses, not a second one. It reads it through `PreferencesStore`, which +/// owns the rules for existing users, new users and unrecognized stored values. +@MainActor +final class OrganizeFolderIntentConfigurationTests: XCTestCase { + private var suiteName: String! + private var defaults: UserDefaults! + + override func setUp() async throws { + try await super.setUp() + suiteName = "OrganizeFolderIntentConfigurationTests-\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suiteName) + defaults.removePersistentDomain(forName: suiteName) + } + + override func tearDown() async throws { + defaults.removePersistentDomain(forName: suiteName) + defaults = nil + suiteName = nil + try await super.tearDown() + } + + private func configuration() -> RunConfiguration { + OrganizeFolderIntent.makeConfiguration( + sourcePath: "/Volumes/Card", + destinationPath: "/Volumes/Archive", + preferences: PreferencesStore(defaults: defaults) + ) + } + + func testStoredYearMonthLayoutIsUsed() { + defaults.set(FolderStructure.yyyyMM.rawValue, forKey: "folderStructure") + + XCTAssertEqual(configuration().folderStructure, .yyyyMM) + } + + func testStoredYearMonthDayLayoutIsUsed() { + defaults.set(FolderStructure.yyyyMMDD.rawValue, forKey: "folderStructure") + + XCTAssertEqual(configuration().folderStructure, .yyyyMMDD) + } + + func testNewUserGetsTheAppsNewUserLayout() { + XCTAssertEqual(configuration().folderStructure, .yyyyMM) + } + + func testExistingUserWithoutAStoredLayoutKeepsYearMonthDay() { + defaults.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + + XCTAssertEqual(configuration().folderStructure, .yyyyMMDD) + } + + func testUnknownStoredLayoutKeepsYearMonthDay() { + defaults.set("not-a-layout", forKey: "folderStructure") + + XCTAssertEqual(configuration().folderStructure, .yyyyMMDD) + } + + /// Everything but the layout is what the intent shipped with. + func testTheRestOfTheConfigurationIsUnchanged() { + let config = configuration() + + XCTAssertEqual(config.mode, .transfer) + XCTAssertEqual(config.sourcePath, "/Volumes/Card") + XCTAssertEqual(config.destinationPath, "/Volumes/Archive") + XCTAssertNil(config.profileName) + XCTAssertTrue(config.verifyCopies) + XCTAssertTrue(config.parallelTransferEnabled) + XCTAssertEqual(config.workerCount, 8) + } +} From e9981365464d6a3c179ec0444082ca0137ccec61 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:31:27 -0800 Subject: [PATCH 04/10] German: localize alert, safety-card and History text; locale decimals and grouped counts Text that bypassed the catalog and so showed English in German: - "Chronoframe Needs Attention" alert messages set by the Setup, Run, History and Source Watch coordinators are looked up when set. - The setup safety card and the History reconnect body are %@ templates filled after lookup; the folder name is shown verbatim, not as Markdown. Formatting: - Deduplicate match reasons use the locale's decimal separator; English output is unchanged. - Deduplicate and contact-sheet counts use grouping separators. Singular forms for a count of 1: "1 was skipped", "Unlock to Remove 1 Duplicate", the contact-sheet empty message, and the Library shape accessibility label. Co-Authored-By: Claude Fable 5.2 --- .../App/Coordinators/HistoryCoordinator.swift | 2 +- .../App/Coordinators/RunCoordinator.swift | 4 +- .../App/Coordinators/SetupCoordinator.swift | 6 +- .../Coordinators/SourceWatchCoordinator.swift | 10 +- .../Resources/Localizable.xcstrings | 136 ++++++++++++++++++ .../Views/Components/ContactSheetView.swift | 8 +- .../Deduplicate/DeduplicateReviewLanes.swift | 8 +- .../Views/Deduplicate/DeduplicateView.swift | 14 +- .../Deduplicate/MatchReasonFormatter.swift | 99 ++++++++----- .../Views/Organize/HealthDashboardView.swift | 2 +- .../ChronoframeApp/Views/PluralPhrases.swift | 15 ++ .../ChronoframeApp/Views/RunHistoryView.swift | 12 +- .../ChronoframeApp/Views/SharedViews.swift | 43 +++++- .../Resources/LocalizableCore.xcstrings | 34 +++++ .../Services/SwiftOrganizerEngine.swift | 4 +- .../Support/CorePlurals.swift | 16 +++ .../CorePluralTests.swift | 43 ++++++ .../ContactSheetViewTests.swift | 20 ++- .../DeduplicateReviewViewsTests.swift | 8 ++ .../DeduplicateStatusViewTests.swift | 11 ++ .../MatchReasonFormatterBranchTests.swift | 102 +++++++++++++ .../PluralPhraseTests.swift | 32 +++++ .../RunHistoryViewTests.swift | 15 ++ .../SetupScreenModelTests.swift | 44 ++++++ .../TransientErrorLocalizationTests.swift | 95 ++++++++++++ 25 files changed, 713 insertions(+), 70 deletions(-) create mode 100644 ui/Tests/ChronoframeAppTests/TransientErrorLocalizationTests.swift diff --git a/ui/Sources/ChronoframeApp/App/Coordinators/HistoryCoordinator.swift b/ui/Sources/ChronoframeApp/App/Coordinators/HistoryCoordinator.swift index 4c39f9a6..677a9ea7 100644 --- a/ui/Sources/ChronoframeApp/App/Coordinators/HistoryCoordinator.swift +++ b/ui/Sources/ChronoframeApp/App/Coordinators/HistoryCoordinator.swift @@ -48,7 +48,7 @@ final class HistoryCoordinator { /// its own commit-progress surface. func revertHistoryEntry(_ entry: RunHistoryEntry) { guard !runSessionStore.isRunning, !deduplicateSessionStore.isWorking else { - reportTransientError("Stop the current run before reverting history.") + reportTransientError(String(localized: "Stop the current run before reverting history.", bundle: .module)) return } diff --git a/ui/Sources/ChronoframeApp/App/Coordinators/RunCoordinator.swift b/ui/Sources/ChronoframeApp/App/Coordinators/RunCoordinator.swift index e0dd9121..8363d4ec 100644 --- a/ui/Sources/ChronoframeApp/App/Coordinators/RunCoordinator.swift +++ b/ui/Sources/ChronoframeApp/App/Coordinators/RunCoordinator.swift @@ -173,7 +173,7 @@ final class RunCoordinator { guard Self.pathsMatch(activeDestination, context.destinationPath) else { activeWatchedImportContext = nil reportTransientError( - "The destination changed after this import was previewed. Open Sources and use Review & Import again." + String(localized: "The destination changed after this import was previewed. Open Sources and use Review & Import again.", bundle: .module) ) return } @@ -195,7 +195,7 @@ final class RunCoordinator { guard Self.pathsMatch(activeDestination, context.destinationPath) else { discardPhotosImportContext() reportTransientError( - "The destination changed after this import was previewed. Open Photos and use Review & Import again." + String(localized: "The destination changed after this import was previewed. Open Photos and use Review & Import again.", bundle: .module) ) return } diff --git a/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift b/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift index d59e8e94..d089d9b5 100644 --- a/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift +++ b/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift @@ -563,17 +563,17 @@ final class SetupCoordinator { func saveCurrentPathsAsProfile() { let name = setupStore.newProfileName.trimmingCharacters(in: .whitespacesAndNewlines) guard !name.isEmpty else { - setTransientErrorMessage("Enter a profile name before saving.") + setTransientErrorMessage(String(localized: "Enter a profile name before saving.", bundle: .module)) return } guard setupStore.sourceItems.count <= 1 else { - setTransientErrorMessage("A saved profile holds one folder. Keep this list as it is (Chronoframe remembers it), or remove the extra folders to save a profile.") + setTransientErrorMessage(String(localized: "A saved profile holds one folder. Keep this list as it is (Chronoframe remembers it), or remove the extra folders to save a profile.", bundle: .module)) return } guard !setupStore.sourcePath.isEmpty, !setupStore.destinationPath.isEmpty else { - setTransientErrorMessage("Choose both a source and destination before saving a profile.") + setTransientErrorMessage(String(localized: "Choose both a source and destination before saving a profile.", bundle: .module)) return } diff --git a/ui/Sources/ChronoframeApp/App/Coordinators/SourceWatchCoordinator.swift b/ui/Sources/ChronoframeApp/App/Coordinators/SourceWatchCoordinator.swift index 6597dd89..3ae15688 100644 --- a/ui/Sources/ChronoframeApp/App/Coordinators/SourceWatchCoordinator.swift +++ b/ui/Sources/ChronoframeApp/App/Coordinators/SourceWatchCoordinator.swift @@ -649,7 +649,7 @@ final class SourceWatchCoordinator { destinationPaths: [setupStore.destinationPath, deduplicateDestinationPath()], existingWatchedPaths: store.states.map(\.source.path) ) { - reportTransientError(conflict.errorDescription ?? "That folder can't be watched.") + reportTransientError(conflict.errorDescription ?? String(localized: "That folder can't be watched.", bundle: .module)) return } @@ -722,7 +722,7 @@ final class SourceWatchCoordinator { destinationPaths: [setupStore.destinationPath, deduplicateDestinationPath()], existingWatchedPaths: otherPaths ) { - reportTransientError(conflict.errorDescription ?? "That folder can't be watched.") + reportTransientError(conflict.errorDescription ?? String(localized: "That folder can't be watched.", bundle: .module)) return } @@ -779,7 +779,7 @@ final class SourceWatchCoordinator { try runScan(rootURL, scanTime) }.value guard let result = scanResult, result.completeness.isComplete else { - reportTransientError("Chronoframe couldn't fully check this folder, so it can't safely ignore its items yet. Try again once the folder is readable.") + reportTransientError(String(localized: "Chronoframe couldn't fully check this folder, so it can't safely ignore its items yet. Try again once the folder is readable.", bundle: .module)) return } entries = result.entries @@ -810,12 +810,12 @@ final class SourceWatchCoordinator { } let destination = setupStore.destinationPath.trimmingCharacters(in: .whitespacesAndNewlines) guard !destination.isEmpty else { - reportTransientError("Choose a destination folder in Organize → Choose Folders first; watched folders import into it.") + reportTransientError(String(localized: "Choose a destination folder in Organize → Choose Folders first; watched folders import into it.", bundle: .module)) return } guard let bookmark = preferencesStore.bookmark(for: Self.bookmarkKey(for: id)) else { store.setAvailability(id: id, .accessLost) - reportTransientError("Chronoframe lost access to this folder. Choose it again to keep watching.") + reportTransientError(String(localized: "Chronoframe lost access to this folder. Choose it again to keep watching.", bundle: .module)) return } diff --git a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings index 00134a66..cc10b038 100644 --- a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings +++ b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings @@ -435,6 +435,23 @@ } } }, + "%@ need review" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ zu prüfen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ need review" + } + } + } + }, "1 more is waiting. Your choices are saved; scan again to continue." : { "extractionState" : "manual", "localizations" : { @@ -1096,6 +1113,23 @@ } } }, + "1 needs review" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 zu prüfen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 needs review" + } + } + } + }, "1 photo or video" : { "extractionState" : "manual", "localizations" : { @@ -3077,6 +3111,23 @@ } } }, + "Chronoframe can’t currently access “%@”. Choose this same folder again to restore access and load History. Reconnecting does not change your media files." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe kann derzeit nicht auf „%@“ zugreifen. Wähle genau diesen Ordner erneut, um den Zugriff wiederherzustellen und den Verlauf zu laden. Das erneute Verbinden ändert deine Mediendateien nicht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe can’t currently access “%@”. Choose this same folder again to restore access and load History. Reconnecting does not change your media files." + } + } + } + }, "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." : { "extractionState" : "manual", "localizations" : { @@ -3305,6 +3356,74 @@ } } }, + "Found 1 media file, but a preview couldn't be created for it." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 Mediendatei gefunden, aber es konnte keine Vorschau erstellt werden." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Found 1 media file, but a preview couldn't be created for it." + } + } + } + }, + "Library shape: %@ healthy, %@, %@ critical" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Zustand der Mediathek: %@ einwandfrei, %@, %@ kritisch" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Library shape: %@ healthy, %@, %@ critical" + } + } + } + }, + "the folders you choose" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "deinen gewählten Ordnern" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "the folders you choose" + } + } + } + }, + "Unlock to Remove 1 Duplicate" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Freischalten, um 1 Duplikat zu entfernen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unlock to Remove 1 Duplicate" + } + } + } + }, "Your originals are never changed and nothing is copied yet. You can keep using your Mac." : { "extractionState" : "manual", "localizations" : { @@ -11996,6 +12115,23 @@ } } }, + "Your originals in %@ are opened as read-only. Original files are never modified, moved, or deleted." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Deine Originale in %@ werden schreibgeschützt geöffnet. Originaldateien werden nie verändert, verschoben oder gelöscht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your originals in %@ are opened as read-only. Original files are never modified, moved, or deleted." + } + } + } + }, "Your originals were not changed. The report and the receipt for undoing this copy are in History." : { "extractionState" : "manual", "localizations" : { diff --git a/ui/Sources/ChronoframeApp/Views/Components/ContactSheetView.swift b/ui/Sources/ChronoframeApp/Views/Components/ContactSheetView.swift index af854f25..cb787a70 100644 --- a/ui/Sources/ChronoframeApp/Views/Components/ContactSheetView.swift +++ b/ui/Sources/ChronoframeApp/Views/Components/ContactSheetView.swift @@ -194,13 +194,13 @@ enum ContactSheetLayout { /// Copy for the collapsed empty state, distinguishing "this folder has no /// media" from "media exists but previews could not be generated" — the /// second is a signal worth surfacing, not hiding behind a generic line. - static func emptyResultMessage(foundMediaCount: Int) -> String { + static func emptyResultMessage(foundMediaCount: Int, bundle: Bundle = .module) -> String { if foundMediaCount > 0 { return foundMediaCount == 1 - ? String(localized: "Found 1 media file, but previews couldn't be created for them.", bundle: .module) - : String(localized: "Found \(String(foundMediaCount)) media files, but previews couldn't be created for them.", bundle: .module) + ? String(localized: "Found 1 media file, but a preview couldn't be created for it.", bundle: bundle) + : String(localized: "Found \(String(foundMediaCount.formatted())) media files, but previews couldn't be created for them.", bundle: bundle) } - return String(localized: "No photos or videos in this folder yet. Frames appear here as soon as Chronoframe can see them.", bundle: .module) + return String(localized: "No photos or videos in this folder yet. Frames appear here as soon as Chronoframe can see them.", bundle: bundle) } } diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift index 50d14aa3..f4f72cd1 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift @@ -393,8 +393,12 @@ enum DeduplicateFooterCopy { (store.laneSummaries[.identical]?.groups ?? 0) > 0 } - static func unlockAllTitle(count: Int) -> String { - String(localized: "Unlock to Remove All \(count.formatted())", bundle: .module) + /// One duplicate has no "all": "Unlock to Remove 1 Duplicate", like the unlock + /// sheet's "Remove all 1 duplicate" branch. + static func unlockAllTitle(count: Int, bundle: Bundle = .module) -> String { + count == 1 + ? String(localized: "Unlock to Remove 1 Duplicate", bundle: bundle) + : String(localized: "Unlock to Remove All \(count.formatted())", bundle: bundle) } /// Added to the summary after a free removal: what is still waiting. diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift index 9a360026..1708cbd9 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift @@ -567,7 +567,7 @@ struct DeduplicateView: View { .confirmationDialog( confirmationCount == 1 ? String(localized: "Move 1 file to Trash?", bundle: .module) - : String(localized: "Move \(String(confirmationCount)) files to Trash?", bundle: .module), + : String(localized: "Move \(String(confirmationCount.formatted())) files to Trash?", bundle: .module), isPresented: $showingCommitConfirmation ) { Button("Move to Trash", role: .destructive) { @@ -651,8 +651,8 @@ struct DeduplicateView: View { if count == 0 { return String(localized: "No deletions in reviewed groups", bundle: .module) } - let files = count == 1 ? String(localized: "1 file", bundle: .module) : String(localized: "\(String(count)) files", bundle: .module) - let groups = reviewed == 1 ? String(localized: "1 reviewed group", bundle: .module) : String(localized: "\(String(reviewed)) reviewed groups", bundle: .module) + let files = count == 1 ? String(localized: "1 file", bundle: .module) : String(localized: "\(String(count.formatted())) files", bundle: .module) + let groups = reviewed == 1 ? String(localized: "1 reviewed group", bundle: .module) : String(localized: "\(String(reviewed.formatted())) reviewed groups", bundle: .module) return String(localized: "Move \(files) from \(groups) to Trash?", bundle: .module) } @@ -810,7 +810,7 @@ struct DeduplicateView: View { Divider() Button(reviewedCount == 1 ? String(localized: "Move Reviewed to Trash (1 group)", bundle: .module) - : String(localized: "Move Reviewed to Trash (\(String(reviewedCount)) groups)", bundle: .module)) { + : String(localized: "Move Reviewed to Trash (\(String(reviewedCount.formatted())) groups)", bundle: .module)) { sessionStore.prepareReviewedCommitPlan() showingCommitReviewedConfirmation = true } @@ -1131,7 +1131,7 @@ struct DeduplicateView: View { let count = summary.totalCandidatesScanned var parts = [count == 1 ? String(localized: "Scanned 1 file in \(formattedDuration(summary.scanDuration)). No duplicate groups found.", bundle: .module) - : String(localized: "Scanned \(String(count)) files in \(formattedDuration(summary.scanDuration)). No duplicate groups found.", bundle: .module)] + : String(localized: "Scanned \(String(count.formatted())) files in \(formattedDuration(summary.scanDuration)). No duplicate groups found.", bundle: .module)] if let note = videoAnalysisNote(for: summary) { parts.append(note) } @@ -1200,7 +1200,7 @@ extension DeduplicateView { static func committingTitle(fileCount: Int) -> String { if fileCount == 1 { return String(localized: "Moving 1 file to Trash…", bundle: .module) } return fileCount > 0 - ? String(localized: "Moving \(String(fileCount)) files to Trash…", bundle: .module) + ? String(localized: "Moving \(String(fileCount.formatted())) files to Trash…", bundle: .module) : String(localized: "Moving files to Trash…", bundle: .module) } @@ -1351,7 +1351,7 @@ enum CommitFooterButtonDensity { case .full: if fileCount == 1 { return String(localized: "Move 1 File to Trash", bundle: .module) } return fileCount > 0 - ? String(localized: "Move \(String(fileCount)) Files to Trash", bundle: .module) + ? String(localized: "Move \(String(fileCount.formatted())) Files to Trash", bundle: .module) : String(localized: "Move to Trash", bundle: .module) case .compact: return String(localized: "Move to Trash", bundle: .module) diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/MatchReasonFormatter.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/MatchReasonFormatter.swift index c2719639..d46799f3 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/MatchReasonFormatter.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/MatchReasonFormatter.swift @@ -4,11 +4,14 @@ import ChronoframeCore import Foundation enum MatchReasonFormatter { - static func summary(_ annotation: ClusterAnnotation, in cluster: DuplicateCluster? = nil) -> String { + /// Every function that prints a decimal takes `locale` so the separator + /// follows the user's language ("1,5 min" in German). Digits and rounding + /// are unchanged: see `decimal(_:_:locale:)`. + static func summary(_ annotation: ClusterAnnotation, in cluster: DuplicateCluster? = nil, locale: Locale = .current) -> String { if let evidence = annotation.videoEvidence { - return videoEvidenceSummary(evidence) + return videoEvidenceSummary(evidence, locale: locale) } - return summary(annotation.matchReason, in: cluster) + return summary(annotation.matchReason, in: cluster, locale: locale) } /// `cluster` makes the edited-variant wording media-aware ("same photo" / @@ -19,22 +22,23 @@ enum MatchReasonFormatter { static func summary( _ reason: MatchReason, in cluster: DuplicateCluster? = nil, - videoEvidence: VideoMatchEvidence? = nil + videoEvidence: VideoMatchEvidence? = nil, + locale: Locale = .current ) -> String { switch reason.kind { case .exactDuplicate: return String(localized: "Identical file content", bundle: .module) case .burst: - return burstSummary(reason) + return burstSummary(reason, locale: locale) case .nearDuplicate: - return nearDuplicateSummary(reason, videoEvidence: videoEvidence) + return nearDuplicateSummary(reason, videoEvidence: videoEvidence, locale: locale) case .editedVariant: let noun = cluster.map(DeduplicateAccessibilityText.mediaNoun) ?? String(localized: "item", bundle: .module) return String(localized: "Edited version of the same \(String(noun))", bundle: .module) } } - static func oneLiner(_ annotation: ClusterAnnotation) -> String { + static func oneLiner(_ annotation: ClusterAnnotation, locale: Locale = .current) -> String { if let evidence = annotation.videoEvidence { return String(localized: "\(String(evidence.agreeingSamples)) of \(String(evidence.usableSamples)) sampled frames match", bundle: .module) } @@ -45,12 +49,12 @@ enum MatchReasonFormatter { case .burst: guard let similarity else { if let delta = annotation.matchReason.timeDeltaSeconds { - return String(localized: "Possible match, \(String(formattedTimeDelta(delta))) apart — review", bundle: .module) + return String(localized: "Possible match, \(String(formattedTimeDelta(delta, locale: locale))) apart — review", bundle: .module) } return String(localized: "Possible burst match — review", bundle: .module) } if let delta = annotation.matchReason.timeDeltaSeconds { - return String(localized: "\(String(similarity)) similar, \(String(formattedTimeDelta(delta))) apart", bundle: .module) + return String(localized: "\(String(similarity)) similar, \(String(formattedTimeDelta(delta, locale: locale))) apart", bundle: .module) } return String(localized: "\(String(similarity)) similar burst", bundle: .module) case .nearDuplicate: @@ -64,20 +68,20 @@ enum MatchReasonFormatter { } } - static func keeperSummary(_ reason: KeeperReason) -> String { + static func keeperSummary(_ reason: KeeperReason, locale: Locale = .current) -> String { guard !reason.factors.isEmpty else { return String(localized: "Best overall quality", bundle: .module) } - let parts = reason.factors.map(factorDescription) + let parts = reason.factors.map { factorDescription($0, locale: locale) } return String(localized: "Kept: ", bundle: .module) + parts.joined(separator: ", ") } - static func warningSummary(_ warning: SafetyWarning) -> String { + static func warningSummary(_ warning: SafetyWarning, locale: Locale = .current) -> String { switch warning { case .differentPeople(let delta): return String(localized: "Different number of faces detected (±\(String(delta)))", bundle: .module) case .differentFraming(let delta): - return String(format: String(localized: "Different framing (%.0f%% crop difference)", bundle: .module), delta * 100) + return decimal(String(localized: "Different framing (%.0f%% crop difference)", bundle: .module), delta * 100, locale: locale) case .largeTimeGap(let seconds): - return String(localized: "Taken \(String(formattedTimeDelta(seconds))) apart", bundle: .module) + return String(localized: "Taken \(String(formattedTimeDelta(seconds, locale: locale))) apart", bundle: .module) case .textOverlayDetected: return String(localized: "Text overlay detected in one version", bundle: .module) case .significantExposureDifference: @@ -96,18 +100,18 @@ enum MatchReasonFormatter { } } - static func videoEvidenceSummary(_ evidence: VideoMatchEvidence) -> String { + static func videoEvidenceSummary(_ evidence: VideoMatchEvidence, locale: Locale = .current) -> String { let frameWord = evidence.usableSamples == 1 ? String(localized: "frame", bundle: .module) : String(localized: "frames", bundle: .module) - let duration = String(format: "%.1f", evidence.durationDeltaSeconds) + let duration = decimal("%.1f", evidence.durationDeltaSeconds, locale: locale) return String(localized: "\(String(evidence.agreeingSamples)) of \(String(evidence.usableSamples)) sampled \(String(frameWord)) agree. Video lengths differ by \(String(duration)) seconds.", bundle: .module) } // MARK: - Private - private static func burstSummary(_ reason: MatchReason) -> String { + private static func burstSummary(_ reason: MatchReason, locale: Locale) -> String { var parts: [String] = [] if let delta = reason.timeDeltaSeconds { - parts.append(String(localized: "taken \(String(formattedTimeDelta(delta))) apart", bundle: .module)) + parts.append(String(localized: "taken \(String(formattedTimeDelta(delta, locale: locale))) apart", bundle: .module)) } if let similarity = similarityPercentage(reason) { parts.append(similarity + String(localized: " visually similar", bundle: .module)) @@ -117,26 +121,26 @@ enum MatchReasonFormatter { return parts.joined(separator: ", ").prefix(1).uppercased() + parts.joined(separator: ", ").dropFirst() } - private static func nearDuplicateSummary(_ reason: MatchReason, videoEvidence: VideoMatchEvidence?) -> String { + private static func nearDuplicateSummary(_ reason: MatchReason, videoEvidence: VideoMatchEvidence?, locale: Locale) -> String { if let evidence = videoEvidence { - return videoFrameSummary(evidence) + return videoFrameSummary(evidence, locale: locale) } guard let pct = similarityPercentage(reason) else { if let delta = reason.timeDeltaSeconds { - return String(localized: "Possible visual match, taken \(String(formattedTimeDelta(delta))) apart — review to confirm", bundle: .module) + return String(localized: "Possible visual match, taken \(String(formattedTimeDelta(delta, locale: locale))) apart — review to confirm", bundle: .module) } return unconfirmedSimilaritySummary } if let delta = reason.timeDeltaSeconds { - return String(localized: "\(String(pct)) visually similar, taken \(String(formattedTimeDelta(delta))) apart", bundle: .module) + return String(localized: "\(String(pct)) visually similar, taken \(String(formattedTimeDelta(delta, locale: locale))) apart", bundle: .module) } return String(localized: "\(String(pct)) visually similar", bundle: .module) } - private static func videoFrameSummary(_ evidence: VideoMatchEvidence) -> String { + private static func videoFrameSummary(_ evidence: VideoMatchEvidence, locale: Locale) -> String { let frames = String(localized: "\(String(evidence.agreeingSamples)) of \(String(evidence.usableSamples)) sample frames matched", bundle: .module) if evidence.durationDeltaSeconds >= 0.1 { - return String(localized: "\(String(frames)) · \(String(String(format: "%.1fs", evidence.durationDeltaSeconds))) duration difference", bundle: .module) + return String(localized: "\(String(frames)) · \(String(secondsText(evidence.durationDeltaSeconds, fractionDigits: 1, locale: locale))) duration difference", bundle: .module) } return frames } @@ -166,20 +170,47 @@ enum MatchReasonFormatter { return "\(pct)%" } - private static func formattedTimeDelta(_ seconds: TimeInterval) -> String { + private static func formattedTimeDelta(_ seconds: TimeInterval, locale: Locale) -> String { let abs = Swift.abs(seconds) if abs < 2 { return String(localized: "< 1s", bundle: .module) } - if abs < 60 { return String(format: "%.0fs", abs) } - if abs < 3600 { return String(format: "%.1f min", abs / 60) } - return String(format: String(localized: "%.1f hr", bundle: .module), abs / 3600) + if abs < 60 { return secondsText(abs, fractionDigits: 0, locale: locale) } + if abs < 3600 { return decimal(String(localized: "%.1f min", bundle: .module), abs / 60, locale: locale) } + return decimal(String(localized: "%.1f hr", bundle: .module), abs / 3600, locale: locale) + } + + /// "12s" / "1.5s": the number is formatted here and the unit comes from the + /// shared `%@s` template ("12 s" in German). + private static func secondsText(_ value: Double, fractionDigits: Int, locale: Locale) -> String { + let number = decimal("%.\(fractionDigits)f", value, locale: locale) + return String(localized: "\(String(number))s", bundle: .module) + } + + /// Fills the first `%.Nf` in `template` (and turns `%%` into `%`). + /// + /// The digits come from printf, exactly as before, so English output and + /// rounding are unchanged; only the decimal separator is swapped for the + /// locale's. `String(format:locale:)` is not used because it also adds + /// grouping separators and rounds some halves differently from printf + /// (0.35 gives "0,4", not "0,3"). + static func decimal(_ template: String, _ value: Double, locale: Locale) -> String { + guard let range = template.range(of: #"%\.\d+f"#, options: .regularExpression) else { + return template.replacingOccurrences(of: "%%", with: "%") + } + var digits = String(format: String(template[range]), value) + if let separator = locale.decimalSeparator, separator != "." { + digits = digits.replacingOccurrences(of: ".", with: separator) + } + var filled = template + filled.replaceSubrange(range, with: digits) + return filled.replacingOccurrences(of: "%%", with: "%") } - private static func factorDescription(_ factor: KeeperFactor) -> String { + private static func factorDescription(_ factor: KeeperFactor, locale: Locale) -> String { switch factor { case .sharperFaces(let delta): - return String(format: String(localized: "sharper faces (+%.1f)", bundle: .module), delta) + return decimal(String(localized: "sharper faces (+%.1f)", bundle: .module), delta, locale: locale) case .higherResolution(let factor): - return String(format: String(localized: "%.1f× resolution", bundle: .module), factor) + return decimal(String(localized: "%.1f× resolution", bundle: .module), factor, locale: locale) case .isRaw: return String(localized: "RAW format", bundle: .module) case .largerFile(let delta): @@ -187,13 +218,13 @@ enum MatchReasonFormatter { formatter.countStyle = .file return String(localized: "larger file (+\(String(formatter.string(fromByteCount: delta))))", bundle: .module) case .betterSharpness(let delta): - return String(format: String(localized: "sharper (+%.2f)", bundle: .module), delta) + return decimal(String(localized: "sharper (+%.2f)", bundle: .module), delta, locale: locale) case .eyesOpen: return String(localized: "eyes open", bundle: .module) case .betterExpression(let delta): - return String(format: String(localized: "better expression (+%.1f)", bundle: .module), delta) + return decimal(String(localized: "better expression (+%.1f)", bundle: .module), delta, locale: locale) case .betterOverallQuality(let delta): - return String(format: String(localized: "better quality (+%.2f)", bundle: .module), delta) + return decimal(String(localized: "better quality (+%.2f)", bundle: .module), delta, locale: locale) } } } diff --git a/ui/Sources/ChronoframeApp/Views/Organize/HealthDashboardView.swift b/ui/Sources/ChronoframeApp/Views/Organize/HealthDashboardView.swift index 181a049b..fcd4b66a 100644 --- a/ui/Sources/ChronoframeApp/Views/Organize/HealthDashboardView.swift +++ b/ui/Sources/ChronoframeApp/Views/Organize/HealthDashboardView.swift @@ -308,7 +308,7 @@ private struct LibraryHealthHero: View { ) } .accessibilityElement(children: .combine) - .accessibilityLabel("Library shape: \(counts.good) healthy, \(counts.attention) needs review, \(counts.critical) critical") + .accessibilityLabel(PluralPhrases.libraryShape(healthy: counts.good, needReview: counts.attention, critical: counts.critical)) } private var readinessDial: some View { diff --git a/ui/Sources/ChronoframeApp/Views/PluralPhrases.swift b/ui/Sources/ChronoframeApp/Views/PluralPhrases.swift index dd44cb25..e3d508cb 100644 --- a/ui/Sources/ChronoframeApp/Views/PluralPhrases.swift +++ b/ui/Sources/ChronoframeApp/Views/PluralPhrases.swift @@ -163,6 +163,21 @@ enum PluralPhrases { "\(folders(folderCount, bundle: bundle)), \(files(fileCount, bundle: bundle))" } + // MARK: Library health + + /// "1 needs review" / "3 need review": the verb agrees with the count. + static func needReview(_ count: Int, bundle: Bundle = .module) -> String { + phrase(count, one: "1 needs review", other: "%@ need review", bundle: bundle) + } + + /// Accessibility label for the Library shape card. + static func libraryShape(healthy: Int, needReview reviewCount: Int, critical: Int, bundle: Bundle = .module) -> String { + String( + localized: "Library shape: \(String(healthy.formatted())) healthy, \(String(needReview(reviewCount, bundle: bundle))), \(String(critical.formatted())) critical", + bundle: bundle + ) + } + // MARK: Preview review static func itemsNeedAttention(_ count: Int, bundle: Bundle = .module) -> String { diff --git a/ui/Sources/ChronoframeApp/Views/RunHistoryView.swift b/ui/Sources/ChronoframeApp/Views/RunHistoryView.swift index 2873e9cb..fcb017c6 100644 --- a/ui/Sources/ChronoframeApp/Views/RunHistoryView.swift +++ b/ui/Sources/ChronoframeApp/Views/RunHistoryView.swift @@ -356,6 +356,16 @@ struct RunHistoryView: View { return "\(monthName) \(yearPart)" } + /// Looks the sentence up as a `%@` template and fills the folder name in + /// afterwards, so it is translated whatever the folder is called. + static func reconnectBody(folderName: String, bundle: Bundle = .module) -> String { + AppLocalization.format( + "Chronoframe can’t currently access “%@”. Choose this same folder again to restore access and load History. Reconnecting does not change your media files.", + folderName, + bundle: bundle + ) + } + private func refreshErrorStrip(_ message: String) -> some View { HStack(alignment: .top, spacing: DesignTokens.Spacing.sm) { Image(systemName: "exclamationmark.triangle.fill") @@ -364,7 +374,7 @@ struct RunHistoryView: View { Text(LocalizedStringKey(historyStore.needsFolderAccess ? "Reconnect your archive folder" : "History unavailable"), bundle: .module) .font(.headline) Text(historyStore.needsFolderAccess - ? "Chronoframe can’t currently access “\(URL(fileURLWithPath: historyStore.destinationRoot).lastPathComponent)”. Choose this same folder again to restore access and load History. Reconnecting does not change your media files." + ? Self.reconnectBody(folderName: URL(fileURLWithPath: historyStore.destinationRoot).lastPathComponent) : message) Text(historyStore.destinationRoot) .font(.caption) diff --git a/ui/Sources/ChronoframeApp/Views/SharedViews.swift b/ui/Sources/ChronoframeApp/Views/SharedViews.swift index f48bee93..f28f1375 100644 --- a/ui/Sources/ChronoframeApp/Views/SharedViews.swift +++ b/ui/Sources/ChronoframeApp/Views/SharedViews.swift @@ -810,14 +810,25 @@ struct TrustProofItem: Identifiable, Equatable { let tone: TrustProofTone let accessibilityLabel: String let actionLabel: String? + /// True when `message` is a finished sentence that names something at + /// runtime (a folder), already localized. It is shown verbatim: looking it + /// up as a catalog key can never match, and `Text(LocalizedStringKey:)` + /// would read the folder name as Markdown. False means `message` is a + /// catalog key. + var messageIsResolved = false static func == (lhs: TrustProofItem, rhs: TrustProofItem) -> Bool { - lhs.id == rhs.id && lhs.title == rhs.title && lhs.message == rhs.message && lhs.symbol == rhs.symbol && lhs.tone == rhs.tone && lhs.accessibilityLabel == rhs.accessibilityLabel && lhs.actionLabel == rhs.actionLabel + lhs.id == rhs.id && lhs.title == rhs.title && lhs.message == rhs.message && lhs.symbol == rhs.symbol && lhs.tone == rhs.tone && lhs.accessibilityLabel == rhs.accessibilityLabel && lhs.actionLabel == rhs.actionLabel && lhs.messageIsResolved == rhs.messageIsResolved + } + + /// The message as a plain string, for help text. + var localizedMessage: String { + messageIsResolved ? message : AppLocalization.string(message) } } struct TrustProofModel { - static func setupSafetySummary(source: String, destination: String, verifyCopies: Bool) -> [TrustProofItem] { + static func setupSafetySummary(source: String, destination: String, verifyCopies: Bool, bundle: Bundle = .module) -> [TrustProofItem] { var items: [TrustProofItem] = [] // 1. Local Processing Guarantee @@ -832,15 +843,24 @@ struct TrustProofModel { )) // 2. Source Safe Protection - let sourceName = source.isEmpty ? "the folders you choose" : URL(fileURLWithPath: source).lastPathComponent + // The sentence is looked up as a `%@` template and filled afterwards, + // so the folder name never has to match a catalog key. + let sourceName = source.isEmpty + ? AppLocalization.string("the folders you choose", bundle: bundle) + : URL(fileURLWithPath: source).lastPathComponent items.append(TrustProofItem( id: "source_safe", title: "Original Photos Protected", - message: "Your originals in \(sourceName) are opened as read-only. Original files are never modified, moved, or deleted.", + message: AppLocalization.format( + "Your originals in %@ are opened as read-only. Original files are never modified, moved, or deleted.", + sourceName, + bundle: bundle + ), symbol: "lock.shield", tone: .success, accessibilityLabel: "Your original files are read-only and safe", - actionLabel: nil + actionLabel: nil, + messageIsResolved: true )) // 3. Copy Verification Status @@ -1194,12 +1214,21 @@ struct TrustProofSurface: View { .foregroundStyle(item.tone.color) } .fixedSize() - .help(AppLocalization.string(item.message)) + .help(item.localizedMessage) .accessibilityElement(children: .combine) .accessibilityLabel(AppLocalization.string(item.accessibilityLabel)) } } + @ViewBuilder + private func messageText(for item: TrustProofItem) -> some View { + if item.messageIsResolved { + Text(verbatim: item.message) + } else { + Text(LocalizedStringKey(item.message), bundle: .module) + } + } + private var cards: some View { VStack(alignment: .leading, spacing: 10) { ForEach(items) { item in @@ -1214,7 +1243,7 @@ struct TrustProofSurface: View { .scaledFont(.body, weight: .semibold) .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) - Text(LocalizedStringKey(item.message), bundle: .module) + messageText(for: item) .scaledFont(.body) .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) .fixedSize(horizontal: false, vertical: true) diff --git a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings index d5e25142..9b3db145 100644 --- a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings +++ b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings @@ -2862,6 +2862,23 @@ } } }, + "The resumed transfer did not finish: %lld failed and 1 was skipped. Originals were left untouched.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Der fortgesetzte Kopiervorgang wurde nicht abgeschlossen: %lld fehlgeschlagen und 1 übersprungen. Die Originale blieben unangetastet." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The resumed transfer did not finish: %lld failed and 1 was skipped. Originals were left untouched." + } + } + } + }, "The selected revert receipt could not be found. It may have been moved or deleted. Receipt: %@.": { "extractionState": "manual", "localizations": { @@ -2915,6 +2932,23 @@ } } }, + "The transfer did not finish: %lld failed and 1 was skipped. Originals were left untouched.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Der Kopiervorgang wurde nicht abgeschlossen: %lld fehlgeschlagen und 1 übersprungen. Die Originale blieben unangetastet." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The transfer did not finish: %lld failed and 1 was skipped. Originals were left untouched." + } + } + } + }, "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.": { "extractionState": "manual", "localizations": { diff --git a/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift b/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift index 1981fec2..e07755f4 100644 --- a/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift +++ b/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift @@ -1039,7 +1039,7 @@ public final class SwiftOrganizerEngine: OrganizerEngine { ), artifacts: summaryArtifacts, failureMessage: completedStatus == .failed - ? CoreL10n.text("The transfer did not finish: \(executionResult.failedCount) failed and \(executionResult.skippedCount) were skipped. Originals were left untouched.") + ? CorePlurals.transferDidNotFinish(failed: executionResult.failedCount, skipped: executionResult.skippedCount) : nil, // Only report retained batch paths on an actual finish: // `retainedBatchSourcePaths` is the set the re-plan @@ -1214,7 +1214,7 @@ public final class SwiftOrganizerEngine: OrganizerEngine { ), artifacts: executionResult.artifacts, failureMessage: completedStatus == .failed - ? CoreL10n.text("The resumed transfer did not finish: \(executionResult.failedCount) failed and \(executionResult.skippedCount) were skipped. Originals were left untouched.") + ? CorePlurals.transferDidNotFinish(failed: executionResult.failedCount, skipped: executionResult.skippedCount, resumed: true) : nil ) ) diff --git a/ui/Sources/ChronoframeAppCore/Support/CorePlurals.swift b/ui/Sources/ChronoframeAppCore/Support/CorePlurals.swift index 2b0956d2..33696af0 100644 --- a/ui/Sources/ChronoframeAppCore/Support/CorePlurals.swift +++ b/ui/Sources/ChronoframeAppCore/Support/CorePlurals.swift @@ -37,6 +37,22 @@ enum CorePlurals { : CoreL10n.text("\(count) items couldn't be read and were skipped. Your Photos library was not changed.", bundle: bundle) } + /// "…2 failed and 1 was skipped." The verb follows the skipped count; the + /// failed count is a number followed by "failed", which reads the same at + /// any count. + static func transferDidNotFinish(failed: Int, skipped: Int, resumed: Bool = false, bundle: Bundle = .module) -> String { + switch (resumed, skipped == 1) { + case (false, true): + return CoreL10n.text("The transfer did not finish: \(failed) failed and 1 was skipped. Originals were left untouched.", bundle: bundle) + case (false, false): + return CoreL10n.text("The transfer did not finish: \(failed) failed and \(skipped) were skipped. Originals were left untouched.", bundle: bundle) + case (true, true): + return CoreL10n.text("The resumed transfer did not finish: \(failed) failed and 1 was skipped. Originals were left untouched.", bundle: bundle) + case (true, false): + return CoreL10n.text("The resumed transfer did not finish: \(failed) failed and \(skipped) were skipped. Originals were left untouched.", bundle: bundle) + } + } + static func importStopped(completed: Int, total: Int, bundle: Bundle = .module) -> String { let done = completed.formatted() return total == 1 diff --git a/ui/Tests/ChronoframeAppCoreTests/CorePluralTests.swift b/ui/Tests/ChronoframeAppCoreTests/CorePluralTests.swift index 0374f038..664fc829 100644 --- a/ui/Tests/ChronoframeAppCoreTests/CorePluralTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/CorePluralTests.swift @@ -101,4 +101,47 @@ final class CorePluralTests: XCTestCase { XCTAssertTrue(CorePlurals.importPausedLowSpace(completed: 0, total: 1, bundle: de).contains("0 von 1 Objekt ist bereit und wurde aufbewahrt.")) XCTAssertTrue(CorePlurals.importProgressNotSaved(completed: 0, total: 1, bundle: de).contains("0 von 1 Objekt ist bereit und wurde aufbewahrt.")) } + + func testTransferFailureVerbFollowsTheSkippedCount() { + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 2, skipped: 1), + "The transfer did not finish: 2 failed and 1 was skipped. Originals were left untouched." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 1, skipped: 3), + "The transfer did not finish: 1 failed and 3 were skipped. Originals were left untouched." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 4, skipped: 0), + "The transfer did not finish: 4 failed and 0 were skipped. Originals were left untouched." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 2, skipped: 1, resumed: true), + "The resumed transfer did not finish: 2 failed and 1 was skipped. Originals were left untouched." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 2, skipped: 5, resumed: true), + "The resumed transfer did not finish: 2 failed and 5 were skipped. Originals were left untouched." + ) + } + + func testGermanTransferFailureSentences() throws { + let de = try germanBundle() + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 2, skipped: 1, bundle: de), + "Der Kopiervorgang wurde nicht abgeschlossen: 2 fehlgeschlagen und 1 übersprungen. Die Originale blieben unangetastet." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 2, skipped: 3, bundle: de), + "Der Kopiervorgang wurde nicht abgeschlossen: 2 fehlgeschlagen und 3 übersprungen. Die Originale blieben unangetastet." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 1, skipped: 1, resumed: true, bundle: de), + "Der fortgesetzte Kopiervorgang wurde nicht abgeschlossen: 1 fehlgeschlagen und 1 übersprungen. Die Originale blieben unangetastet." + ) + XCTAssertEqual( + CorePlurals.transferDidNotFinish(failed: 1, skipped: 4, resumed: true, bundle: de), + "Der fortgesetzte Kopiervorgang wurde nicht abgeschlossen: 1 fehlgeschlagen und 4 übersprungen. Die Originale blieben unangetastet." + ) + } } diff --git a/ui/Tests/ChronoframeAppTests/ContactSheetViewTests.swift b/ui/Tests/ChronoframeAppTests/ContactSheetViewTests.swift index 7f3f22d6..de51b098 100644 --- a/ui/Tests/ChronoframeAppTests/ContactSheetViewTests.swift +++ b/ui/Tests/ChronoframeAppTests/ContactSheetViewTests.swift @@ -117,7 +117,7 @@ final class ContactSheetViewTests: XCTestCase { ) XCTAssertEqual( ContactSheetLayout.emptyResultMessage(foundMediaCount: 1), - "Found 1 media file, but previews couldn't be created for them." + "Found 1 media file, but a preview couldn't be created for it." ) XCTAssertEqual( ContactSheetLayout.emptyResultMessage(foundMediaCount: 12), @@ -125,6 +125,24 @@ final class ContactSheetViewTests: XCTestCase { ) } + /// A count of 1 says "a preview … for it", and a large count gets the + /// locale's grouping like every other count in the app. + func testEmptyResultMessageSingularAndGroupedCounts() throws { + XCTAssertEqual( + ContactSheetLayout.emptyResultMessage(foundMediaCount: 1_234), + "Found \(1_234.formatted()) media files, but previews couldn't be created for them." + ) + let de = try germanAppBundle() + XCTAssertEqual( + ContactSheetLayout.emptyResultMessage(foundMediaCount: 1, bundle: de), + "1 Mediendatei gefunden, aber es konnte keine Vorschau erstellt werden." + ) + XCTAssertEqual( + ContactSheetLayout.emptyResultMessage(foundMediaCount: 12, bundle: de), + "12 Mediendateien gefunden, aber es konnten keine Vorschaubilder erstellt werden." + ) + } + private func render(_ view: V, size: NSSize) throws -> NSBitmapImageRep { let hostingView = NSHostingView(rootView: view) hostingView.frame = NSRect(origin: .zero, size: size) diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift index aaf5345f..96dfe6fa 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift @@ -353,6 +353,8 @@ final class DeduplicateReviewViewsTests: XCTestCase { XCTAssertEqual(DeduplicateFooterCopy.freeBatchCommitTitle(fileCount: 1), "Move 1 File to Trash Free") XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 4), "Unlock to Remove All 4") XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 1_200), "Unlock to Remove All \(1_200.formatted())") + // One duplicate has no "all": it must not read "Remove All 1". + XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 1), "Unlock to Remove 1 Duplicate") // The line appears only when the allowance applies and the reviewed plan exceeds it. XCTAssertTrue(DeduplicateFooterCopy.showsFreeRemoval(remaining: 2, reviewedCount: 4)) @@ -515,4 +517,10 @@ final class DeduplicateReviewViewsTests: XCTestCase { XCTAssertEqual(DeduplicateFooterCopy.menuQuickReviewLane(nearlyIdenticalGroups: 1), .nearlyIdentical) XCTAssertEqual(DeduplicateFooterCopy.menuQuickReviewLane(nearlyIdenticalGroups: 0), .lookAtEach) } + + func testUnlockAllTitleIsGermanAndSingularForOne() throws { + let de = try germanAppBundle() + XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 4, bundle: de), "Freischalten, um alle 4 zu entfernen") + XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 1, bundle: de), "Freischalten, um 1 Duplikat zu entfernen") + } } diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift index d7a53867..dc957e9e 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift @@ -586,4 +586,15 @@ final class DeduplicateStatusViewTests: XCTestCase { "daniel-stiel-dlkVbwOITY8-unsplash copy.jpg" ) } + + /// Counts on the Deduplicate screen use the locale's grouping like the rest + /// of the app ("1,234", "1.234"), not a bare `String(count)`. + func testLargeCountsAreGroupedLikeTheRestOfTheApp() { + let grouped = 12_345.formatted() + XCTAssertNotEqual(grouped, "12345", "The test locale must group digits for this check to mean anything") + XCTAssertEqual(DeduplicateView.committingTitle(fileCount: 12_345), "Moving \(grouped) files to Trash…") + XCTAssertEqual(CommitFooterButtonDensity.full.commitTitle(fileCount: 12_345), "Move \(grouped) Files to Trash") + let summary = DeduplicateSummary(totalCandidatesScanned: 12_345) + XCTAssertTrue(DeduplicateView.emptyResultsMessage(summary).contains("Scanned \(grouped) files")) + } } diff --git a/ui/Tests/ChronoframeAppTests/MatchReasonFormatterBranchTests.swift b/ui/Tests/ChronoframeAppTests/MatchReasonFormatterBranchTests.swift index d7a3f497..a245a7e4 100644 --- a/ui/Tests/ChronoframeAppTests/MatchReasonFormatterBranchTests.swift +++ b/ui/Tests/ChronoframeAppTests/MatchReasonFormatterBranchTests.swift @@ -156,6 +156,108 @@ final class MatchReasonFormatterBranchTests: XCTestCase { XCTAssertEqual(MatchReasonFormatter.warningSummary(.largeTimeGap(seconds: 7200)), "Taken 2.0 hr apart") } + // MARK: - Locale + + private let english = Locale(identifier: "en_US") + private let german = Locale(identifier: "de_DE") + + /// The decimal separator follows the locale; English output is the printf + /// text it always was. + func testTimeDeltaDecimalsFollowTheLocale() { + let burst = annotation(.burst, distance: 0.1, timeDelta: 90) + XCTAssertEqual(MatchReasonFormatter.oneLiner(burst, locale: english), "90% similar, 1.5 min apart") + XCTAssertEqual(MatchReasonFormatter.oneLiner(burst, locale: german), "90% similar, 1,5 min apart") + + let hours = MatchReason(timeDeltaSeconds: 7200, averageVisionDistance: 0.1, kind: .nearDuplicate) + XCTAssertEqual(MatchReasonFormatter.summary(hours, locale: english), "90% visually similar, taken 2.0 hr apart") + XCTAssertEqual(MatchReasonFormatter.summary(hours, locale: german), "90% visually similar, taken 2,0 hr apart") + + // Whole seconds carry no separator, so both locales agree. + let seconds = MatchReason(timeDeltaSeconds: 45, averageVisionDistance: 0.1, kind: .nearDuplicate) + XCTAssertEqual(MatchReasonFormatter.summary(seconds, locale: german), "90% visually similar, taken 45s apart") + XCTAssertEqual(MatchReasonFormatter.warningSummary(.largeTimeGap(seconds: 7200), locale: german), "Taken 2,0 hr apart") + XCTAssertEqual(MatchReasonFormatter.warningSummary(.largeTimeGap(seconds: 7200), locale: english), "Taken 2.0 hr apart") + } + + func testVideoDurationDecimalsFollowTheLocale() { + let evidence = VideoMatchEvidence( + usableSamples: 5, + agreeingSamples: 4, + medianHammingDistance: 3, + durationDeltaSeconds: 1.5, + visionCorroborated: false + ) + XCTAssertEqual( + MatchReasonFormatter.videoEvidenceSummary(evidence, locale: english), + "4 of 5 sampled frames agree. Video lengths differ by 1.5 seconds." + ) + XCTAssertEqual( + MatchReasonFormatter.videoEvidenceSummary(evidence, locale: german), + "4 of 5 sampled frames agree. Video lengths differ by 1,5 seconds." + ) + let reason = MatchReason(kind: .nearDuplicate) + XCTAssertEqual( + MatchReasonFormatter.summary(reason, videoEvidence: evidence, locale: english), + "4 of 5 sample frames matched · 1.5s duration difference" + ) + XCTAssertEqual( + MatchReasonFormatter.summary(reason, videoEvidence: evidence, locale: german), + "4 of 5 sample frames matched · 1,5s duration difference" + ) + } + + func testKeeperFactorDecimalsFollowTheLocale() { + let reason = KeeperReason(factors: [ + .sharperFaces(delta: 1.5), + .higherResolution(factor: 2.5), + .betterSharpness(delta: 0.25), + .betterExpression(delta: 0.5), + .betterOverallQuality(delta: 0.75), + ]) + XCTAssertEqual( + MatchReasonFormatter.keeperSummary(reason, locale: english), + "Kept: sharper faces (+1.5), 2.5× resolution, sharper (+0.25), better expression (+0.5), better quality (+0.75)" + ) + XCTAssertEqual( + MatchReasonFormatter.keeperSummary(reason, locale: german), + "Kept: sharper faces (+1,5), 2,5× resolution, sharper (+0,25), better expression (+0,5), better quality (+0,75)" + ) + } + + func testFramingWarningKeepsItsPercentSign() { + XCTAssertEqual( + MatchReasonFormatter.warningSummary(.differentFraming(cropDelta: 0.4), locale: german), + "Different framing (40% crop difference)" + ) + } + + /// printf digits, locale separator, no grouping: the English text is what + /// `String(format:)` always printed. + func testDecimalHelperKeepsPrintfDigitsAndAddsNoGrouping() { + XCTAssertEqual(MatchReasonFormatter.decimal("%.1f hr", 1234.5, locale: english), "1234.5 hr") + XCTAssertEqual(MatchReasonFormatter.decimal("%.1f hr", 1234.5, locale: german), "1234,5 hr") + // printf rounds 0.35 down (the double is just under it); ICU would give 0.4. + XCTAssertEqual(MatchReasonFormatter.decimal("%.1f", 0.35, locale: german), "0,3") + XCTAssertEqual(MatchReasonFormatter.decimal("%.0fs", 12, locale: german), "12s") + } + + func testGermanUnitTemplatesKeepTheirPlaceholdersAndGetGermanUnits() throws { + let de = try germanAppBundle() + // Seconds share one `%@s` template: "12s" in English, "12 s" in German. + XCTAssertEqual(AppLocalization.format("%@s", MatchReasonFormatter.decimal("%.0f", 12, locale: german), bundle: de), "12 s") + XCTAssertEqual(AppLocalization.format("%@s", MatchReasonFormatter.decimal("%.1f", 1.5, locale: german), bundle: de), "1,5 s") + XCTAssertEqual( + MatchReasonFormatter.decimal(AppLocalization.string("%.1f min", bundle: de), 1.5, locale: german), + "1,5 Min." + ) + XCTAssertEqual( + MatchReasonFormatter.decimal(AppLocalization.string("%.1f hr", bundle: de), 2, locale: german), + "2,0 Std." + ) + } + + // MARK: - Helpers + // MARK: - Helpers private func annotation( diff --git a/ui/Tests/ChronoframeAppTests/PluralPhraseTests.swift b/ui/Tests/ChronoframeAppTests/PluralPhraseTests.swift index d48c85cd..54e3a83f 100644 --- a/ui/Tests/ChronoframeAppTests/PluralPhraseTests.swift +++ b/ui/Tests/ChronoframeAppTests/PluralPhraseTests.swift @@ -255,4 +255,36 @@ final class PluralPhraseTests: XCTestCase { "Ein neuer Import verwirft das vorbereitete Element des unterbrochenen Imports. Deine Fotos-Mediathek bleibt in beiden Fällen unverändert." ) } + + // MARK: Library shape label + + func testLibraryShapeVerbAgreesWithTheReviewCount() { + XCTAssertEqual(PluralPhrases.needReview(1), "1 needs review") + XCTAssertEqual(PluralPhrases.needReview(0), "0 need review") + XCTAssertEqual(PluralPhrases.needReview(3), "3 need review") + XCTAssertEqual( + PluralPhrases.libraryShape(healthy: 4, needReview: 1, critical: 0), + "Library shape: 4 healthy, 1 needs review, 0 critical" + ) + XCTAssertEqual( + PluralPhrases.libraryShape(healthy: 2, needReview: 3, critical: 1), + "Library shape: 2 healthy, 3 need review, 1 critical" + ) + XCTAssertEqual( + PluralPhrases.libraryShape(healthy: 0, needReview: 0, critical: 0), + "Library shape: 0 healthy, 0 need review, 0 critical" + ) + } + + func testGermanLibraryShapeLabel() throws { + let de = try germanAppBundle() + XCTAssertEqual( + PluralPhrases.libraryShape(healthy: 4, needReview: 1, critical: 0, bundle: de), + "Zustand der Mediathek: 4 einwandfrei, 1 zu prüfen, 0 kritisch" + ) + XCTAssertEqual( + PluralPhrases.libraryShape(healthy: 2, needReview: 3, critical: 1, bundle: de), + "Zustand der Mediathek: 2 einwandfrei, 3 zu prüfen, 1 kritisch" + ) + } } diff --git a/ui/Tests/ChronoframeAppTests/RunHistoryViewTests.swift b/ui/Tests/ChronoframeAppTests/RunHistoryViewTests.swift index b56c62d4..969bb0f9 100644 --- a/ui/Tests/ChronoframeAppTests/RunHistoryViewTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunHistoryViewTests.swift @@ -197,4 +197,19 @@ final class RunHistoryViewTests: XCTestCase { let filteredNone = RunHistoryView.filterEntries(allEntries, filter: .all, searchText: "", selectedTimelineMonth: nil) XCTAssertEqual(filteredNone.count, 4) } + + /// The reconnect body names the archive folder, so the sentence is a + /// `%@` template looked up first; as an interpolated `String` it stayed + /// English in German. + func testReconnectBodyIsATranslatedTemplateWithTheFolderNameFilledIn() throws { + XCTAssertEqual( + RunHistoryView.reconnectBody(folderName: "Trips"), + "Chronoframe can’t currently access “Trips”. Choose this same folder again to restore access and load History. Reconnecting does not change your media files." + ) + let de = try germanAppBundle() + XCTAssertEqual( + RunHistoryView.reconnectBody(folderName: "Reisen", bundle: de), + "Chronoframe kann derzeit nicht auf „Reisen“ zugreifen. Wähle genau diesen Ordner erneut, um den Zugriff wiederherzustellen und den Verlauf zu laden. Das erneute Verbinden ändert deine Mediendateien nicht." + ) + } } diff --git a/ui/Tests/ChronoframeAppTests/SetupScreenModelTests.swift b/ui/Tests/ChronoframeAppTests/SetupScreenModelTests.swift index a1f3adba..601d8237 100644 --- a/ui/Tests/ChronoframeAppTests/SetupScreenModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/SetupScreenModelTests.swift @@ -374,6 +374,50 @@ final class SetupScreenModelTests: XCTestCase { XCTAssertEqual(itemsNoVerify[2].tone, .warning) } + /// The source sentence names a folder at runtime, so it is looked up as a + /// template and filled afterwards. The result is flagged as resolved so the + /// view shows it verbatim instead of reading the folder name as Markdown. + func testSetupSafetySummaryNamesTheSourceFolderVerbatim() throws { + let items = TrustProofModel.setupSafetySummary(source: "/Volumes/*Card*_1", destination: "/Volumes/Archive", verifyCopies: true) + let source = try XCTUnwrap(items.first { $0.id == "source_safe" }) + XCTAssertEqual( + source.message, + "Your originals in *Card*_1 are opened as read-only. Original files are never modified, moved, or deleted." + ) + XCTAssertTrue(source.messageIsResolved) + XCTAssertEqual(source.localizedMessage, source.message) + // The other cards stay catalog keys, rendered through the catalog as before. + XCTAssertEqual(items.filter(\.messageIsResolved).map(\.id), ["source_safe"]) + + let fallback = try XCTUnwrap( + TrustProofModel.setupSafetySummary(source: "", destination: "", verifyCopies: true).first { $0.id == "source_safe" } + ) + XCTAssertEqual( + fallback.message, + "Your originals in the folders you choose are opened as read-only. Original files are never modified, moved, or deleted." + ) + } + + func testSetupSafetySummaryIsTranslatedIncludingTheFallbackFolderPhrase() throws { + let de = try germanAppBundle() + let named = try XCTUnwrap( + TrustProofModel.setupSafetySummary(source: "/Volumes/Card", destination: "", verifyCopies: true, bundle: de) + .first { $0.id == "source_safe" } + ) + XCTAssertEqual( + named.message, + "Deine Originale in Card werden schreibgeschützt geöffnet. Originaldateien werden nie verändert, verschoben oder gelöscht." + ) + let fallback = try XCTUnwrap( + TrustProofModel.setupSafetySummary(source: "", destination: "", verifyCopies: true, bundle: de) + .first { $0.id == "source_safe" } + ) + XCTAssertEqual( + fallback.message, + "Deine Originale in deinen gewählten Ordnern werden schreibgeschützt geöffnet. Originaldateien werden nie verändert, verschoben oder gelöscht." + ) + } + /// The preview reassurance must not claim zero disk writes: planning /// writes `.organize_logs/dry_run_report_*.csv`, /// `.organize_logs/preview_review_*.jsonl` and `.organize_cache.db` rows. diff --git a/ui/Tests/ChronoframeAppTests/TransientErrorLocalizationTests.swift b/ui/Tests/ChronoframeAppTests/TransientErrorLocalizationTests.swift new file mode 100644 index 00000000..ff5e2a70 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/TransientErrorLocalizationTests.swift @@ -0,0 +1,95 @@ +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif +import Foundation +import XCTest +@testable import ChronoframeApp + +/// The "Chronoframe Needs Attention" alert renders `transientErrorMessage` as a +/// plain `String`, so a message is only translated if the call site looked it +/// up when it was set. +final class TransientErrorLocalizationTests: XCTestCase { + /// Every sentence the Setup, Source Watch, History and Run coordinators + /// pass to the alert as a literal. + private let coordinatorSentences = [ + "Enter a profile name before saving.", + "A saved profile holds one folder. Keep this list as it is (Chronoframe remembers it), or remove the extra folders to save a profile.", + "Choose both a source and destination before saving a profile.", + "Chronoframe couldn't fully check this folder, so it can't safely ignore its items yet. Try again once the folder is readable.", + "Choose a destination folder in Organize → Choose Folders first; watched folders import into it.", + "Chronoframe lost access to this folder. Choose it again to keep watching.", + "That folder can't be watched.", + "Stop the current run before reverting history.", + "The destination changed after this import was previewed. Open Sources and use Review & Import again.", + "The destination changed after this import was previewed. Open Photos and use Review & Import again.", + ] + + func testCoordinatorAlertSentencesAreCatalogKeysWithGerman() throws { + let german = try germanAppBundle() + for sentence in coordinatorSentences { + XCTAssertNotEqual( + AppLocalization.string(sentence, bundle: german), + sentence, + "No German for alert sentence: \(sentence)" + ) + } + XCTAssertEqual( + AppLocalization.string("Enter a profile name before saving.", bundle: german), + "Gib vor dem Sichern einen Profilnamen ein." + ) + } + + /// A bare literal handed to the alert is shown in English whatever the + /// language: it must be `String(localized:bundle:)` at the call site. + func testNoCoordinatorPassesABareLiteralToTheAlert() throws { + let appDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() + .appendingPathComponent("Sources/ChronoframeApp/App", isDirectory: true) + let pattern = try NSRegularExpression( + pattern: #"(setTransientErrorMessage|reportTransientError)\(\s*"|transientErrorMessage\s*=\s*""# + ) + let enumerator = try XCTUnwrap(FileManager.default.enumerator(at: appDirectory, includingPropertiesForKeys: nil)) + var scanned = 0 + for case let file as URL in enumerator where file.pathExtension == "swift" { + scanned += 1 + let text = try String(contentsOf: file, encoding: .utf8) + let range = NSRange(text.startIndex..., in: text) + for match in pattern.matches(in: text, range: range) { + let line = text.prefix(match.range.location).filter { $0 == "\n" }.count + 1 + XCTFail("\(file.lastPathComponent):\(line) passes a bare string literal to the alert; wrap it in String(localized:bundle:)") + } + } + XCTAssertGreaterThan(scanned, 5, "The scan found no coordinator files") + } + + @MainActor + func testProfileValidationMessagesResolveToGerman() throws { + let german = try germanAppBundle() + let harness = AppStateHarness() + let resolver = BookmarkPathResolver( + preferencesStore: harness.preferencesStore, + folderAccessService: harness.folderAccessService + ) + var messages: [String] = [] + let coordinator = SetupCoordinator( + preferencesStore: harness.preferencesStore, + setupStore: harness.setupStore, + historyStore: harness.historyStore, + folderAccessService: harness.folderAccessService, + profilesRepository: harness.repository, + droppedItemStager: DroppedItemStager(), + bookmarkPathResolver: resolver, + navigate: { _ in }, + setTransientErrorMessage: { if let message = $0 { messages.append(message) } } + ) + + coordinator.saveCurrentPathsAsProfile() + harness.setupStore.newProfileName = "travel" + coordinator.saveCurrentPathsAsProfile() + + XCTAssertEqual(messages.count, 2) + for message in messages { + XCTAssertNotEqual(AppLocalization.string(message, bundle: german), message, message) + } + } +} From 6977a5c239ceb5549350b4377374276c2f37ff1d Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:43:02 -0800 Subject: [PATCH 05/10] Dedupe: pair fan-out never reaches an unreviewed group; stale Undo is discarded INV-14. The commit plan is built from reviewed groups only, so a RAW or Live Photo partner that belongs to a group the person has not reviewed had no decision in the plan and was added by pair fan-out, while its own group still showed it as kept. The planner takes fanoutProtectedPaths and skips those partners; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. Planning over all groups is unchanged, and the change only ever removes items from a plan. Undo closures captured one scan's decisions and group IDs but survived Scan Again, so an Undo could wipe a restored review and delete its saved file. The store now discards its own undo actions when a scan starts, on reset, and when a commit completes. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 2 +- DECISIONS.md | 8 ++ .../Stores/DeduplicateSessionStore.swift | 25 +++- .../DeduplicationPlanner.swift | 8 +- .../FreeDedupeBatchPlanner.swift | 7 +- ...frameCoreFreeDedupeBatchPlannerTests.swift | 42 +++++- .../DeduplicateReviewPersistenceTests.swift | 96 ++++++++++++++ .../DeduplicateSessionStoreTests.swift | 82 ++++++++++++ .../DeduplicationPlannerGroupRailTests.swift | 120 +++++++++++++++++- .../DeduplicationPlannerPropertyTests.swift | 38 ++++++ 10 files changed, 419 insertions(+), 9 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index f6795489..24d9af6b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ Do not weaken these unless the user explicitly asks for a product change. - **INV-11:** Failure thresholds intentionally stop bad runs: 5 consecutive failures or 20 total failures. - **INV-12:** Deduplicate moves files to the macOS Trash only. Hard delete is not available in the production UI or executor commit path. - **INV-13:** The dedupe audit receipt directory (`.organize_logs/`) is preflighted before any deletion. An unwritable destination aborts the commit with `ReceiptPreflightError` and zero files touched. -- **INV-14:** Pair-as-unit conflict resolution is **Keep-wins**: when either half of a RAW+JPEG or Live Photo HEIC+MOV pair has an effective Keep — explicit, automatic (the cluster's auto-suggested keeper), or implicit (default-Keep in an unreviewed low/medium-confidence cluster) — neither half is deleted. Pair-fanout deletes a partner only when that partner is itself marked Delete, auto-selected for Delete by a high-confidence cluster, or is a singleton outside any cluster. Metadata sidecars (`.xmp`, and `.aae` edit instructions, including the iPhone form where `IMG_.` owns `IMG_E.aae` in the same folder with exactly the same digits) extend this rule: a sidecar travels with its parent photo as a unit and is trashed only when **every** photo that references it is also being deleted (and no surviving pair partner shares its basename). A sidecar shared across a basename unit — `photo.xmp` applies to both `photo.raw` and `photo.jpg` — survives if any owner is kept. +- **INV-14:** Pair-as-unit conflict resolution is **Keep-wins**: when either half of a RAW+JPEG or Live Photo HEIC+MOV pair has an effective Keep — explicit, automatic (the cluster's auto-suggested keeper), or implicit (default-Keep in an unreviewed low/medium-confidence cluster) — neither half is deleted. Pair-fanout deletes a partner only when that partner is itself marked Delete, auto-selected for Delete by a high-confidence cluster, or is a singleton outside any cluster. When a plan is built from reviewed groups only, a partner that belongs to a group not yet reviewed is never added by fan-out; its own group decides once it is reviewed. Metadata sidecars (`.xmp`, and `.aae` edit instructions, including the iPhone form where `IMG_.` owns `IMG_E.aae` in the same folder with exactly the same digits) extend this rule: a sidecar travels with its parent photo as a unit and is trashed only when **every** photo that references it is also being deleted (and no surviving pair partner shares its basename). A sidecar shared across a basename unit — `photo.xmp` applies to both `photo.raw` and `photo.jpg` — survives if any owner is kept. - **INV-15:** Organize and dedupe traversal must not follow symlinks or aliases by default. Skip symlink files/directories, app bundles, photo libraries, packages, hidden system-like containers, and any path that escapes the selected root. - **INV-16:** Fast destination scans are validating scans: cached records are trusted only when the file still exists and size/mtime still match; stale cache rows are refreshed or removed. - **INV-17:** Dedupe mutation plans are immutable content-verified snapshots. The planner never reads live filesystem identity; missing target hashes fail closed and exclude that path from deletion. diff --git a/DECISIONS.md b/DECISIONS.md index e4e34633..0c41070b 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -1,5 +1,13 @@ # Decisions +## Release 2.1 bug sweep (2026-11-29) + +- Pair fan-out and unreviewed groups (INV-14, approved by the sweep brief, not yet read by the owner): the commit plan is built from reviewed groups only, so a RAW or Live Photo partner sitting in an unreviewed group had no decision and was added to the plan while its own group showed it as kept. The planner now takes `fanoutProtectedPaths`; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. A held-back partner stays until its own group is reviewed, which can leave a RAW without its JPEG. Planning over all groups is unchanged. +- Undo history in Deduplicate is discarded when a scan starts, on reset, and when a commit completes, so an Undo from an earlier scan cannot rewrite a restored review. +- The unlock sheet's Return key takes the free action whenever one is offered, even where the action list puts Buy first. +- A count of 1 on the dedupe unlock button reads "Unlock to Remove 1 Duplicate" (implementer's wording). +- Not built, needs a design decision: skipping a companion whose owner failed verification (edit preservation B-2, item 3). Copy jobs carry no owner link and owner and companion can be prepared in the same concurrent batch. + ## German translation import (2026-11-15) - Merge only German translations for existing keys from `/Users/nishithnand/Downloads/Translation DE`; preserve current keys, English, other languages and extraction metadata. The supplied catalogs predate newer app copy, which continues to fall back to English. Omit the unused incoming `%d duplicates found` key. diff --git a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift index 9845eb2b..5f4948cb 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift @@ -88,6 +88,11 @@ public final class DeduplicateSessionStore: ObservableObject { } } + /// Undo closures capture one scan's decisions and group IDs; they must not outlive it. + private func discardUndoHistory() { + undoManager?.removeAllActions(withTarget: self) + } + private let engine: any DeduplicateEngine private let runHistoryStore: any DeduplicateRunHistoryStoring private var streamTask: Task? @@ -185,6 +190,13 @@ public final class DeduplicateSessionStore: ObservableObject { clusters.filter { approvedClusterIDs.contains($0.id) } } + /// Members of groups the person has not reviewed. A reviewed group's pair + /// fan-out never reaches them: their own group decides when it is reviewed. + private var unreviewedMemberPaths: Set { + let approved = approvedClusterIDs + return Set(clusters.lazy.filter { !approved.contains($0.id) }.flatMap { $0.members.lazy.map(\.path) }) + } + /// Deletion plan scoped to reviewed clusters only. public func reviewedDeletionPlan() -> DeduplicationPlan { guard let configuration = lastScanConfiguration else { @@ -194,7 +206,8 @@ public final class DeduplicateSessionStore: ObservableObject { decisions: decisions, clusters: reviewedClusters, configuration: configuration, - snapshot: summary?.scanSnapshot ?? DeduplicateScanSnapshot() + snapshot: summary?.scanSnapshot ?? DeduplicateScanSnapshot(), + fanoutProtectedPaths: unreviewedMemberPaths ) } @@ -245,6 +258,7 @@ public final class DeduplicateSessionStore: ObservableObject { reviewedClusters: reviewedClusters, configuration: configuration, snapshot: summary?.scanSnapshot ?? DeduplicateScanSnapshot(), + fanoutProtectedPaths: unreviewedMemberPaths, limit: remaining ) freeBatchOfferCache = (decisions, approvedClusterIDs, remaining, offer) @@ -376,6 +390,7 @@ public final class DeduplicateSessionStore: ObservableObject { ) { flushPendingReviewSave() cancelStream() + discardUndoHistory() self.securityScope = securityScope clusters = [] summary = nil @@ -628,6 +643,7 @@ public final class DeduplicateSessionStore: ObservableObject { reviewHasUserChanges = false engine.cancelCurrentScan() cancelStream() + discardUndoHistory() clusters = [] summary = nil preparedCommitPlan = nil @@ -813,6 +829,7 @@ public final class DeduplicateSessionStore: ObservableObject { // no per-item path attached. issues.append(DeduplicateIssue(severity: .error, message: message)) case let .complete(summary): + discardUndoHistory() commitSummary = summary if !isHandlingRevert, let destinationPath = activeCommitConfiguration?.destinationPath { runHistory = runHistoryStore.recordRun( @@ -847,11 +864,15 @@ public final class DeduplicateSessionStore: ObservableObject { var result: [DeduplicateReviewLane: DeduplicateLaneSummary] = [:] for lane in DeduplicateReviewLane.allCases { let laneClusters = unreviewedByLane[lane] ?? [] + // Accepting this lane leaves the other lanes unreviewed, so fan-out + // from here cannot reach their files. + let otherLanePaths = Set(unreviewedByLane.filter { $0.key != lane }.values.flatMap { $0.flatMap { $0.members.map(\.path) } }) let plan = DeduplicationPlanner.plan( decisions: suggestedDecisions(for: laneClusters), clusters: laneClusters, configuration: configuration, - snapshot: snapshot + snapshot: snapshot, + fanoutProtectedPaths: otherLanePaths ) result[lane] = DeduplicateLaneSummary(groups: laneClusters.count, files: plan.count, bytes: plan.totalBytes) } diff --git a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift index 49aa62ed..c7cd5ce3 100644 --- a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift +++ b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift @@ -22,12 +22,15 @@ import Foundation /// RAW pairing no longer accidentally leaves Live Photo pairing's /// expansion untouched, and vice versa. Partner inherits its /// triggering member's cluster ownership so the receipt is complete. +/// A partner listed in `fanoutProtectedPaths` (members of groups the +/// caller did not pass because they are not reviewed) is never added. public enum DeduplicationPlanner { public static func plan( decisions: DedupeDecisions, clusters: [DuplicateCluster], configuration: DeduplicateConfiguration, - snapshot: DeduplicateScanSnapshot + snapshot: DeduplicateScanSnapshot, + fanoutProtectedPaths: Set = [] ) -> DeduplicationPlan { // 1. Effective decision per cluster member. struct Effective { @@ -161,6 +164,9 @@ public enum DeduplicationPlanner { continue } if railProtectedPaths.contains(partner) { continue } + // A partner that belongs to a group nobody has reviewed stays; + // its own group decides its fate once it is reviewed. + if fanoutProtectedPaths.contains(partner) { continue } // INV-31: pair fanout never adds an edited variant. A partner // outside every cluster carries no scanner flag, so the file // name convention is the fail-closed fallback. diff --git a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift index 43b7a48c..d057891d 100644 --- a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift +++ b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift @@ -19,6 +19,7 @@ public enum FreeDedupeBatchPlanner { reviewedClusters: [DuplicateCluster], configuration: DeduplicateConfiguration, snapshot: DeduplicateScanSnapshot, + fanoutProtectedPaths: Set, limit: Int ) -> FreeDedupeBatch? { // 1. The person's full reviewed plan. @@ -26,7 +27,8 @@ public enum FreeDedupeBatchPlanner { decisions: decisions, clusters: reviewedClusters, configuration: configuration, - snapshot: snapshot + snapshot: snapshot, + fanoutProtectedPaths: fanoutProtectedPaths ) guard limit > 0, full.count > limit else { return nil } let fullIdentities = Dictionary( @@ -68,7 +70,8 @@ public enum FreeDedupeBatchPlanner { decisions: candidateDecisions, clusters: reviewedClusters, configuration: configuration, - snapshot: snapshot + snapshot: snapshot, + fanoutProtectedPaths: fanoutProtectedPaths ) let withinFullPlan = candidate.items.allSatisfy { item in fullIdentities[item.path] == item.expectedIdentity diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift index 2aafe4e7..5f6a6316 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift @@ -237,6 +237,42 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { XCTAssertFalse(batch.plan.items.contains { $0.path == "/fx/a/d1.mov" }) } + // AGENTS-INVARIANT: 14 + func testBatchNeverFansOutIntoAnUnreviewedGroup() throws { + var fixture = Fixture() + // The reviewed group holds a/X.jpg (Keep) and b/X.jpg (Delete). Each JPEG pairs with a + // DNG; the DNGs form a group nobody has reviewed, and b/X.dng is its suggested keeper. + fixture.addGroup("r", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/a/X.jpg" + members[0].pairedPath = "/fx/a/X.dng" + members[1].path = "/fx/b/X.jpg" + members[1].pairedPath = "/fx/b/X.dng" + } + fixture.addGroup("other", deletes: 2, lane: .lookAtEach) + fixture.fanoutProtectedPaths = ["/fx/a/X.dng", "/fx/b/X.dng"] + + // Premise: unprotected, the keeper follows its pair partner into the plan. + let unprotected = DeduplicationPlanner.plan( + decisions: fixture.decisions, + clusters: fixture.clusters, + configuration: fixture.configuration, + snapshot: fixture.snapshot + ) + XCTAssertTrue(unprotected.items.contains { $0.path == "/fx/b/X.dng" }) + + let full = fixture.fullPlan() + XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/b/X.jpg", "/fx/other/d1.jpg", "/fx/other/d2.jpg"]) + + // Every batch item is in the full plan with the same identity, and none is the keeper. + let batch = try XCTUnwrap(fixture.batch(limit: 2)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/b/X.jpg"]) + XCTAssertFalse(batch.plan.items.contains { $0.path == "/fx/b/X.dng" }) + let fullIdentities = Dictionary(uniqueKeysWithValues: full.items.map { ($0.path, $0.expectedIdentity) }) + for item in batch.plan.items { + XCTAssertEqual(fullIdentities[item.path], item.expectedIdentity) + } + } + func testForcedKeepThatWouldUnskipAGroupStopsTheWalk() { var fixture = Fixture() // Group Y: y1 and y2 are both Delete (the planner's rail skips Y), and y1 is @@ -359,6 +395,8 @@ private struct Fixture { var clusters: [DuplicateCluster] = [] var decisions = DedupeDecisions() var sidecarOwners: [String: Set] = [:] + /// Members of groups the person has not reviewed. + var fanoutProtectedPaths: Set = [] var configuration = DeduplicateConfiguration( destinationPath: "/fx", timeWindowSeconds: 30, @@ -430,7 +468,8 @@ private struct Fixture { decisions: decisions, clusters: clusters, configuration: configuration, - snapshot: snapshot + snapshot: snapshot, + fanoutProtectedPaths: fanoutProtectedPaths ) } @@ -440,6 +479,7 @@ private struct Fixture { reviewedClusters: clusters, configuration: configuration, snapshot: snapshot, + fanoutProtectedPaths: fanoutProtectedPaths, limit: limit ) } diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateReviewPersistenceTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateReviewPersistenceTests.swift index 358694a2..0c70df0f 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateReviewPersistenceTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateReviewPersistenceTests.swift @@ -392,6 +392,102 @@ final class DeduplicateReviewPersistenceTests: XCTestCase { XCTAssertEqual(snapshotStore.saves.count, 2, "Nothing is under review, so undo has nothing to save.") } + @MainActor + func testUndoFromAnEarlierScanCannotChangeARestoredReview() { + // Synchronous on purpose: UndoManager inside an async XCTest method + // crashes the Swift task allocator. The run loop is pumped instead. + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let store = makeStore( + engine: MockDeduplicateEngine(clusters: [cluster]), + snapshotStore: snapshotStore, + debounce: shortDebounce + ) + let undoManager = UndoManager() + undoManager.groupsByEvent = false + store.undoManager = undoManager + store.startScan(configuration: configuration) + XCTAssertTrue(pump { store.status == .readyToReview }) + undoManager.beginUndoGrouping() + store.setDecision(.keep, forPath: file2.path) + undoManager.endUndoGrouping() + XCTAssertTrue(pump { snapshotStore.saves.count == 1 }) + + // Scan Again restores that review. + store.startScan(configuration: configuration) + XCTAssertTrue(pump { store.status == .readyToReview }) + XCTAssertEqual(store.approvedClusterIDs, [clusterID], "premise: the saved review came back") + XCTAssertEqual(store.decisions.byPath[file2.path], .keep) + let savesBefore = snapshotStore.saves.count + + // The earlier scan's undo must not apply to this review. + if undoManager.canUndo { undoManager.undo() } + _ = pump(timeout: 0.3) { false } + + XCTAssertEqual(store.approvedClusterIDs, [clusterID], "A stale undo must not empty the restored approvals.") + XCTAssertEqual(store.decisions.byPath[file2.path], .keep) + XCTAssertEqual(snapshotStore.saves.count, savesBefore, "A stale undo must not overwrite the saved review.") + } + + @MainActor + func testUndoAfterACommitCompletesCannotChangeTheFinishedReview() { + let engine = MockDeduplicateEngine( + clusters: [cluster], + commitEvents: [ + .complete(DeduplicateCommitSummary( + deletedCount: 1, + failedCount: 0, + bytesReclaimed: 100, + receiptPath: "/dest/.organize_logs/dedupe_audit_receipt.json", + hardDelete: false + )), + ] + ) + let store = makeStore( + engine: engine, + snapshotStore: InMemoryDeduplicateReviewSnapshotStore(), + debounce: longDebounce + ) + let undoManager = UndoManager() + undoManager.groupsByEvent = false + store.undoManager = undoManager + store.startScan(configuration: configuration) + XCTAssertTrue(pump { store.status == .readyToReview }) + undoManager.beginUndoGrouping() + store.setDecision(.delete, forPath: file2.path) + undoManager.endUndoGrouping() + XCTAssertEqual(store.approvedClusterIDs, [clusterID]) + + store.commitReviewed(configuration: configuration) + XCTAssertTrue(pump { store.status == .completed }) + + if undoManager.canUndo { undoManager.undo() } + + XCTAssertEqual(store.approvedClusterIDs, [clusterID], "The finished review is not editable by undo.") + } + + @MainActor + func testUndoAfterResetHasNothingToApply() { + let store = makeStore( + engine: MockDeduplicateEngine(clusters: [cluster]), + snapshotStore: InMemoryDeduplicateReviewSnapshotStore(), + debounce: longDebounce + ) + let undoManager = UndoManager() + undoManager.groupsByEvent = false + store.undoManager = undoManager + store.startScan(configuration: configuration) + XCTAssertTrue(pump { store.status == .readyToReview }) + undoManager.beginUndoGrouping() + store.setDecision(.keep, forPath: file2.path) + undoManager.endUndoGrouping() + + store.reset() + if undoManager.canUndo { undoManager.undo() } + + XCTAssertTrue(store.decisions.byPath.isEmpty, "A reset review is not rebuilt by undo.") + XCTAssertTrue(store.approvedClusterIDs.isEmpty) + } + // MARK: - Restoring // AGENTS-INVARIANT: 29 diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift index 04dd2c4c..d99147fd 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift @@ -1351,6 +1351,88 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.laneSummaries[.lookAtEach], DeduplicateLaneSummary(groups: 1, files: 3, bytes: 300)) } + /// Two folders each hold X.jpg and X.dng. The JPEG group is exact (keeper a/X.jpg); the DNG + /// group is nearly identical (suggested keeper b/X.dng). The JPEGs pair with the DNGs. + private func jpegAndDngGroups() -> (jpegs: DuplicateCluster, dngs: DuplicateCluster) { + func candidate(_ path: String, isRaw: Bool, paired: String) -> PhotoCandidate { + PhotoCandidate(path: path, size: 100, modificationTime: 0, isRaw: isRaw, pairedPath: paired) + } + let jpegMembers = [ + candidate("/dest/a/X.jpg", isRaw: false, paired: "/dest/a/X.dng"), + candidate("/dest/b/X.jpg", isRaw: false, paired: "/dest/b/X.dng"), + ] + let dngMembers = [ + candidate("/dest/b/X.dng", isRaw: true, paired: "/dest/b/X.jpg"), + candidate("/dest/a/X.dng", isRaw: true, paired: "/dest/a/X.jpg"), + ] + func group(_ members: [PhotoCandidate], kind: ClusterKind) -> DuplicateCluster { + DuplicateCluster( + kind: kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 100, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: kind)) + ) + } + return (group(jpegMembers, kind: .exactDuplicate), group(dngMembers, kind: .nearDuplicate)) + } + + /// Pair fan-out from a reviewed group must not trash a file that an unreviewed group + /// still shows as its keeper. The reviewed plan, the frozen commit plan and the free + /// batch all take the same protection. + @MainActor + // AGENTS-INVARIANT: 14 + func testReviewedPlanNeverFansOutIntoAnUnreviewedGroup() async throws { + let (jpegs, dngs) = jpegAndDngGroups() + let other = laneCluster("other", lane: .lookAtEach, deletes: 2) + let (store, engine) = await scannedLaneStore([jpegs, dngs, other]) + store.setDecision(.keep, forPath: "/dest/a/X.jpg") + store.setDecision(.delete, forPath: "/dest/b/X.jpg") + store.setDecision(.delete, forPath: "/dest/other/d1.jpg") + store.setDecision(.delete, forPath: "/dest/other/d2.jpg") + XCTAssertEqual(store.approvedClusterIDs, [jpegs.id, other.id], "premise: the DNG group is unreviewed") + + let expected: Set = ["/dest/b/X.jpg", "/dest/other/d1.jpg", "/dest/other/d2.jpg"] + XCTAssertEqual(Set(store.reviewedDeletionPlan().items.map(\.path)), expected) + let frozen = store.prepareReviewedCommitPlan() + XCTAssertEqual(Set(frozen.items.map(\.path)), expected) + XCTAssertEqual(store.preparedCommitPlan, frozen, "the plan shown is the plan frozen") + + // The free batch (allowance 2) is a slice of that same plan and never includes the keeper. + let offer = try XCTUnwrap(store.freeBatchOffer(remaining: 2)) + XCTAssertEqual(offer.plan.items.map(\.path), ["/dest/b/X.jpg"]) + + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let committed = await waitForCondition { engine.lastCommitPlan != nil } + XCTAssertTrue(committed) + XCTAssertEqual(Set(engine.lastCommitPlan?.items.map(\.path) ?? []), expected) + + // Premise: unprotected, the DNG keeper rides along with its JPEG. + let unprotected = DeduplicationPlanner.plan( + decisions: store.decisions, + clusters: [jpegs, other], + configuration: DeduplicateConfiguration(destinationPath: "/dest"), + snapshot: engine.summary.scanSnapshot + ) + XCTAssertTrue(unprotected.items.contains { $0.path == "/dest/b/X.dng" }) + } + + /// The count a lane card shows is what accepting the lane would plan, so it holds back + /// files that belong to the other, still unreviewed lanes. + @MainActor + // AGENTS-INVARIANT: 14 + func testLaneSummaryHoldsBackFilesOfOtherUnreviewedLanes() async throws { + let (jpegs, dngs) = jpegAndDngGroups() + let (store, _) = await scannedLaneStore([jpegs, dngs]) + XCTAssertEqual(store.lane(for: jpegs), .identical) + XCTAssertEqual(store.lane(for: dngs), .nearlyIdentical) + + // Accepting the JPEG lane removes b/X.jpg only; b/X.dng is the DNG group's keeper. + XCTAssertEqual(store.laneSummaries[.identical], DeduplicateLaneSummary(groups: 1, files: 1, bytes: 100)) + // Accepting the DNG lane removes a/X.dng only; a/X.jpg is the JPEG group's keeper. + XCTAssertEqual(store.laneSummaries[.nearlyIdentical], DeduplicateLaneSummary(groups: 1, files: 1, bytes: 100)) + } + @MainActor func testLaneSummariesUpdateAfterAccept() async throws { let same = laneCluster("same", lane: .identical, deletes: 2) diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift index 59dfdafc..3cb6d00f 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift @@ -108,10 +108,126 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { XCTAssertEqual(Set(plan.items.map(\.path)), [rawB.path, jpegB.path]) } + // MARK: Pair fan-out and groups nobody has reviewed + + // AGENTS-INVARIANT: 14 + func testPairFanoutNeverReachesAMemberOfAnUnreviewedGroup() { + // Two folders each hold X.jpg and X.dng. The person approved the JPEG + // group only; the DNG group has not been looked at and its suggested + // keeper is b/X.dng. + let jpegA = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") + let jpegB = candidate("/lib/b/X.jpg", pairedPath: "/lib/b/X.dng") + let dngA = candidate("/lib/a/X.dng", isRaw: true, pairedPath: "/lib/a/X.jpg") + let dngB = candidate("/lib/b/X.dng", isRaw: true, pairedPath: "/lib/b/X.jpg") + let reviewed = cluster([jpegA, jpegB]) + let unreviewed = cluster([dngB, dngA]) + let decisions = DedupeDecisions(byPath: [jpegA.path: .keep, jpegB.path: .delete]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [reviewed], + configuration: configuration(), + snapshot: testScanSnapshot(for: [reviewed]), + fanoutProtectedPaths: Set(unreviewed.members.map(\.path)) + ) + + XCTAssertEqual(plan.items.map(\.path), [jpegB.path], "b/X.dng is the unreviewed group's keeper and must stay") + + // Premise: without the protected set the keeper follows its pair partner into the plan. + let unprotected = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [reviewed], + configuration: configuration(), + snapshot: testScanSnapshot(for: [reviewed]) + ) + XCTAssertEqual(Set(unprotected.items.map(\.path)), [jpegB.path, dngB.path]) + } + + // AGENTS-INVARIANT: 14 + func testLivePhotoFanoutNeverReachesAMemberOfAnUnreviewedGroup() { + let stillA = candidate("/lib/a/IMG_1.HEIC", pairedPath: "/lib/a/IMG_1.MOV", isLivePhotoStill: true) + let stillB = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let movieA = candidate("/lib/a/IMG_1.MOV", pairedPath: "/lib/a/IMG_1.HEIC") + let movieB = candidate("/lib/b/IMG_1.MOV", pairedPath: "/lib/b/IMG_1.HEIC") + let reviewed = cluster([stillA, stillB]) + let unreviewed = cluster([movieB, movieA]) + let decisions = DedupeDecisions(byPath: [stillA.path: .keep, stillB.path: .delete]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [reviewed], + configuration: configuration(), + snapshot: testScanSnapshot(for: [reviewed]), + fanoutProtectedPaths: Set(unreviewed.members.map(\.path)) + ) + + XCTAssertEqual(plan.items.map(\.path), [stillB.path], "the unreviewed group's movie must stay") + + let unprotected = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [reviewed], + configuration: configuration(), + snapshot: testScanSnapshot(for: [reviewed]) + ) + XCTAssertEqual(Set(unprotected.items.map(\.path)), [stillB.path, movieB.path]) + } + + // AGENTS-INVARIANT: 14 + func testPairPartnerInNoGroupStillFansOut() { + // Only the protected paths are shielded; a true singleton partner is unchanged behaviour. + let jpegA = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") + let jpegB = candidate("/lib/b/X.jpg", pairedPath: "/lib/b/X.dng") + let reviewed = cluster([jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [jpegA.path: .keep, jpegB.path: .delete]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [reviewed], + configuration: configuration(), + snapshot: testScanSnapshot(for: [reviewed]), + fanoutProtectedPaths: ["/lib/c/unrelated.dng"] + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [jpegB.path, "/lib/b/X.dng"]) + } + + // AGENTS-INVARIANT: 14 + func testReviewingBothGroupsKeepsKeepWinsForTheSamePair() { + let jpegA = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") + let jpegB = candidate("/lib/b/X.jpg", pairedPath: "/lib/b/X.dng") + let dngA = candidate("/lib/a/X.dng", isRaw: true, pairedPath: "/lib/a/X.jpg") + let dngB = candidate("/lib/b/X.dng", isRaw: true, pairedPath: "/lib/b/X.jpg") + let jpegs = cluster([jpegA, jpegB]) + let dngs = cluster([dngB, dngA]) + let decisions = DedupeDecisions(byPath: [jpegA.path: .keep, jpegB.path: .delete]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [jpegs, dngs], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, dngs]) + ) + + // b/X.dng is kept by its own group, so Keep-wins keeps b/X.jpg; a/X.jpg's Keep keeps a/X.dng. + XCTAssertEqual(plan.items.map(\.path), []) + } + // MARK: Helpers - private func candidate(_ path: String, isRaw: Bool = false, pairedPath: String? = nil) -> PhotoCandidate { - PhotoCandidate(path: path, size: 1_000, modificationTime: 0, isRaw: isRaw, pairedPath: pairedPath) + private func candidate( + _ path: String, + isRaw: Bool = false, + pairedPath: String? = nil, + isLivePhotoStill: Bool = false + ) -> PhotoCandidate { + PhotoCandidate( + path: path, + size: 1_000, + modificationTime: 0, + isRaw: isRaw, + isLivePhotoStill: isLivePhotoStill, + pairedPath: pairedPath + ) } private func cluster(_ members: [PhotoCandidate], kind: ClusterKind = .exactDuplicate) -> DuplicateCluster { diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift index 9833fc22..2015237c 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift @@ -142,6 +142,44 @@ final class DeduplicationPlannerPropertyTests: XCTestCase { } } + /// Only some groups are reviewed (as in the app's reviewed plan). Pairs cross + /// reviewed and unreviewed groups; pair fan-out must never reach a file that + /// only an unreviewed group lists. Direct deletes of a reviewed group's own + /// members are unchanged. + // AGENTS-INVARIANT: 14 + func testPropertyFanoutNeverReachesAnUnreviewedGroupsMember() { + var prng = SeededPRNG(seed: 0x0A11_E0F1_A5ED_F00D) + var exercisedCrossPairs = 0 + for iteration in 0..<(Self.iterations * 4) { + let scenario = randomScenario(prng: &prng, crossClusterStructure: true) + let reviewed = scenario.clusters.filter { _ in prng.bool() } + let reviewedIDs = Set(reviewed.map(\.id)) + let reviewedPaths = Set(reviewed.flatMap { $0.members.map(\.path) }) + let protectedPaths = Set( + scenario.clusters.filter { !reviewedIDs.contains($0.id) }.flatMap { $0.members.map(\.path) } + ) + let plan = DeduplicationPlanner.plan( + decisions: scenario.decisions, + clusters: reviewed, + configuration: scenario.configuration, + snapshot: testScanSnapshot(for: scenario.clusters), + fanoutProtectedPaths: protectedPaths + ) + for item in plan.items where !reviewedPaths.contains(item.path) { + XCTAssertFalse( + protectedPaths.contains(item.path), + "iteration \(iteration): \(item.path) belongs to an unreviewed group but was planned (origin \(String(describing: item.pairOrigin)))" + ) + } + exercisedCrossPairs += reviewed.reduce(0) { total, cluster in + total + cluster.members.filter { member in + member.pairedPath.map { protectedPaths.contains($0) && !reviewedPaths.contains($0) } ?? false + }.count + } + } + XCTAssertGreaterThan(exercisedCrossPairs, 50, "the generator must build pairs across reviewed and unreviewed groups") + } + /// Per-pair-kind toggles are independent. /// AGENTS.md: "disabling RAW pairing must not affect Live Photo /// behaviour and vice versa." From c3f3a8d39896bba85d72455a27cf0697ea4ef908 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:43:31 -0800 Subject: [PATCH 06/10] Companions: index owners per folder instead of scanning it for each sidecar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CompanionResolver.resolve compared every sidecar with every media file in its folder, so a flat folder of N photos and N sidecars cost N² name comparisons on every preview. Each folder's media is now indexed once by stem, full name and IMG_ digits. Results are unchanged: a seeded equivalence test compares the index with the previous per-pair logic, and 20,000 photos with 20,000 sidecars resolve in about 0.2 s. Co-Authored-By: Claude Fable 5.2 --- .../ChronoframeCore/CompanionResolver.swift | 47 +++- .../CompanionResolverTests.swift | 207 ++++++++++++++++++ 2 files changed, 249 insertions(+), 5 deletions(-) diff --git a/ui/Sources/ChronoframeCore/CompanionResolver.swift b/ui/Sources/ChronoframeCore/CompanionResolver.swift index fff0517e..48ba2810 100644 --- a/ui/Sources/ChronoframeCore/CompanionResolver.swift +++ b/ui/Sources/ChronoframeCore/CompanionResolver.swift @@ -70,13 +70,52 @@ public enum CompanionResolver { case appended } + /// One directory's media files, indexed by the names a companion can use + /// to claim them, so each companion is a few lookups rather than a scan of + /// the folder. Must agree with `nameForm` (the rules, not this index, are + /// the source of truth; `CompanionResolverTests` compares the two). + private struct OwnerIndex { + private var byStem: [String: Set] = [:] + private var byFullName: [String: Set] = [:] + /// `IMG_` stems by what follows `img_`, for the iOS edit form. + private var byImageDigits: [String: Set] = [:] + + mutating func insert(_ path: String) { + let url = URL(fileURLWithPath: path) + let stem = url.deletingPathExtension().lastPathComponent.lowercased() + byStem[stem, default: []].insert(path) + byFullName[url.lastPathComponent.lowercased(), default: []].insert(path) + if stem.hasPrefix("img_") { + byImageDigits[String(stem.dropFirst(4)), default: []].insert(path) + } + } + + func owners(of companion: String) -> Set { + let base = URL(fileURLWithPath: companion).deletingPathExtension().lastPathComponent.lowercased() + var result = byStem[base] ?? [] + if let appended = byFullName[base] { + result.formUnion(appended) + } + if MediaLibraryRules.normalizedExtension(for: companion) == ".aae", + base.hasPrefix("img_e") { + let digits = base.dropFirst(5) + if !digits.isEmpty, + digits.allSatisfy({ $0.isASCII && $0.isNumber }), + let edited = byImageDigits[String(digits)] { + result.formUnion(edited) + } + } + return result + } + } + /// Resolves each companion to the single media file that owns it. /// Eligible owners are only the paths in `mediaPaths`, in the same /// directory; names compare case-insensitively. public static func resolve(companionPaths: [String], mediaPaths: [String]) -> Resolution { - var mediaByDirectory: [String: [String]] = [:] + var indexByDirectory: [String: OwnerIndex] = [:] for path in mediaPaths { - mediaByDirectory[directory(of: path), default: []].append(path) + indexByDirectory[directory(of: path), default: OwnerIndex()].insert(path) } var owners: [String: String] = [:] @@ -84,9 +123,7 @@ public enum CompanionResolver { var seen = Set() for companion in companionPaths where seen.insert(companion).inserted { - let eligible = Set((mediaByDirectory[directory(of: companion)] ?? []).filter { - nameForm(companion: companion, owner: $0) != nil - }) + let eligible = indexByDirectory[directory(of: companion)]?.owners(of: companion) ?? [] if eligible.count == 1, let owner = eligible.first { owners[companion] = owner } else { diff --git a/ui/Tests/ChronoframeAppCoreTests/CompanionResolverTests.swift b/ui/Tests/ChronoframeAppCoreTests/CompanionResolverTests.swift index e0641c64..5fcc5891 100644 --- a/ui/Tests/ChronoframeAppCoreTests/CompanionResolverTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/CompanionResolverTests.swift @@ -224,4 +224,211 @@ final class CompanionResolverTests: XCTestCase { XCTAssertEqual(single.transfers.map(\.destinationPath), ["/dst/2026/04/19/2026-04-19_001.xmp"]) XCTAssertEqual(single.unresolved, [UnresolvedCompanion(sourcePath: "/src/IMG_2.xmp", reason: .unreadable)]) } + + // MARK: - Indexed resolution equivalence and scale + + /// The pre-index brute-force implementation, kept verbatim as the oracle + /// for `testIndexedResolveMatchesBruteForceReference`. + private enum ReferenceForm { case stem, appended } + + private static func referenceDirectory(of path: String) -> String { + URL(fileURLWithPath: path).deletingLastPathComponent().path + } + + private static func referenceNameForm(companion: String, owner: String) -> ReferenceForm? { + let companionURL = URL(fileURLWithPath: companion) + let ownerURL = URL(fileURLWithPath: owner) + let companionBase = companionURL.deletingPathExtension().lastPathComponent.lowercased() + let ownerStem = ownerURL.deletingPathExtension().lastPathComponent.lowercased() + let ownerFullName = ownerURL.lastPathComponent.lowercased() + + if companionBase == ownerStem { return .stem } + if companionBase == ownerFullName { return .appended } + + if MediaLibraryRules.normalizedExtension(for: companion) == ".aae", + companionBase.hasPrefix("img_e"), + ownerStem.hasPrefix("img_") { + let companionDigits = companionBase.dropFirst(5) + let ownerDigits = ownerStem.dropFirst(4) + if !companionDigits.isEmpty, + companionDigits == ownerDigits, + companionDigits.allSatisfy({ $0.isASCII && $0.isNumber }) { + return .stem + } + } + return nil + } + + private static func referenceResolve( + companionPaths: [String], + mediaPaths: [String] + ) -> CompanionResolver.Resolution { + var mediaByDirectory: [String: [String]] = [:] + for path in mediaPaths { + mediaByDirectory[referenceDirectory(of: path), default: []].append(path) + } + + var owners: [String: String] = [:] + var unresolved: [UnresolvedCompanion] = [] + var seen = Set() + + for companion in companionPaths where seen.insert(companion).inserted { + let eligible = Set((mediaByDirectory[referenceDirectory(of: companion)] ?? []).filter { + referenceNameForm(companion: companion, owner: $0) != nil + }) + if eligible.count == 1, let owner = eligible.first { + owners[companion] = owner + } else { + unresolved.append(UnresolvedCompanion( + sourcePath: companion, + reason: eligible.isEmpty ? .noOwner : .multipleOwners + )) + } + } + + return CompanionResolver.Resolution( + ownersByCompanion: owners, + unresolved: unresolved.sorted { $0.sourcePath < $1.sourcePath } + ) + } + + private struct SplitMix64: RandomNumberGenerator { + var state: UInt64 + mutating func next() -> UInt64 { + state &+= 0x9E37_79B9_7F4A_7C15 + var z = state + z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 + z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB + return z ^ (z >> 31) + } + } + + private static func randomCase(_ text: String, using rng: inout SplitMix64) -> String { + switch Int.random(in: 0..<4, using: &rng) { + case 0: return text + case 1: return text.uppercased() + case 2: return text.lowercased() + default: + return String(text.map { Bool.random(using: &rng) ? Character($0.uppercased()) : Character($0.lowercased()) }) + } + } + + func testIndexedResolveMatchesBruteForceReference() { + let directories = ["/src/a", "/src/A", "/src/b/c", "/src", "/src/a/", "/src/d e"] + // Small pools so stems, digits and extensions collide often. + let stems = [ + "IMG_1234", "img_1234", "IMG_1235", "IMG_12", "IMG_012", "IMG_", "IMG_E1234", "IMG_E", + "IMG_12a", "IMG_\u{0661}", "photo", "Photo", "PHOTO", "a.b.c", "a.b", "trip.v2", "x", "", ".hidden", + "IMG_1234.jpg", "photo.jpg", + ] + let mediaExtensions = ["jpg", "JPG", "jpeg", "heic", "HEIC", "cr3", "mov", "png", "", "xmp", "aae"] + let companionExtensions = ["xmp", "XMP", "aae", "AAE", "Aae", ""] + + var rng = SplitMix64(state: 0xC0DE_F00D) + var totalResolved = 0 + var totalMultiple = 0 + var totalNoOwner = 0 + + for _ in 0..<400 { + let mediaCount = Int.random(in: 0...14, using: &rng) + var media: [String] = [] + for _ in 0.. Date: Sun, 29 Nov 2026 14:43:31 -0800 Subject: [PATCH 07/10] Run: Not Now on a refused copy brings the finished preview back A copy request clears the session before the engine can refuse it, so closing the free-month or unlock sheet left the Run page without the preview the person had just read. The store now keeps the finished preview when a copy is requested from it and restores it if the refusal is dismissed. A run that starts, a retry and any new request drop it. The destination lease is still released before the sheet. Co-Authored-By: Claude Fable 5.2 --- .../Stores/RunSessionStore.swift | 80 ++++++ .../RunSessionStoreTests.swift | 271 ++++++++++++++++++ .../ChronoframeAppTests/AppStateTests.swift | 37 +++ 3 files changed, 388 insertions(+) diff --git a/ui/Sources/ChronoframeAppCore/Stores/RunSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/RunSessionStore.swift index 21d15634..03d73ff8 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/RunSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/RunSessionStore.swift @@ -118,6 +118,34 @@ public final class RunSessionStore: ObservableObject { /// to the request they initiated. public private(set) var currentRunToken = UUID() + /// What a finished preview looked like when a copy request began from it. + /// + /// A request clears the session before the engine can refuse it, so a + /// refused month proposal would otherwise cost the person their preview. + /// Held only to put that preview back if the refusal is dismissed (FRX + /// H-FRX-2, "Not Now changes nothing"); status is `.dryRunFinished` by + /// construction. + private struct FinishedPreviewSnapshot { + let currentMode: RunMode? + let currentTaskTitle: String + let currentPhase: RunPhase? + let progress: Double + let metrics: RunMetrics + let artifacts: RunArtifactPaths + let summary: RunSummary? + let prompt: RunPrompt? + let lastPreflight: RunPreflight? + let lastErrorMessage: String? + let latestPreviewReviewPath: String? + let currentFileURL: URL? + let logLines: [String] + } + + /// Set by `requestRun` for a copy requested from a finished preview; dropped + /// by every other request (`resetSessionState`) and consumed by + /// `dismissRefusal`. Only ever read together with `lastRefusal`. + private var previewBeforeCopyRequest: FinishedPreviewSnapshot? + private let engine: any OrganizerEngine private let logStore: RunLogStore private let historyStore: HistoryStore @@ -191,7 +219,9 @@ public final class RunSessionStore: ObservableObject { batch: FreeTestBatchSelection? = nil ) async { guard !isCancelling else { return } + let finishedPreview = (status == .dryRunFinished && mode == .transfer) ? finishedPreviewSnapshot() : nil resetSessionState(mode: mode) + previewBeforeCopyRequest = finishedPreview // Finding #7: capture the epoch AFTER resetSessionState bumps it. If a // newer run starts (or the user cancels) while we await preflight, the // epoch advances and this completion is stale — its security scope has @@ -578,6 +608,7 @@ public final class RunSessionStore: ObservableObject { directOperationLease = nil closeSecurityScope() currentMode = mode + previewBeforeCopyRequest = nil currentRunUsedFreeTestBatch = false currentRunBatchSourcePaths = nil currentRunResumedPendingJobs = false @@ -1192,9 +1223,58 @@ public final class RunSessionStore: ObservableObject { /// For a customer who closes the unlock sheet. The run stays un-run; there /// is nothing to clean up because `handleRefusal` already released /// everything it held. + /// + /// If the refused request was a copy asked for from a finished preview, + /// that preview comes back exactly as it was: closing the sheet changes + /// nothing (FRX H-FRX-2). Nothing is restored while a run is in flight or + /// after any other outcome, and the restored preview is subject to the same + /// staleness checks as before the request (they live outside this store). public func dismissRefusal() { + let wasRefused = lastRefusal != nil lastRefusal = nil lastOfferedBatch = nil + let snapshot = previewBeforeCopyRequest + previewBeforeCopyRequest = nil + guard wasRefused, status == .idle, let snapshot else { return } + restoreFinishedPreview(snapshot) + } + + private func finishedPreviewSnapshot() -> FinishedPreviewSnapshot { + FinishedPreviewSnapshot( + currentMode: currentMode, + currentTaskTitle: currentTaskTitle, + currentPhase: currentPhase, + progress: progress, + metrics: metrics, + artifacts: artifacts, + summary: summary, + prompt: prompt, + lastPreflight: lastPreflight, + lastErrorMessage: lastErrorMessage, + latestPreviewReviewPath: latestPreviewReviewPath, + currentFileURL: currentFileURL, + logLines: logStore.lines + ) + } + + private func restoreFinishedPreview(_ snapshot: FinishedPreviewSnapshot) { + status = .dryRunFinished + currentMode = snapshot.currentMode + currentTaskTitle = snapshot.currentTaskTitle + currentPhase = snapshot.currentPhase + progress = snapshot.progress + metrics = snapshot.metrics + artifacts = snapshot.artifacts + summary = snapshot.summary + prompt = snapshot.prompt + lastPreflight = snapshot.lastPreflight + lastErrorMessage = snapshot.lastErrorMessage + latestPreviewReviewPath = snapshot.latestPreviewReviewPath + currentFileURL = snapshot.currentFileURL + logStore.clear() + for line in snapshot.logLines { + logStore.append(line) + } } private func handleFailure(message: String) { diff --git a/ui/Tests/ChronoframeAppCoreTests/RunSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/RunSessionStoreTests.swift index d3bc9fce..0850041a 100644 --- a/ui/Tests/ChronoframeAppCoreTests/RunSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/RunSessionStoreTests.swift @@ -525,6 +525,277 @@ final class RunSessionStoreTests: XCTestCase { XCTAssertNil(store.lastRefusal, "A stale refusal would make the next failure look like a paywall") } + // MARK: - Not Now leaves a finished preview alone (FRX H-FRX-2) + + private struct SessionPicture: Equatable { + var status: RunStatus + var currentMode: RunMode? + var currentTaskTitle: String + var currentPhase: RunPhase? + var progress: Double + var metrics: RunMetrics + var artifacts: RunArtifactPaths + var summary: RunSummary? + var promptTitle: String? + var lastPreflight: RunPreflight? + var lastErrorMessage: String? + var latestPreviewReviewPath: String? + var logLines: [String] + } + + @MainActor + private func picture(of store: RunSessionStore) -> SessionPicture { + SessionPicture( + status: store.status, + currentMode: store.currentMode, + currentTaskTitle: store.currentTaskTitle, + currentPhase: store.currentPhase, + progress: store.progress, + metrics: store.metrics, + artifacts: store.artifacts, + summary: store.summary, + promptTitle: store.prompt?.title, + lastPreflight: store.lastPreflight, + lastErrorMessage: store.lastErrorMessage, + latestPreviewReviewPath: store.latestPreviewReviewPath, + logLines: store.logLines + ) + } + + private func configuration(_ mode: RunMode) -> RunConfiguration { + RunConfiguration(mode: mode, sourcePath: "/tmp/source", destinationPath: tempDestinationURL.path) + } + + private func preflight(_ mode: RunMode) -> RunPreflight { + let configuration = configuration(mode) + return RunPreflight( + configuration: configuration, + resolvedSourcePath: configuration.sourcePath, + resolvedDestinationPath: configuration.destinationPath + ) + } + + private func monthRefusal() -> TrialAuthorizationError { + let transfer = PlannedTransfer( + sourcePath: "/tmp/source/a.jpg", + destinationPath: tempDestinationURL.appendingPathComponent("2026/03/a.jpg").path, + identity: FileIdentity(size: 1, digest: "a"), + dateBucket: "2026-03", + isDuplicate: false + ) + return TrialAuthorizationError( + refusal: .allowanceSpent(TrialRefusal(meter: .organize, requested: 40, remaining: 12)), + offeredBatch: FreeTestBatch(included: [transfer], deferredCount: 39, monthKey: "2026-03", wasRequested: true) + ) + } + + private func monthRequest() -> FreeTestBatchSelection { + FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: "2026-03", limit: 12)) + } + + /// A ready preview with distinctive values in every field a new request resets. + @MainActor + private func makeFinishedPreview(engine: MockOrganizerEngine) async -> RunSessionStore { + let reviewPath = tempDestinationURL.appendingPathComponent(".organize_logs/preview_review_1.jsonl").path + let summary = RunSummary( + status: .dryRunFinished, + title: "Preview complete", + metrics: RunMetrics( + discoveredCount: 55, + plannedCount: 40, + errorCount: 1, + newFilesByMonth: ["2026-03": 25, "2026-04": 15] + ), + artifacts: RunArtifactPaths( + destinationRoot: tempDestinationURL.path, + reportPath: tempDestinationURL.appendingPathComponent(".organize_logs/report.csv").path, + previewReviewPath: reviewPath, + logFilePath: tempDestinationURL.appendingPathComponent(".organize_log.txt").path, + logsDirectoryPath: tempDestinationURL.appendingPathComponent(".organize_logs", isDirectory: true).path + ) + ) + engine.preflightResult = .success(preflight(.preview)) + engine.startMode = .events([ + .startup, + .issue(RunIssue(severity: .warning, message: "Two files have no date")), + .complete(summary), + ]) + let store = RunSessionStore(engine: engine, logStore: logStore, historyStore: historyStore) + await store.requestRun(mode: .preview, configuration: configuration(.preview)) + let ready = await waitForCondition { store.status == .dryRunFinished && store.latestPreviewReviewPath != nil } + XCTAssertTrue(ready) + return store + } + + /// FRX H-FRX-2: "Not Now changes nothing". The month request clears the + /// session before the engine refuses it, so closing the sheet has to put the + /// finished preview back exactly as it was. + @MainActor + func testNotNowOnAMonthProposalRestoresTheFinishedPreview() async throws { + let engine = MockOrganizerEngine(preflightResult: .success(preflight(.preview))) + let store = await makeFinishedPreview(engine: engine) + let before = picture(of: store) + XCTAssertEqual(before.metrics.newFilesByMonth, ["2026-03": 25, "2026-04": 15]) + + engine.preflightResult = .success(preflight(.transfer)) + engine.startMode = .fails(monthRefusal()) + await store.requestRun(mode: .transfer, configuration: configuration(.transfer), batch: monthRequest()) + let refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + XCTAssertEqual(store.status, .idle, "While the sheet is open nothing is running") + XCTAssertNotNil(store.lastOfferedBatch) + + // The destination lock is never held while the sheet is open. + let lease = try DestinationOperationLock.acquire( + destinationRoot: engine.lockRoot, + surface: "test", + operation: "while-sheet-open" + ) + lease.release() + + store.dismissRefusal() + + XCTAssertNil(store.lastRefusal) + XCTAssertNil(store.lastOfferedBatch) + XCTAssertEqual(picture(of: store), before, "Not Now must leave the preview exactly as it was") + XCTAssertEqual(engine.startBatches.count, 1, "Dismissing must not start a run") + } + + /// The person confirms the month instead: the run proceeds as it always did + /// and nothing of the old preview is brought back. + @MainActor + func testConfirmingTheMonthProposalRunsAndRestoresNothing() async throws { + let engine = MockOrganizerEngine(preflightResult: .success(preflight(.preview))) + let store = await makeFinishedPreview(engine: engine) + + engine.preflightResult = .success(preflight(.transfer)) + engine.startMode = .fails(monthRefusal()) + await store.requestRun(mode: .transfer, configuration: configuration(.transfer), batch: monthRequest()) + let refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + + let finished = RunSummary( + status: .finished, + title: "Copy complete", + metrics: RunMetrics(plannedCount: 12, copiedCount: 12), + artifacts: RunArtifactPaths(destinationRoot: tempDestinationURL.path) + ) + engine.startMode = .events([.startup, .complete(finished)]) + + // What `AppState.runOfferedFreeTestBatch` does: close the refusal, then restart. + store.dismissRefusal() + await store.requestRun(mode: .transfer, configuration: configuration(.transfer), batch: monthRequest()) + let done = await waitForCondition { store.status == .finished } + XCTAssertTrue(done) + + XCTAssertEqual(store.summary?.status, .finished) + XCTAssertEqual(store.metrics.copiedCount, 12) + XCTAssertEqual(store.metrics.newFilesByMonth, [:]) + XCTAssertNil(store.latestPreviewReviewPath) + XCTAssertEqual(store.currentMode, .transfer) + + // Nothing is left to restore later. + let afterRun = picture(of: store) + store.dismissRefusal() + XCTAssertEqual(picture(of: store), afterRun) + } + + /// Unlock-and-retry restarts without going through the batch sheet. + @MainActor + func testRetryingAfterARefusedRunNeverBringsTheOldPreviewBack() async throws { + let engine = MockOrganizerEngine(preflightResult: .success(preflight(.preview))) + let store = await makeFinishedPreview(engine: engine) + + engine.preflightResult = .success(preflight(.transfer)) + engine.startMode = .fails(TrialAuthorizationError(refusal: .requiresUnlock)) + await store.requestRun(mode: .transfer, configuration: configuration(.transfer)) + let prompted = await waitForCondition { store.prompt != nil } + XCTAssertTrue(prompted) + store.confirmPrompt() + let refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + + engine.startMode = .events([.startup, .complete(RunSummary( + status: .finished, + title: "Copy complete", + metrics: RunMetrics(plannedCount: 40, copiedCount: 40), + artifacts: RunArtifactPaths(destinationRoot: tempDestinationURL.path) + ))]) + store.dismissRefusal() + await store.requestRun(mode: .transfer, configuration: configuration(.transfer)) + let prompted2 = await waitForCondition { store.prompt != nil } + XCTAssertTrue(prompted2) + store.confirmPrompt() + let done = await waitForCondition { store.status == .finished } + XCTAssertTrue(done) + + XCTAssertEqual(store.summary?.metrics.copiedCount, 40) + XCTAssertNil(store.latestPreviewReviewPath) + } + + /// With no finished preview behind the request there is nothing to put back: + /// dismissing only clears the refusal, as before. + @MainActor + func testNotNowWithoutAFinishedPreviewRestoresNothing() async throws { + let engine = MockOrganizerEngine( + preflightResult: .success(preflight(.transfer)), + startMode: .fails(monthRefusal()) + ) + let store = RunSessionStore(engine: engine, logStore: logStore, historyStore: historyStore) + + await store.requestRun(mode: .transfer, configuration: configuration(.transfer), batch: monthRequest()) + let refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + let whileOpen = picture(of: store) + + store.dismissRefusal() + + XCTAssertNil(store.lastRefusal) + XCTAssertEqual(picture(of: store), whileOpen) + XCTAssertEqual(store.status, .idle) + XCTAssertNil(store.summary) + XCTAssertEqual(store.metrics, RunMetrics()) + } + + /// Only a copy request made from a ready preview restores it. A refused + /// request to build a new preview, or a request made after a finished copy, + /// keeps today's behaviour. + @MainActor + func testNotNowAfterOtherRequestsStillRestoresNothing() async throws { + let engine = MockOrganizerEngine(preflightResult: .success(preflight(.preview))) + let store = await makeFinishedPreview(engine: engine) + + // A new preview being refused: the old one was replaced by that request. + engine.startMode = .fails(TrialAuthorizationError(refusal: .requiresUnlock)) + await store.requestRun(mode: .preview, configuration: configuration(.preview)) + var refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + var whileOpen = picture(of: store) + store.dismissRefusal() + XCTAssertEqual(picture(of: store), whileOpen) + XCTAssertNil(store.summary) + + // A request made after a finished copy. + engine.preflightResult = .success(preflight(.transfer)) + engine.startMode = .events([.startup, .complete(RunSummary( + status: .finished, + title: "Copy complete", + metrics: RunMetrics(plannedCount: 3, copiedCount: 3), + artifacts: RunArtifactPaths(destinationRoot: tempDestinationURL.path) + ))]) + await store.requestRun(mode: .transfer, configuration: configuration(.transfer), batch: monthRequest()) + let finished = await waitForCondition { store.status == .finished } + XCTAssertTrue(finished) + engine.startMode = .fails(monthRefusal()) + await store.requestRun(mode: .transfer, configuration: configuration(.transfer), batch: monthRequest()) + refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + whileOpen = picture(of: store) + store.dismissRefusal() + XCTAssertEqual(picture(of: store), whileOpen) + XCTAssertNil(store.summary) + } + /// The Copied card must report files that actually landed. Copy progress /// carries both the attempted-job count (which drives the progress fraction) /// and the executor's running copied count; crediting attempts used to show diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index 0156bdfc..ead2a7d3 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -1197,6 +1197,43 @@ final class AppStateTests: XCTestCase { XCTAssertEqual(harness.engine.startConfigurations.count, 1) } + /// FRX H-FRX-2: pressing Not Now on the free-month sheet changes nothing, so + /// the ready preview (and the free-copy offer built from it) is still there. + @MainActor + func testNotNowOnTheFreeMonthSheetKeepsTheReadyPreview() async throws { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness, organizeUsed: 120) + let summary = RunSummary( + status: .dryRunFinished, + title: "Preview complete", + metrics: RunMetrics(plannedCount: 18_412, newFilesByMonth: ["2026-10": 212, "2026-09": 148]), + artifacts: RunArtifactPaths(destinationRoot: "/tmp/destination") + ) + harness.engine.startMode = .events([.complete(summary)]) + await state.startPreview() + let previewed = await waitForCondition { harness.runSessionStore.summary?.status == .dryRunFinished } + XCTAssertTrue(previewed) + let options = FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 212, "2026-09": 148], remaining: 380) + let september = try XCTUnwrap(options.first { $0.key == "2026-09" }) + + harness.engine.startMode = .fails(TrialAuthorizationError( + refusal: .allowanceSpent(TrialRefusal(meter: .organize, requested: 18_412, remaining: 380)), + offeredBatch: FreeTestBatch(included: [], deferredCount: 0, monthKey: "2026-09", wasRequested: true) + )) + await state.startFreeMonthCopy(september) + let refused = await waitForCondition { state.unlockRefusal != nil } + XCTAssertTrue(refused) + XCTAssertEqual(harness.runSessionStore.status, .idle) + + state.dismissUnlockSheet() + + XCTAssertNil(state.unlockRefusal) + XCTAssertEqual(harness.runSessionStore.status, .dryRunFinished) + XCTAssertEqual(harness.runSessionStore.summary, summary) + XCTAssertEqual(harness.runSessionStore.metrics.plannedCount, 18_412) + XCTAssertEqual(harness.runSessionStore.metrics.newFilesByMonth, ["2026-10": 212, "2026-09": 148]) + } + @MainActor func testOverAllowanceScenarioPreviewMatchesTheFixtureContract() async throws { let appState = UITestAppStateFactory.make(scenario: .runPreviewOverAllowance) From b8ed39aeb276a34515000ef34edbd330b96bd2e6 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:43:50 -0800 Subject: [PATCH 08/10] Docs: record the 2.1 sweep decisions and the edit-preservation follow-up status Co-Authored-By: Claude Fable 5.2 --- DECISIONS.md | 5 ++++- docs/plan/edit-preservation/BLOCKED.md | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/DECISIONS.md b/DECISIONS.md index 0c41070b..493065ff 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -2,9 +2,12 @@ ## Release 2.1 bug sweep (2026-11-29) -- Pair fan-out and unreviewed groups (INV-14, approved by the sweep brief, not yet read by the owner): the commit plan is built from reviewed groups only, so a RAW or Live Photo partner sitting in an unreviewed group had no decision and was added to the plan while its own group showed it as kept. The planner now takes `fanoutProtectedPaths`; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. A held-back partner stays until its own group is reviewed, which can leave a RAW without its JPEG. Planning over all groups is unchanged. +- Pair fan-out and unreviewed groups (INV-14; decided by the agent during the sweep, the owner has not reviewed it): the commit plan is built from reviewed groups only, so a RAW or Live Photo partner sitting in an unreviewed group had no decision and was added to the plan while its own group showed it as kept. The planner now takes `fanoutProtectedPaths`; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. A held-back partner stays until its own group is reviewed, which can leave a RAW without its JPEG. Planning over all groups is unchanged. - Undo history in Deduplicate is discarded when a scan starts, on reset, and when a commit completes, so an Undo from an earlier scan cannot rewrite a restored review. - The unlock sheet's Return key takes the free action whenever one is offered, even where the action list puts Buy first. +- Dedupe review panes show Keep for a member with no decision in a group the planner will not auto-select, because that is what the plan does (edit preservation B-3). +- Companion owner lookup is indexed per folder; a seeded equivalence test pins it to the per-pair rules in `nameForm`. +- Closing a refusal sheet after a copy requested from a finished preview restores that preview. This also covers a refused plain Start Copying, not only the free-month proposal. - A count of 1 on the dedupe unlock button reads "Unlock to Remove 1 Duplicate" (implementer's wording). - Not built, needs a design decision: skipping a companion whose owner failed verification (edit preservation B-2, item 3). Copy jobs carry no owner link and owner and companion can be prepared in the same concurrent batch. diff --git a/docs/plan/edit-preservation/BLOCKED.md b/docs/plan/edit-preservation/BLOCKED.md index ac8859e7..1ad75bb3 100644 --- a/docs/plan/edit-preservation/BLOCKED.md +++ b/docs/plan/edit-preservation/BLOCKED.md @@ -29,7 +29,7 @@ Rule: log it, then continue with the next independent WP. Only Nishith marks an - **Tried:** confirmed none needs a cache or receipt schema change and none breaks an AGENTS.md invariant (no overwrite, no deletion); WP-04 proceeds. - **Options:** 1) Follow-up PR: widen the tmp regex to `\.[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)?` before the UUID, and teach `parseFileBucket` to strip a known companion extension first. 2) Map appended-form companions to stem form in the destination (contradicts C-03.4 and breaks darktable's naming). - **Recommendation:** Option 1 as a small follow-up PR with tests, since both are one-line pattern changes in safety-adjacent files that deserve their own review. -- **Status:** open +- **Status:** partly built, awaiting the owner's mark. Items 1 and 2 (temp pattern, `parseFileBucket`) are in `1c2c6633` on `fix/release-2.1-followups`. Item 4 (skip a companion whose owner did not finalize) and item 3 (`_collision_N`) are not built: copy jobs carry no owner link, and owner and companion can be prepared in the same concurrent batch, so both need the same design decision (in-memory link passed to the executor, a `CopyJobs` column, or ordering companions after their owner). ### B-3 — Review panes can label a protected edited variant "Suggested for removal" (non-blocking) - **WP:** WP-08 @@ -38,4 +38,4 @@ Rule: log it, then continue with the next independent WP. Only Nishith marks an - **Tried:** confirmed outside WP-08's owned paths (D-EPR-122 covers the store only); not folded in. - **Options:** 1) Follow-up PR routing those panes through `DedupeDecisions.keepersForCluster` (or a shared effective-decision helper) with an App test. 2) Leave as is. - **Recommendation:** Option 1, a small follow-up so the review UI never contradicts the plan. -- **Status:** open +- **Status:** fix built, awaiting the owner's mark. `5379edf7` on `fix/release-2.1-followups`: the panes read `DedupeDecisions.effectiveDecision`. From 9ad795e4d1cc67afa9faaf7d4dcece5e227117d6 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:02:16 -0800 Subject: [PATCH 09/10] Docs: mark the three sweep decisions the owner approved Co-Authored-By: Claude Fable 5.2 --- DECISIONS.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DECISIONS.md b/DECISIONS.md index 493065ff..60bb1fbe 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -2,13 +2,13 @@ ## Release 2.1 bug sweep (2026-11-29) -- Pair fan-out and unreviewed groups (INV-14; decided by the agent during the sweep, the owner has not reviewed it): the commit plan is built from reviewed groups only, so a RAW or Live Photo partner sitting in an unreviewed group had no decision and was added to the plan while its own group showed it as kept. The planner now takes `fanoutProtectedPaths`; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. A held-back partner stays until its own group is reviewed, which can leave a RAW without its JPEG. Planning over all groups is unchanged. +- Pair fan-out and unreviewed groups (INV-14; decided by the agent during the sweep, approved by the owner 2026-11-29): the commit plan is built from reviewed groups only, so a RAW or Live Photo partner sitting in an unreviewed group had no decision and was added to the plan while its own group showed it as kept. The planner now takes `fanoutProtectedPaths`; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. A held-back partner stays until its own group is reviewed, which can leave a RAW without its JPEG. Planning over all groups is unchanged. - Undo history in Deduplicate is discarded when a scan starts, on reset, and when a commit completes, so an Undo from an earlier scan cannot rewrite a restored review. - The unlock sheet's Return key takes the free action whenever one is offered, even where the action list puts Buy first. -- Dedupe review panes show Keep for a member with no decision in a group the planner will not auto-select, because that is what the plan does (edit preservation B-3). +- Dedupe review panes show Keep for a member with no decision in a group the planner will not auto-select, because that is what the plan does (edit preservation B-3; approved by the owner 2026-11-29). - Companion owner lookup is indexed per folder; a seeded equivalence test pins it to the per-pair rules in `nameForm`. - Closing a refusal sheet after a copy requested from a finished preview restores that preview. This also covers a refused plain Start Copying, not only the free-month proposal. -- A count of 1 on the dedupe unlock button reads "Unlock to Remove 1 Duplicate" (implementer's wording). +- A count of 1 on the dedupe unlock button reads "Unlock to Remove 1 Duplicate" (implementer's wording; approved by the owner 2026-11-29). - Not built, needs a design decision: skipping a companion whose owner failed verification (edit preservation B-2, item 3). Copy jobs carry no owner link and owner and companion can be prepared in the same concurrent batch. ## German translation import (2026-11-15) From 20a6dba745ea48e2ff4565ea78910d55e29efe1b Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:23:00 -0800 Subject: [PATCH 10/10] Tests: Shortcut configuration tests compile on Swift 6.0.3 Co-Authored-By: Claude Fable 5.2 --- .../OrganizeFolderIntentConfigurationTests.swift | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift index 3342c80b..ea4e54ac 100644 --- a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift +++ b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift @@ -12,8 +12,8 @@ final class OrganizeFolderIntentConfigurationTests: XCTestCase { private var suiteName: String! private var defaults: UserDefaults! + // No `super` call: on Swift 6.0.3 it sends the non-Sendable test case off the main actor. override func setUp() async throws { - try await super.setUp() suiteName = "OrganizeFolderIntentConfigurationTests-\(UUID().uuidString)" defaults = UserDefaults(suiteName: suiteName) defaults.removePersistentDomain(forName: suiteName) @@ -23,7 +23,6 @@ final class OrganizeFolderIntentConfigurationTests: XCTestCase { defaults.removePersistentDomain(forName: suiteName) defaults = nil suiteName = nil - try await super.tearDown() } private func configuration() -> RunConfiguration {