From 1c2c6633f957cf73c25e1b6144a484a0328f7759 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 14:12:40 -0800 Subject: [PATCH 01/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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/17] 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 { From 625b5e77d0e40368659227cc72dd2f490b3d1319 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:07:06 -0800 Subject: [PATCH 11/17] Shortcut: Organize Folder uses the stored verify, parallel and worker preferences Co-Authored-By: Claude Fable 5.2 --- .../AppIntents/OrganizeFolderIntent.swift | 11 +++---- ...ganizeFolderIntentConfigurationTests.swift | 29 +++++++++++++++++-- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift b/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift index 6ad65258..09e6d756 100644 --- a/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift +++ b/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift @@ -100,8 +100,9 @@ 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. + /// The run this intent performs. Layout, verify-copies, parallel transfer and worker count are + /// the person's own, read through `PreferencesStore` the way `SetupStore.makeConfiguration` + /// does, so a Shortcut run behaves like a run started in the app. @MainActor static func makeConfiguration( sourcePath: String, @@ -113,9 +114,9 @@ public struct OrganizeFolderIntent: AppIntent { sourcePath: sourcePath, destinationPath: destinationPath, profileName: nil, - verifyCopies: true, - parallelTransferEnabled: true, - workerCount: 8, + verifyCopies: preferences.verifyCopies, + parallelTransferEnabled: preferences.parallelTransferEnabled, + workerCount: max(1, preferences.workerCount), folderStructure: preferences.folderStructure ) } diff --git a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift index ea4e54ac..d20232a5 100644 --- a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift +++ b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift @@ -61,8 +61,8 @@ final class OrganizeFolderIntentConfigurationTests: XCTestCase { XCTAssertEqual(configuration().folderStructure, .yyyyMMDD) } - /// Everything but the layout is what the intent shipped with. - func testTheRestOfTheConfigurationIsUnchanged() { + /// With nothing stored, the stored-preference defaults match what the intent shipped with. + func testDefaultsMatchWhatTheIntentShippedWith() { let config = configuration() XCTAssertEqual(config.mode, .transfer) @@ -73,4 +73,29 @@ final class OrganizeFolderIntentConfigurationTests: XCTestCase { XCTAssertTrue(config.parallelTransferEnabled) XCTAssertEqual(config.workerCount, 8) } + + func testStoredVerifyCopiesOffIsHonored() { + defaults.set(false, forKey: "verifyCopies") + + XCTAssertFalse(configuration().verifyCopies) + } + + func testStoredWorkerCountIsHonored() { + defaults.set(3, forKey: "workerCount") + + XCTAssertEqual(configuration().workerCount, 3) + } + + /// The app's own run path never hands the engine fewer than one worker. + func testStoredWorkerCountIsClampedToAtLeastOne() { + defaults.set(0, forKey: "workerCount") + + XCTAssertEqual(configuration().workerCount, 1) + } + + func testStoredParallelTransferOffIsHonored() { + defaults.set(false, forKey: "parallelTransferEnabled") + + XCTAssertFalse(configuration().parallelTransferEnabled) + } } From ac29b36fa592b4b50a28db802e0cc9b40b0a7c14 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:07:06 -0800 Subject: [PATCH 12/17] Release: version 2.1 and draft 2.1 What's New in English and German Co-Authored-By: Claude Fable 5.2 --- docs/APP_STORE_METADATA.md | 39 ++++++++++++++++-------- docs/APP_STORE_RELEASE.md | 2 +- ui/Chronoframe.xcodeproj/project.pbxproj | 4 +-- 3 files changed, 30 insertions(+), 15 deletions(-) diff --git a/docs/APP_STORE_METADATA.md b/docs/APP_STORE_METADATA.md index 92b5332b..f3dc2a12 100644 --- a/docs/APP_STORE_METADATA.md +++ b/docs/APP_STORE_METADATA.md @@ -13,7 +13,7 @@ Copy-paste-ready source for Chronoframe's current Mac App Store listing. Charact | Bundle ID | `com.nishith.chronoframe` | | Primary category | Photo & Video | | Secondary category | Utilities | -| Version | `2.0` | +| Version | `2.1` | | Copyright | `2026 Nishith Nand` | | Age rating | 4+ (no objectionable content) | @@ -72,22 +72,33 @@ The owner confirmed there are no existing users (2026-10-16), so the earlier pai > duplicate,dedupe,photos,organizer,EXIF,cleanup,media,folder,backup,video,sort,library,metadata -## What's New (release notes for version 2.0) +## What's New (release notes for version 2.1) -> Chronoframe 2.0 brings new ways to build and care for your photo library: +Version 2.0's text is kept in `marketing/release-2.0/metadata/whats_new.txt`. + +> Chronoframe 2.1 makes the first run clearer and keeps your edits safe. > -> • Import selected original photos and videos from Apple Photos without changing the Photos library. -> • Register watched source folders, see an estimate of new items, and review each import before copying. -> • Review similar videos with optional perceptual matching, alongside exact photo and video duplicates. -> • Preview your library with contact sheets and timelines, compare duplicates, and choose what moves to Trash. -> • Improved copy compatibility on external drives, visible duplicate names in Trash, interruption recovery, and clearer verification and history. -> • Refined layouts and accessibility throughout the organizing and duplicate-review workflows. +> • Chronoframe now speaks German and follows your Mac's language setting. +> • A short guided setup on first launch, and a preview that shows the free limit and how your library will be arranged before anything is copied. +> • Try it free: copy one month of new photos, or remove whole groups of duplicates, within the free allowance. The allowance and the one-time unlock are unchanged. +> • Edit files (.xmp and .aae) are copied with their photo, and Deduplicate never selects an edited version, such as IMG_0001-edited.jpg, on its own. +> • Undo This Copy on the completion screen, with a count showing that every file found is accounted for. +> • Fixes: conflicting capture dates are flagged in the preview, saved duplicate reviews survive a relaunch, a Photos import can be stopped and resumed, and the live Copied count counts only files that were copied. > -> Dates near midnight now use the capture date’s recorded time zone. For a previously organized library, use Health → Reorganize to correct affected destination folders; originals are unchanged. +> No subscription. Your source files and Photos library remain untouched. + +### Was ist neu (Deutsch, Version 2.1) + +> Chronoframe 2.1 macht den ersten Start übersichtlicher und schützt deine Bearbeitungen. > -> Now free to download: organize 500 files and move 100 duplicates to Trash before purchasing. These allowances are cumulative per Apple Account on each Mac. One $14.99 US lifetime unlock removes the limits, with Family Sharing. Scanning, preview, review, and history remain free; revert remains available without purchasing and returns the corresponding allowance. +> • Chronoframe gibt es jetzt auf Deutsch und folgt der Sprache deines Macs. +> • Eine kurze geführte Einrichtung beim ersten Start und eine Vorschau, die das kostenlose Limit und die Struktur deiner Mediathek zeigt, bevor etwas kopiert wird. +> • Kostenlos ausprobieren: Kopiere einen Monat neuer Fotos oder entferne ganze Duplikatgruppen im Rahmen des kostenlosen Kontingents. Kontingent und einmalige Freischaltung bleiben unverändert. +> • Bearbeitungsdateien (.xmp und .aae) werden zusammen mit ihrem Foto kopiert, und beim Bereinigen von Duplikaten wählt Chronoframe eine bearbeitete Version, etwa IMG_0001-edited.jpg, nie von selbst aus. +> • „Diesen Kopiervorgang rückgängig machen…“ auf dem Abschlussbildschirm, mit einer Zählung, die zeigt, dass alle gefundenen Dateien berücksichtigt sind. +> • Korrekturen: Widersprüchliche Aufnahmedaten werden in der Vorschau markiert, gespeicherte Duplikatprüfungen bleiben nach einem Neustart erhalten, ein Fotos-Import lässt sich anhalten und fortsetzen, und der laufende Zähler „Kopiert“ zählt nur tatsächlich kopierte Dateien. > -> No subscription. Your organizing source files and Photos library remain untouched. +> Kein Abo. Deine Originaldateien und deine Fotos-Mediathek bleiben unverändert. ## Review Notes @@ -103,6 +114,10 @@ The purchase path below leads the saved review notes; it requires a build with t > > LAUNCH: Version 2.0 launches directly as a free download with the $14.99 US lifetime unlock. There are no existing customers to migrate and no paid rollout or acquisition-date legacy unlock. New customers receive the allowance regardless of the app transaction's original purchase date. Submit the app and first non-consumable together. +### Version 2.1 addendum (draft) + +No new in-app purchase, product, price or allowance cap. Version 2.1 adds a guided first-run setup, a free copy of one month of new files and a free removal of whole duplicate groups, both inside the existing 500-file and 100-duplicate allowance, German localization, and protection for edit files. The free month lists its files and waits for confirmation before copying. The purchase path in the notes above is unchanged. Update the saved App Review notes in App Store Connect with this paragraph when 2.1 is submitted. + ## App Privacy (questionnaire answers) These mirror `docs/PRIVACY_POLICY.md` and `ui/Resources/PrivacyInfo.xcprivacy`. diff --git a/docs/APP_STORE_RELEASE.md b/docs/APP_STORE_RELEASE.md index 7d7587f0..8730c089 100644 --- a/docs/APP_STORE_RELEASE.md +++ b/docs/APP_STORE_RELEASE.md @@ -19,7 +19,7 @@ Chronoframe is ready to submit only when all items below are complete: - Internal TestFlight passes the manual matrix below, including the free trial and unlock rows, and the focused manual session in `remaining-work-plan.md`. - App Store metadata, screenshots, privacy policy URL, support URL, and pricing are complete in App Store Connect. - The in-app purchase exists in App Store Connect with Family Sharing ON, and is attached to this version for submission. -- `ChronoframeUnlock.defaultPolicy()` disables both live and cached legacy unlocks. A new customer receives the allowance regardless of acquisition date; the verified non-consumable unlock removes limits. `MARKETING_VERSION` is `2.0`. +- `ChronoframeUnlock.defaultPolicy()` disables both live and cached legacy unlocks. A new customer receives the allowance regardless of acquisition date; the verified non-consumable unlock removes limits. `MARKETING_VERSION` is `2.1`. ## App Store Connect Metadata diff --git a/ui/Chronoframe.xcodeproj/project.pbxproj b/ui/Chronoframe.xcodeproj/project.pbxproj index 662505c7..f8bc5627 100644 --- a/ui/Chronoframe.xcodeproj/project.pbxproj +++ b/ui/Chronoframe.xcodeproj/project.pbxproj @@ -424,7 +424,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0; + MARKETING_VERSION = 2.1; ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = ( "$(inherited)", @@ -455,7 +455,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0; + MARKETING_VERSION = 2.1; OTHER_LDFLAGS = ( "$(inherited)", "-lsqlite3", From 41496dec05d48ebbe41851b0d3df00013b545e4e Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:11:50 -0800 Subject: [PATCH 13/17] Photos import: staging a pending copy still reads from survives cleanup Launch cleanup and the post-run cleanup removed a finished export even when the destination's pending copy jobs still read from it, so a copy that was quit, stopped or failed could not be finished. The folder now stays while a pending job references it. When the destination cannot be checked at launch it is kept for 30 days. Co-Authored-By: Claude Fable 5.2 --- .../PhotosStagingReferenceChecker.swift | 79 ++++++ .../Stores/PhotosImportStore.swift | 42 +++- .../PhotosImportResumeTests.swift | 224 ++++++++++++++++++ 3 files changed, 344 insertions(+), 1 deletion(-) create mode 100644 ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift diff --git a/ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift b/ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift new file mode 100644 index 00000000..418b4531 --- /dev/null +++ b/ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift @@ -0,0 +1,79 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// Whether a destination's copy queue still reads from a staging folder. +public enum PhotosStagingReference: Equatable, Sendable { + /// A pending copy job names a file inside the folder: the copy needs it. + case referenced + /// The queue was read (or provably does not exist) and no pending job names the folder. + case unreferenced + /// The destination or its queue could not be read, so nothing is proven. + case undetermined +} + +/// Answers "does an unfinished copy still read from this staging folder?" +/// for launch cleanup. Pending jobs in the destination's `.organize_cache.db` +/// carry their source path, and a Photos import's source is its staging +/// folder, so a pending job under the folder means a resume needs it. +public protocol PhotosStagingReferenceChecking: Sendable { + func reference(toStagingDirectory stagingDirectory: URL, destinationPath: String) -> PhotosStagingReference +} + +/// Reads the destination's copy queue without writing anything: the same +/// read-only open the run preflight uses to count pending jobs, which takes no +/// destination lease because it mutates nothing. Anything it cannot read is +/// `.undetermined`, never "nothing pending": an unmounted or unreachable +/// destination, a denied path, an unreadable database. +public struct PendingCopyJobStagingReferenceChecker: PhotosStagingReferenceChecking { + private let presenceChecker: any FilesystemPresenceChecking + + public init(presenceChecker: any FilesystemPresenceChecking = POSIXFilesystemPresenceChecker()) { + self.presenceChecker = presenceChecker + } + + private struct FoundReference: Error {} + + public func reference(toStagingDirectory stagingDirectory: URL, destinationPath: String) -> PhotosStagingReference { + guard !destinationPath.isEmpty else { return .undetermined } + let root = URL(fileURLWithPath: destinationPath, isDirectory: true) + // A destination root that is not there may be an unmounted volume. + guard presenceChecker.presence(at: root.path) == .exists else { return .undetermined } + + let databaseURL = root.appendingPathComponent(EngineArtifactLayout.chronoframeDefault.queueDatabaseFilename) + switch presenceChecker.presence(at: databaseURL.path) { + case .inaccessible: + return .undetermined + case .missing: + // The run preflight reads a missing queue as zero pending jobs, so + // there is no copy to resume from this destination. + return .unreferenced + case .exists: + break + } + + guard let database = try? OrganizerDatabase(url: databaseURL, readOnly: true) else { return .undetermined } + defer { database.close() } + + // Job paths are whatever string the run was given as its source, so + // match both the folder as named and with symlinks (/var) resolved. + let prefixes = Set([ + stagingDirectory.standardizedFileURL.path, + stagingDirectory.resolvingSymlinksInPath().standardizedFileURL.path + ]).map { $0.hasSuffix("/") ? $0 : $0 + "/" } + + do { + try database.enumerateQueuedJobBatches(status: .pending) { batch in + if batch.contains(where: { job in prefixes.contains(where: job.sourcePath.hasPrefix) }) { + throw FoundReference() + } + } + } catch is FoundReference { + return .referenced + } catch { + return .undetermined + } + return .unreferenced + } +} diff --git a/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift b/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift index a01116cf..b9551f96 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift @@ -94,6 +94,7 @@ public final class PhotosImportStore: ObservableObject { private let stagingParentURL: URL private let pageSize: Int private let checkpointStore: any PhotosImportCheckpointStoring + private let stagingReferenceChecker: any PhotosStagingReferenceChecking private let exportExecutorFactory: (any PhotosResourceExporting) -> PhotosExportExecutor private let now: @Sendable () -> Date private let cancellation = PhotosPreparationCancellation() @@ -129,6 +130,7 @@ public final class PhotosImportStore: ObservableObject { stagingParentURL: URL, pageSize: Int = 120, checkpointStore: any PhotosImportCheckpointStoring = PhotosImportFileCheckpointStore(), + stagingReferenceChecker: any PhotosStagingReferenceChecking = PendingCopyJobStagingReferenceChecker(), exportExecutorFactory: @escaping (any PhotosResourceExporting) -> PhotosExportExecutor = { PhotosExportExecutor(exporter: $0) }, now: @escaping @Sendable () -> Date = Date.init ) { @@ -138,6 +140,7 @@ public final class PhotosImportStore: ObservableObject { self.stagingParentURL = stagingParentURL self.pageSize = max(1, pageSize) self.checkpointStore = checkpointStore + self.stagingReferenceChecker = stagingReferenceChecker self.exportExecutorFactory = exportExecutorFactory self.now = now self.authorization = access.currentAuthorization() @@ -377,6 +380,10 @@ public final class PhotosImportStore: ObservableObject { guard Self.isChronoframeStagingDirectory(child) else { continue } guard let candidate = resumableCandidate(at: child, destination: destination) else { + // A finished export is the source of its copy. If the person + // quit mid-copy, the destination's pending jobs still read + // from this folder and a resume fails without it. + if isStillNeededByUnfinishedCopy(child) { continue } try? fileManager.removeItem(at: child) continue } @@ -395,6 +402,30 @@ public final class PhotosImportStore: ObservableObject { resumable = candidates.first } + /// How long a finished export is kept when its destination cannot be + /// checked (offline volume, denied path, unreadable queue) and so cannot + /// prove the folder unneeded. Past this it is removed: it can be many GB, + /// and losing it costs only a repeat export, never a user file. + private static let uncheckedStagingRetention: TimeInterval = 30 * 24 * 60 * 60 + + /// True when the finished (`.ready`) export in `directory` must survive + /// cleanup: a pending copy job still reads from it, or its destination + /// cannot be checked and the export is recent. Reads only. + private func isStillNeededByUnfinishedCopy(_ directory: URL) -> Bool { + guard let checkpoint = checkpointStore.load(in: directory), checkpoint.state == .ready else { return false } + switch stagingReferenceChecker.reference( + toStagingDirectory: directory, + destinationPath: checkpoint.destinationPath + ) { + case .referenced: + return true + case .unreferenced: + return false + case .undetermined: + return now().timeIntervalSince(checkpoint.updatedAt) < Self.uncheckedStagingRetention + } + } + /// The resumable import in `directory`, or nil when it has no usable /// checkpoint (missing, consumed, damaged or untrusted). Reads only. private func resumableCandidate(at directory: URL, destination: DestinationCapture?) -> PhotosResumableImport? { @@ -416,7 +447,16 @@ public final class PhotosImportStore: ObservableObject { /// once; a missing directory is not an error. public func cleanupStaging(for context: PhotosImportContext) { preparedStagingPaths.remove(context.stagingDirectoryURL.standardizedFileURL.path) - try? FileManager.default.removeItem(at: context.stagingDirectoryURL) + // A copy that stopped, failed or hit the free limit leaves pending + // jobs that still read from this folder; launch cleanup removes it + // once nothing does. + let reference = stagingReferenceChecker.reference( + toStagingDirectory: context.stagingDirectoryURL, + destinationPath: context.destinationPath + ) + if reference != .referenced { + try? FileManager.default.removeItem(at: context.stagingDirectoryURL) + } includeEditedVersions = false } diff --git a/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift b/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift index 944b8f89..5a0fc780 100644 --- a/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift @@ -845,6 +845,230 @@ final class PhotosImportResumeTests: XCTestCase { XCTAssertNil(store.resumable) } + // MARK: Launch cleanup keeps staging an unfinished copy still needs + + /// A `.ready` staging folder (the state a copy reads from) next to a + /// destination whose copy queue names `jobs`, each a file in the staging + /// folder and the status its job reached: the disk a transfer that was + /// quit part-way through leaves behind. + private func seedReadyStagingWithQueue( + parent: URL, + name: String, + assetIDs: [String] = ["a", "b"], + updatedAt: Date, + jobs: [(file: String, status: CopyJobStatus)], + resolveJobPaths: Bool = false + ) throws -> (staging: URL, destination: URL) { + let staging = parent.appendingPathComponent(name, isDirectory: true) + let destination = makeTempParent() + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + let database = try OrganizerDatabase(url: destination.appendingPathComponent(".organize_cache.db")) + defer { database.close() } + let base = resolveJobPaths ? staging.resolvingSymlinksInPath().standardizedFileURL.path : staging.path + try database.enqueueQueuedJobs(jobs.enumerated().map { index, job in + QueuedCopyJob( + sourcePath: base + "/" + job.file, + destinationPath: destination.appendingPathComponent("2024/photo-\(index).jpg").path, + hash: FileIdentity(size: 1, digest: "d\(index)").rawValue, + status: job.status + ) + }) + let seeded = try seedCheckpoint( + parent: parent, name: name, state: .ready, assetIDs: assetIDs, + updatedAt: updatedAt, destinationPath: destination.path + ) + return (seeded, destination) + } + + private func capture(_ destination: URL) -> PhotosImportStore.DestinationCapture { + PhotosImportStore.DestinationCapture(path: destination.path, bookmarkKeys: ["k"]) + } + + @MainActor + func testRelaunchKeepsReadyStagingWhilePendingCopyJobsStillReferenceIt() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "mid-copy", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .pending)] + ) + + // A new store over the same staging parent is a relaunch: nothing is + // remembered in memory, so only what is on disk can protect the folder. + let relaunched = makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + relaunched.refreshResumableImport(destination: capture(destination)) + + XCTAssertTrue(exists(staging.path), "A staged export a pending copy job reads from must survive launch cleanup") + XCTAssertTrue(exists(staging.appendingPathComponent("b.jpg").path)) + XCTAssertNil(relaunched.resumable, "A copy-phase folder is kept for the copy, not offered as an interrupted export") + } + + @MainActor + func testReferenceIsFoundWhenTheJobPathIsTheSymlinkResolvedForm() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "mid-copy", assetIDs: ["a"], updatedAt: fixedDate(10), + jobs: [("a.jpg", .pending)], resolveJobPaths: true + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + + XCTAssertTrue(exists(staging.path)) + } + + @MainActor + func testReferencedStagingSurvivesRegardlessOfAge() throws { + // Age never overrides proof: the queue still names the folder. + let parent = makeTempParent() + let (staging, _) = try seedReadyStagingWithQueue( + parent: parent, name: "old", assetIDs: ["a"], updatedAt: fixedDate(-86_400 * 400), + jobs: [("a.jpg", .pending)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent).refreshResumableImport(destination: nil) + + XCTAssertTrue(exists(staging.path)) + } + + private func context(staging: URL, destination: URL) -> PhotosImportContext { + PhotosImportContext( + importID: UUID(), stagingDirectoryURL: staging, destinationPath: destination.path, + destinationBookmarkKeys: ["k"], assetIDs: ["a", "b"], sourceDateHints: [:] + ) + } + + @MainActor + func testCleanupAfterAStoppedCopyKeepsStagingItsPendingJobsStillRead() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "stopped", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .pending)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .cleanupStaging(for: context(staging: staging, destination: destination)) + + XCTAssertTrue(exists(staging.appendingPathComponent("b.jpg").path), "A stopped copy can only be finished from its staged export") + } + + @MainActor + func testCleanupAfterAFinishedCopyRemovesStaging() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "done", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .copied)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .cleanupStaging(for: context(staging: staging, destination: destination)) + + XCTAssertFalse(exists(staging.path)) + } + + @MainActor + func testRelaunchRemovesReadyStagingOnceItsCopyJobsFinished() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "finished", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .skipped)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + + XCTAssertFalse(exists(staging.path), "Staging nothing references any more is cleaned up") + } + + @MainActor + func testStagingIsRemovedOnceTheResumedCopyHasFinishedIt() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "mid-copy", assetIDs: ["a"], updatedAt: fixedDate(10), + jobs: [("a.jpg", .pending)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + XCTAssertTrue(exists(staging.path)) + + let database = try OrganizerDatabase(url: destination.appendingPathComponent(".organize_cache.db")) + try database.updateJobStatus(sourcePath: staging.path + "/a.jpg", status: .copied) + database.close() + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + XCTAssertFalse(exists(staging.path), "Once the copy finished, the next launch frees the space") + } + + @MainActor + func testRelaunchRemovesReadyStagingTheQueueNeverReferenced() throws { + let parent = makeTempParent() + let unrelated = try seedReadyStagingWithQueue( + parent: parent, name: "unrelated", assetIDs: ["a"], updatedAt: fixedDate(10), + jobs: [] + ) + // A pending job for some other source does not protect this folder. + let database = try OrganizerDatabase(url: unrelated.destination.appendingPathComponent(".organize_cache.db")) + try database.enqueueQueuedJobs([QueuedCopyJob( + sourcePath: "/Volumes/Other/IMG_1.jpg", + destinationPath: unrelated.destination.appendingPathComponent("x.jpg").path, + hash: FileIdentity(size: 1, digest: "z").rawValue, + status: .pending + )]) + database.close() + // A reachable destination with no copy queue has nothing to resume. + let emptyDestination = makeTempParent() + try FileManager.default.createDirectory(at: emptyDestination, withIntermediateDirectories: true) + let noQueue = try seedCheckpoint( + parent: parent, name: "no-queue", state: .ready, assetIDs: ["a"], + updatedAt: fixedDate(20), destinationPath: emptyDestination.path + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(unrelated.destination)) + + XCTAssertFalse(exists(unrelated.staging.path)) + XCTAssertFalse(exists(noQueue.path)) + } + + @MainActor + func testStagingIsKeptWhileTheDestinationCannotBeChecked() throws { + let parent = makeTempParent() + let now = Date(timeIntervalSince1970: 1_700_000_000) + // The destination is an unmounted volume: its absence proves nothing. + let unmounted = try seedCheckpoint( + parent: parent, name: "unmounted", state: .ready, assetIDs: ["a"], + updatedAt: now.addingTimeInterval(-86_400), destinationPath: "/Volumes/PIR-not-mounted/Photos" + ) + // The destination is reachable but its queue cannot be read. + let unreadableDestination = makeTempParent() + try FileManager.default.createDirectory(at: unreadableDestination, withIntermediateDirectories: true) + try Data("this is not a database".utf8).write(to: unreadableDestination.appendingPathComponent(".organize_cache.db")) + let unreadable = try seedCheckpoint( + parent: parent, name: "unreadable", state: .ready, assetIDs: ["a"], + updatedAt: now.addingTimeInterval(-86_400), destinationPath: unreadableDestination.path + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent).refreshResumableImport(destination: nil) + + XCTAssertTrue(exists(unmounted.path), "Never infer that an unreachable destination has nothing pending") + XCTAssertTrue(exists(unreadable.path), "Never infer that an unreadable queue has nothing pending") + } + + @MainActor + func testUncheckableStagingIsEventuallyCleanedUp() throws { + let parent = makeTempParent() + let now = Date(timeIntervalSince1970: 1_700_000_000) + let abandoned = try seedCheckpoint( + parent: parent, name: "abandoned", state: .ready, assetIDs: ["a"], + updatedAt: now.addingTimeInterval(-86_400 * 31), destinationPath: "/Volumes/PIR-not-mounted/Photos" + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent).refreshResumableImport(destination: nil) + + XCTAssertFalse(exists(abandoned.path), "Staging nobody can prove is needed does not stay for ever") + } + // AGENTS-INVARIANT: 22 @MainActor func testCheckpointSaveFailureStopsTheExportInsteadOfContinuing() async throws { From a27dc513de890cfe5005a530da005194d0ccb10f Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:21:42 -0800 Subject: [PATCH 14/17] Dedupe: a unique RAW partner is never trashed; faster free offer; review kept - INV-14: the copy that has a RAW or Live Photo video partner is the suggested keeper, and pair fan-out leaves a partner outside every cluster in place. A Live Photo video, which is never clustered, goes only when a kept copy has its own video. - The free removal batch is found by a prefix search (about 2 planner runs, was about 101); every candidate is still a checked planner result. - A commit that moved nothing keeps the saved review. - Quick Review Accept the Rest leaves groups skipped earlier unreviewed. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 2 +- .../Views/Deduplicate/RapidTriageView.swift | 31 ++- .../Stores/DeduplicateSessionStore.swift | 26 +- .../DeduplicationPlanner.swift | 31 +++ .../ChronoframeCore/DuplicateClusterer.swift | 4 + .../FreeDedupeBatchPlanner.swift | 118 +++++++-- ...frameCoreFreeDedupeBatchPlannerTests.swift | 111 ++++++++- .../DeduplicateSessionStoreTests.swift | 76 +++++- .../DeduplicateTests.swift | 37 ++- .../DeduplicationPlannerGroupRailTests.swift | 11 +- ...duplicationPlannerPartnerFanoutTests.swift | 223 ++++++++++++++++++ .../DeduplicateReviewViewsTests.swift | 48 ++++ 12 files changed, 664 insertions(+), 54 deletions(-) create mode 100644 ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift diff --git a/AGENTS.md b/AGENTS.md index 24d9af6b..30b06ee2 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. 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-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 a duplicate: marked Delete, or auto-selected for Delete by a high-confidence cluster. A partner outside every cluster stays, because it is the only copy of that content; the one exception is a Live Photo video (never clustered), which goes with its still only when a copy the plan keeps has its own video. Among otherwise identical copies, the one that has a RAW or Live Photo video partner is the suggested keeper, so the lone copy is the one removed. 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/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift index 1d71176b..d881d7c0 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift @@ -16,6 +16,17 @@ enum QuickReviewScope { clusters.filter { !reviewedIDs.contains($0.id) && laneOf($0) == lane } } + /// What "Accept the Rest" accepts: the groups from the person's position on that are + /// still unreviewed. A group they skipped earlier is behind that position and stays whole. + static func restClusters( + from walk: [DuplicateCluster], + currentIndex: Int, + reviewedIDs: Set + ) -> [DuplicateCluster] { + guard currentIndex < walk.count else { return [] } + return walk[max(currentIndex, 0)...].filter { !reviewedIDs.contains($0.id) } + } + /// The number on "Accept the Rest": only for nearly identical groups, only once /// the person has passed at least one group, and only while groups remain. static func acceptTheRestCount(lane: DeduplicateReviewLane, currentIndex: Int, remainingInLane: Int) -> Int? { @@ -330,19 +341,29 @@ struct RapidTriageView: View { advance() } - /// Groups still unreviewed in this lane: exactly what "Accept the Rest" accepts. + /// The groups from the person's position on that are still unreviewed: exactly what + /// "Accept the Rest" accepts. Groups they skipped earlier are not among them. + private var restClusters: [DuplicateCluster] { + QuickReviewScope.restClusters( + from: clustersToReview, + currentIndex: currentIndex, + reviewedIDs: sessionStore.approvedClusterIDs + ) + } + private var acceptTheRestCount: Int? { QuickReviewScope.acceptTheRestCount( lane: lane, currentIndex: currentIndex, - remainingInLane: sessionStore.laneSummaries[lane]?.groups ?? 0 + remainingInLane: restClusters.count ) } - /// Accepts the suggestion for every group still unreviewed in the nearly identical - /// lane, then shows the completion screen. Nothing is moved to the Trash here. + /// Accepts the suggestion for every group from here on that is still unreviewed, + /// then shows the completion screen. Skipped groups stay unreviewed. Nothing is + /// moved to the Trash here. private func acceptTheRest() { - sessionStore.acceptSuggestions(in: .nearlyIdentical) + sessionStore.acceptSuggestions(forClusters: restClusters) dragOffset = .zero currentIndex = clustersToReview.count } diff --git a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift index 5f4948cb..67627a8f 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift @@ -610,6 +610,29 @@ public final class DeduplicateSessionStore: ObservableObject { scheduleSave() } + /// Accepts the suggestions for the listed groups that are still unreviewed and + /// automatically eligible. Any other group, including one the person skipped, is left alone. + public func acceptSuggestions(forClusters candidates: [DuplicateCluster]) { + let listed = candidates.filter { + DeduplicationPlanner.isAutomaticCommitEligible($0) && !approvedClusterIDs.contains($0.id) + } + guard !listed.isEmpty else { return } + let oldDecisions = decisions + let oldApproved = approvedClusterIDs + var byPath = decisions.byPath + for (path, decision) in suggestedDecisions(for: listed).byPath { + byPath[path] = decision + } + decisions = DedupeDecisions(byPath: byPath, pairKeepOverrides: decisions.pairKeepOverrides) + approvedClusterIDs.formUnion(listed.map(\.id)) + registerUndo( + oldDecisions: oldDecisions, + oldApproved: oldApproved, + actionName: String(localized: "Accept Nearly Identical", bundle: Bundle.module) + ) + scheduleSave() + } + /// Reviewed groups in which every member is marked Delete. public var fullyMarkedClusterIDs: Set { Set(reviewedClusters.filter { cluster in @@ -837,7 +860,8 @@ public final class DeduplicateSessionStore: ObservableObject { summary: summary, completedAt: Date() ) - if !preparedPlanIsFreeBatch { + // A commit that moved nothing has not used up the review, so it stays for the next scan. + if !preparedPlanIsFreeBatch && summary.deletedCount > 0 { reviewSnapshotStore.remove(folderPath: destinationPath) restoredReview = nil savedReviewForCurrentFolder = nil diff --git a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift index c7cd5ce3..106a60e3 100644 --- a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift +++ b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift @@ -24,6 +24,11 @@ import Foundation /// 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. +/// A partner is trashed only when it is itself a duplicate (INV-14): a +/// partner outside every cluster stays, except a Live Photo MOV, which is +/// never clustered and so is added only when a member the plan keeps owns +/// a MOV of its own. The scanner also ranks the copy that has a partner +/// as the suggested keeper, so the lone copy is the one removed. public enum DeduplicationPlanner { public static func plan( decisions: DedupeDecisions, @@ -182,6 +187,18 @@ public enum DeduplicationPlanner { if decisions.pairKeepOverrides.contains(partner) { continue } + // INV-14: a partner is trashed only when it is itself a + // duplicate. A partner that is no cluster member is never a + // duplicate by exact content: RAW files are identity-hashed + // and exact-clustered, so a RAW outside every cluster has no + // identical copy and stays. Live Photo MOVs are never + // clustered, so a MOV outside every cluster goes only when a + // member this plan keeps owns a MOV of its own. + if effective[partner] == nil { + guard kind == .livePhoto, clusterKeepsAMemberWithItsOwnPartner( + of: kind, in: cluster, planItems: planItems, configuration: configuration + ) else { continue } + } if planItems[partner] != nil { continue } guard let expectedIdentity = snapshot.identitiesByPath[partner] else { continue @@ -307,6 +324,20 @@ public enum DeduplicationPlanner { // MARK: - Helpers + private static func clusterKeepsAMemberWithItsOwnPartner( + of kind: DeduplicatePairDetector.Pair.Kind, + in cluster: DuplicateCluster, + planItems: [String: DeduplicationPlan.Item], + configuration: DeduplicateConfiguration + ) -> Bool { + cluster.members.contains { member in + planItems[member.path] == nil + && member.pairedPath != nil + && pairKind(for: member) == kind + && pairKindEnabled(kind, in: configuration) + } + } + public static func isAutomaticCommitEligible(_ cluster: DuplicateCluster) -> Bool { // AGENTS-INVARIANT: 6 — Structural guard: a non-exact video cluster is // never eligible for automatic deletion, even if a future annotation diff --git a/ui/Sources/ChronoframeCore/DuplicateClusterer.swift b/ui/Sources/ChronoframeCore/DuplicateClusterer.swift index 2d40b67a..15d929d1 100644 --- a/ui/Sources/ChronoframeCore/DuplicateClusterer.swift +++ b/ui/Sources/ChronoframeCore/DuplicateClusterer.swift @@ -229,6 +229,10 @@ public enum DuplicateClusterer { let rhsSmile = rhs.smileScore ?? 0 if lhsSmile != rhsSmile { return lhsSmile > rhsSmile } if lhs.isRaw != rhs.isRaw { return lhs.isRaw } + // INV-14: among otherwise tied copies, the one with a RAW/MOV partner + // is kept, so the lone copy is the one removed and a partner is + // never trashed for lack of a keeper that owns one. + if (lhs.pairedPath != nil) != (rhs.pairedPath != nil) { return lhs.pairedPath != nil } return lhs.path < rhs.path } diff --git a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift index d057891d..ade7c172 100644 --- a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift +++ b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift @@ -20,9 +20,11 @@ public enum FreeDedupeBatchPlanner { configuration: DeduplicateConfiguration, snapshot: DeduplicateScanSnapshot, fanoutProtectedPaths: Set, - limit: Int + limit: Int, + onPlannerRun: (() -> Void)? = nil ) -> FreeDedupeBatch? { // 1. The person's full reviewed plan. + onPlannerRun?() let full = DeduplicationPlanner.plan( decisions: decisions, clusters: reviewedClusters, @@ -46,28 +48,35 @@ public enum FreeDedupeBatchPlanner { } } - // 3 and 4. Grow the selection one group at a time. Forcing Keep is not - // monotone (pair Keep-wins can carry a Keep into another group and - // un-skip a group the all-Delete rail skipped), so a candidate is - // accepted only if it fits and deletes nothing the full plan does not. - var selected: Set = [] - var selectedOrder: [UUID] = [] - var accepted: DeduplicationPlan? + // 3 and 4. Search over how many groups of `ordered` to take. Forcing + // Keep is not monotone (pair Keep-wins can carry a Keep into another + // group and un-skip a group the all-Delete rail skipped), so a prefix + // is accepted only if it fits and deletes nothing the full plan does + // not. Each probe is one planner run, so the search starts from the + // prefix the full plan's own per-group counts predict and, only if that + // fails, gallops down then bisects: one run in the common case, about + // log2(N) at worst, instead of one per group. `lo` always passed both + // checks, `hi` always failed (the whole list is the full plan, which + // exceeds the limit). + var forced = ForcedKeepDecisions(decisions: decisions, groups: ordered.map { $0.members.map(\.path) }) + var deletesPerGroup: [UUID: Int] = [:] + for item in full.items { deletesPerGroup[item.owningClusterID, default: 0] += 1 } + var estimate = 0 + var running = 0 for cluster in ordered { - var trial = selected - trial.insert(cluster.id) - - var candidateDecisions = decisions - var byPath = decisions.byPath - for other in reviewedClusters where !trial.contains(other.id) { - for member in other.members { - byPath[member.path] = .keep - } - } - candidateDecisions.byPath = byPath + running += deletesPerGroup[cluster.id, default: 0] + guard running <= limit else { break } + estimate += 1 + } + var accepted: DeduplicationPlan? + var lo = 0 + var hi = ordered.count + func probe(_ prefixLength: Int) -> Bool { + forced.select(prefixLength) + onPlannerRun?() let candidate = DeduplicationPlanner.plan( - decisions: candidateDecisions, + decisions: forced.decisions, clusters: reviewedClusters, configuration: configuration, snapshot: snapshot, @@ -76,12 +85,33 @@ public enum FreeDedupeBatchPlanner { let withinFullPlan = candidate.items.allSatisfy { item in fullIdentities[item.path] == item.expectedIdentity } - guard candidate.count <= limit, withinFullPlan else { break } - + guard candidate.count <= limit, withinFullPlan else { return false } accepted = candidate - selected = trial - selectedOrder.append(cluster.id) + return true + } + + let first = min(max(estimate, 1), hi - 1) + if first >= 1 { + if probe(first) { + // The full plan's own count for the next group already + // overshoots the limit, so a larger prefix is not worth + // another full planner run to look for. + lo = first + hi = first + 1 + } else { + hi = first + var step = 1 + while hi > 1 { + let next = max(hi - step, 1) + if probe(next) { lo = next; break } else { hi = next; step *= 2 } + } + } + while hi - lo > 1 { + let mid = (lo + hi) / 2 + if probe(mid) { lo = mid } else { hi = mid } + } } + let selectedOrder = ordered.prefix(lo).map(\.id) // 5. guard let plan = accepted, !plan.items.isEmpty else { return nil } @@ -93,3 +123,43 @@ public enum FreeDedupeBatchPlanner { ) } } + +/// The decisions with every group after the first `selectedCount` forced to +/// Keep. Moving the prefix only touches the paths of the groups it crosses, +/// so a probe does not rebuild the whole dictionary. A path listed by several +/// groups stays Keep while any unselected group still lists it. +private struct ForcedKeepDecisions { + private let original: [String: DedupeDecision] + private let groups: [[String]] + private var unselectedGroupsListing: [String: Int] = [:] + private var selectedCount = 0 + private(set) var decisions: DedupeDecisions + + init(decisions: DedupeDecisions, groups: [[String]]) { + original = decisions.byPath + self.groups = groups + self.decisions = decisions + for path in groups.joined() { + unselectedGroupsListing[path, default: 0] += 1 + self.decisions.byPath[path] = .keep + } + } + + mutating func select(_ count: Int) { + while selectedCount < count { + for path in groups[selectedCount] { + let remaining = (unselectedGroupsListing[path] ?? 1) - 1 + unselectedGroupsListing[path] = remaining + if remaining == 0 { decisions.byPath[path] = original[path] } + } + selectedCount += 1 + } + while selectedCount > count { + selectedCount -= 1 + for path in groups[selectedCount] { + unselectedGroupsListing[path, default: 0] += 1 + decisions.byPath[path] = .keep + } + } + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift index 5f6a6316..1c2328b5 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift @@ -97,6 +97,9 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { fixture.addGroup("a", deletes: 2, lane: .identical) fixture.addGroup("b", deletes: 2, lane: .nearlyIdentical) fixture.addGroup("c", deletes: 2, lane: .lookAtEach) { members in + // The kept still owns a movie of its own, so the dropped still's movie is a duplicate. + members[0].pairedPath = "/fx/c/keep.mov" + members[0].isLivePhotoStill = true members[1].pairedPath = "/fx/c/d1.mov" members[1].isLivePhotoStill = true } @@ -212,6 +215,9 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { var fixture = Fixture() // a/d1 is a Live Photo still whose MOV is not in any cluster; the person kept the MOV. fixture.addGroup("a", deletes: 1, lane: .lookAtEach) { members in + // The kept still owns a movie of its own, so the dropped still's movie is a duplicate. + members[0].pairedPath = "/fx/a/keep.mov" + members[0].isLivePhotoStill = true members[1].pairedPath = "/fx/a/d1.mov" members[1].isLivePhotoStill = true } @@ -251,14 +257,15 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { 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. + // INV-14: a DNG outside the passed groups is unique content, so even an unprotected + // plan no longer carries it along with its JPEG. 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" }) + XCTAssertFalse(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"]) @@ -333,6 +340,106 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { XCTAssertEqual(Set(skipped.items.map(\.path)), ["/fx/z/z1.jpg"]) } + // MARK: Search + + /// Limit 1 on the Y/Z/W review above: the walk used to stop at Y, whose candidate + /// un-skips Y. The prefix search verifies Y+Z too, and that candidate passes both + /// checks, so the free batch is Z's single file. + func testPrefixSearchTakesALaterPrefixThatPassesBothChecks() throws { + var fixture = Fixture() + fixture.addGroup("y", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/y/y1.jpg" + members[1].path = "/fx/y/y2.jpg" + members[0].pairedPath = "/fx/z/z1.jpg" + } + let z = fixture.addGroup("z", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/z/z2.jpg" + members[1].path = "/fx/z/z1.jpg" + members[1].pairedPath = "/fx/y/y1.jpg" + } + fixture.addGroup("w", deletes: 1, lane: .lookAtEach) + fixture.decisions.byPath = [ + "/fx/y/y1.jpg": .delete, + "/fx/y/y2.jpg": .delete, + "/fx/z/z1.jpg": .delete, + "/fx/z/z2.jpg": .keep, + "/fx/w/keep.jpg": .keep, + "/fx/w/d1.jpg": .delete, + ] + XCTAssertEqual(fixture.fullPlan().count, 2) + + let batch = try XCTUnwrap(fixture.batch(limit: 1)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/z/z1.jpg"]) + XCTAssertEqual(batch.includedClusterIDs, [z.id]) + XCTAssertEqual(batch.deferredFileCount, 1) + } + + /// The predicted prefix fails (it un-skips Y); the search falls back to a smaller + /// prefix that passes, as the one-group-at-a-time walk did. + func testFailedPredictionFallsBackToASmallerPassingPrefix() throws { + var fixture = Fixture() + let p = fixture.addGroup("p", deletes: 1, lane: .lookAtEach) + fixture.addGroup("y", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/y/y1.jpg" + members[1].path = "/fx/y/y2.jpg" + members[0].pairedPath = "/fx/z/z1.jpg" + } + fixture.addGroup("w", deletes: 1, lane: .lookAtEach) + fixture.addGroup("z", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/z/z2.jpg" + members[1].path = "/fx/z/z1.jpg" + members[1].pairedPath = "/fx/y/y1.jpg" + } + fixture.decisions.byPath = [ + "/fx/p/keep.jpg": .keep, + "/fx/p/d1.jpg": .delete, + "/fx/y/y1.jpg": .delete, + "/fx/y/y2.jpg": .delete, + "/fx/z/z1.jpg": .delete, + "/fx/z/z2.jpg": .keep, + "/fx/w/keep.jpg": .keep, + "/fx/w/d1.jpg": .delete, + ] + XCTAssertEqual(Set(fixture.fullPlan().items.map(\.path)), ["/fx/p/d1.jpg", "/fx/z/z1.jpg", "/fx/w/d1.jpg"]) + + let batch = try XCTUnwrap(fixture.batch(limit: 2)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/p/d1.jpg"]) + XCTAssertEqual(batch.includedClusterIDs, [p.id]) + } + + /// The offer is recomputed on the main actor whenever a decision changes, so the + /// number of full planner runs must stay logarithmic in the reviewed group count, + /// not one per group taken. + func testTenThousandReviewedGroupsNeedOnlyAHandfulOfPlannerRuns() throws { + var fixture = Fixture() + let lanes = DeduplicateReviewLane.allCases + for index in 0..<10_000 { + fixture.addGroup("g\(index)", deletes: 1 + index % 3, lane: lanes[index % lanes.count]) + } + let full = fixture.fullPlan() + XCTAssertGreaterThan(full.count, 100) + let fullIdentities = Dictionary(uniqueKeysWithValues: full.items.map { ($0.path, $0.expectedIdentity) }) + + var runs = 0 + let batch = try XCTUnwrap(FreeDedupeBatchPlanner.batch( + decisions: fixture.decisions, + reviewedClusters: fixture.clusters, + configuration: fixture.configuration, + snapshot: fixture.snapshot, + fanoutProtectedPaths: fixture.fanoutProtectedPaths, + limit: 100, + onPlannerRun: { runs += 1 } + )) + + XCTAssertLessThanOrEqual(runs, 4, "the old walk ran the planner about 100 times") + XCTAssertLessThanOrEqual(batch.plan.count, 100) + XCTAssertGreaterThan(batch.plan.count, 90, "the prediction should fill the allowance") + for item in batch.plan.items { + XCTAssertEqual(fullIdentities[item.path], item.expectedIdentity) + } + XCTAssertEqual(batch.deferredFileCount, full.count - batch.plan.count) + } + // MARK: Property func testPropertyRandomReviewsNeverExceedLimitOrLeaveTheFullPlan() { diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift index d99147fd..4bc8e72d 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift @@ -171,7 +171,9 @@ final class DeduplicateSessionStoreTests: XCTestCase { path: "/dest/OTHER.HEIC", size: 50, modificationTime: 0, - qualityScore: 0.9 + qualityScore: 0.9, + isLivePhotoStill: true, + pairedPath: "/dest/OTHER.MOV" ) let cluster = DuplicateCluster( id: clusterID, @@ -618,7 +620,9 @@ final class DeduplicateSessionStoreTests: XCTestCase { path: "/dest/OTHER.HEIC", size: 50, modificationTime: 0, - qualityScore: 0.9 + qualityScore: 0.9, + isLivePhotoStill: true, + pairedPath: "/dest/OTHER.MOV" ) let cluster = DuplicateCluster( kind: .burst, @@ -1407,14 +1411,15 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertTrue(committed) XCTAssertEqual(Set(engine.lastCommitPlan?.items.map(\.path) ?? []), expected) - // Premise: unprotected, the DNG keeper rides along with its JPEG. + // INV-14: a DNG outside the passed groups is unique content, so even an unprotected + // plan no longer carries it 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" }) + XCTAssertFalse(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 @@ -1483,6 +1488,24 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.laneSummaries[.nearlyIdentical]?.groups, 0) } + @MainActor + func testAcceptSuggestionsForClustersTakesOnlyTheGivenUnreviewedEligibleGroups() async throws { + let listed = laneCluster("listed", lane: .nearlyIdentical, deletes: 1) + let unlisted = laneCluster("unlisted", lane: .nearlyIdentical, deletes: 1) + let alreadyDone = laneCluster("alreadyDone", lane: .nearlyIdentical, deletes: 1) + let look = laneCluster("look", lane: .lookAtEach, deletes: 1) + let (store, _) = await scannedLaneStore([listed, unlisted, alreadyDone, look]) + store.acceptSuggestionsForCluster(alreadyDone) + let decisionsBefore = store.decisions + + store.acceptSuggestions(forClusters: [listed, alreadyDone, look]) + + XCTAssertEqual(store.approvedClusterIDs, [listed.id, alreadyDone.id], "Only listed, eligible, unreviewed groups") + XCTAssertFalse(store.approvedClusterIDs.contains(unlisted.id)) + XCTAssertFalse(store.approvedClusterIDs.contains(look.id), "A group to look at stays review-only") + XCTAssertEqual(store.decisions, decisionsBefore) + } + @MainActor func testAcceptLookAtEachDoesNothing() async throws { let look = laneCluster("look", lane: .lookAtEach, deletes: 1) @@ -1758,7 +1781,11 @@ final class DeduplicateSessionStoreTests: XCTestCase { var still = PhotoCandidate(path: "/dest/live/d1.heic", size: 100, modificationTime: 0) still.pairedPath = "/dest/live/d1.mov" still.isLivePhotoStill = true - let members = [PhotoCandidate(path: "/dest/live/keep.heic", size: 100, modificationTime: 0), still] + // The kept still owns a movie of its own, so the dropped still's movie is a duplicate. + var keeper = PhotoCandidate(path: "/dest/live/keep.heic", size: 100, modificationTime: 0) + keeper.pairedPath = "/dest/live/keep.mov" + keeper.isLivePhotoStill = true + let members = [keeper, still] let cluster = DuplicateCluster( kind: .exactDuplicate, members: members, @@ -1950,6 +1977,45 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.decisions.byPath["/dest/live/d1.heic"], .keep) } + /// A commit that moved nothing (every item failed or was skipped) has not used + /// up the person's review, so the saved review stays for the next scan. + @MainActor + func testCommitThatMovedNothingKeepsSavedReview() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let cluster = laneCluster("only", lane: .identical, deletes: 2) + let nothingMoved = DeduplicateCommitSummary(deletedCount: 0, failedCount: 2, bytesReclaimed: 0, receiptPath: nil, hardDelete: false) + let (store, _) = await scannedLaneStore([cluster], commitEvents: [.complete(nothingMoved)], snapshotStore: snapshotStore) + store.refreshSavedReview(folderPath: "/dest") + store.acceptSuggestions(in: .identical) + store.prepareReviewedCommitPlan() + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let completed = await waitForCondition { store.status == .completed } + XCTAssertTrue(completed) + + XCTAssertEqual(store.commitSummary?.deletedCount, 0) + XCTAssertTrue(snapshotStore.removals.isEmpty, "Nothing moved, so the review work is not spent") + XCTAssertNotNil(snapshotStore.load(folderPath: "/dest")) + XCTAssertNotNil(store.savedReviewForCurrentFolder) + } + + /// One file moved and one failed: the review is spent, as before. + @MainActor + func testCommitThatMovedSomethingStillRemovesSavedReviewEvenWithFailures() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let cluster = laneCluster("only", lane: .identical, deletes: 2) + let partial = DeduplicateCommitSummary(deletedCount: 1, failedCount: 1, bytesReclaimed: 100, receiptPath: nil, hardDelete: false) + let (store, _) = await scannedLaneStore([cluster], commitEvents: [.complete(partial)], snapshotStore: snapshotStore) + store.refreshSavedReview(folderPath: "/dest") + store.acceptSuggestions(in: .identical) + store.prepareReviewedCommitPlan() + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let completed = await waitForCondition { store.status == .completed } + XCTAssertTrue(completed) + + XCTAssertEqual(snapshotStore.removals, ["/dest"]) + XCTAssertNil(store.savedReviewForCurrentFolder) + } + @MainActor func testOrdinaryCommitStillRemovesSavedReview() async throws { let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift index c586cfd4..5dcef12d 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift @@ -805,13 +805,14 @@ final class DeduplicateTests: XCTestCase { // MARK: - DeduplicationPlanner - /// Verifies step 5 of the planner — paired singletons (typically the - /// RAW half of a RAW+JPEG pair sitting outside any duplicate cluster) - /// are fanned into the plan when their JPEG counterpart inside the - /// cluster is deleted and the RAW pairing toggle is on. Mirrors the - /// "partner outside cluster" pattern used by + /// Verifies step 5 of the planner — a RAW half of a RAW+JPEG pair + /// sitting outside any duplicate cluster has no identical copy in the + /// scan, so deleting its JPEG counterpart inside the cluster must NOT + /// fan it into the plan, even with the RAW pairing toggle on (INV-14). + /// Mirrors the "partner outside cluster" pattern used by /// `testPlannerHonorsPairTogglesIndependently`. - func testPlannerExpandsRawJpegPairWhenToggleEnabled() { + // AGENTS-INVARIANT: 14 + func testPlannerLeavesUniqueRawPartnerWhenToggleEnabled() { let jpeg = candidate(path: "/dest/IMG.JPG", pairedPath: "/dest/IMG.CR2") let other = candidate(path: "/dest/OTHER.JPG") @@ -830,7 +831,7 @@ final class DeduplicateTests: XCTestCase { let plan = DeduplicationPlanner.plan(decisions: decisions, clusters: [cluster], configuration: config, snapshot: testScanSnapshot(for: [cluster])) let paths = Set(plan.pathsToDelete) XCTAssertTrue(paths.contains("/dest/IMG.JPG")) - XCTAssertTrue(paths.contains("/dest/IMG.CR2"), "Singleton RAW partner must be fanned into the plan") + XCTAssertFalse(paths.contains("/dest/IMG.CR2"), "A RAW partner outside every cluster is unique content and must stay") XCTAssertFalse(paths.contains("/dest/OTHER.JPG")) } @@ -1242,7 +1243,9 @@ final class DeduplicateTests: XCTestCase { configuration: configRawOn, snapshot: testScanSnapshot(for: [cluster]) ) - XCTAssertTrue(Set(planRawOn.pathsToDelete).contains("/dest/IMG.CR2")) + // INV-14: the RAW sits outside every cluster, so it is unique and + // stays whichever way the toggle is set. + XCTAssertFalse(Set(planRawOn.pathsToDelete).contains("/dest/IMG.CR2")) } /// Live Photo pairing toggle is honored independently of the @@ -1295,7 +1298,12 @@ final class DeduplicateTests: XCTestCase { pairedPath: "/dest/IMG.MOV", isLivePhotoStill: true ) - let other = candidate(path: "/dest/OTHER.HEIC", qualityScore: 0.9) + let other = candidate( + path: "/dest/OTHER.HEIC", + qualityScore: 0.9, + pairedPath: "/dest/OTHER.MOV", + isLivePhotoStill: true + ) let cluster = DuplicateCluster( kind: .burst, members: [heic, other], @@ -1454,7 +1462,12 @@ final class DeduplicateTests: XCTestCase { pairedPath: "/dest/IMG.MOV", isLivePhotoStill: true ) - let other = candidate(path: "/dest/OTHER.HEIC", qualityScore: 0.9) + let other = candidate( + path: "/dest/OTHER.HEIC", + qualityScore: 0.9, + pairedPath: "/dest/OTHER.MOV", + isLivePhotoStill: true + ) let cluster = DuplicateCluster( kind: .burst, members: [heic, other], @@ -1499,7 +1512,9 @@ final class DeduplicateTests: XCTestCase { let other = candidate( path: temporaryDirectory.appendingPathComponent("OTHER.HEIC").path, qualityScore: 0.9, - size: 50 + size: 50, + pairedPath: temporaryDirectory.appendingPathComponent("OTHER.MOV").path, + isLivePhotoStill: true ) let cluster = DuplicateCluster( kind: .burst, diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift index 3cb6d00f..034171fc 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift @@ -133,14 +133,15 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { 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. + // INV-14: a DNG outside the passed groups is unique content, so even without the + // protected set it no longer 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]) + XCTAssertEqual(Set(unprotected.items.map(\.path)), [jpegB.path]) } // AGENTS-INVARIANT: 14 @@ -173,8 +174,8 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { } // AGENTS-INVARIANT: 14 - func testPairPartnerInNoGroupStillFansOut() { - // Only the protected paths are shielded; a true singleton partner is unchanged behaviour. + func testPairPartnerInNoGroupIsNeverFannedOut() { + // A RAW in no group has no identical copy in the scan, so it stays (INV-14). 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]) @@ -188,7 +189,7 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { fanoutProtectedPaths: ["/lib/c/unrelated.dng"] ) - XCTAssertEqual(Set(plan.items.map(\.path)), [jpegB.path, "/lib/b/X.dng"]) + XCTAssertEqual(Set(plan.items.map(\.path)), [jpegB.path]) } // AGENTS-INVARIANT: 14 diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift new file mode 100644 index 00000000..774f28d8 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift @@ -0,0 +1,223 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +/// INV-14 partner rule: the copy that has a RAW/MOV partner is the suggested +/// keeper, and a partner is trashed only when it is itself a duplicate. A RAW +/// outside every cluster has no identical copy in the scan (RAW files are +/// identity-hashed and exact-clustered), so fan-out never adds it. A Live +/// Photo MOV is never clustered, so a singleton MOV is added only when a +/// member the plan keeps owns a MOV of its own. +final class DeduplicationPlannerPartnerFanoutTests: XCTestCase { + // MARK: Keeper suggestion + + // AGENTS-INVARIANT: 14 + func testPairedCopyOutranksLoneCopyWhenOtherwiseTied() throws { + // The lone copy sorts first by path, so only the partner tie-break can pick the paired one. + let lone = candidate("/lib/a/X.jpg") + let paired = candidate("/lib/z/X.jpg", pairedPath: "/lib/z/X.dng") + + let clusters = DuplicateClusterer.exactDuplicateClusters( + candidatesByIdentity: [FileIdentity(size: 1_000, digest: "same"): [lone, paired]] + ) + let cluster = try XCTUnwrap(clusters.first) + + XCTAssertEqual(cluster.suggestedKeeperIDs, [paired.id]) + } + + // AGENTS-INVARIANT: 14 + func testPartnerTieBreakDoesNotOverrideQualityEvidence() { + let sharper = candidate("/lib/a/X.jpg", qualityScore: 0.9) + let paired = candidate("/lib/z/X.jpg", pairedPath: "/lib/z/X.dng", qualityScore: 0.5) + + let keepers = DuplicateClusterer.suggestKeeperIDs(for: [paired, sharper]) + + XCTAssertEqual(keepers, [sharper.id]) + } + + // AGENTS-INVARIANT: 14 + func testAcceptingIdenticalCopiesTrashesOnlyTheLoneJpeg() throws { + let lone = candidate("/lib/a/X.jpg") + let paired = candidate("/lib/z/X.jpg", pairedPath: "/lib/z/X.dng") + let cluster = try XCTUnwrap(DuplicateClusterer.exactDuplicateClusters( + candidatesByIdentity: [FileIdentity(size: 1_000, digest: "same"): [lone, paired]] + ).first) + + let decisions = DeduplicationPlanner.automaticDecisions(for: [cluster], configuration: configuration()) + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [lone.path]) + } + + // MARK: RAW fan-out + + // AGENTS-INVARIANT: 14 + func testExplicitDeleteOnPairedJpegLeavesUniqueRawOutOfThePlan() { + let paired = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") + let lone = candidate("/lib/b/X.jpg") + let cluster = exactCluster([paired, lone], keeper: lone) + let decisions = DedupeDecisions(byPath: [paired.path: .delete, lone.path: .keep]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [paired.path]) + } + + // AGENTS-INVARIANT: 14 + func testPartnerThatIsItselfADuplicateStillGoes() { + 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 rawA = candidate("/lib/a/X.dng", isRaw: true, pairedPath: "/lib/a/X.jpg") + let rawB = candidate("/lib/b/X.dng", isRaw: true, pairedPath: "/lib/b/X.jpg") + let jpegs = exactCluster([jpegA, jpegB], keeper: jpegB) + let raws = exactCluster([rawA, rawB], keeper: rawB) + + // Auto-selected: both high-confidence clusters mark the "a" copies Delete. + let auto = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [jpegs, raws], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, raws]) + ) + XCTAssertEqual(Set(auto.items.map(\.path)), [jpegA.path, rawA.path]) + + // Explicit: the partner is marked Delete by the user. + let explicit = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [ + jpegA.path: .delete, jpegB.path: .keep, rawA.path: .delete, rawB.path: .keep, + ]), + clusters: [jpegs, raws], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, raws]) + ) + XCTAssertEqual(Set(explicit.items.map(\.path)), [jpegA.path, rawA.path]) + } + + // MARK: Live Photo fan-out (MOVs are never clustered) + + // AGENTS-INVARIANT: 14 + func testSingletonMovGoesWhenTheKeptStillHasItsOwnMov() { + let kept = candidate("/lib/a/IMG_1.HEIC", pairedPath: "/lib/a/IMG_1.MOV", isLivePhotoStill: true) + let dropped = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let cluster = exactCluster([kept, dropped], keeper: kept) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [dropped.path, "/lib/b/IMG_1.MOV"]) + XCTAssertEqual(plan.items.first { $0.path == "/lib/b/IMG_1.MOV" }?.pairOrigin, .livePhoto) + } + + // AGENTS-INVARIANT: 14 + func testSingletonMovStaysWhenTheKeptStillHasNoMov() { + let kept = candidate("/lib/a/IMG_1.HEIC") + let dropped = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let cluster = exactCluster([kept, dropped], keeper: kept) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [dropped.path]) + } + + // AGENTS-INVARIANT: 14 + func testSingletonMovStaysWhenTheKeptMemberHasARawPartnerInstead() { + // Same extension class: a kept RAW+JPEG partner does not justify trashing a MOV. + let kept = candidate("/lib/a/IMG_1.HEIC", pairedPath: "/lib/a/IMG_1.DNG") + let dropped = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let cluster = exactCluster([kept, dropped], keeper: kept) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [dropped.path]) + } + + // MARK: Sidecars + + // AGENTS-INVARIANT: 14 + func testSidecarSharedWithASurvivingRawPartnerSurvives() { + let paired = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng", sidecarPaths: ["/lib/a/X.xmp"]) + let lone = candidate("/lib/b/X.jpg") + let cluster = exactCluster([paired, lone], keeper: lone) + let snapshot = testScanSnapshot( + for: [cluster], + sidecarOwners: ["/lib/a/X.xmp": ["/lib/a/X.jpg", "/lib/a/X.dng"]] + ) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [paired.path: .delete, lone.path: .keep]), + clusters: [cluster], + configuration: configuration(), + snapshot: snapshot + ) + + XCTAssertEqual(plan.items.map(\.path), [paired.path], "the RAW stays, so the sidecar it shares stays") + } + + // MARK: Helpers + + private func candidate( + _ path: String, + isRaw: Bool = false, + pairedPath: String? = nil, + isLivePhotoStill: Bool = false, + qualityScore: Double = 0.5, + sidecarPaths: [String] = [] + ) -> PhotoCandidate { + PhotoCandidate( + path: path, + size: 1_000, + modificationTime: 0, + qualityScore: qualityScore, + isRaw: isRaw, + isLivePhotoStill: isLivePhotoStill, + pairedPath: pairedPath, + sidecarPaths: sidecarPaths + ) + } + + private func exactCluster(_ members: [PhotoCandidate], keeper: PhotoCandidate) -> DuplicateCluster { + DuplicateCluster( + kind: .exactDuplicate, + members: members, + suggestedKeeperIDs: [keeper.id], + bytesIfPruned: 0, + annotation: ClusterAnnotation( + confidence: .high, + matchReason: MatchReason(kind: .exactDuplicate), + warnings: [] + ) + ) + } + + private func configuration() -> DeduplicateConfiguration { + DeduplicateConfiguration( + destinationPath: "/tmp/destination", + treatRawJpegPairsAsUnit: true, + treatLivePhotoPairsAsUnit: true + ) + } +} diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift index 96dfe6fa..3cea3b84 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift @@ -308,6 +308,54 @@ final class DeduplicateReviewViewsTests: XCTestCase { XCTAssertEqual(AccessibilityIdentifiers.quickReviewAcceptRest, "quickReview.acceptRest") } + /// "Accept the Rest" is the groups from the person's position on. A group they skipped + /// earlier stays unreviewed, and the count on the button is exactly what it accepts. + func testAcceptTheRestLeavesSkippedGroupsAloneAndCountMatches() async throws { + let first = laneCluster("first", lane: .nearlyIdentical) + let skipped = laneCluster("skipped", lane: .nearlyIdentical) + let third = laneCluster("third", lane: .nearlyIdentical) + let fourth = laneCluster("fourth", lane: .nearlyIdentical) + let store = try await scannedStore([first, skipped, third, fourth]) + let walk = QuickReviewScope.clusters( + in: .nearlyIdentical, + from: store.clusters, + reviewedIDs: store.approvedClusterIDs, + laneOf: store.lane(for:) + ) + XCTAssertEqual(walk.map(\.id), [first.id, skipped.id, third.id, fourth.id]) + + // Accept the first group, skip the second, then stop on the third. + store.acceptSuggestionsForCluster(first) + let currentIndex = 2 + let rest = QuickReviewScope.restClusters(from: walk, currentIndex: currentIndex, reviewedIDs: store.approvedClusterIDs) + XCTAssertEqual(rest.map(\.id), [third.id, fourth.id]) + XCTAssertEqual( + QuickReviewScope.acceptTheRestCount(lane: .nearlyIdentical, currentIndex: currentIndex, remainingInLane: rest.count), + 2 + ) + + store.acceptSuggestions(forClusters: rest) + + XCTAssertEqual(store.approvedClusterIDs, [first.id, third.id, fourth.id], "The skipped group is not accepted") + XCTAssertFalse(store.approvedClusterIDs.contains(skipped.id)) + XCTAssertEqual(store.laneSummaries[.nearlyIdentical]?.groups, 1, "The skipped group is still waiting for review") + } + + func testAcceptTheRestLeavesOutGroupsReviewedSinceTheWalkStarted() async throws { + let one = laneCluster("one", lane: .nearlyIdentical) + let two = laneCluster("two", lane: .nearlyIdentical) + let three = laneCluster("three", lane: .nearlyIdentical) + let store = try await scannedStore([one, two, three]) + store.acceptSuggestionsForCluster(three) + let rest = QuickReviewScope.restClusters( + from: [one, two, three], + currentIndex: 1, + reviewedIDs: store.approvedClusterIDs + ) + XCTAssertEqual(rest.map(\.id), [two.id]) + XCTAssertTrue(QuickReviewScope.restClusters(from: [one, two, three], currentIndex: 3, reviewedIDs: []).isEmpty) + } + func testFullyMarkedNoticeText() { XCTAssertNil(DeduplicateFooterCopy.fullyMarkedNotice(groupCount: 0)) XCTAssertEqual( From 511ec157b8c5bb08cf1308869c5416416eda9e02 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sun, 29 Nov 2026 16:21:42 -0800 Subject: [PATCH 15/17] Docs: record the 2.1 second-batch decisions and known items Co-Authored-By: Claude Fable 5.2 --- DECISIONS.md | 19 +++++++++++++++++++ docs/plan/photos-import-resume/DECISIONS.md | 1 + 2 files changed, 20 insertions(+) diff --git a/DECISIONS.md b/DECISIONS.md index 60bb1fbe..80dc4f5d 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -11,6 +11,25 @@ - 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. +## Release 2.1 second batch (2026-11-29) + +Owner decisions, given as answers to a question list on 2026-11-29: + +- Lone RAW (INV-14, approved): the copy that has a RAW or Live Photo video partner is the suggested keeper, and a partner is trashed only if it is itself a duplicate. Built as a keeper tie-break after RAW-first and before the path tie-break in `DuplicateClusterer`, and a guard in planner step 5: a partner outside every cluster stays. +- Fix before 2.1 (approved): the free-removal offer speed, Photos staging kept for an unfinished copy (D-PIR-130 in `docs/plan/photos-import-resume/DECISIONS.md`), the Shortcut using stored preferences, and saved-review loss. +- Version 2.1 and draft 2.1 store text in English and German (approved to draft; the text itself is not reviewed). + +Decided by the agent while building these; the owner has not reviewed them: + +- Live Photo videos are never hashed or clustered, so "outside every cluster" proves nothing for a MOV. A MOV outside every cluster goes with its still only when a copy the plan keeps has its own MOV; otherwise it stays as a standalone video. MOV content is not compared, as before. +- The free removal batch is found by searching over a prefix of the lane-ordered groups, starting from the prefix the full plan's per-group counts predict, instead of growing one group at a time. Every candidate is still a real planner result checked against the limit and the full plan. In rare pair cases the batch can differ from the old walk: it may take a later prefix that passes, and it does not probe one group past a passing first guess. +- A dedupe commit that moved 0 files keeps the saved review. +- Quick Review "Accept the Rest" accepts only the unreviewed groups from the current position on; groups skipped earlier stay unreviewed, and the button count is the same list. +- The Shortcut also takes the parallel-transfer preference, since worker count means nothing without it. It still does not take the event-suggestion preference. +- Photos staging is also kept by the post-run cleanup when a pending job reads from it, so a copy that stopped, failed or hit the free limit in the same session can be finished. + +Known items left for a later release (owner did not pick them for 2.1): companion owner link (edit preservation B-2 item 3 and `_collision_N`); a stopped free copy that may be resumable only from the menu (unverified); Shortcut result text and Core error messages in English only; setup edge cases (late overlap check after relaunch, profile saved from one dropped file); two iPhone `.aae` name forms ending "Not copied"; the keeper-reason text does not mention the partner tie-break; `reviewedDeletionPlan()` and `freeBatchOffer` each compute the full reviewed plan. + ## 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/docs/plan/photos-import-resume/DECISIONS.md b/docs/plan/photos-import-resume/DECISIONS.md index 0f97c0ac..29df5d1a 100644 --- a/docs/plan/photos-import-resume/DECISIONS.md +++ b/docs/plan/photos-import-resume/DECISIONS.md @@ -55,3 +55,4 @@ When a gap appears that no contract or decision covers, choose the option that, - **D-PIR-127 (item 7) Resume validates the card's own directory.** Amends D-PIR-106 and D-PIR-112. `resumeImport` takes the `resumable` the card shows, re-validates only that directory (destination and files as they are now) and resumes it; it no longer runs the full refresh first, which could pick or delete another import. If that directory is gone or invalid it runs the refresh (so the card shows what really exists), sets "That interrupted import is no longer available. Your Photos library was not changed." and resumes nothing. With no `resumable` at all it still returns nil silently. The "couldn't prepare" text for this case in `testResumeRevalidatesDestinationAndFilesAtResumeTime` was updated to the new message. - **D-PIR-128 (item 6) Asset size joins the low-space threshold.** Amends D-PIR-05 and D-PIR-103. `PhotosExportableResource` gains `fileSize: Int64?` (default nil). After an asset's resources are listed the executor stops with `PhotosExportStop.lowStagingSpace` when free space is below floor + the asset's summed known sizes (`floorBytes` in the stop is that threshold). The first, size-less check before `.assetStarted` is unchanged, so D-PIR-103 holds for it; the size check runs after `.assetStarted`, and nothing of the asset is written. Unknown sizes and unknown free space never stop the export. `PhotosResourceExportService` passes nil: PhotoKit has no public resource size, and the undocumented `fileSize` KVC key was rejected as an App Review risk during review of #268. Production therefore behaves as before; the threshold logic is in place and tested for when a public size source exists (e.g. an exporter that knows the size up front). - **D-PIR-129 Filename collisions in the export executor fixed (renumbered from D-PIR-121 when merged with #268; owner, 2026-11-12: separate fix for D-PIR-104; PR #270).** On branch `fix/photos-export-name-collision`, stacked on `feature/clear-path`. Names are compared by a filesystem-style key: canonical decomposition plus case folding (`nameKey`), diacritics kept, so "Cafe" and "Caf\u00e9" stay distinct. Reserved names use the same key. `lowercased()` was not enough: small and final sigma fold together on APFS but lowercase apart (`testStemsThatFoldTogetherButDoNotLowercaseTogetherDoNotShareAFile`). Unicode normalization needed no code change, because Swift `String` equality already treats canonical equivalents as equal; the composed/decomposed tests are regression guards that passed before the fix. The name is claimed with an exclusive create (`O_CREAT|O_EXCL|O_NOFOLLOW`) before `writeResource` runs; EEXIST means a file the key did not foresee is already there, so the next candidate is tried and that file is never touched, and rollback removes only files this call created. The exporter then replaces the empty claimed file. Search is bounded (`maxNameAttempts`, 10,000); exhaustion fails only that asset. Failing-first: `testFallbackNameNeverLandsOnAnotherAssetsFile`, `testNamesDifferingOnlyByCaseDoNotShareAFile`, `testReservedFilenameIsMatchedIgnoringCase` (the third showed a reserved staged file being overwritten), then `testUnreservedStagedFileOfCaseVariantNameSurvivesByteForByte`, `testRollbackNeverRemovesAFileTheExecutorDidNotCreate`, `testExhaustedNameAttemptsFailOnlyThatAsset` and the sigma test (all tagged INV-22). Full case folding also merges ß and SS, which APFS keeps apart; accepted, an extra rename is harmless. Out of scope: case-sensitive volumes still rename stems that differ only by case. `cf_swift.sh suite` 0; `coverage` 0 (meaningful 96.04%); `guards feature/clear-path` 0 (14/14); `xcode` 0 (these four lanes ran before the fold and exclusive-create change and have not been re-run). Not verified in the running app. +- **D-PIR-130 A finished export survives cleanup while a pending copy still reads from it (owner, 2026-11-29: fix chosen from the 2.1 sweep). Amends C-04 and D-PIR-109.** Launch cleanup and the post-run `cleanupStaging` no longer remove a `.ready` staging folder when a PENDING job in the destination's `.organize_cache.db` has its source under that folder (`PendingCopyJobStagingReferenceChecker`, a read-only open with no lease, the same as the run preflight's pending count). The folder is removed once the queue is read and nothing pending is under it, or the destination has no queue. At launch, when the destination or its queue cannot be read, the folder is kept for 30 days from the checkpoint's `updatedAt` and then removed (agent's choice of 30 days, not reviewed by the owner). The post-run cleanup keeps the folder only on a proven reference. A `.ready` checkpoint is still not offered as an interrupted export. From 795ec0b6d5569bec5898d46f7425c05e68ce7b7d Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Tue, 1 Dec 2026 00:06:25 -0800 Subject: [PATCH 16/17] Docs: approve the 2.1 scope and build order; add the release tracker Reorders the remaining next-half work for the press release, adds cards B12 to B14 (Shortcuts and Finder actions, reviewer sample library, technical post and press page), and records the owner's decisions. docs/plan/release-2.1/PROGRESS.md tracks feature state, the 44 owner checks still owed and the release gates. Co-Authored-By: Claude Fable 5.2 --- DECISIONS.md | 9 ++ docs/next-half-product-review-2026-11-07.md | 4 +- docs/plan/next-half/README.md | 102 +++++++++++++++++++- docs/plan/release-2.1/PROGRESS.md | 77 +++++++++++++++ 4 files changed, 186 insertions(+), 6 deletions(-) create mode 100644 docs/plan/release-2.1/PROGRESS.md diff --git a/DECISIONS.md b/DECISIONS.md index 80dc4f5d..844e1d1d 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -1,5 +1,14 @@ # Decisions +## Release 2.1 scope and press lens (2026-11-30) + +- Owner: 2.1 ships when ranks 1 to 11 of the next-half review and anything added since are done; there is no date. Press outreach follows 2.1. +- Owner, 2026-12-01: accepted the build order, the press scope additions and cards B12 (Shortcuts and Finder actions), B13 (reviewer sample library) and B14 (technical post and press page) in `docs/plan/next-half/README.md`, "Release 2.1 scope and press lens". NAS public is required for 2.1. +- Agent's judgment, not challenged by the owner: Guardian mirror and restore stay deferred and B9 (scrub-only) is the press headline; card ingest, a library timeline, metadata-complete Photos export and direct iPhone import are declined for 2.1. +- Owner, 2026-11-30: B12 gains a Finder Quick Action on folders that opens the Organize preview. Owner, 2026-12-01: B12 also gains a Quick Action on files that copies them into their dated place in the default destination. It completes from Finder only when every item has a certain date, no conflicting-date warning and no name collision; otherwise it opens the app's preview (full rules in the B12 card). +- Owner, 2026-12-01: B9 gains an explicit "start tracking this folder as it is today" baseline through `GuardianManifestUpdater.accept`, which INV-23 already permits. +- Owner, 2026-12-01: release state is tracked in `docs/plan/release-2.1/PROGRESS.md` (features, owner checks, release gates). Plan folders stay the source of truth; no GitHub Project or per-work-package issues. + ## Release 2.1 bug sweep (2026-11-29) - 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. diff --git a/docs/next-half-product-review-2026-11-07.md b/docs/next-half-product-review-2026-11-07.md index e32096b1..0fa03166 100644 --- a/docs/next-half-product-review-2026-11-07.md +++ b/docs/next-half-product-review-2026-11-07.md @@ -10,10 +10,12 @@ > | 2 | Dedupe review survives relaunch | Done: #267 (UI-test isolation #276). | > | 3 | Visible, cancellable, resumable Photos import | Done in part: #268 "Stop and resume a Photos import", #270. Whether bounded staging and checkpoint-by-complete-asset are fully delivered is unverified; see `docs/plan/photos-import-resume/PROGRESS.md`. | > | 4 | Find and account (item-level reconciliation plus original-name lookup) | Not started on main (plan folder only). | -> | 5 | First ten minutes (preflight, free batch, proof) | Not delivered as scoped; only wording changes landed (#278). | +> | 5 | First ten minutes (preflight, free batch, proof) | Superseded 2026-11-28 by first-run experience, shipped in #307 to #311. | > | 6 (B11) | Already-archived view and date-range selection in Photos import | Not started. | > | 7 to 11 | Batch clock correction, protected folders then keeper preference, XMP companions, verify-my-archive (scrub-only Guardian), Takeout rescue | Not started. The conflicting-date review these build on shipped: #261, #272, #273. | > +> **Update 2026-11-30:** XMP companions (rank 9) shipped in #299 together with edited Photos versions, so "Edited-appearance import from Photos" under "Decided against" below no longer holds. The remaining ranks are ordered for release 2.1 in `docs/plan/next-half/README.md`, "Release 2.1 scope and press lens"; that order supersedes the ranking below. +> > Preconditions in the review are met or changed: build 508 is superseded; V2 is public and Free with a $14.99 unlock since 2026-10-22 (see `docs/APP_STORE_RELEASE.md`). Open PRs right now (#282 run-outcome accuracy, #283 marketing tooling, #284 German UI fit) are not part of this list. ## Product judgment diff --git a/docs/plan/next-half/README.md b/docs/plan/next-half/README.md index ad5e2c9d..382b569e 100644 --- a/docs/plan/next-half/README.md +++ b/docs/plan/next-half/README.md @@ -1,6 +1,6 @@ # Next-half implementation plans (Nov 2026 – Apr 2027) -Status: plans 1 to 3a shipped (PRs #266 to #269, follow-up #274); plans 4 and 5 are not started; the backlog cards are unapproved proposals. Prepared 2026-11-07 from the Round 3 ranking in [`docs/next-half-product-review-2026-11-07.md`](../../next-half-product-review-2026-11-07.md). A plan changes product behavior only when its orchestrator runs and Nishith merges its branch. +Status (2026-11-30): plans 1 to 3a shipped (PRs #266 to #269, follow-up #274); plan 5 was superseded by plan 6, which shipped in #307 to #311; B8 shipped as edit preservation (#299); plan 4 is not started. The rest of the 2.1 queue is in [Release 2.1 scope and press lens](#release-21-scope-and-press-lens-2026-11-30); its scope and order were approved 2026-12-01, and each card still needs an implementation plan before code is written. Prepared 2026-11-07 from the Round 3 ranking in [`docs/next-half-product-review-2026-11-07.md`](../../next-half-product-review-2026-11-07.md). A plan changes product behavior only when its orchestrator runs and Nishith merges its branch. Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as backlog cards; finish NAS on `feature/nas-v1`, then one branch and one plan folder per feature; Opus orchestrates, Sonnet implements and reviews, Haiku does data entry; agents never touch App Review, StoreKit, hardware checks or release flag values. @@ -14,7 +14,8 @@ Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as | 3a | [`clear-path/`](../clear-path/) | `feature/clear-path` | `feature/photos-import-resume` (stacked, D-CLP-01) | `CLP` | UX review 2026-11-12 — plain-language Organize and Deduplicate flow, several folders at once | shipped in #269, follow-up #274 | | 4 | [`find-and-account/`](../find-and-account/) | `feature/find-and-account` | `main` after #3 merges | `FAA` | 4 — item-level reconciliation and original-name lookup | not started | | 5 | [`first-ten-minutes/`](../first-ten-minutes/) | `feature/first-ten-minutes` | `main` after #4 merges | `FTM` | 5 — preflight, free batch, proof | superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | -| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | built, not merged | +| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | shipped in #307 to #309, follow-ups #310 and #311; owner rows H-FRX-1 to H-FRX-8 not run | +| 6a | [`edit-preservation/`](../edit-preservation/) | `feature/edit-preservation-impl` | `main` after #298 | `EPR` | 9 (B8) plus edited Photos versions | shipped in #299 (INV-31) | Each plan is self-contained: `CONTRACTS.md`, `DECISIONS.md`, `IMPLEMENTATION_PLAN.md`, `PROGRESS.md`, `ACCEPTANCE_MATRIX.md`, `BLOCKED.md`, `EVIDENCE_LEDGER.md`. Shared files live here: [`AGENT_RULES.md`](AGENT_RULES.md), [`bin/cf_swift.sh`](bin/cf_swift.sh), [`ORCHESTRATOR_KICKOFF.md`](ORCHESTRATOR_KICKOFF.md), [`claude-config/`](claude-config/) (install into the gitignored `.claude/`). @@ -28,11 +29,79 @@ Plans 2–5 may be reordered by the owner; each `DECISIONS.md` D-01 names its ba - **NAS hardware checks H1–H8.** Owner-only; procedures in `docs/plan/nas-v1/EVIDENCE_LEDGER.md`, results in `docs/plan/nas-public/EVIDENCE_LEDGER.md` (H1 failed on the Synology profile; several rows still open). - **Release flag flips** (`NASCapability.isEnabled` release value). Owner-only, after the ledger rows read `pass-hardware`. -## Backlog cards (ranks 6–11; not planned this pass) +## Release 2.1 scope and press lens (2026-11-30) + +Status: **approved 2026-12-01** (prepared 2026-11-30). Owner decisions: 2.1 ships when ranks 1 to 11 and everything added here are done, with no date; press outreach follows 2.1; the build order, the press scope additions and cards B12 to B14 are accepted; NAS public is required for 2.1. Each card still needs its own implementation plan and approval before code is written. Statuses below were checked against `git log origin/main` and each plan's `PROGRESS.md` on 2026-11-30; nothing was built or run. + +State for every item, the owner checks still owed and the release gates are tracked in [`../release-2.1/PROGRESS.md`](../release-2.1/PROGRESS.md). This section holds scope and order only. + +### The story 2.1 has to carry + +One sentence a writer can repeat: **Chronoframe organizes a photo archive and can show that every file is accounted for and unchanged.** Each remaining item is judged by whether a reviewer can see that for themselves in a few minutes. + +| Audience | Outlets on the outreach list | What they need to see | Carried by | +|---|---|---|---| +| Mac generalists | Six Colors, 9to5Mac, TidBITS | A plain job done safely; proof, not claims | Find and account, B9, B11 | +| Technical | Michael Tsai, TidBITS | How verification, receipts and undo work | B9, B14 post | +| Automation | MacStories, MacSparky | Shortcuts actions with usable output | B12 | +| Photographers | Thomas Fitzgerald | RAW and sidecar safety, clock repair | Edit preservation (shipped), B6 | + +### Build order + +One branch and one plan folder per item, each based on `main` after the previous one merges unless its plan's D-01 says otherwise. Items with no dependency between them may be reordered. + +| Order | Item | Plan folder (prefix) | Depends on | Press role | State | +|---|---|---|---|---|---| +| 1 | Find and account (rank 4) | `find-and-account/` (`FAA`) | none | The demo: "where did IMG_1234 go" | Plan written 2026-11-07, not started. Refresh before running (see below). | +| 2 | B9 Verify my archive | `guardian-verify/` (`GVF`) | none; reads FAA records when present | The headline for Mac and technical press | Card only | +| 3 | B6 Batch camera-clock correction | `batch-clock/` (`BCL`) | none | The photographer feature | Card only | +| 4 | B11 Already-archived view in Photos import | `photos-archived-view/` (`PAV`) | FAA index; plan 3 checkpoint | Leaving iCloud, the most common reader job | Card only | +| 5 | B10 Takeout rescue | `takeout-dates/` (`TKO`) | companion rule (shipped in #299) | Leaving Google Photos | Card only | +| 6 | B7 Protected folders, then keeper preference | `protected-folders/` (`PRF`) | none | None; built for users | Card only | +| 7 | B12 Shortcuts actions and Finder Quick Actions | `shortcuts-actions/` (`SCA`) | FAA, B9, B6 | Required for MacStories and MacSparky | New card | +| 8 | B13 Reviewer sample library | `press-kit/` (`PRK`) | every item above | Lets a writer see the value in five minutes | New card | +| 9 | B14 Technical post and press page | `press-kit/` (`PRK`) | B9, FAA | What Tsai and TidBITS link to | New card | +| owner | NAS public (rank 1) | `nas-public/` | hardware rows H1 to H8, flag flip | Second angle for NAS owners | Merged, flag off; H1 failed on the Synology profile. Required for 2.1 (owner, 2026-12-01). | + +Changes from the Round 4 order: B9 moves from rank 10 to second, because it is the headline and nothing blocks it; B10 is no longer "first to drop", since 2.1 has no capacity limit and leaving Google Photos is a broad reader job; B7 moves last among features because it has no press role. B11 stays behind FAA because it needs the mapping index. + +### Before each implementation plan is written + +- **Find and account.** The plan predates clear-path, first-run experience and edit preservation. Refresh every line reference into `Views/Setup/`, `Views/Run/`, `SetupCoordinator.swift` and `RunSessionStore.swift`, and all UI copy. Decide how companions and edited variants appear in the outcome record. INV-30 is reserved for it (D-EPR-12); `AGENTS.md` has no INV-30 yet. +- **B9.** Read `GuardianScheduler`, `GuardianStore` and `SwiftGuardianEngine` to list what the scrub-only workspace reuses. Confirm `GuardianManifestUpdater.accept` covers a first baseline of a whole existing folder (press scope below). +- **B6.** Confirm `ReviewOverrides` can record which batch wrote an override, so undo removes exactly that batch. +- **B11.** Answer the card's open question: whether the Photos asset identifier is persisted with the destination mapping. +- **B12.** List what each intent returns and which intents may run without the app in front. No intent may purchase (existing CI guard) or mutate without the same lock and receipt path as the app. + +### Press scope added to existing cards + +These widen the cards below. Accepted 2026-12-01. + +- **B9, start from an existing archive.** The card baselines only from a verified Organize receipt, so a reviewer could verify nothing but what Chronoframe copied. Add an explicit "Start tracking this folder as it is today" action that records the current digests through `GuardianManifestUpdater.accept`. INV-23 already allows trust by explicit user acceptance. Copy must say it records today's state and proves nothing about earlier damage. +- **B9, results a writer can quote.** The report names each changed or missing file with its path, the date it was last verified and the date the change was found, and exports as CSV. +- **B6, the before and after is the screenshot.** The preview shows old date, new date and the destination folder each item moves to, for the whole batch. +- **B10 and B11, wording.** Neither may say or imply "safe to delete" from Google or iCloud. This is unchanged from Round 4 and matters more when a journalist is quoting the screen. +- **Find and account, a visible answer.** Typing an original file name returns where it is now, which run put it there and whether it is still present. + +### Considered for the press lens and declined + +- **Guardian mirror and restore.** The Round 4 reasons stand: largest expansion of responsibility, and a same-drive mirror is not a backup. B9 tells the same story for a fraction of the risk. +- **Card ingest with a "safe to format" verdict.** Conflicts with the "never imply safe to delete" rule and serves working professionals, who are not the primary customer. +- **Library timeline with gaps.** Overlaps the "reviewed through" calendar and space report removed in Round 3. +- **Metadata-complete export from Photos, direct iPhone import.** PhotoKit cannot deliver the first in full; the second carries a high support cost and no proof story. + +### Owner decisions (2026-12-01) + +1. Build order accepted as written. +2. B12, B13 and B14 are 2.1 scope, including the technical post and the press page. +3. B9 gets the "start from an existing archive" action. +4. NAS public is required for 2.1; the release waits for its hardware rows. + +## Backlog cards (ranks 6–11 and press additions B12–B14) Each card is the seed of a future plan folder. Scope lines are the Round 3 boundaries; nothing below is approved for implementation. -Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 (10), B10 (11). Card IDs are unchanged so existing references stay valid. +Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 (10), B10 (11). Card IDs are unchanged so existing references stay valid. The 2.1 build order in the section above supersedes this order (2026-11-30); B8 has shipped. ### B11 — Already-archived view and date-range selection in Photos import (`feature/photos-archived-view`) - **Job:** "I offload from iCloud every few months; show me what is already in my archive and import only the rest." @@ -57,7 +126,7 @@ Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 ( - **Out:** cross-root protection, Organize-source protection (sources are already read-only), near-duplicate auto decisions. - **Invariants to tag:** Trash-only; plan integrity/expected identity; Keep-wins pair/sidecar. -### B8 — Existing XMP companions travel with organized photos (`feature/xmp-companions`) +### B8 — Existing XMP companions travel with organized photos (shipped in #299 as `edit-preservation/`) - **Job:** a Lightroom user's `.xmp` ratings and edits are left behind by Organize today. - **Builds on:** dedupe's sidecar discovery; `MediaDiscovery` extension allowlist; collision renaming in `CopyPlanBuilder`. - **Scope:** discover `.xmp` whose basename matches exactly one supported media file in the same directory; copy unchanged beside the owner, renamed in lockstep on collision; verified, receipted and reverted with the owner; ambiguous or orphan companions listed as unresolved in the plan. @@ -77,3 +146,26 @@ Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 ( - **Scope:** for `name.ext` match exactly one of `name.ext.json`, `name.ext.supplemental-metadata.json` or the truncated-name variant Google documents, in the same directory; read `photoTakenTime.timestamp` as an alternative date shown in the existing conflicting-date review, never applied automatically; copy the JSON as a companion when B8 exists, otherwise leave it and say so. - **Out:** Google login, album JSON, edited-variant `-edited` files, any date rewrite without review. - **First to drop** if customer recruitment finds no demand. + +### B12 — Shortcuts actions and Finder Quick Actions for the 2.1 capabilities (`feature/shortcuts-actions`) +- **Status:** accepted as 2.1 scope 2026-12-01 (added 2026-11-30 from the press lens; promoted from the maintenance bucket in the product review). No implementation plan yet. +- **Job:** "run my archive chores from Shortcuts and use the result in the next step." +- **Builds on:** `OrganizeFolderIntent` (the only intent today), the FAA lookup index, the B9 scrub, B6 overrides. +- **Scope:** Verify Archive (returns counts and the list of changed or missing files), Find Photo (original name in, current location and presence out), Preview Organize (dry run, returns counts and the report file). Each returns typed output another action can consume, and result text is localized. +- **Finder Quick Action, folder (accepted 2026-11-30):** right-click a folder, "Preview Organize in Chronoframe" opens the app with that folder staged as the source and the preview running. It copies nothing from Finder. +- **Finder Quick Action, files (accepted 2026-12-01, owner idea):** right-click one or more photos or videos, "File in Chronoframe Archive" copies them into their dated place in the default destination. It is a verified copy through the same engine, lock, receipt and free limit as a run, so it appears in History and can be undone; the original stays where it is. It completes from Finder only when every item has a certain date, no conflicting-date warning and no name collision, and then posts a notification with Reveal and Undo. Otherwise it opens the app's preview with the items staged. Companions and RAW+JPEG partners in the same folder travel with the selected file. With no default destination set, it opens Setup. +- **Out:** any intent that deletes, deduplicates or purchases; any intent that copies without the app's lock, receipt and free-limit path; background scheduling. +- **Open questions:** whether a clock-correction intent is useful without the preview, or should be left out; how a sandboxed Finder extension receives access to the selected files and the bookmarked destination. +- **Invariants to tag:** Guardian scrub read-only (23); source read-only; App Intents never purchase (existing guard). + +### B13 — Reviewer sample library (`feature/press-kit`) +- **Status:** accepted as 2.1 scope 2026-12-01. No implementation plan yet. +- **Job:** a writer with no messy archive to hand sees every 2.1 capability in a few minutes. +- **Scope:** a script that generates a small folder from synthetic, license-free images: exact and near duplicates, a RAW+JPEG pair, an `.xmp` and an `.aae` companion, a batch with a wrong camera clock, a Takeout-style JSON pair, and a conflicting-date file. A second step changes one byte in one organized file so Verify has something to find. A one-page walkthrough lists the steps and what each shows. +- **Out:** real photographs, anything bundled in the app, any network download at run time. +- **Reuses:** existing test fixture builders where they already produce these shapes. + +### B14 — Technical post and press page (`feature/press-kit`) +- **Status:** accepted as 2.1 scope 2026-12-01. Documentation and site work; no app code. +- **Scope:** one post explaining receipts, verified copies, undo and the scrub, written from `docs/SAFETY_AND_RECOVERY.md` and `docs/TECHNICAL.md`; a press page with the one-sentence story, screenshots, pricing, the sample library link and contact. +- **Out:** claims not backed by a tagged invariant test; competitor comparisons beyond the hand-checked compare page. diff --git a/docs/plan/release-2.1/PROGRESS.md b/docs/plan/release-2.1/PROGRESS.md new file mode 100644 index 00000000..30e6bfd9 --- /dev/null +++ b/docs/plan/release-2.1/PROGRESS.md @@ -0,0 +1,77 @@ +# Release 2.1 — tracker + +Status (2026-12-01): scope approved, no 2.1 feature plan started. 2.1 ships when every row in the three tables below is done; there is no date. Press outreach follows the release. + +This file holds state and links only. Scope and order live in [`../next-half/README.md`](../next-half/README.md), "Release 2.1 scope and press lens". Detail lives in each plan folder, which stays the source of truth: when this file and a plan's `PROGRESS.md` disagree, the plan is right and this file is stale. + +## How to update + +- An orchestrator updates its feature row at each gate and when its PR merges, through the data-entry agent. +- Only Nishith moves an owner-check row to `pass` or `fail`; he records the result in the plan's `EVIDENCE_LEDGER.md` first, then the count here. +- Feature states, in order: `card` → `plan written` → `plan approved` → `in progress` → `built` (final gate passed on the branch) → `merged` → `verified` (owner rows for that feature pass in the running app). "Merged" never implies "verified". + +## 1. Features + +| # | Item | Plan folder | State | PR | Owner checks | Notes | +|---|---|---|---|---|---|---| +| 1 | Find and account (rank 4) | [`find-and-account/`](../find-and-account/) | plan written | — | not defined yet | Plan dates from 2026-11-07 and must be refreshed against clear-path, first-run and edit preservation before approval. Reserves INV-30. | +| 2 | B9 Verify my archive | `guardian-verify/` (to create) | card | — | — | Includes "start tracking this folder as it is today". | +| 3 | B6 Batch camera-clock correction | `batch-clock/` (to create) | card | — | — | | +| 4 | B11 Already-archived view in Photos import | `photos-archived-view/` (to create) | card | — | — | Needs item 1's index. | +| 5 | B10 Takeout rescue | `takeout-dates/` (to create) | card | — | — | | +| 6 | B7 Protected folders, then keeper preference | `protected-folders/` (to create) | card | — | — | | +| 7 | B12 Shortcuts actions and Finder Quick Actions | `shortcuts-actions/` (to create) | card | — | — | Needs items 1, 2 and 3. | +| 8 | B13 Reviewer sample library | `press-kit/` (to create) | card | — | — | Needs every item above. | +| 9 | B14 Technical post and press page | `press-kit/` (to create) | card | — | — | No app code. | +| — | NAS public (rank 1) | [`nas-public/`](../nas-public/) | merged (#266), flag off | #266 | 2 pass, 1 fail, 9 open | Required for 2.1. Blocked on H1, which failed on the Synology profile. | + +Already merged and counted in 2.1, awaiting owner checks only (section 2): dedupe persistence (#267), Photos import resume (#268, #270), clear path (#269, #274), edit preservation (#299), first-run experience (#307 to #311). + +In flight outside the feature list: branch `fix/release-2.1-second` (2.1 bug sweep, version bump and What's New draft), 15 commits ahead of `origin/main` on 2026-12-01, not merged. + +## 2. Owner checks + +Rows only Nishith can run: hardware, the running app, VoiceOver, a signed or MAS build. Counts were read from each ledger on 2026-12-01. Totals: 44 rows, 2 pass, 1 fail, 3 with an agent-run result awaiting the owner, 38 not run. + +| Plan | Ledger | Rows | Pass | Fail | Awaiting owner | Not run | What they cover | +|---|---|---|---|---|---|---|---| +| NAS public | [`nas-public/EVIDENCE_LEDGER.md`](../nas-public/EVIDENCE_LEDGER.md) | 12 | 2 (H-NASP-1, H-NASP-2) | 1 (H1) | 3 (H2, H6, H8) | 6 (H3, H4, H5, H7, H-NASP-3, FLAG) | Real-share probe, parity, relaunch and remount, read-only share, disconnect and sleep, verified copy, accessibility, performance, the flag flip | +| Dedupe persistence | [`dedupe-persistence/EVIDENCE_LEDGER.md`](../dedupe-persistence/EVIDENCE_LEDGER.md) | 5 | 0 | 0 | 0 | 5 (H-DDP-1 to 5) | Review restored after relaunch, changed file re-enters review, commit, VoiceOver, app smoke | +| Photos import resume | [`photos-import-resume/EVIDENCE_LEDGER.md`](../photos-import-resume/EVIDENCE_LEDGER.md) | 6 | 0 | 0 | 0 | 6 (H-PIR-1 to 6) | Stop and resume with iCloud assets, low space, destination mismatch, VoiceOver, app smoke | +| Clear path | [`clear-path/EVIDENCE_LEDGER.md`](../clear-path/EVIDENCE_LEDGER.md) | 7 | 0 | 0 | 0 | 7 (H-CLP-1 to 7) | Sandboxed folder list, the real 65,000-file library, VoiceOver, UI-test lane, screenshot recapture, a first-time user session, store and site wording | +| Edit preservation | [`edit-preservation/EVIDENCE_LEDGER.md`](../edit-preservation/EVIDENCE_LEDGER.md) | 6 | 0 | 0 | 0 | 6 (H-EPR-1 to 6) | Companions in dedupe, organize and revert; edited Photos versions; resume; wording | +| First-run experience | [`first-run-experience/EVIDENCE_LEDGER.md`](../first-run-experience/EVIDENCE_LEDGER.md) | 8 | 0 | 0 | 0 | 8 (H-FRX-1 to 8) | MAS build on a clean account: accounted-for line and Undo, free limit, duplicate lanes, free removal, guided setup, a 20,000-file collection, existing-account layout, VoiceOver | + +Several rows overlap and can be run in one sitting: the VoiceOver rows (H7, H-DDP-4, H-PIR-5, H-CLP-3, H-FRX-8), the app-smoke rows (H-DDP-5, H-PIR-6), and the clean-account MAS rows (H-FRX-1 to 5). + +### Blocked items that name the owner + +Pointers only; read each file for its current state. + +| Plan | Item | Subject | +|---|---|---| +| First-run experience | [B-1](../first-run-experience/BLOCKED.md) | Planner fan-out fix (INV-32) is built and merged; only Nishith marks it resolved. | +| Clear path | [B-5](../clear-path/BLOCKED.md) | App smoke screenshots could not be taken by the agent. | +| Photos import resume | [B-1](../photos-import-resume/BLOCKED.md) | G2 app smoke not completed; screen access declined. | +| Edit preservation | [B-2](../edit-preservation/BLOCKED.md) | Companion follow-ups left for a later release (see root `DECISIONS.md`). | + +## 3. Release gates + +Run once, on the commit that will ship, after every feature row is `merged`. + +| Gate | State | Evidence | +|---|---|---| +| Full SwiftPM suite, coverage gate, invariant script, all `script/check_*.sh` | todo | command and exit code | +| Xcode build and UI-test lane | todo | command and exit code | +| German strings for every new key; `check_german_localization.py` | todo | command and exit code | +| What's New, English and German, rewritten for the final scope | draft exists for the current scope (ac29b36f); redo at the end | commit | +| `docs/screenshots/` recaptured (also H-CLP-5) | todo | commit | +| App Store metadata, site and compare page match the shipped labels (also H-CLP-7) | todo | note | +| FAQ, TROUBLESHOOTING, SAFETY_AND_RECOVERY and TECHNICAL cover every new feature | todo | commit | +| Reviewer sample library walkthrough run end to end on the release build | todo | notes | +| Technical post and press page published | todo | links | +| MAS archive built, uploaded and approved | todo | build number | + +## Log + +- 2026-12-01: tracker created. Owner-check counts read from the six ledgers; feature states read from each `PROGRESS.md` and `git log origin/main`. Nothing was built or run. From 2e3b59f96bb7559a6f34b801689ee0f7b53ec1ea Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Tue, 1 Dec 2026 07:06:24 -0800 Subject: [PATCH 17/17] Docs: NAS copy limit comes from macOS SMB, not the NAS; reword H1 The exclusive rename Chronoframe requires is not implemented by the macOS SMB client, so copying into any SMB share is refused (D-NASP-130). The owner kept ADR-NAS-03 and INV-28 as written (D-NASP-131): H1 now expects the probe result recorded and the refusal proven by H-NASP-3. FAQ and Troubleshooting say the limit is not a NAS setting. Co-Authored-By: Claude Fable 5.2 --- docs/FAQ.md | 2 +- docs/TROUBLESHOOTING.md | 4 ++-- docs/plan/nas-public/DECISIONS.md | 2 ++ docs/plan/nas-public/EVIDENCE_LEDGER.md | 2 +- docs/plan/next-half/README.md | 2 +- docs/plan/release-2.1/PROGRESS.md | 8 +++++--- 6 files changed, 12 insertions(+), 8 deletions(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index f600f1ed..2a554643 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -136,7 +136,7 @@ A: No, not for now. Deduplicate moves files to the macOS Trash, and Chronoframe **Q: Can I organize into a folder on my NAS?** -A: Only when the share supports a rename that refuses to replace an existing file. Chronoframe checks this before it plans anything and stops if the share can't guarantee it. Nothing is copied, and your originals are untouched. Many SMB shares, including the Synology share tested, do not support it. Copying from a share to a folder on this Mac is not affected. See [Troubleshooting](./TROUBLESHOOTING.md#nas-and-network-folder-issues). +A: Not over SMB, which is how a Mac normally connects to a NAS. Chronoframe copies into a network folder only when it can use a rename that refuses to replace an existing file, and macOS does not offer that on SMB connections. This comes from macOS, not from your NAS brand or its settings, so there is no NAS option to change. Chronoframe checks before it plans anything and stops; nothing is copied, and your originals are untouched. Copying from a share to a folder on this Mac is not affected, so you can organize the photos on a NAS onto this Mac or an attached drive. See [Troubleshooting](./TROUBLESHOOTING.md#nas-and-network-folder-issues). **Q: What if a file changes after a deduplicate scan?** diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 9b5c89b5..e6697f94 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -256,12 +256,12 @@ The NAS Library workspace isn't available in release builds yet. The copy rules, **Message:** "This network folder can't guarantee that a copy never replaces an existing file, so Chronoframe won't organize into it. Choose a folder on this Mac or an attached drive. Nothing was copied, and your originals were untouched." -**Problem:** Before it plans a preview or a copy into a network folder, Chronoframe checks that the share supports a rename that refuses to replace an existing file. This share doesn't, so Chronoframe stops before scanning or copying instead of using a weaker method. Many SMB shares, including the Synology share tested, don't support it. +**Problem:** Before it plans a preview or a copy into a network folder, Chronoframe checks that the share supports a rename that refuses to replace an existing file. macOS does not offer that rename on SMB connections, so Chronoframe stops before scanning or copying instead of using a weaker method. This comes from macOS, not from your NAS brand or its settings; it was confirmed on a Synology share and applies to SMB shares in general. **Solution:** - Choose a destination folder on this Mac or an attached drive - Copying from the share to a folder on this Mac is not affected -- Choosing the same network folder again will stop the same way; Chronoframe checks again each time, so a different share or server setup is picked up +- Changing settings on the NAS will not help. Chronoframe checks again each time, so if a future macOS version adds support, the same folder will start working without an update ### "The network folder ... disconnected or changed" diff --git a/docs/plan/nas-public/DECISIONS.md b/docs/plan/nas-public/DECISIONS.md index 3437e4e2..95421bef 100644 --- a/docs/plan/nas-public/DECISIONS.md +++ b/docs/plan/nas-public/DECISIONS.md @@ -48,3 +48,5 @@ Same as every next-half plan: keep every invariant and every `docs/NAS_REQUIREME - **D-NASP-127 H2 corpus built locally and copied (2026-11-08).** `make-corpus` straight onto the share failed on its 7th file: the Synology refuses to create `@eaDir` over SMB (the folder silently never appears), so the generator's `@eaDir` exclusion fixtures can't be written. The corpus was generated locally with the same seed (manifest SHA-256 `caf67e8d93c4b0c123701e76ed8f2cf4caf36c0f047a8405e1d8fc8d2c98008c`) and copied with `rsync -rt --exclude '@eaDir'` to `/Volumes/photo/chronoframe-h2-corpus-2` (9,998 of 10,000 files; the two missing are the `@eaDir` fixtures, which an SMB client can never see on this server). `assess-parity` compares against an exhaustive hash of what is actually on the share, so parity stays valid. Follow-up (not done): `make-corpus` could skip fixtures the server refuses. The first attempt left `/Volumes/photo/chronoframe-h2-corpus` (6 files) for the owner to delete. - **D-NASP-128 H6 reworded (2026-11-08).** Copying into this profile is refused (D-NASP-115), so "each way" becomes share → Mac verified copy plus refusal evidence (H-NASP-3) for Mac → share. The quota fault moves to a local 2 GiB disk image destination, because a DSM quota change is an account setting the agent does not make. - **D-NASP-129 Disk-space resume check looks wrong (observation, not fixed, 2026-11-09).** In H6's disk-full run the CLI paused three times ("71 MB free, 106 MB needed", then 61 MB), then printed "Disk space check passed. Resuming run." while still short, and the next copy hit ENOSPC. Safety held (no partial file under a final name, receipt ABORTED, originals untouched), but the resume condition should be reviewed. Not folded into NASP; flagged for the owner. +- **D-NASP-130 The H1 result is a macOS SMB client limit, not a Synology one (finding, 2026-12-01; no decision made).** Apple's published SMB client source (`apple-oss-distributions/SMBClient`, `main`, `kernel/smbfs/smbfs_vnops.c` and `smbfs_vfsops.c`, read 2026-12-01) contains no `RENAME_EXCL` handling, never sets `VOL_CAP_INT_RENAME_EXCL`, and `smbfs_vnop_link` returns `err_link`, so hard links are not available as a no-replace install either. That matches H1 on macOS 27 (P03 ENOTSUP on a free name). Limits: the published source may not match the macOS 27 kernel extension, and only one server was probed. If it holds, P03 cannot pass on any SMB share, so (a) D-NASP-115's "this profile" is every SMB destination, and (b) the FLAG row's condition "every row above is `pass-hardware`" cannot be met while H1 expects P03 to pass. Open for the owner: reword H1's expectation to "P03 result recorded and the app refuses copying into the share (H-NASP-3)", or reopen ADR-NAS-03. Exclusive create (`O_CREAT | O_EXCL`) is the only no-replace primitive left on SMB; it is the basis of options B and C that D-NASP-115 rejected. +- **D-NASP-131 H1 reworded; copying into an SMB share stays refused (owner, 2026-12-01).** Nishith chose option A after D-NASP-130: keep ADR-NAS-03 and INV-28 as written and do not reopen the exclusive-create install paths. H1 now expects the P03 result to be recorded, P04 and P05 to pass, and the refusal to be proven by H-NASP-3. NAS public therefore means assessment, review and verified copies from a share to this Mac. FAQ and TROUBLESHOOTING now say the limit comes from macOS on SMB connections, not from the NAS (replaces the D-NASP-123 wording, 2026-12-01). Still open: press and store copy must not claim organizing onto a NAS. diff --git a/docs/plan/nas-public/EVIDENCE_LEDGER.md b/docs/plan/nas-public/EVIDENCE_LEDGER.md index a8fc6dfb..4ddb9e9e 100644 --- a/docs/plan/nas-public/EVIDENCE_LEDGER.md +++ b/docs/plan/nas-public/EVIDENCE_LEDGER.md @@ -6,7 +6,7 @@ Only Nishith records results. Rows H1–H8 are the v1 hardware checks; run them | Row | What to run | Pass when | Status | Evidence | |---|---|---|---|---| -| H1 | `probe --test-dir` on the share (P01 to P07), including whether RENAME_EXCL is supported; save `probe.json` (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H1) | P03, P04, P05 pass; P04 leaves the existing bytes' digest unchanged | fail-hardware (2026-11-08, Nishith) | `evidence/H1-probe.json`. Synology SMB, macOS 27, mount `smbfs` (server redacted). P03 `unsupported` (ENOTSUP); P04 pass (EEXIST, digest unchanged); P01, P02, P05, P06, P07 pass. Copying into this profile does not ship (ADR-NAS-03, D-NASP-115); WP-05 adds the preflight. Profile: DS416play, DSM 7.2.1-69057 Update 13; mount SMB 3.1.1, signed (`SMB_CURR_SIGN_ALGORITHM AES_128_GMAC`), encryption off, Apple extensions on (`OS_X_SERVER TRUE`), file IDs supported (`smbutil statshares -m`); DSM `enable_server_signing=0`, `smb_min_protocol=1`, `smb_max_protocol=3`. | +| H1 | `probe --test-dir` on the share (P01 to P07), including whether RENAME_EXCL is supported; save `probe.json` (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H1) | Reworded 2026-12-01 (D-NASP-131): P03 result recorded; P04 leaves the existing bytes' digest unchanged; P05 passes. Where P03 is `unsupported`, the app refuses copying into the share (H-NASP-3). Original wording: P03, P04, P05 pass | meets the reworded expectation on the 2026-11-08 evidence; awaiting owner mark (was fail-hardware, 2026-11-08, Nishith) | `evidence/H1-probe.json`. Synology SMB, macOS 27, mount `smbfs` (server redacted). P03 `unsupported` (ENOTSUP); P04 pass (EEXIST, digest unchanged); P01, P02, P05, P06, P07 pass. Copying into this profile does not ship (ADR-NAS-03, D-NASP-115); WP-05 adds the preflight. Profile: DS416play, DSM 7.2.1-69057 Update 13; mount SMB 3.1.1, signed (`SMB_CURR_SIGN_ALGORITHM AES_128_GMAC`), encryption off, Apple extensions on (`OS_X_SERVER TRUE`), file IDs supported (`smbutil statshares -m`); DSM `enable_server_signing=0`, `smb_min_protocol=1`, `smb_max_protocol=3`. | | H2 | `make-corpus` (10,000 files, 20% duplicates, seed 42), then `assess-parity` three matched cold runs; save `parity.json` per run (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H2) | `parity: true`, ledger within the NAS-NFR-09 budget in all three runs | result recorded, awaiting owner (agent-run 2026-11-08, D-NASP-125) | Commit `bfdf036`. Corpus seed 42, 10,000 files / 307,745,135 bytes, manifest SHA-256 `caf67e8d93c4b0c123701e76ed8f2cf4caf36c0f047a8405e1d8fc8d2c98008c`; on the share 9,998 files (D-NASP-127). `assess-parity --root /Volumes/photo/chronoframe-h2-corpus-2`, fresh `--state-dir` per run (D-NASP-126): run 1 `parity: true` 1783/1783 groups, bytesReadClean 134,306,952 = H, budget 142,695,560, unresolved 0, wallSeconds 352.2; run 2 same, 183.9 s; run 3 same, 178.8 s. Exit 0 each. `evidence/H2-parity-run{1,2,3}.json`, `evidence/H2-make-corpus.json`. Limitation: runs 2–3 may have a warm SMB client cache | | H3 | Choose share, assess, quit, relaunch, confirm review restored, remount under another path (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H3) | Saved review restored; remount recognized as the same library | todo-hardware | | | H4 | Assess a share with no write access to the account; compare server-side change history before and after (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H4) | No server-side changes | todo-hardware | | diff --git a/docs/plan/next-half/README.md b/docs/plan/next-half/README.md index 382b569e..64512c48 100644 --- a/docs/plan/next-half/README.md +++ b/docs/plan/next-half/README.md @@ -61,7 +61,7 @@ One branch and one plan folder per item, each based on `main` after the previous | 7 | B12 Shortcuts actions and Finder Quick Actions | `shortcuts-actions/` (`SCA`) | FAA, B9, B6 | Required for MacStories and MacSparky | New card | | 8 | B13 Reviewer sample library | `press-kit/` (`PRK`) | every item above | Lets a writer see the value in five minutes | New card | | 9 | B14 Technical post and press page | `press-kit/` (`PRK`) | B9, FAA | What Tsai and TidBITS link to | New card | -| owner | NAS public (rank 1) | `nas-public/` | hardware rows H1 to H8, flag flip | Second angle for NAS owners | Merged, flag off; H1 failed on the Synology profile. Required for 2.1 (owner, 2026-12-01). | +| owner | NAS public (rank 1) | `nas-public/` | hardware rows H1 to H8, flag flip | Second angle for NAS owners, stated as "organize the photos on your NAS onto a drive, and check a NAS library"; never "organize onto a NAS" | Merged, flag off. Required for 2.1 (owner, 2026-12-01). Copying into an SMB share is refused by design (D-NASP-130, D-NASP-131). | Changes from the Round 4 order: B9 moves from rank 10 to second, because it is the headline and nothing blocks it; B10 is no longer "first to drop", since 2.1 has no capacity limit and leaving Google Photos is a broad reader job; B7 moves last among features because it has no press role. B11 stays behind FAA because it needs the mapping index. diff --git a/docs/plan/release-2.1/PROGRESS.md b/docs/plan/release-2.1/PROGRESS.md index 30e6bfd9..05c66904 100644 --- a/docs/plan/release-2.1/PROGRESS.md +++ b/docs/plan/release-2.1/PROGRESS.md @@ -23,7 +23,7 @@ This file holds state and links only. Scope and order live in [`../next-half/REA | 7 | B12 Shortcuts actions and Finder Quick Actions | `shortcuts-actions/` (to create) | card | — | — | Needs items 1, 2 and 3. | | 8 | B13 Reviewer sample library | `press-kit/` (to create) | card | — | — | Needs every item above. | | 9 | B14 Technical post and press page | `press-kit/` (to create) | card | — | — | No app code. | -| — | NAS public (rank 1) | [`nas-public/`](../nas-public/) | merged (#266), flag off | #266 | 2 pass, 1 fail, 9 open | Required for 2.1. Blocked on H1, which failed on the Synology profile. | +| — | NAS public (rank 1) | [`nas-public/`](../nas-public/) | merged (#266), flag off | #266 | 2 pass, 0 fail, 10 open | Required for 2.1. Ships as read-from-NAS: assess, review and copy from a share to this Mac. Copying into an SMB share stays refused (D-NASP-130, D-NASP-131). | Already merged and counted in 2.1, awaiting owner checks only (section 2): dedupe persistence (#267), Photos import resume (#268, #270), clear path (#269, #274), edit preservation (#299), first-run experience (#307 to #311). @@ -31,11 +31,11 @@ In flight outside the feature list: branch `fix/release-2.1-second` (2.1 bug swe ## 2. Owner checks -Rows only Nishith can run: hardware, the running app, VoiceOver, a signed or MAS build. Counts were read from each ledger on 2026-12-01. Totals: 44 rows, 2 pass, 1 fail, 3 with an agent-run result awaiting the owner, 38 not run. +Rows only Nishith can run: hardware, the running app, VoiceOver, a signed or MAS build. Counts were read from each ledger on 2026-12-01. Totals: 44 rows, 2 pass, 0 fail, 4 with a recorded result awaiting the owner's mark, 38 not run. | Plan | Ledger | Rows | Pass | Fail | Awaiting owner | Not run | What they cover | |---|---|---|---|---|---|---|---| -| NAS public | [`nas-public/EVIDENCE_LEDGER.md`](../nas-public/EVIDENCE_LEDGER.md) | 12 | 2 (H-NASP-1, H-NASP-2) | 1 (H1) | 3 (H2, H6, H8) | 6 (H3, H4, H5, H7, H-NASP-3, FLAG) | Real-share probe, parity, relaunch and remount, read-only share, disconnect and sleep, verified copy, accessibility, performance, the flag flip | +| NAS public | [`nas-public/EVIDENCE_LEDGER.md`](../nas-public/EVIDENCE_LEDGER.md) | 12 | 2 (H-NASP-1, H-NASP-2) | 0 | 4 (H1, H2, H6, H8) | 6 (H3, H4, H5, H7, H-NASP-3, FLAG) | Real-share probe, parity, relaunch and remount, read-only share, disconnect and sleep, verified copy, accessibility, performance, the flag flip | | Dedupe persistence | [`dedupe-persistence/EVIDENCE_LEDGER.md`](../dedupe-persistence/EVIDENCE_LEDGER.md) | 5 | 0 | 0 | 0 | 5 (H-DDP-1 to 5) | Review restored after relaunch, changed file re-enters review, commit, VoiceOver, app smoke | | Photos import resume | [`photos-import-resume/EVIDENCE_LEDGER.md`](../photos-import-resume/EVIDENCE_LEDGER.md) | 6 | 0 | 0 | 0 | 6 (H-PIR-1 to 6) | Stop and resume with iCloud assets, low space, destination mismatch, VoiceOver, app smoke | | Clear path | [`clear-path/EVIDENCE_LEDGER.md`](../clear-path/EVIDENCE_LEDGER.md) | 7 | 0 | 0 | 0 | 7 (H-CLP-1 to 7) | Sandboxed folder list, the real 65,000-file library, VoiceOver, UI-test lane, screenshot recapture, a first-time user session, store and site wording | @@ -75,3 +75,5 @@ Run once, on the commit that will ship, after every feature row is `merged`. ## Log - 2026-12-01: tracker created. Owner-check counts read from the six ledgers; feature states read from each `PROGRESS.md` and `git log origin/main`. Nothing was built or run. +- 2026-12-01: H1 diagnosed (D-NASP-130): the missing exclusive rename is a macOS SMB client limit. No code or ledger status changed. +- 2026-12-01: owner chose option A (D-NASP-131). H1 reworded; it now awaits the owner's mark instead of reading fail.