diff --git a/README.md b/README.md index eeda5afa..b6da6c5f 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ When you open Chronoframe with nothing set up, **Choose Folders** asks two quest 1. Open **Organize → Choose Folders**. 2. Click **Add Folders…** and pick the folders with your unsorted photos and videos. 3. Click **Choose Destination…** and pick where organized copies should go. -4. Click **Preview Plan**. Chronoframe scans the source, resolves dates, and builds a transfer plan. While it works, the screen says Chronoframe is only reading and nothing is copied yet. A new install organizes into **Year / Month** folders by default; if Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day**, and a layout you chose is never changed. +4. Click **Preview Plan**. Chronoframe scans the source, resolves dates, and builds a transfer plan. While it works, the screen says your originals are never changed and nothing is copied yet. A new install organizes into **Year / Month** folders by default; if Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day**, and a layout you chose is never changed. ![Preview Ready for Review — a timeline of the library by month, with discovered, planned, and issue counts.](docs/screenshots/preview-timeline.jpg) diff --git a/docs/FAQ.md b/docs/FAQ.md index 4fb37ebe..f600f1ed 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -24,7 +24,7 @@ A: Yes. Open **Organize** → **History** and click **Undo** next to the copy yo **Q: How do I know what Chronoframe will copy?** -A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. While the preview is being built, the screen says Chronoframe is only reading and nothing is copied yet. When it is ready, the newest month is selected so a sample from that month is on screen, and **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets. +A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. While the preview is being built, the screen says your originals are never changed and nothing is copied yet. When it is ready, the newest month is selected so a sample from that month is on screen, and **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets. --- diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md index d1c32f1e..cad5381d 100644 --- a/docs/QUICK_START.md +++ b/docs/QUICK_START.md @@ -28,13 +28,13 @@ When you open Chronoframe with nothing set up, **Choose Folders** asks two quest ### Step 2: Preview Your Plan 5. Click **Preview Plan** - - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet. While it works, the screen says Chronoframe is only reading, and you can keep using your Mac + - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet. While it works, the screen says your originals are never changed, and you can keep using your Mac - This takes 10–60 seconds depending on your library size 6. When it finishes, **Preview & Copy** shows the plan: a headline saying how many photos and videos will be copied, a **What will happen** card that lists anything unusual, a timeline of your library, and counts for what was found, what will be copied, what is already there, exact copies, and problems - The first line of the **What will happen** card says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, the line says how many do not add up and asks you to rebuild the preview before copying - The newest month is selected in the timeline, so a sample from that month is on screen when the preview opens. Select another month to see a sample from it - **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets, in three layouts: **Year / Month**, **Year / Month / Day** (a line notes each day gets its own folder) and **Year**. Click a layout to use it. Chronoframe rebuilds the preview, and nothing is copied. While a copy or Deduplicate is running, or when the preview cannot be rebuilt, the layouts cannot be changed. If the preview came from a watched folder or the Apple Photos app, or you use **Year / Month / Event** or **One folder**, it shows your layout on one line instead, and you change it in **Settings**. Under it: "You can change this later with Reorganize, which needs the unlock." - - **Details** is closed on a ready preview. Open it for the **Status** card and **Reports and Logs**, with buttons to open the destination and the preview report + - **Status, reports and logs** is closed on a ready preview. Open it for the **Status** card and **Reports and Logs**, with buttons to open the destination and the preview report ### Step 3: Review (Optional) @@ -138,7 +138,7 @@ After a free removal, the choices you made for the groups still waiting are save - **Edit uncertain dates.** If a photo has an unknown date, fix it in Review and Chronoframe will use your correction. - **Review duplicate groups carefully.** Exact copies are straightforward, but similar shots still need your judgment. - **Keep destination support files during recovery.** Do not remove `.organize_cache.db` or `.organize_logs/` while a copy is active or History shows interrupted work. -- **Don't delete your originals yet.** Keep them for a few days to make sure everything looks right. +- **Chronoframe never deletes or changes your originals.** Copying leaves them where they are, so whether to keep them afterwards is your decision. Check the organized library first if you want to be sure everything looks right. - **Keyboard shortcuts** (once you're comfortable): - `Cmd+R` to preview - `Cmd+Return` to start copying diff --git a/docs/SAFETY_AND_RECOVERY.md b/docs/SAFETY_AND_RECOVERY.md index 0bfd270c..f526b409 100644 --- a/docs/SAFETY_AND_RECOVERY.md +++ b/docs/SAFETY_AND_RECOVERY.md @@ -49,9 +49,9 @@ important library, especially before a large first run or filesystem migration. planned files were not copied, it says how many, that your originals were not changed, and points to Problems. After a free copy it says how many are waiting for the next copy. The line counts files; it never changes a file. -- **While the preview is built.** The screen says Chronoframe is only reading - and nothing is copied yet. Building a preview never changes your source - folders, and nothing is copied. It writes only its own report, log, review data and cache in the destination. +- **While the preview is built.** The screen says your originals are never + changed and nothing is copied yet. Building a preview never changes your + source folders, and nothing is copied. It writes only its own report, log, review data and cache in the destination. - **First-time setup and free space.** The two-question first-time setup measures the folder you chose by listing it and reading file attributes. It never opens, changes or follows anything: it counts regular files, and skips diff --git a/ui/Sources/ChronoframeApp/App/DesignTokens.swift b/ui/Sources/ChronoframeApp/App/DesignTokens.swift index a58732d9..3aa0db03 100644 --- a/ui/Sources/ChronoframeApp/App/DesignTokens.swift +++ b/ui/Sources/ChronoframeApp/App/DesignTokens.swift @@ -80,8 +80,9 @@ enum DesignTokens { /// grows with Dynamic Type; the review body is sized from what is left. static let compactLanesBarMinHeight: CGFloat = 26 /// Review heights below this show the commit footer's safeguards as one - /// line. The default 820pt window stays above it. - static let condensedTrustSummaryBelowHeight: CGFloat = 720 + /// line. The default 820pt window (about 768pt of review area) is below + /// it: with the cards the group list was left about three rows tall. + static let condensedTrustSummaryBelowHeight: CGFloat = 780 /// Same rule in the compact (stacked) layout, where the group list also /// takes 32% of the height: with cards the preview stays under /// `compactPreviewMinHeight` until the review area is about 780pt tall. diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index 0c827d3e..33ebc486 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -483,28 +483,61 @@ enum UITestAppStateFactory { ) } + /// One month of the over-allowance plan: new files, and extra copies of files + /// already in the plan. The month's histogram bar is the two together; the + /// free-month card counts only the new ones (FRX C-08). + private struct OverAllowanceMonth { + let key: String + let newFiles: Int + let extraCopies: Int + } + + /// 14 months ending 2026-10. Every figure on the preview comes from this one + /// table, so the Timeline header, the selected month and the free-month card + /// cannot disagree: 17,208 new files plus 1,204 extra copies is the plan's + /// 18,412. The newest three months have no extra copies, so for them the bar + /// and the card read the same number. + private static let overAllowanceMonths: [OverAllowanceMonth] = [ + OverAllowanceMonth(key: "2025-09", newFiles: 1_180, extraCopies: 90), + OverAllowanceMonth(key: "2025-10", newFiles: 1_290, extraCopies: 100), + OverAllowanceMonth(key: "2025-11", newFiles: 1_350, extraCopies: 110), + OverAllowanceMonth(key: "2025-12", newFiles: 1_520, extraCopies: 120), + OverAllowanceMonth(key: "2026-01", newFiles: 1_410, extraCopies: 105), + OverAllowanceMonth(key: "2026-02", newFiles: 1_330, extraCopies: 95), + OverAllowanceMonth(key: "2026-03", newFiles: 1_560, extraCopies: 115), + OverAllowanceMonth(key: "2026-04", newFiles: 1_620, extraCopies: 120), + OverAllowanceMonth(key: "2026-05", newFiles: 1_740, extraCopies: 130), + OverAllowanceMonth(key: "2026-06", newFiles: 1_850, extraCopies: 140), + OverAllowanceMonth(key: "2026-07", newFiles: 1_264, extraCopies: 79), + OverAllowanceMonth(key: "2026-08", newFiles: 734, extraCopies: 0), + OverAllowanceMonth(key: "2026-09", newFiles: 148, extraCopies: 0), + OverAllowanceMonth(key: "2026-10", newFiles: 212, extraCopies: 0), + ] + /// The over-allowance preview: 18,475 found = 18,412 to copy + 63 already - /// there, a 14-month histogram ending 2026-10, and three months of new - /// files to offer for free (FRX C-08). + /// there, a 14-month histogram ending 2026-10, and the new files of every + /// month to offer for free (FRX C-08). private static func overAllowanceEngine(preflight: RunPreflight, destinationPath: String) -> MockOrganizerEngine { - let months = [ - "2025-09", "2025-10", "2025-11", "2025-12", "2026-01", "2026-02", "2026-03", - "2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10", - ] - let histogram = months.enumerated().map { index, key in + let months = overAllowanceMonths + let histogram = months.map { month in DateHistogramBucket( - key: key, - plannedCount: 600 + index * 140, - samplePaths: ["/Volumes/Card/April Session/\(key)/IMG_0001.jpg"] + key: month.key, + plannedCount: month.newFiles + month.extraCopies, + samplePaths: ["/Volumes/Card/April Session/\(month.key)/IMG_0001.jpg"] ) } + let newFiles = months.reduce(0) { $0 + $1.newFiles } + let extraCopies = months.reduce(0) { $0 + $1.extraCopies } + let alreadyThere = 63 + let planned = newFiles + extraCopies + let found = planned + alreadyThere let metrics = RunMetrics( - discoveredCount: 18_475, - plannedCount: 18_412, - alreadyInDestinationCount: 63, - duplicateCount: 1_204, + discoveredCount: found, + plannedCount: planned, + alreadyInDestinationCount: alreadyThere, + duplicateCount: extraCopies, dateHistogram: histogram, - newFilesByMonth: ["2026-10": 212, "2026-09": 148, "2026-08": 734] + newFilesByMonth: Dictionary(uniqueKeysWithValues: months.map { ($0.key, $0.newFiles) }) ) let summary = RunSummary( status: .dryRunFinished, @@ -522,13 +555,13 @@ enum UITestAppStateFactory { startMode: .events([ .startup, .dateHistogram(buckets: histogram), - .phaseStarted(phase: .discovery, total: 18_475), - .phaseCompleted(phase: .sourceHashing, result: RunPhaseResult(found: 18_475)), + .phaseStarted(phase: .discovery, total: found), + .phaseCompleted(phase: .sourceHashing, result: RunPhaseResult(found: found)), .phaseCompleted( phase: .classification, - result: RunPhaseResult(newCount: 17_208, alreadyInDestinationCount: 63, duplicateCount: 1_204) + result: RunPhaseResult(newCount: newFiles, alreadyInDestinationCount: alreadyThere, duplicateCount: extraCopies) ), - .copyPlanReady(count: 18_412), + .copyPlanReady(count: planned), .complete(summary), ]) ) @@ -550,8 +583,11 @@ enum UITestAppStateFactory { return overAllowanceEngine(preflight: preflight, destinationPath: destinationPath) } + // Two months, so a person (and the UI tests) can choose a month other than + // the newest one that is selected on arrival. They sum to the plan's 42. let sampleHistogram = [ - DateHistogramBucket(key: "2026-04", plannedCount: 42, samplePaths: ["/Volumes/Card/April Session/pic1.jpg"]) + DateHistogramBucket(key: "2026-03", plannedCount: 18, samplePaths: ["/Volumes/Card/April Session/pic0.jpg"]), + DateHistogramBucket(key: "2026-04", plannedCount: 24, samplePaths: ["/Volumes/Card/April Session/pic1.jpg"]), ] let reviewPath: String? diff --git a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings index 90c6f0aa..192d0c6a 100644 --- a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings +++ b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings @@ -435,6 +435,23 @@ } } }, + "1 more is waiting. Your choices are saved; scan again to continue." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 weitere Datei wartet. Deine Auswahl ist gespeichert; scanne erneut, um fortzufahren." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 more is waiting. Your choices are saved; scan again to continue." + } + } + } + }, "%@ nearly identical" : { "extractionState" : "manual", "localizations" : { @@ -3179,6 +3196,40 @@ } } }, + "Chronoframe found %1$@, but this copy handled %2$@ more. Open History for the full record." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe hat %1$@ gefunden, aber diese Kopie hat %2$@ mehr verarbeitet. Öffne den Verlauf für die vollständige Aufzeichnung." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe found %1$@, but this copy handled %2$@ more. Open History for the full record." + } + } + } + }, + "Chronoframe found %1$@, but this plan lists %2$@ more. Rebuild the preview before copying." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe hat %1$@ gefunden, aber dieser Plan führt %2$@ mehr auf. Erstelle die Vorschau vor dem Kopieren neu." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe found %1$@, but this plan lists %2$@ more. Rebuild the preview before copying." + } + } + } + }, "Chronoframe found %1$@, and %2$@. Rebuild the preview before copying." : { "extractionState" : "manual", "localizations" : { @@ -3254,6 +3305,23 @@ } } }, + "Your originals are never changed and nothing is copied yet. You can keep using your Mac." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Deine Originale werden nie verändert, und es wird noch nichts kopiert. Du kannst deinen Mac weiterverwenden." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your originals are never changed and nothing is copied yet. You can keep using your Mac." + } + } + } + }, "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." : { "extractionState" : "manual", "localizations" : { @@ -4341,6 +4409,23 @@ } } }, + "Status, reports and logs" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Status, Berichte und Protokolle" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Status, reports and logs" + } + } + } + }, "Details" : { "extractionState" : "manual", "localizations" : { @@ -14810,6 +14895,23 @@ } } }, + "Open comparison in Quick Review" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vergleich in der Schnellprüfung öffnen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Open comparison in Quick Review" + } + } + } + }, "Open comparison in Rapid Triage" : { "localizations" : { "en" : { @@ -28660,6 +28762,57 @@ } } }, + "Each bar is one month of files this plan is copying." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Jeder Balken steht für einen Monat an Dateien, die dieser Plan gerade kopiert." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Each bar is one month of files this plan is copying." + } + } + } + }, + "Quick Review progress" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fortschritt der Schnellprüfung" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Quick Review progress" + } + } + } + }, + "Each bar is one month of files this plan will copy." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Jeder Balken steht für einen Monat an Dateien, die dieser Plan kopiert." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Each bar is one month of files this plan will copy." + } + } + } + }, "Every bar is a month of planned transfers waiting to land." : { "localizations" : { "en" : { diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift index 01d5b3b6..50d14aa3 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift @@ -379,13 +379,30 @@ enum DeduplicateFooterCopy { : String(localized: "Move \(fileCount.formatted()) Files to Trash Free", bundle: .module) } + /// What the footer status line counts. Beside "Move N Files to Trash Free" it counts + /// that batch, so the status and the button agree; the free line above them says + /// how many more the reviewed groups hold. + static func statusCounts(reviewedFileCount: Int, reviewedBytes: Int64, freeBatch: FreeDedupeBatch?) -> (files: Int, bytes: Int64) { + guard let freeBatch else { return (reviewedFileCount, reviewedBytes) } + return (freeBatch.plan.count, freeBatch.plan.totalBytes) + } + + /// The footer's Accept Identical Copies has nothing to do when no identical group is waiting. + @MainActor + static func hasIdenticalCopiesToAccept(in store: DeduplicateSessionStore) -> Bool { + (store.laneSummaries[.identical]?.groups ?? 0) > 0 + } + static func unlockAllTitle(count: Int) -> String { String(localized: "Unlock to Remove All \(count.formatted())", bundle: .module) } /// Added to the summary after a free removal: what is still waiting. static func waitingLine(deferredFileCount: Int) -> String { - String(localized: "\(deferredFileCount.formatted()) more are waiting. Your choices are saved; scan again to continue.", bundle: .module) + if deferredFileCount == 1 { + return String(localized: "1 more is waiting. Your choices are saved; scan again to continue.", bundle: .module) + } + return String(localized: "\(deferredFileCount.formatted()) more are waiting. Your choices are saved; scan again to continue.", bundle: .module) } /// The count both confirmation dialogs show: the frozen plan when one is diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift index 0cf9b86d..9a360026 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift @@ -27,8 +27,6 @@ struct DeduplicateView: View { @State private var showingRapidTriage = false /// The lane Quick Review opens over; set by whichever control opened it. @State private var quickReviewLane: DeduplicateReviewLane = .lookAtEach - /// Files a free removal leaves for later, remembered from the confirmed batch for the summary. - @State private var freeBatchDeferredCount: Int? @AppStorage("didOnboardDeduplicate") private var didOnboardDeduplicate = false @State private var selectedDedupeItemURL: URL? = nil /// `savedAt` of the restored review whose banner the user dismissed. The store @@ -577,7 +575,6 @@ struct DeduplicateView: View { } Button("Cancel", role: .cancel) { sessionStore.discardPreparedCommitPlan() - freeBatchDeferredCount = nil } } message: { Text(DeduplicateFooterCopy.dialogMessage( @@ -597,7 +594,6 @@ struct DeduplicateView: View { } Button("Cancel", role: .cancel) { sessionStore.discardPreparedCommitPlan() - freeBatchDeferredCount = nil } } message: { Text(DeduplicateFooterCopy.dialogMessage( @@ -629,13 +625,10 @@ struct DeduplicateView: View { } /// Freezes the free batch and opens the first confirmation dialog. Nothing is - /// moved to the Trash until that dialog is confirmed. Never prepares while a - /// commit is running: the store reads its free-batch flag when that commit ends. + /// moved to the Trash until that dialog is confirmed. The store refuses to prepare + /// while a commit is running, and remembers the deferred count for the summary. private func openFreeBatchConfirmation(remaining: Int) { - guard sessionStore.status != .committing, - let batch = sessionStore.freeBatchOffer(remaining: remaining), - sessionStore.prepareFreeBatchCommitPlan(remaining: remaining) != nil else { return } - freeBatchDeferredCount = batch.deferredFileCount + guard sessionStore.prepareFreeBatchCommitPlan(remaining: remaining) != nil else { return } showingCommitConfirmation = true } @@ -702,8 +695,14 @@ struct DeduplicateView: View { private func commitFooterStatus(toDelete: Int, bytes: Int64, hardDelete: Bool, editedVersionsKept: Int) -> some View { let reviewedCount = sessionStore.reviewedClusters.count let suggestedCount = max(0, sessionStore.clusters.count - reviewedCount) - let title = Self.commitFooterTitle(fileCount: toDelete, hardDelete: hardDelete) - let detail = Self.commitFooterDetail(byteCount: bytes, hardDelete: hardDelete) + // Beside a free-batch button the status counts that batch, not the whole reviewed plan. + let counts = DeduplicateFooterCopy.statusCounts( + reviewedFileCount: toDelete, + reviewedBytes: bytes, + freeBatch: freeBatchFooterOffer(toDelete: toDelete)?.batch + ) + let title = Self.commitFooterTitle(fileCount: counts.files, hardDelete: hardDelete) + let detail = Self.commitFooterDetail(byteCount: counts.bytes, hardDelete: hardDelete) let reviewed = reviewedCount == 1 ? String(localized: "1 group reviewed", bundle: .module) : String(localized: "\(reviewedCount) groups reviewed", bundle: .module) @@ -813,7 +812,6 @@ struct DeduplicateView: View { ? String(localized: "Move Reviewed to Trash (1 group)", bundle: .module) : String(localized: "Move Reviewed to Trash (\(String(reviewedCount)) groups)", bundle: .module)) { sessionStore.prepareReviewedCommitPlan() - freeBatchDeferredCount = nil showingCommitReviewedConfirmation = true } .accessibilityIdentifier(AccessibilityIdentifiers.dedupeCommitReviewedButton) @@ -853,6 +851,7 @@ struct DeduplicateView: View { .keyboardShortcut(.return, modifiers: [.command, .shift]) .buttonStyle(.borderedMicroDelight) .fixedSize() + .disabled(!DeduplicateFooterCopy.hasIdenticalCopiesToAccept(in: sessionStore)) .help(Text(LocalizedStringKey(DeduplicateFooterCopy.acceptIdenticalHelp), bundle: .module)) .accessibilityLabel("Accept identical copies") .accessibilityIdentifier(AccessibilityIdentifiers.dedupeAcceptAllSuggestionsButton) @@ -881,7 +880,6 @@ struct DeduplicateView: View { } else { Button(density.commitTitle(fileCount: toDelete), role: .destructive) { sessionStore.prepareReviewedCommitPlan() - freeBatchDeferredCount = nil showingCommitConfirmation = true } .keyboardShortcut(.return, modifiers: .command) @@ -896,7 +894,7 @@ struct DeduplicateView: View { // MARK: - Completed private var completedView: some View { - let copy = Self.completedStatusCopy(for: sessionStore.commitSummary, deferredFileCount: freeBatchDeferredCount) + let copy = Self.completedStatusCopy(for: sessionStore.commitSummary, deferredFileCount: sessionStore.freeBatchDeferredFileCount) return DeduplicateStatusView( style: .success, title: "Deduplicate complete", diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift index 7162b67f..943044ad 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift @@ -120,7 +120,7 @@ struct RapidTriageView: View { } ProgressView(value: progress) .tint(DesignTokens.ColorSystem.accentAction) - .accessibilityLabel("Rapid triage progress") + .accessibilityLabel("Quick Review progress") .accessibilityValue(PluralPhrases.triageProgress(current: currentIndex, total: clustersToReview.count)) } .padding(DesignTokens.Spacing.md) diff --git a/ui/Sources/ChronoframeApp/Views/Help/HelpView.swift b/ui/Sources/ChronoframeApp/Views/Help/HelpView.swift index aa9dd696..7461ba5c 100644 --- a/ui/Sources/ChronoframeApp/Views/Help/HelpView.swift +++ b/ui/Sources/ChronoframeApp/Views/Help/HelpView.swift @@ -142,7 +142,7 @@ private struct HelpShortcutsSection: View { ShortcutRow(keys: "← / →", label: "Move between photos in a duplicate group") ShortcutRow(keys: "↩", label: "Confirm the current duplicate group") ShortcutRow(keys: "C", label: "Compare duplicate candidates") - ShortcutRow(keys: "Space", label: "Open comparison in Rapid Triage") + ShortcutRow(keys: "Space", label: "Open comparison in Quick Review") } HelpListPanel(title: "App") { diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift b/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift index 41e72635..23f9b711 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift @@ -27,10 +27,21 @@ enum RunAccountingText { ) } + // A positive remainder is files the plan is missing; a negative one is + // a plan that lists more than was found. Each direction has its own + // sentence so neither claims the other's gap. + if accounting.remainder < 0 { + return String( + format: AppLocalization.string("Chronoframe found %1$@, but this plan lists %2$@ more. Rebuild the preview before copying."), + PluralPhrases.photosAndVideos(accounting.found), + (-accounting.remainder).formatted() + ) + } + return String( format: AppLocalization.string("Chronoframe found %1$@, and %2$@. Rebuild the preview before copying."), PluralPhrases.photosAndVideos(accounting.found), - notInPlanPhrase(abs(accounting.remainder)) + notInPlanPhrase(accounting.remainder) ) } @@ -70,10 +81,20 @@ enum RunAccountingText { ) } + // A negative remainder is a copy that handled more than was found; it + // gets its own sentence so it never claims files are "not accounted for". + if accounting.remainder < 0 { + return String( + format: AppLocalization.string("Chronoframe found %1$@, but this copy handled %2$@ more. Open History for the full record."), + PluralPhrases.photosAndVideos(accounting.found), + (-accounting.remainder).formatted() + ) + } + return String( format: AppLocalization.string("Chronoframe found %1$@, and %2$@. Open History for the full record."), PluralPhrases.photosAndVideos(accounting.found), - notAccountedForPhrase(abs(accounting.remainder)) + notAccountedForPhrase(accounting.remainder) ) } diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index 98503f5b..8cd498f0 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -507,7 +507,7 @@ struct RunWorkspaceShell: View { .padding(.top, DesignTokens.Spacing.sm) } label: { // The whole row opens it, not only the small triangle. - Text("Details") + Text("Status, reports and logs") .frame(maxWidth: .infinity, alignment: .leading) .contentShape(Rectangle()) .onTapGesture { showsOverviewDetails.toggle() } diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift b/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift index ae353778..f86a296c 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift @@ -268,11 +268,11 @@ struct RunTimelineView: View { switch model.context.status { case .running: if model.context.currentPhase == .copy { - return String(localized: "Every bar is a month of planned transfers. Progress is counted for the run as a whole.", bundle: .module) + return String(localized: "Each bar is one month of files this plan is copying.", bundle: .module) } return String(localized: "Reading dates from your folders.", bundle: .module) case .dryRunFinished: - return String(localized: "Every bar is a month of planned transfers waiting to land.", bundle: .module) + return String(localized: "Each bar is one month of files this plan will copy.", bundle: .module) case .finished: return String(localized: "Every frame is home.", bundle: .module) case .nothingToCopy: diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift index 4292f3a9..3d5cc731 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift @@ -360,7 +360,7 @@ struct RunWorkspaceModel { return RunHeroState( title: mode == .preview ? String(localized: "Building the preview", bundle: .module) : String(localized: "Copying your photos", bundle: .module), message: mode == .preview - ? String(localized: "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", bundle: .module) + ? String(localized: "Your originals are never changed and nothing is copied yet. You can keep using your Mac.", bundle: .module) : String(localized: "You can keep using your Mac. Originals are only read, never changed.", bundle: .module), badgeTitle: mode == .preview ? String(localized: "Previewing", bundle: .module) : String(localized: "Copying", bundle: .module), badgeSymbol: "arrow.triangle.2.circlepath", @@ -956,7 +956,7 @@ enum RunFreeCopyText { let counts = String( format: AppLocalization.string("You can copy %1$@ free. This plan has %2$@."), PluralPhrases.files(remaining), - planned.formatted() + PluralPhrases.files(planned) ) guard let suggested else { return counts } let month = monthYearName(forKey: suggested.key) diff --git a/ui/Sources/ChronoframeApp/Views/Run/TimelinePlurals.swift b/ui/Sources/ChronoframeApp/Views/Run/TimelinePlurals.swift index 1b67ab51..642786af 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/TimelinePlurals.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/TimelinePlurals.swift @@ -19,10 +19,6 @@ enum TimelinePlurals { phrase(count, one: "across 1 month", other: "across %@ months", bundle: bundle) } - static func filesToCopy(_ count: Int, bundle: Bundle = .module) -> String { - phrase(count, one: "1 file to copy", other: "%@ files to copy", bundle: bundle) - } - /// "2 of 5 phases complete"; the noun follows the total, so only a total of 1 is singular. static func phasesComplete(_ completed: Int, of total: Int, bundle: Bundle = .module) -> String { total == 1 diff --git a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift index 7cddf68c..022a7b0c 100644 --- a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift +++ b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift @@ -47,7 +47,14 @@ struct GuidedSetupModel: Equatable { var destinationPath: String var isMeasuring: Bool var estimate: FolderSizeEstimate? - var destinationFreeBytes: Int64? + /// The free-space figure and the destination it was measured for. The figure is only ever read + /// back for that same destination, so a newly chosen folder never shows the previous one's figure. + private var measuredFreeBytes: Int64? + private var measuredFreeBytesPath: String? + + var destinationFreeBytes: Int64? { + measuredFreeBytesPath == destinationPath ? measuredFreeBytes : nil + } init( step: GuidedSetupStep = .source, @@ -64,7 +71,29 @@ struct GuidedSetupModel: Equatable { self.destinationPath = destinationPath self.isMeasuring = isMeasuring self.estimate = estimate - self.destinationFreeBytes = destinationFreeBytes + self.measuredFreeBytes = destinationFreeBytes + self.measuredFreeBytesPath = destinationPath + } + + mutating func recordDestinationFreeBytes(_ bytes: Int64?, for path: String) { + measuredFreeBytes = bytes + measuredFreeBytesPath = path + } + + mutating func clearDestinationFreeBytes() { + measuredFreeBytes = nil + measuredFreeBytesPath = nil + } + + /// True when a source appeared from outside the screen (the Library menu's Add Folders, say) while + /// the first question is up. A drop already ends guided setup; this makes the menu route do the same. + /// The screen's own picker is excluded because it advances the step itself. + static func sourceAddedElsewhereEndsGuidedSetup( + step: GuidedSetupStep, + isChoosingSource: Bool, + sourcePath: String + ) -> Bool { + step == .source && !isChoosingSource && !sourcePath.isEmpty } var title: String { diff --git a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift index 2edbff6d..c8a89179 100644 --- a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift +++ b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift @@ -60,6 +60,16 @@ struct GuidedSetupView: View { } .task(id: measurementRoot) { await measureFolder() } .task(id: freeSpaceKey) { await refreshFreeSpace() } + .onChange(of: setupStore.sourcePath) { _, path in + // A source added from the menu ends guided setup, the same as a drop (SetupView's onDrop). + if GuidedSetupModel.sourceAddedElsewhereEndsGuidedSetup( + step: model.step, + isChoosingSource: isChoosingSource, + sourcePath: path + ) { + didOnboard = true + } + } } // MARK: Source step @@ -225,7 +235,7 @@ struct GuidedSetupView: View { private func enterDestinationStep(sourceKind: GuidedSourceKind) { model.sourceKind = sourceKind model.estimate = nil - model.destinationFreeBytes = nil + model.clearDestinationFreeBytes() model.isMeasuring = sourceKind == .folder model.step = .destination } @@ -235,7 +245,7 @@ struct GuidedSetupView: View { model.step = .source model.isMeasuring = false model.estimate = nil - model.destinationFreeBytes = nil + model.clearDestinationFreeBytes() } private func start() { @@ -309,6 +319,6 @@ struct GuidedSetupView: View { PhotosExportExecutor.liveFreeSpace(at: URL(fileURLWithPath: path, isDirectory: true)) }.value guard !Task.isCancelled else { return } - model.destinationFreeBytes = free + model.recordDestinationFreeBytes(free, for: path) } } diff --git a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings index f0936d09..d5e25142 100644 --- a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings +++ b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings @@ -6739,6 +6739,16 @@ } } }, + "Choose This Folder": { + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Diesen Ordner wählen" + } + } + } + }, "Watch Folder": { "localizations": { "de": { diff --git a/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift b/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift index 15fb6927..38f16322 100644 --- a/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift +++ b/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift @@ -153,10 +153,12 @@ public final class FolderAccessService: FolderAccessServicing { } /// `directory` itself when it is an existing folder on a local volume, otherwise the place - /// `initialPanelDirectoryURL` uses when it is given no path. + /// `initialPanelDirectoryURL` uses when it is given no path. Like `initialPanelDirectoryURL`, it + /// never opens inside a protected media library (Music, Movies), and checks that before touching disk. static func panelDirectoryURL(openingAt directory: URL) -> URL { var isDirectory: ObjCBool = false - if FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), + if !isProtectedMediaLibraryPath(directory.standardizedFileURL), + FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), isDirectory.boolValue, let values = try? directory.resourceValues(forKeys: [.volumeIsLocalKey]), values.volumeIsLocal == true { diff --git a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift index fd5922d2..0150494b 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift @@ -55,6 +55,10 @@ public final class DeduplicateSessionStore: ObservableObject { } @Published public private(set) var laneSummaries: [DeduplicateReviewLane: DeduplicateLaneSummary] = [:] @Published public var wantsFreeBatchConfirmation: Bool = false + /// Files a free removal left for later, set when that batch is prepared and kept + /// until the next scan or an ordinary prepare. The summary reads it, so it survives + /// the Deduplicate view being rebuilt while the commit runs. + @Published public private(set) var freeBatchDeferredFileCount: Int? /// Set when a saved review was restored after a scan; cleared by `reset()` and `startScan`. @Published public private(set) var restoredReview: DeduplicateReviewRestoration? /// The saved review for the idle card; refreshed by `refreshSavedReview(folderPath:)`. @@ -196,17 +200,28 @@ public final class DeduplicateSessionStore: ObservableObject { /// Freezes the exact plan shown by the destructive confirmation dialog. /// The same value is later passed to the engine without recomputation. + /// + /// While a commit is running this freezes nothing and returns the current plan: + /// the commit reads the free-batch flag when it completes, so a prepare then + /// would change what that commit does to the saved review. @discardableResult public func prepareReviewedCommitPlan() -> DeduplicationPlan { + guard status != .committing else { return reviewedDeletionPlan() } + return freezeReviewedCommitPlan() + } + + private func freezeReviewedCommitPlan() -> DeduplicationPlan { let plan = reviewedDeletionPlan() preparedCommitPlan = plan preparedPlanIsFreeBatch = false + freeBatchDeferredFileCount = nil return plan } public func discardPreparedCommitPlan() { preparedCommitPlan = nil preparedPlanIsFreeBatch = false + freeBatchDeferredFileCount = nil } /// File count of the frozen plan the confirmation dialog shows. @@ -237,12 +252,14 @@ public final class DeduplicateSessionStore: ObservableObject { } /// Freezes the free removal batch as the prepared commit plan. Nil, and no - /// change, when there is no offer. + /// change, when there is no offer or a commit is running. @discardableResult public func prepareFreeBatchCommitPlan(remaining: Int) -> DeduplicationPlan? { - guard let offer = freeBatchOffer(remaining: remaining) else { return nil } + guard status != .committing, + let offer = freeBatchOffer(remaining: remaining) else { return nil } preparedCommitPlan = offer.plan preparedPlanIsFreeBatch = true + freeBatchDeferredFileCount = offer.deferredFileCount return offer.plan } @@ -268,7 +285,7 @@ public final class DeduplicateSessionStore: ObservableObject { status = .committing let commitConfiguration = lastScanConfiguration ?? configuration activeCommitConfiguration = commitConfiguration - let plan = preparedCommitPlan ?? prepareReviewedCommitPlan() + let plan = preparedCommitPlan ?? freezeReviewedCommitPlan() preparedCommitPlan = nil do { let stream = try engine.commit( @@ -363,6 +380,7 @@ public final class DeduplicateSessionStore: ObservableObject { clusters = [] summary = nil preparedCommitPlan = nil + freeBatchDeferredFileCount = nil commitSummary = nil issues = [] lastErrorMessage = nil @@ -491,7 +509,8 @@ public final class DeduplicateSessionStore: ObservableObject { for (path, decision) in suggestedDecisions(for: [cluster]).byPath { byPath[path] = decision } - decisions = DedupeDecisions(byPath: byPath) + // #301: keep the person's pair keep-overrides; only the per-path choices change. + decisions = DedupeDecisions(byPath: byPath, pairKeepOverrides: decisions.pairKeepOverrides) approvedClusterIDs.insert(cluster.id) registerUndo( oldDecisions: oldDecisions, @@ -536,42 +555,12 @@ public final class DeduplicateSessionStore: ObservableObject { scheduleSave() } - public func acceptAllSuggestions() { - // Phase 1 finding #10: scope this to *automatically eligible* - // clusters (high-confidence) only, matching the AGENTS.md - // invariant that non-exact / weak matches stay review-only - // until the user explicitly approves them. The previous - // implementation approved every cluster regardless of - // confidence, so a user clicking "Accept all suggestions" - // would silently commit low/medium-confidence preselects on - // commit. - // Groups the user already reviewed keep their own choices (D-CLP-123). - let eligibleClusters = clusters.filter { - DeduplicationPlanner.isAutomaticCommitEligible($0) && !approvedClusterIDs.contains($0.id) - } - guard !eligibleClusters.isEmpty else { return } - let oldDecisions = decisions - let oldApproved = approvedClusterIDs - var byPath = decisions.byPath - for (path, decision) in suggestedDecisions(for: eligibleClusters).byPath { - byPath[path] = decision - } - decisions = DedupeDecisions(byPath: byPath) - approvedClusterIDs.formUnion(eligibleClusters.map(\.id)) - registerUndo( - oldDecisions: oldDecisions, - oldApproved: oldApproved, - actionName: String(localized: "Accept All Suggestions", bundle: Bundle.module) - ) - scheduleSave() - } - public func lane(for cluster: DuplicateCluster) -> DeduplicateReviewLane { DeduplicateReviewLane.lane(for: cluster, snapshot: summary?.scanSnapshot ?? DeduplicateScanSnapshot()) } - /// Accepts the suggestions for the unreviewed groups of one lane, the way - /// `acceptAllSuggestions()` does for every eligible group. Look at each does nothing. + /// Accepts the suggestions for the unreviewed, automatically eligible groups + /// of one lane. Look at each does nothing. public func acceptSuggestions(in lane: DeduplicateReviewLane) { let actionName: String switch lane { @@ -594,7 +583,8 @@ public final class DeduplicateSessionStore: ObservableObject { for (path, decision) in suggestedDecisions(for: laneClusters).byPath { byPath[path] = decision } - decisions = DedupeDecisions(byPath: byPath) + // #301: keep the person's pair keep-overrides; only the per-path choices change. + decisions = DedupeDecisions(byPath: byPath, pairKeepOverrides: decisions.pairKeepOverrides) approvedClusterIDs.formUnion(laneClusters.map(\.id)) registerUndo( oldDecisions: oldDecisions, @@ -624,31 +614,6 @@ public final class DeduplicateSessionStore: ObservableObject { return buckets } - public func acceptAllHighConfidence() { - // Filter through the same eligibility gate as the auto-accept path so a - // non-exact video cluster (which must stay review-only) can never be - // bulk-accepted into explicit delete decisions the planner can't undo. - // Groups the user already reviewed keep their own choices (D-CLP-123). - let highClusters = (triageBuckets[.high] ?? []).filter { - DeduplicationPlanner.isAutomaticCommitEligible($0) && !approvedClusterIDs.contains($0.id) - } - guard !highClusters.isEmpty else { return } - let oldDecisions = decisions - let oldApproved = approvedClusterIDs - var byPath = decisions.byPath - for (path, decision) in suggestedDecisions(for: highClusters).byPath { - byPath[path] = decision - } - decisions = DedupeDecisions(byPath: byPath) - approvedClusterIDs.formUnion(highClusters.map(\.id)) - registerUndo( - oldDecisions: oldDecisions, - oldApproved: oldApproved, - actionName: String(localized: "Accept All Safe", bundle: Bundle.module) - ) - scheduleSave() - } - public func pauseReview() { guard status == .readyToReview, !clusters.isEmpty else { return } saveNow() @@ -678,6 +643,7 @@ public final class DeduplicateSessionStore: ObservableObject { clusters = [] summary = nil preparedCommitPlan = nil + freeBatchDeferredFileCount = nil commitSummary = nil issues = [] lastErrorMessage = nil diff --git a/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift b/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift index 0c4812c8..dd6301d8 100644 --- a/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift +++ b/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift @@ -64,11 +64,7 @@ public enum FolderSizeEstimator { } entriesSeen += 1 - guard let url = next as? URL else { - sawUnreadableEntry = true - continue - } - guard let values = try? url.resourceValues(forKeys: Set(keys)) else { + guard let url = next as? URL, let values = try? url.resourceValues(forKeys: Set(keys)) else { sawUnreadableEntry = true continue } diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift index eb379e48..dc03f70c 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift @@ -109,6 +109,21 @@ final class ChronoframeCoreFolderSizeEstimatorTests: XCTestCase { XCTAssertEqual(finished.fileCount, 1_200) } + func testUnreadableSubfolderIsSkippedAndMarksTheEstimateIncomplete() throws { + try write(Data(repeating: 1, count: 10), to: "readable.jpg") + try write(Data(repeating: 2, count: 999), to: "locked/hidden-from-us.jpg") + let locked = root.appendingPathComponent("locked", isDirectory: true) + try fileManager.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path) + defer { try? fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + // What could be read is still counted, but the figure must not claim to be the whole folder. + XCTAssertEqual(estimate.fileCount, 1) + XCTAssertEqual(estimate.totalBytes, 10) + XCTAssertFalse(estimate.isComplete) + } + // AGENTS-INVARIANT: 1 func testCreatesAndModifiesNothing() throws { try write(Data(repeating: 1, count: 100), to: "a.jpg") diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift index a5a633b8..cfaaa64b 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift @@ -511,50 +511,11 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.triageBuckets[.medium]?.map(\.id), [unannotated.id]) } + /// Defense-in-depth: a non-exact *video* cluster annotated high confidence + /// must stay review-only in every lane, because perceptual video matching is + /// never auto-accepted. The exact video cluster is still accepted. @MainActor - func testAcceptAllHighConfidenceOnlyAppliesHighBucketSuggestions() async throws { - let high = DuplicateCluster( - kind: .exactDuplicate, - members: [ - PhotoCandidate(path: "/dest/high-a.jpg", size: 100, modificationTime: 0, qualityScore: 0.9), - PhotoCandidate(path: "/dest/high-b.jpg", size: 100, modificationTime: 0, qualityScore: 0.4), - ], - suggestedKeeperIDs: ["/dest/high-a.jpg"], - bytesIfPruned: 100, - annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) - ) - let medium = DuplicateCluster( - kind: .nearDuplicate, - members: [ - PhotoCandidate(path: "/dest/medium-a.jpg", size: 100, modificationTime: 0, qualityScore: 0.9), - PhotoCandidate(path: "/dest/medium-b.jpg", size: 100, modificationTime: 0, qualityScore: 0.4), - ], - suggestedKeeperIDs: ["/dest/medium-a.jpg"], - bytesIfPruned: 100, - annotation: ClusterAnnotation(confidence: .medium, matchReason: MatchReason(kind: .nearDuplicate)) - ) - let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [high, medium])) - - store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) - _ = await waitForCondition { store.status == .readyToReview } - store.setDecision(.keep, forPath: "/dest/high-b.jpg") - store.setDecision(.keep, forPath: "/dest/medium-b.jpg") - - store.acceptAllHighConfidence() - - XCTAssertEqual(store.decisions.byPath["/dest/high-a.jpg"], .keep) - // D-CLP-123: the high group was reviewed above (setDecision), so bulk accept leaves it alone. - XCTAssertEqual(store.decisions.byPath["/dest/high-b.jpg"], .keep) - XCTAssertEqual(store.decisions.byPath["/dest/medium-a.jpg"], .keep) - XCTAssertEqual(store.decisions.byPath["/dest/medium-b.jpg"], .keep) - } - - /// Defense-in-depth: even if a non-exact *video* cluster is (incorrectly) - /// annotated high confidence, bulk "Accept all high confidence" must not - /// turn it into delete decisions — perceptual video stays review-only. The - /// exact video cluster in the same bucket is still accepted. - @MainActor - func testAcceptAllHighConfidenceSkipsNonExactVideoCluster() async throws { + func testAcceptInLaneSkipsNonExactVideoCluster() async throws { let exactVideo = DuplicateCluster( kind: .exactDuplicate, members: [ @@ -575,154 +536,32 @@ final class DeduplicateSessionStoreTests: XCTestCase { bytesIfPruned: 100, annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .nearDuplicate)) ) - let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [exactVideo, perceptualVideo])) + let (store, _) = await scannedLaneStore([exactVideo, perceptualVideo]) - store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) - _ = await waitForCondition { store.status == .readyToReview } - store.acceptAllHighConfidence() - - // The exact video cluster is approved by the bulk action; the - // non-exact video cluster is not — so it never enters the reviewed set - // the executor commits, regardless of its (here, deliberately wrong) - // high annotation. Suggested decisions are pre-populated for every - // cluster as a plan preview, so the safety signal is approval, not the - // raw decision map. + for lane in DeduplicateReviewLane.allCases { + store.acceptSuggestions(in: lane) + } + + // Suggested decisions are pre-populated for every cluster as a plan + // preview, so the safety signal is approval, not the raw decision map. XCTAssertTrue(store.approvedClusterIDs.contains(exactVideo.id)) XCTAssertFalse(store.approvedClusterIDs.contains(perceptualVideo.id)) } - /// Phase 1 finding #10 regression: `acceptAllSuggestions` used to - /// approve every cluster regardless of confidence, so a user - /// clicking this single button would commit low/medium-confidence - /// preselects on commit — violating the AGENTS.md invariant that - /// non-exact / weak matches stay review-only until the user - /// explicitly approves them. The fix scopes "Accept all" to the - /// high-confidence bucket only. - @MainActor - func testAcceptAllSuggestionsOnlyApprovesHighConfidenceClusters() async throws { - let high = DuplicateCluster( - kind: .exactDuplicate, - members: [ - PhotoCandidate(path: "/dest/auto-a.jpg", size: 100, modificationTime: 0, qualityScore: 0.9), - PhotoCandidate(path: "/dest/auto-b.jpg", size: 100, modificationTime: 0, qualityScore: 0.4), - ], - suggestedKeeperIDs: ["/dest/auto-a.jpg"], - bytesIfPruned: 100, - annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) - ) - let medium = DuplicateCluster( - kind: .nearDuplicate, - members: [ - PhotoCandidate(path: "/dest/weak-a.jpg", size: 100, modificationTime: 0, qualityScore: 0.9), - PhotoCandidate(path: "/dest/weak-b.jpg", size: 100, modificationTime: 0, qualityScore: 0.4), - ], - suggestedKeeperIDs: ["/dest/weak-a.jpg"], - bytesIfPruned: 100, - annotation: ClusterAnnotation(confidence: .medium, matchReason: MatchReason(kind: .nearDuplicate)) - ) - let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [high, medium])) - store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) - _ = await waitForCondition { store.status == .readyToReview } - - store.acceptAllSuggestions() - - XCTAssertTrue(store.approvedClusterIDs.contains(high.id), - "High-confidence cluster should be approved by Accept All.") - XCTAssertFalse(store.approvedClusterIDs.contains(medium.id), - "Medium-confidence cluster must stay review-only after Accept All.") - XCTAssertEqual(store.decisions.byPath["/dest/auto-b.jpg"], .delete, - "High-confidence non-keeper should be marked Delete.") - // The weak cluster's preselects exist in `decisions.byPath` - // (set at scan completion by `suggestedDecisions`) but the - // cluster is NOT approved, so the *reviewed* deletion plan — - // which is what the executor actually consumes — must not - // include weak-cluster items. - let reviewedPaths = Set(store.reviewedDeletionPlan().items.map(\.path)) - XCTAssertTrue(reviewedPaths.contains("/dest/auto-b.jpg")) - XCTAssertFalse(reviewedPaths.contains("/dest/weak-a.jpg"), - "Weak cluster member must NOT be in the reviewed deletion plan.") - XCTAssertFalse(reviewedPaths.contains("/dest/weak-b.jpg"), - "Weak cluster member must NOT be in the reviewed deletion plan.") - } - - private func eligibleExactCluster(_ name: String) -> DuplicateCluster { - DuplicateCluster( - kind: .exactDuplicate, - members: [ - PhotoCandidate(path: "/dest/\(name)-a.jpg", size: 100, modificationTime: 0, qualityScore: 0.9), - PhotoCandidate(path: "/dest/\(name)-b.jpg", size: 100, modificationTime: 0, qualityScore: 0.4), - ], - suggestedKeeperIDs: ["/dest/\(name)-a.jpg"], - bytesIfPruned: 100, - annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) - ) - } - - /// Flips the suggested keeper so the group is reviewed with custom choices. - @MainActor - private func reviewWithFlippedKeeper(_ store: DeduplicateSessionStore, name: String) { - store.setDecision(.delete, forPath: "/dest/\(name)-a.jpg") - store.setDecision(.keep, forPath: "/dest/\(name)-b.jpg") - } - - @MainActor - func testAcceptAllSuggestionsKeepsChoicesInReviewedGroups() async throws { - let first = eligibleExactCluster("first") - let second = eligibleExactCluster("second") - let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [first, second])) - store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) - _ = await waitForCondition { store.status == .readyToReview } - reviewWithFlippedKeeper(store, name: "first") - XCTAssertEqual(store.approvedClusterIDs, [first.id]) - - store.acceptAllSuggestions() - - XCTAssertEqual(store.decisions.byPath["/dest/first-a.jpg"], .delete, - "A reviewed group's custom choice must survive Accept All.") - XCTAssertEqual(store.decisions.byPath["/dest/first-b.jpg"], .keep, - "A reviewed group's custom choice must survive Accept All.") - XCTAssertTrue(store.approvedClusterIDs.contains(first.id)) - XCTAssertTrue(store.approvedClusterIDs.contains(second.id)) - XCTAssertEqual(store.decisions.byPath["/dest/second-a.jpg"], .keep) - XCTAssertEqual(store.decisions.byPath["/dest/second-b.jpg"], .delete) - } - @MainActor - func testAcceptAllHighConfidenceKeepsChoicesInReviewedGroups() async throws { - let first = eligibleExactCluster("first") - let second = eligibleExactCluster("second") - let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [first, second])) - store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) - _ = await waitForCondition { store.status == .readyToReview } - reviewWithFlippedKeeper(store, name: "first") - XCTAssertEqual(store.approvedClusterIDs, [first.id]) - - store.acceptAllHighConfidence() - - XCTAssertEqual(store.decisions.byPath["/dest/first-a.jpg"], .delete, - "A reviewed group's custom choice must survive Accept All Safe.") - XCTAssertEqual(store.decisions.byPath["/dest/first-b.jpg"], .keep, - "A reviewed group's custom choice must survive Accept All Safe.") - XCTAssertTrue(store.approvedClusterIDs.contains(first.id)) - XCTAssertTrue(store.approvedClusterIDs.contains(second.id)) - XCTAssertEqual(store.decisions.byPath["/dest/second-a.jpg"], .keep) - XCTAssertEqual(store.decisions.byPath["/dest/second-b.jpg"], .delete) - } - - @MainActor - func testAcceptAllSuggestionsDoesNothingWhenEveryEligibleGroupIsReviewed() async throws { - let first = eligibleExactCluster("first") - let second = eligibleExactCluster("second") - let store = DeduplicateSessionStore(engine: MockDeduplicateEngine(clusters: [first, second])) - store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) - _ = await waitForCondition { store.status == .readyToReview } - reviewWithFlippedKeeper(store, name: "first") - reviewWithFlippedKeeper(store, name: "second") + func testAcceptInLaneDoesNothingWhenEveryGroupInTheLaneIsReviewed() async throws { + let first = laneCluster("first", lane: .identical, deletes: 1) + let second = laneCluster("second", lane: .identical, deletes: 1) + let (store, _) = await scannedLaneStore([first, second]) + store.setDecision(.delete, forPath: "/dest/first/keep.jpg") + store.setDecision(.keep, forPath: "/dest/first/d1.jpg") + store.setDecision(.delete, forPath: "/dest/second/keep.jpg") + store.setDecision(.keep, forPath: "/dest/second/d1.jpg") let decisionsBefore = store.decisions let approvedBefore = store.approvedClusterIDs XCTAssertEqual(approvedBefore, [first.id, second.id]) - store.acceptAllSuggestions() + store.acceptSuggestions(in: .identical) XCTAssertEqual(store.decisions, decisionsBefore) XCTAssertEqual(store.approvedClusterIDs, approvedBefore) @@ -1798,6 +1637,173 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(engine.lastCommitPlan, commitCallsBefore, "Restoring committed nothing") } + /// #301: accepting a lane rebuilt `decisions` from the paths alone and dropped + /// the person's pair keep-overrides. + @MainActor + // AGENTS-INVARIANT: 14 + func testAcceptLanePreservesPairKeepOverrides() async throws { + 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] + let cluster = DuplicateCluster( + kind: .exactDuplicate, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 100, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) + ) + let engine = laneEngine([cluster]) + engine.summary = DeduplicateSummary(scanSnapshot: laneSnapshot([cluster], overriding: [ + "/dest/live/d1.mov": FileIdentity(size: 100, digest: "live-movie"), + ])) + let store = laneStore(engine: engine) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + // The person chose to keep the movie half of the Live Photo. + store.decisions = DedupeDecisions(byPath: store.decisions.byPath, pairKeepOverrides: ["/dest/live/d1.mov"]) + + store.acceptSuggestions(in: .identical) + + XCTAssertEqual(store.approvedClusterIDs, [cluster.id]) + XCTAssertEqual(store.decisions.pairKeepOverrides, ["/dest/live/d1.mov"], "Accepting a lane keeps the person's override") + let plan = store.reviewedDeletionPlan() + XCTAssertTrue(plan.items.contains { $0.path == "/dest/live/d1.heic" }) + XCTAssertFalse(plan.items.contains { $0.path == "/dest/live/d1.mov" }, "The plan honours the override") + + // Premise: without the override the movie follows its still into the plan. + var withoutOverride = store.decisions + withoutOverride.pairKeepOverrides = [] + let unprotected = DeduplicationPlanner.plan( + decisions: withoutOverride, + clusters: [cluster], + configuration: DeduplicateConfiguration(destinationPath: "/dest"), + snapshot: engine.summary.scanSnapshot + ) + XCTAssertTrue(unprotected.items.contains { $0.path == "/dest/live/d1.mov" }) + } + + /// #302: "more are waiting" was view state, lost if the view was rebuilt mid-commit. + @MainActor + func testFreeBatchDeferredCountLivesInTheStoreThroughTheCommit() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let (store, engine, _, _) = try await commitFreeBatchThenRescan(snapshotStore: snapshotStore, free: true) + + XCTAssertEqual(store.status, .completed) + XCTAssertEqual(store.freeBatchDeferredFileCount, 3, "Still there after the commit; no view had to remember it") + + // A new scan, a discarded prepare, an ordinary prepare and a reset each clear it. + let next = laneCluster("next", lane: .identical, deletes: 2) + let later = laneCluster("later", lane: .identical, deletes: 2) + engine.clustersToEmit = [next, later] + engine.summary = DeduplicateSummary(scanSnapshot: laneSnapshot([next, later])) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + XCTAssertNil(store.freeBatchDeferredFileCount, "A new scan starts clean") + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + store.acceptSuggestions(in: .identical) + XCTAssertNotNil(store.prepareFreeBatchCommitPlan(remaining: 2)) + XCTAssertEqual(store.freeBatchDeferredFileCount, 2) + store.discardPreparedCommitPlan() + XCTAssertNil(store.freeBatchDeferredFileCount, "Cancelling the dialog forgets the batch") + store.prepareFreeBatchCommitPlan(remaining: 2) + store.prepareReviewedCommitPlan() + XCTAssertNil(store.freeBatchDeferredFileCount, "An ordinary prepare replaces the batch") + store.prepareFreeBatchCommitPlan(remaining: 2) + XCTAssertEqual(store.freeBatchDeferredFileCount, 2) + store.reset() + XCTAssertNil(store.freeBatchDeferredFileCount) + } + + /// #302: the free-batch flag is read when a commit completes. An ordinary commit + /// that follows on the same store must not inherit it. + @MainActor + func testOrdinaryCommitAfterFreeBatchCommitOnSameStoreRemovesSavedReview() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let (store, engine, deferred, changed) = try await commitFreeBatchThenRescan(snapshotStore: snapshotStore, free: true) + XCTAssertTrue(snapshotStore.removals.isEmpty, "The free batch kept the saved review") + XCTAssertEqual(engine.lastCommitPlan?.count, 2) + + engine.clustersToEmit = [deferred, changed] + engine.summary = DeduplicateSummary(scanSnapshot: laneSnapshot([deferred, changed])) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + store.acceptSuggestions(in: .identical) + store.acceptSuggestions(in: .nearlyIdentical) + store.prepareReviewedCommitPlan() + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let completed = await waitForCondition { store.status == .completed && engine.lastCommitPlan?.count == 3 } + XCTAssertTrue(completed) + + XCTAssertEqual(engine.lastCommitPlan?.count, 3, "The ordinary commit moves everything reviewed, not a batch") + XCTAssertEqual(snapshotStore.removals, ["/dest"], "An ordinary commit removes the saved review") + XCTAssertNil(store.savedReviewForCurrentFolder) + XCTAssertNil(store.freeBatchDeferredFileCount) + } + + /// #302: a prepare during a commit would flip the free-batch flag the commit reads + /// when it completes, so the store refuses it rather than trusting the view. + @MainActor + func testPrepareIsRefusedWhileACommitIsRunning() async throws { + let first = laneCluster("first", lane: .identical, deletes: 2) + let second = laneCluster("second", lane: .identical, deletes: 2) + let summary = DeduplicateCommitSummary(deletedCount: 4, failedCount: 0, bytesReclaimed: 400, receiptPath: nil, hardDelete: false) + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let (store, _) = await scannedLaneStore([first, second], commitEvents: [.complete(summary)], snapshotStore: snapshotStore) + store.acceptSuggestions(in: .identical) + store.prepareReviewedCommitPlan() + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + XCTAssertEqual(store.status, .committing) + + XCTAssertNil(store.prepareFreeBatchCommitPlan(remaining: 2), "No free batch while a commit runs") + XCTAssertNil(store.preparedCommitPlan) + XCTAssertNil(store.freeBatchDeferredFileCount) + store.prepareReviewedCommitPlan() + XCTAssertNil(store.preparedCommitPlan, "No plan is frozen while a commit runs") + + let completed = await waitForCondition { store.status == .completed } + XCTAssertTrue(completed) + XCTAssertEqual(snapshotStore.removals, ["/dest"], "The running commit stayed an ordinary one") + } + + /// #301: accepting one group's suggestions rebuilt `decisions` from the paths + /// alone and dropped the person's pair keep-overrides. + @MainActor + // AGENTS-INVARIANT: 14 + func testAcceptClusterSuggestionsPreservesPairKeepOverrides() async throws { + 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] + let cluster = DuplicateCluster( + kind: .exactDuplicate, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 100, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) + ) + let engine = laneEngine([cluster]) + engine.summary = DeduplicateSummary(scanSnapshot: laneSnapshot([cluster], overriding: [ + "/dest/live/d1.mov": FileIdentity(size: 100, digest: "live-movie"), + ])) + let store = laneStore(engine: engine) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + // The person chose to keep the movie half of the Live Photo. + store.decisions = DedupeDecisions(byPath: store.decisions.byPath, pairKeepOverrides: ["/dest/live/d1.mov"]) + + store.acceptSuggestionsForCluster(cluster) + + XCTAssertEqual(store.approvedClusterIDs, [cluster.id]) + XCTAssertEqual(store.decisions.pairKeepOverrides, ["/dest/live/d1.mov"], "Accepting a group keeps the person's override") + let plan = store.reviewedDeletionPlan() + XCTAssertTrue(plan.items.contains { $0.path == "/dest/live/d1.heic" }) + XCTAssertFalse(plan.items.contains { $0.path == "/dest/live/d1.mov" }, "The plan honours the override") + } + @MainActor func testOrdinaryCommitStillRemovesSavedReview() async throws { let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() diff --git a/ui/Tests/ChronoframeAppCoreTests/GermanLocalizationTests.swift b/ui/Tests/ChronoframeAppCoreTests/GermanLocalizationTests.swift index 4908c664..2a1ea72d 100644 --- a/ui/Tests/ChronoframeAppCoreTests/GermanLocalizationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/GermanLocalizationTests.swift @@ -42,11 +42,17 @@ final class GermanLocalizationTests: XCTestCase { for key in [ "Add Folders", "Choose Destination Folder", "Watch Folder", "Choose Watched Folder", "Choose Deduplicate Folder", "Reconnect Archive Folder", "Choose Mirror Folder", + "Choose This Folder", ] { XCTAssertNotEqual(CoreL10n.text(String.LocalizationValue(key), bundle: bundle), key, key) } } + func testGuidedSetupFolderPickerPromptIsGerman() throws { + let bundle = try germanBundle() + XCTAssertEqual(CoreL10n.text(String.LocalizationValue("Choose This Folder"), bundle: bundle), "Diesen Ordner wählen") + } + func testGermanCountPhrasesUseSingularAndPluralWithoutEnglishSuffixes() throws { let bundle = try germanBundle() XCTAssertEqual(CoreL10n.files(1, bundle: bundle), "1 Datei") diff --git a/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift b/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift index 2e9ad0f6..15953df0 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift @@ -150,6 +150,23 @@ final class ModelAndServiceTests: XCTestCase { ) } + @MainActor + func testOpeningAtProtectedMediaLibraryFallsBackToTheStartingPlace() throws { + let home = FileManager.default.homeDirectoryForCurrentUser + let fallback = FolderAccessService.initialPanelDirectoryURL(startingAt: nil).path + var checkedAnExistingLibrary = false + for name in ["Music", "Movies"] { + let library = home.appendingPathComponent(name, isDirectory: true) + XCTAssertEqual(FolderAccessService.panelDirectoryURL(openingAt: library.appendingPathComponent("Archive")).path, fallback) + var isDirectory: ObjCBool = false + if FileManager.default.fileExists(atPath: library.path, isDirectory: &isDirectory), isDirectory.boolValue { + checkedAnExistingLibrary = true + XCTAssertEqual(FolderAccessService.panelDirectoryURL(openingAt: library).path, fallback, name) + } + } + try XCTSkipUnless(checkedAnExistingLibrary, "No ~/Music or ~/Movies folder on this machine to open inside.") + } + @MainActor func testOpeningAtMissingFolderFallsBack() throws { let missing = FileManager.default.temporaryDirectory diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index 1094d497..0156bdfc 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -801,7 +801,7 @@ final class AppStateTests: XCTestCase { // User approves only the high-confidence cluster; the weak cluster is // left unreviewed (its non-keeper sits at a scan-time Delete preselect). - harness.deduplicateSessionStore.acceptAllHighConfidence() + harness.deduplicateSessionStore.acceptSuggestionsForCluster(highCluster) XCTAssertTrue(harness.deduplicateSessionStore.approvedClusterIDs.contains(highCluster.id)) XCTAssertFalse(harness.deduplicateSessionStore.approvedClusterIDs.contains(weakCluster.id)) @@ -1209,7 +1209,9 @@ final class AppStateTests: XCTestCase { XCTAssertEqual(metrics.plannedCount, 18_412) XCTAssertEqual(metrics.alreadyInDestinationCount, 63) XCTAssertEqual(metrics.duplicateCount, 1_204) - XCTAssertEqual(metrics.newFilesByMonth, ["2026-10": 212, "2026-09": 148, "2026-08": 734]) + XCTAssertEqual(metrics.newFilesByMonth["2026-10"], 212) + XCTAssertEqual(metrics.newFilesByMonth["2026-09"], 148) + XCTAssertEqual(metrics.newFilesByMonth["2026-08"], 734) XCTAssertGreaterThanOrEqual(metrics.dateHistogram.count, 14) XCTAssertEqual(metrics.dateHistogram.last?.key, "2026-10") XCTAssertTrue(appState.isAppStoreChannel) @@ -1217,6 +1219,46 @@ final class AppStateTests: XCTestCase { XCTAssertEqual(appState.organizeAllowanceRemaining, 500) } + /// #305: the Timeline header, the selected month and the free-month card all + /// read from one set of numbers, so they cannot disagree about the plan. + @MainActor + func testOverAllowanceFixtureIsInternallyConsistent() async throws { + let appState = UITestAppStateFactory.make(scenario: .runPreviewOverAllowance) + let finished = await waitForCondition(timeoutNanoseconds: 2_000_000_000) { + appState.runSessionStore.summary?.status == .dryRunFinished + } + XCTAssertTrue(finished) + let metrics = try XCTUnwrap(appState.runSessionStore.summary?.metrics) + + // The Timeline header sums the histogram: it must be the plan. + XCTAssertEqual(metrics.dateHistogram.reduce(0) { $0 + $1.plannedCount }, metrics.plannedCount) + // New files by month are the plan minus its extra copies. + XCTAssertEqual( + metrics.newFilesByMonth.values.reduce(0, +), + metrics.plannedCount - metrics.duplicateCount + ) + // Found = plan + already there. + XCTAssertEqual(metrics.discoveredCount, metrics.plannedCount + metrics.alreadyInDestinationCount) + + // A month's new files can never exceed the month's bar, and every month + // with a bar has new files listed (a month can be all new). + let barsByMonth = Dictionary(uniqueKeysWithValues: metrics.dateHistogram.map { ($0.key, $0.plannedCount) }) + XCTAssertEqual(Set(metrics.newFilesByMonth.keys), Set(barsByMonth.keys)) + for (key, newFiles) in metrics.newFilesByMonth { + let bar = try XCTUnwrap(barsByMonth[key], key) + XCTAssertLessThanOrEqual(newFiles, bar, key) + } + + // The newest month is selected on arrival, and the card offers that same + // number: no extra copies fall in it. + let newest = try XCTUnwrap(metrics.dateHistogram.last) + XCTAssertEqual(newest.plannedCount, metrics.newFilesByMonth[newest.key]) + XCTAssertEqual(newest.plannedCount, 212) + let options = FreeMonthBatchPlanner.options(newFilesByMonth: metrics.newFilesByMonth, remaining: 500) + XCTAssertEqual(options.first?.key, newest.key) + XCTAssertEqual(options.first?.fileCount, newest.plannedCount) + } + @MainActor func testStartFreeMonthCopyDoesNothingWithoutAKnownAllowance() async throws { let harness = AppStateHarness() diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift index 2ed92ac8..aaf5345f 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift @@ -377,6 +377,72 @@ final class DeduplicateReviewViewsTests: XCTestCase { XCTAssertNil(DeduplicateView.completedStatusCopy(for: summary, deferredFileCount: 0).message?.range(of: "waiting")) } + func testWaitingLineHasASingularForm() throws { + XCTAssertEqual( + DeduplicateFooterCopy.waitingLine(deferredFileCount: 1), + "1 more is waiting. Your choices are saved; scan again to continue." + ) + XCTAssertEqual( + DeduplicateFooterCopy.waitingLine(deferredFileCount: 2), + "2 more are waiting. Your choices are saved; scan again to continue." + ) + let summary = DeduplicateCommitSummary(deletedCount: 1, failedCount: 0, bytesReclaimed: 10_000_000, receiptPath: nil, hardDelete: false) + XCTAssertTrue( + (DeduplicateView.completedStatusCopy(for: summary, deferredFileCount: 1).message ?? "") + .hasSuffix("\n1 more is waiting. Your choices are saved; scan again to continue.") + ) + + let german = try germanAppBundle() + XCTAssertEqual( + german.localizedString(forKey: "1 more is waiting. Your choices are saved; scan again to continue.", value: nil, table: nil), + "1 weitere Datei wartet. Deine Auswahl ist gespeichert; scanne erneut, um fortzufahren." + ) + XCTAssertEqual( + german.localizedString(forKey: "%@ more are waiting. Your choices are saved; scan again to continue.", value: nil, table: nil), + "%@ weitere warten. Deine Auswahl ist gespeichert; scanne erneut, um fortzufahren." + ) + } + + func testFooterStatusCountsFollowTheFreeBatchButton() async throws { + let first = laneCluster("first", lane: .identical, deletes: 2) + let second = laneCluster("second", lane: .identical, deletes: 2) + let store = try await scannedStore([first, second]) + store.acceptSuggestions(in: .identical) + let reviewed = store.reviewedDeletionPlan() + XCTAssertEqual(reviewed.count, 4) + let batch = try XCTUnwrap(store.freeBatchOffer(remaining: 2)) + + // Beside "Move 2 Files to Trash Free" the status says 2 files, not 4; + // the free line above it carries the rest. + let free = DeduplicateFooterCopy.statusCounts( + reviewedFileCount: reviewed.count, reviewedBytes: reviewed.totalBytes, freeBatch: batch + ) + XCTAssertEqual(free.files, 2) + XCTAssertEqual(free.bytes, batch.plan.totalBytes) + XCTAssertLessThan(free.bytes, reviewed.totalBytes) + + let ordinary = DeduplicateFooterCopy.statusCounts( + reviewedFileCount: reviewed.count, reviewedBytes: reviewed.totalBytes, freeBatch: nil + ) + XCTAssertEqual(ordinary.files, 4) + XCTAssertEqual(ordinary.bytes, reviewed.totalBytes) + } + + func testFooterAcceptIsDisabledWhenNoIdenticalGroupIsWaiting() async throws { + let nearly = laneCluster("nearly", lane: .nearlyIdentical) + let identical = laneCluster("identical", lane: .identical) + let store = try await scannedStore([nearly, identical]) + XCTAssertTrue(DeduplicateFooterCopy.hasIdenticalCopiesToAccept(in: store)) + + DeduplicateFooterCopy.acceptIdenticalCopies(in: store) + XCTAssertFalse(DeduplicateFooterCopy.hasIdenticalCopiesToAccept(in: store), "Accepted: nothing identical left") + + let onlyNearly = try await scannedStore([laneCluster("only", lane: .nearlyIdentical)]) + XCTAssertFalse(DeduplicateFooterCopy.hasIdenticalCopiesToAccept(in: onlyNearly)) + let empty = try await scannedStore([]) + XCTAssertFalse(DeduplicateFooterCopy.hasIdenticalCopiesToAccept(in: empty)) + } + func testFooterAcceptCallsIdenticalLaneOnly() async throws { let identicalOne = laneCluster("identicalOne", lane: .identical) let identicalTwo = laneCluster("identicalTwo", lane: .identical) diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift index 4e940d92..d7a53867 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift @@ -356,8 +356,11 @@ final class DeduplicateStatusViewTests: XCTestCase { XCTAssertTrue(DeduplicateReviewLayout.usesCondensedTrustSummary(forAvailableHeight: 648, mode: .wide)) XCTAssertTrue(DeduplicateReviewLayout.usesCondensedTrustSummary(forAvailableHeight: threshold - 1, mode: .wide)) XCTAssertFalse(DeduplicateReviewLayout.usesCondensedTrustSummary(forAvailableHeight: threshold, mode: .wide)) - // Default window (820pt) keeps the full cards. - XCTAssertFalse(DeduplicateReviewLayout.usesCondensedTrustSummary(forAvailableHeight: 768, mode: .wide)) + // Default window (820pt, about 768pt of review area): one line each, so the + // group list keeps its room (#302). The cards come back on a taller window. + XCTAssertTrue(DeduplicateReviewLayout.usesCondensedTrustSummary(forAvailableHeight: 768, mode: .wide)) + XCTAssertFalse(DeduplicateReviewLayout.usesCondensedTrustSummary(forAvailableHeight: 900, mode: .wide)) + XCTAssertEqual(threshold, 780) } func testCompactTrustSummaryDoesNotReturnToCardsWhilePreviewIsStillShort() { diff --git a/ui/Tests/ChronoframeAppTests/GermanLocalizationTests.swift b/ui/Tests/ChronoframeAppTests/GermanLocalizationTests.swift index 061948ae..f3cd4b2a 100644 --- a/ui/Tests/ChronoframeAppTests/GermanLocalizationTests.swift +++ b/ui/Tests/ChronoframeAppTests/GermanLocalizationTests.swift @@ -112,6 +112,61 @@ final class GermanLocalizationTests: XCTestCase { ) } + /// Issue #304 wording: the unbalanced preview line has its own sentence for a + /// plan that lists more than was found, the free-limit line names files, and + /// the leftover names and jargon are gone. + func testFirstRunCopyFixesAreTranslated() throws { + let german = try germanAppBundle() + XCTAssertEqual( + String( + format: AppLocalization.string( + "Chronoframe found %1$@, but this plan lists %2$@ more. Rebuild the preview before copying.", + bundle: german + ), + "100 Fotos und Videos", "10" + ), + "Chronoframe hat 100 Fotos und Videos gefunden, aber dieser Plan führt 10 mehr auf. Erstelle die Vorschau vor dem Kopieren neu." + ) + XCTAssertEqual(PluralPhrases.files(1, bundle: german), "1 Datei") + XCTAssertEqual(PluralPhrases.files(18_412, bundle: german), "\(18_412.formatted()) Dateien") + let expected = [ + "Your originals are never changed and nothing is copied yet. You can keep using your Mac.": + "Deine Originale werden nie verändert, und es wird noch nichts kopiert. Du kannst deinen Mac weiterverwenden.", + "Open comparison in Quick Review": "Vergleich in der Schnellprüfung öffnen", + "Status, reports and logs": "Status, Berichte und Protokolle", + "Each bar is one month of files this plan will copy.": + "Jeder Balken steht für einen Monat an Dateien, die dieser Plan kopiert.", + ] + for (key, value) in expected { + XCTAssertEqual(AppLocalization.string(key, bundle: german), value, key) + } + } + + /// Issue #304 follow-ups: the finished line has its own sentence for a copy + /// that handled more than was found, the running timeline caption is plain, + /// and the Quick Review progress label no longer uses the old screen name. + func testFirstRunCopyFollowUpsAreTranslated() throws { + let german = try germanAppBundle() + XCTAssertEqual( + String( + format: AppLocalization.string( + "Chronoframe found %1$@, but this copy handled %2$@ more. Open History for the full record.", + bundle: german + ), + "100 Fotos und Videos", "10" + ), + "Chronoframe hat 100 Fotos und Videos gefunden, aber diese Kopie hat 10 mehr verarbeitet. Öffne den Verlauf für die vollständige Aufzeichnung." + ) + let expected = [ + "Each bar is one month of files this plan is copying.": + "Jeder Balken steht für einen Monat an Dateien, die dieser Plan gerade kopiert.", + "Quick Review progress": "Fortschritt der Schnellprüfung", + ] + for (key, value) in expected { + XCTAssertEqual(AppLocalization.string(key, bundle: german), value, key) + } + } + /// The Setup tab is now "Choose Folders" ("Ordner wählen"); two hints still /// sent people to "Organize › Setup". func testDestinationHintsNameTheCurrentTab() throws { diff --git a/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift b/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift index f26610d0..bf770dce 100644 --- a/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift @@ -184,6 +184,63 @@ final class GuidedSetupModelTests: XCTestCase { XCTAssertFalse(measuring.spaceIsWarning) } + // MARK: Free space belongs to one destination + + func testFreeSpaceFigureIsDroppedWhenTheDestinationChanges() { + var model = destinationModel(destinationPath: "/Archive A") + model.recordDestinationFreeBytes(20_000_000_000, for: "/Archive A") + XCTAssertEqual(model.spaceLine, "\(size(20_000_000_000)) free here.") + + // The person picks another folder: until it is measured the old figure must not be shown. + model.destinationPath = "/Archive B" + XCTAssertNil(model.destinationFreeBytes) + XCTAssertEqual(model.spaceLine, "Free space on this drive is unknown.") + + model.recordDestinationFreeBytes(500_000_000_000, for: "/Archive B") + XCTAssertEqual(model.destinationFreeBytes, 500_000_000_000) + XCTAssertEqual(model.spaceLine, "\(size(500_000_000_000)) free here.") + } + + func testFreeSpaceFigureNeverWarnsAgainstTheWrongDrive() { + let estimate = FolderSizeEstimate(fileCount: 900, totalBytes: 80_000_000_000, isComplete: true) + var model = destinationModel(destinationPath: "/Small", estimate: estimate) + model.recordDestinationFreeBytes(1_000_000_000, for: "/Small") + XCTAssertTrue(model.spaceIsWarning) + + model.destinationPath = "/Big" + XCTAssertFalse(model.spaceIsWarning) + } + + func testClearingFreeSpaceForgetsTheFigure() { + var model = destinationModel(destinationPath: "/Archive", free: 5_000_000_000) + XCTAssertEqual(model.destinationFreeBytes, 5_000_000_000) + model.clearDestinationFreeBytes() + XCTAssertNil(model.destinationFreeBytes) + } + + // MARK: A source added outside the guided screen + + func testASourceAddedFromTheMenuOnTheFirstQuestionEndsGuidedSetup() { + XCTAssertTrue(GuidedSetupModel.sourceAddedElsewhereEndsGuidedSetup( + step: .source, isChoosingSource: false, sourcePath: "/Photos" + )) + } + + func testGuidedSetupKeepsGoingForItsOwnChoiceOrNoSource() { + // The screen's own picker is advancing the step itself. + XCTAssertFalse(GuidedSetupModel.sourceAddedElsewhereEndsGuidedSetup( + step: .source, isChoosingSource: true, sourcePath: "/Photos" + )) + // On the second question a source change is not the first answer. + XCTAssertFalse(GuidedSetupModel.sourceAddedElsewhereEndsGuidedSetup( + step: .destination, isChoosingSource: false, sourcePath: "/Photos" + )) + // A source being cleared is not an answer either. + XCTAssertFalse(GuidedSetupModel.sourceAddedElsewhereEndsGuidedSetup( + step: .source, isChoosingSource: false, sourcePath: "" + )) + } + // MARK: Places and continuing func testStartingDirectoryForEachPlace() { diff --git a/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift b/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift index bb065ee0..f8435436 100644 --- a/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift @@ -44,14 +44,25 @@ final class RunAccountingTextTests: XCTestCase { "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not in this plan yet. Rebuild the preview before copying." ) - // A negative remainder names the gap by its absolute value. + // A negative remainder is the other direction: the plan lists more than + // was found, so it must not say anything is "not in this plan". let over = preview(RunMetrics(discoveredCount: 100, plannedCount: 70, alreadyInDestinationCount: 40)) XCTAssertEqual(over.remainder, -10) XCTAssertEqual( RunAccountingText.previewLine(over), - "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not in this plan yet. Rebuild the preview before copying." + "Chronoframe found \(100.formatted()) photos and videos, but this plan lists \(10.formatted()) more. Rebuild the preview before copying." + ) + + let overByOne = preview(RunMetrics(discoveredCount: 1, plannedCount: 2)) + XCTAssertEqual(overByOne.remainder, -1) + XCTAssertEqual( + RunAccountingText.previewLine(overByOne), + "Chronoframe found 1 photo or video, but this plan lists 1 more. Rebuild the preview before copying." ) + // Nothing found says nothing, whichever way the plan disagrees. + XCTAssertNil(RunAccountingText.previewLine(preview(RunMetrics(plannedCount: 5)))) + // Singular forms agree on their own count. let one = preview(RunMetrics(discoveredCount: 1)) XCTAssertEqual(one.remainder, 1) @@ -172,12 +183,20 @@ final class RunAccountingTextTests: XCTestCase { "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not accounted for in this copy. Open History for the full record." ) - // Negative remainder: listed more than found. + // Negative remainder: the copy handled more than was found, so it must + // not say anything is "not accounted for". let over = finished(RunMetrics(discoveredCount: 100, plannedCount: 70, alreadyInDestinationCount: 40, copiedCount: 70)) XCTAssertEqual(over.remainder, -10) + let overLine = "Chronoframe found \(100.formatted()) photos and videos, but this copy handled \(10.formatted()) more. Open History for the full record." + XCTAssertEqual(RunAccountingText.finishedLine(over, isFreeBatch: true), overLine) + XCTAssertEqual(RunAccountingText.finishedLine(over, isFreeBatch: false), overLine) + + // One more than found reads as one, and the singular found phrase agrees. + let overByOne = finished(RunMetrics(discoveredCount: 1, plannedCount: 2, copiedCount: 2)) + XCTAssertEqual(overByOne.remainder, -1) XCTAssertEqual( - RunAccountingText.finishedLine(over, isFreeBatch: true), - "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not accounted for in this copy. Open History for the full record." + RunAccountingText.finishedLine(overByOne, isFreeBatch: false), + "Chronoframe found 1 photo or video, but this copy handled 1 more. Open History for the full record." ) } diff --git a/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift b/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift index 6e08159a..7ef990c5 100644 --- a/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift @@ -89,7 +89,10 @@ final class RunTimelinePresentationTests: XCTestCase { XCTAssertEqual(preview.rangeCaption, "2021–2022 · 100 planned files") XCTAssertFalse(preview.subtitle.contains("your source")) - XCTAssertTrue(preview.subtitle.contains("planned")) + XCTAssertEqual(preview.subtitle, "Each bar is one month of files this plan will copy.") + + let running = makeView(status: .running, phase: .copy, planned: 100, copied: 55, buckets: sampleBuckets) + XCTAssertEqual(running.subtitle, "Each bar is one month of files this plan is copying.") let single = makeView( status: .dryRunFinished, @@ -130,14 +133,12 @@ final class RunTimelinePresentationTests: XCTestCase { view.accessibilityValue(selectedKey: "2021-04"), "Selected month: 2021-04. 1 planned file across 1 month. 0 copied so far for the run as a whole." ) - XCTAssertEqual(TimelinePlurals.filesToCopy(1), "1 file to copy") } func testOtherCountsKeepThePluralPhrases() { XCTAssertEqual(TimelinePlurals.plannedFiles(0), "0 planned files") XCTAssertEqual(TimelinePlurals.plannedFiles(2), "2 planned files") XCTAssertEqual(TimelinePlurals.acrossMonths(3), "across 3 months") - XCTAssertEqual(TimelinePlurals.filesToCopy(40), "40 files to copy") } func testPhasesCompleteUsesTheSingularForOnePhase() throws { @@ -158,7 +159,6 @@ final class RunTimelinePresentationTests: XCTestCase { XCTAssertEqual(TimelinePlurals.ofPlannedFiles(12, bundle: german), "von 12 geplanten Dateien") XCTAssertEqual(TimelinePlurals.acrossMonths(1, bundle: german), "in 1 Monat") XCTAssertEqual(TimelinePlurals.acrossMonths(3, bundle: german), "in 3 Monaten") - XCTAssertEqual(TimelinePlurals.filesToCopy(1, bundle: german), "1 Datei zu kopieren") } // MARK: - Photos on arrival (C-25) diff --git a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift index 2c0618bb..554884a5 100644 --- a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift @@ -206,7 +206,7 @@ final class RunWorkspaceModelTests: XCTestCase { badge: "Preparing"), HeroRow(label: "running preview", status: .running, mode: .preview, canStart: true, title: "Building the preview", - message: "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", + message: "Your originals are never changed and nothing is copied yet. You can keep using your Mac.", badge: "Previewing"), HeroRow(label: "running transfer", status: .running, mode: .transfer, canStart: true, title: "Copying your photos", @@ -272,9 +272,11 @@ final class RunWorkspaceModelTests: XCTestCase { ) } - func testRunningPreviewMessageSaysOnlyReading() { + func testRunningPreviewMessageDoesNotClaimItOnlyReads() { let message = heroModel(status: .running, mode: .preview).heroState.message - XCTAssertEqual(message, "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.") + XCTAssertEqual(message, "Your originals are never changed and nothing is copied yet. You can keep using your Mac.") + // The preview writes its own report, log and cache into the destination. + XCTAssertFalse(message.contains("only reading")) // The running transfer message is unchanged. XCTAssertEqual( @@ -654,35 +656,44 @@ final class RunWorkspaceModelTests: XCTestCase { ) XCTAssertEqual( fitting.freeCopyLine, - "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()). " + "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()) files. " + "The newest month that fits is \(monthYear("2026-10")): \(212.formatted()) files." ) // A single file in the suggested month takes the file's singular form. XCTAssertEqual( freeCopyModel(planned: 900, remaining: 500, newFilesByMonth: ["2026-10": 1]).freeCopyLine, - "You can copy \(500.formatted()) files free. This plan has \(900.formatted()). " + "You can copy \(500.formatted()) files free. This plan has \(900.formatted()) files. " + "The newest month that fits is \(monthYear("2026-10")): 1 file." ) // Every month is bigger than what is left: the free copy takes its first days. XCTAssertEqual( freeCopyModel(planned: 18_412, remaining: 500, newFilesByMonth: ["2026-10": 900, "2026-09": 700]).freeCopyLine, - "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()). " + "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()) files. " + "\(monthYear("2026-10")) is larger than that, so the free copy takes its first days." ) // No options: the numbers alone. XCTAssertEqual( freeCopyModel(planned: 18_412, remaining: 500).freeCopyLine, - "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted())." + "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()) files." ) XCTAssertEqual( freeCopyModel(planned: 18_412, remaining: 1).freeCopyLine, - "You can copy 1 file free. This plan has \(18_412.formatted())." + "You can copy 1 file free. This plan has \(18_412.formatted()) files." ) } + func testOverAllowanceLineSaysFilesWithTheirOwnSingularAndPlural() { + func line(planned: Int) -> String? { + RunFreeCopyText.line(for: .overAllowance(remaining: 0, planned: planned, options: [], suggested: nil)) + } + XCTAssertEqual(line(planned: 2), "You can copy 0 files free. This plan has 2 files.") + XCTAssertEqual(line(planned: 1), "You can copy 0 files free. This plan has 1 file.") + XCTAssertEqual(line(planned: 18_412), "You can copy 0 files free. This plan has \(18_412.formatted()) files.") + } + func testFreeMonthButtonAndMenuTitles() { let options = FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 212, "2026-08": 734], remaining: 500) XCTAssertEqual(RunFreeCopyText.copyButtonTitle(for: options[0]), "Copy \(monthYear("2026-10")) Free…") diff --git a/ui/Xcode/UITests/A11yBaseline.json b/ui/Xcode/UITests/A11yBaseline.json index 4e58c368..bc7089f8 100644 --- a/ui/Xcode/UITests/A11yBaseline.json +++ b/ui/Xcode/UITests/A11yBaseline.json @@ -1,14 +1,4 @@ [ - { - "scenario": "setupIncompleteRun", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Not started", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Not started" - }, { "scenario": "setupReady", "auditType": "contrast", @@ -19,16 +9,6 @@ "compactDescription": "Contrast nearly passed", "detailedDescription": "Contrast is not high enough for Next unless font size is larger." }, - { - "scenario": "setupReady", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "A preview copies nothing. It shows where every file would go, and you decide after that.", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for A preview copies nothing. It shows where every file would go, and you decide after that." - }, { "scenario": "runPreviewReview", "auditType": "contrast", @@ -39,16 +19,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for 42 photos and videos will be copied, all from Apr 2026. Nothing has been copied yet." }, - { - "scenario": "runPreviewReview", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "72, FOUND", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 72, FOUND" - }, { "scenario": "runPreviewReview", "auditType": "contrast", @@ -59,66 +29,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for 42, TO COPY" }, - { - "scenario": "runPreviewReview", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "0, COPIED", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 0, COPIED" - }, - { - "scenario": "runPreviewReview", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "29, ALREADY THERE", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 29, ALREADY THERE" - }, - { - "scenario": "runPreviewReview", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "7, EXACT COPIES", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 7, EXACT COPIES" - }, - { - "scenario": "runPreviewReview", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "1, PROBLEMS", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 1, PROBLEMS" - }, - { - "scenario": "healthDashboard", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "To Review", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for To Review" - }, - { - "scenario": "healthDashboard", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Needs destination", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Needs destination" - }, { "scenario": "healthDashboard", "auditType": "contrast", @@ -139,26 +49,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for The destination folder is missing or unavailable." }, - { - "scenario": "healthDashboard", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "No files are waiting in the Unknown_Date folder.", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for No files are waiting in the Unknown_Date folder." - }, - { - "scenario": "healthDashboard", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "No exact copies were set aside during past copies.", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for No exact copies were set aside during past copies." - }, { "scenario": "healthDashboard", "auditType": "contrast", @@ -169,16 +59,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for Nothing has been copied here yet, so there is nothing to undo." }, - { - "scenario": "healthDashboard", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Every recognized file follows the folder layout.", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Every recognized file follows the folder layout." - }, { "scenario": "historyPopulated", "auditType": "contrast", @@ -199,46 +79,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for Recent copies that have a recovery receipt." }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Reports, receipts, and logs from every preview and copy.", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Reports, receipts, and logs from every preview and copy." - }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "12:00 AM", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 12:00 AM" - }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Transfer Receipt", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Transfer Receipt" - }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": ".organize_logs/receipt.json", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for .organize_logs/receipt.json" - }, { "scenario": "profilesPopulated", "auditType": "contrast", @@ -269,26 +109,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for /Volumes/Archive/Studio" }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Chronoframe Library", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Chronoframe Library" - }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "archived", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for archived" - }, { "scenario": "historyPopulated", "auditType": "contrast", @@ -299,26 +119,6 @@ "compactDescription": "Contrast failed", "detailedDescription": "Contrast failed for copies" }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Audit Receipt", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Audit Receipt" - }, - { - "scenario": "historyPopulated", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "8 KB", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 8 KB" - }, { "scenario": "deduplicateReviewWide", "auditType": "contrast", @@ -358,15 +158,5 @@ "value": "42, to copy", "compactDescription": "Contrast nearly passed", "detailedDescription": "Contrast is not high enough for 42, to copy unless font size is larger." - }, - { - "scenario": "previewDateConflict", - "auditType": "contrast", - "role": "staticText", - "identifier": "", - "label": "", - "value": "Preview & Copy", - "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for Preview & Copy" } ] diff --git a/ui/Xcode/UITests/ChronoframeUITests.swift b/ui/Xcode/UITests/ChronoframeUITests.swift index 8c5fc139..1738b72d 100644 --- a/ui/Xcode/UITests/ChronoframeUITests.swift +++ b/ui/Xcode/UITests/ChronoframeUITests.swift @@ -941,6 +941,11 @@ final class ChronoframeUITests: XCTestCase { XCTAssertTrue(details.waitForExistence(timeout: 5)) let detailsTriangle = details.disclosureTriangles.firstMatch XCTAssertTrue(detailsTriangle.waitForExistence(timeout: 5)) + // The disclosure sits under the photos and the folder picture, which + // lay out after the window appears and can leave it below the fold or + // still moving. Bring it on screen and let it settle before clicking. + XCTAssertTrue(Self.scrollIntoView(detailsTriangle, in: app), "Details disclosure should be scrollable into view") + XCTAssertTrue(Self.waitUntilFrameSettles(detailsTriangle), "Details disclosure should stop moving") detailsTriangle.click() XCTAssertTrue(Self.button(identifier: "openDestinationButton", in: app).waitForExistence(timeout: 5)) XCTAssertTrue(app.buttons["openDestinationButton"].exists) @@ -1025,10 +1030,31 @@ final class ChronoframeUITests: XCTestCase { // A click lands on the timeline's centre, so it has to be on screen. XCTAssertTrue(Self.scrollIntoView(timeline, in: app), "Timeline should be scrollable into view") - Self.selectTimelineBucket(timeline, atNormalizedX: 0.9) + + // The preview selects its newest month on arrival, so the first step is + // to see that month, and the second to choose a different one. + // + // The selected month is read from the drawer under the timeline, which + // is the preview a person sees. The timeline's own accessibility value + // says the same, but SwiftUI publishes it as the element's value + // description, which XCTest cannot read (`value` comes back empty). + let newestMonth = Self.timelineSelectionTitle("April 2026: 24 photos and videos", in: app) + let earlierMonth = Self.timelineSelectionTitle("March 2026: 18 photos and videos", in: app) + XCTAssertTrue( + newestMonth.waitForExistence(timeout: 5), + "The newest month should be selected by default. \(app.debugDescription)" + ) + XCTAssertFalse(earlierMonth.exists, "Only the newest month should be shown on arrival") + + Self.selectTimelineBucket(timeline, atNormalizedX: 0.25) + XCTAssertTrue( + earlierMonth.waitForExistence(timeout: 5), + "Choosing the earlier month should show that month. \(app.debugDescription)" + ) + XCTAssertFalse(newestMonth.exists, "The newest month should no longer be shown once another is chosen") let clearButton = Self.button(identifier: "ClearTimelineSelectionButton", in: app) - XCTAssertTrue(clearButton.waitForExistence(timeout: 5), "Clear Selection button should appear after selecting a bucket") + XCTAssertTrue(clearButton.waitForExistence(timeout: 5), "Clear Selection button should be present while a month is selected") // The selection drawer opens below the timeline, which can sit at // the bottom of the window; scroll it into view as a user would. @@ -1038,6 +1064,10 @@ final class ChronoframeUITests: XCTestCase { ) Self.coordinateClick(clearButton) XCTAssertFalse(clearButton.exists, "Clear Selection button should disappear after clearing selection") + XCTAssertFalse( + newestMonth.exists || earlierMonth.exists, + "Clearing should leave no month selected" + ) app.terminate() } @@ -1356,6 +1386,31 @@ final class ChronoframeUITests: XCTestCase { } } + /// #302: the footer's Accept Identical Copies is enabled while an identical + /// group waits, and disabled once there is none left to accept. + @MainActor + func testDeduplicateAcceptIdenticalCopiesIsEnabledOnlyWhileIdenticalGroupsWait() { + // Six identical groups, two of them already accepted. This scenario has + // no case in `Scenario`, which would add it to the accessibility audit. + let app = Self.launchApp(scenarioNamed: "deduplicateReviewLanes") + defer { app.terminate() } + + let footer = Self.element(identifier: "dedupeCommitFooter", in: app) + XCTAssertTrue(footer.waitForExistence(timeout: 10), "Commit footer should render") + let acceptIdentical = Self.button(identifier: "dedupeAcceptAllSuggestionsButton", in: app) + XCTAssertTrue(acceptIdentical.waitForExistence(timeout: 5), "Accept Identical Copies should be in the footer") + XCTAssertTrue( + Self.waitUntilEnabled(acceptIdentical), + "Accept Identical Copies should be enabled while identical groups wait. \(app.debugDescription)" + ) + + Self.coordinateClick(acceptIdentical) + XCTAssertTrue( + Self.waitUntilDisabled(acceptIdentical), + "Accept Identical Copies should be disabled once every identical group is accepted. \(app.debugDescription)" + ) + } + func testDeduplicateReviewKeepsActionsVisibleAtWideAndCompactSizes() async { await MainActor.run { for scenario in [Scenario.deduplicateReviewWide, .deduplicateReviewCompact] { @@ -1373,8 +1428,12 @@ final class ChronoframeUITests: XCTestCase { XCTAssertTrue(acceptCluster.isHittable, "Accept Suggestion should stay hittable for \(scenario.rawValue)") Self.coordinateClick(acceptCluster) - XCTAssertTrue(acceptAll.waitForExistence(timeout: 5), "Accept All Suggestions should stay visible for \(scenario.rawValue)") - XCTAssertTrue(acceptAll.isEnabled, "Accept All Suggestions should stay enabled for \(scenario.rawValue)") + XCTAssertTrue(acceptAll.waitForExistence(timeout: 5), "Accept Identical Copies should stay visible for \(scenario.rawValue)") + // These fixtures hold near-duplicate and burst groups only, so no + // identical group waits and the button has nothing to do (#302). + // testDeduplicateAcceptIdenticalCopiesIsEnabledOnlyWhileIdenticalGroupsWait + // covers a library that has some. + XCTAssertFalse(acceptAll.isEnabled, "Accept Identical Copies should be disabled with no identical group waiting for \(scenario.rawValue)") XCTAssertTrue(commit.waitForExistence(timeout: 5), "Commit should stay visible for \(scenario.rawValue)") XCTAssertTrue(Self.waitUntilEnabled(commit), "Commit should become enabled after accepting a suggestion for \(scenario.rawValue)") @@ -1470,8 +1529,19 @@ final class ChronoframeUITests: XCTestCase { @MainActor private static func launchApp(_ scenario: Scenario, additionalEnvironment: [String: String] = [:]) -> XCUIApplication { + let app = launchApp(scenarioNamed: scenario.rawValue, additionalEnvironment: additionalEnvironment) + if scenario.opensSettingsOnLaunch { + ensureSettingsWindowExists(in: app) + } + return app + } + + /// Launches a scenario by the app's own name for it. For a scenario that + /// has no case in `Scenario`, and so is not part of the accessibility audit. + @MainActor + private static func launchApp(scenarioNamed scenarioName: String, additionalEnvironment: [String: String] = [:]) -> XCUIApplication { let app = XCUIApplication() - app.launchEnvironment["CHRONOFRAME_UI_TEST_SCENARIO"] = scenario.rawValue + app.launchEnvironment["CHRONOFRAME_UI_TEST_SCENARIO"] = scenarioName app.launchEnvironment["CHRONOFRAME_UI_TEST_DISABLE_NOTIFICATIONS"] = "1" app.launchEnvironment["TZ"] = "UTC" // Lets a large development display reproduce a small runner's visible area: @@ -1483,13 +1553,10 @@ final class ChronoframeUITests: XCTestCase { app.launchEnvironment["CHRONOFRAME_UI_TEST_APPEARANCE"] = appearance } app.launchEnvironment.merge(additionalEnvironment) { _, new in new } - app.launchArguments += ["--chronoframe-ui-test-scenario", scenario.rawValue, "-AppleTimeZone", "UTC", "-TZ", "UTC", "-ApplePersistenceIgnoreState", "YES"] + app.launchArguments += ["--chronoframe-ui-test-scenario", scenarioName, "-AppleTimeZone", "UTC", "-TZ", "UTC", "-ApplePersistenceIgnoreState", "YES"] app.launch() app.activate() ensurePrimaryWindowExists(in: app) - if scenario.opensSettingsOnLaunch { - ensureSettingsWindowExists(in: app) - } return app } @@ -1974,6 +2041,13 @@ final class ChronoframeUITests: XCTestCase { } } + /// The title of the drawer under the run timeline, which names the selected + /// month and its count ("April 2026: 24 photos and videos"). + @MainActor + private static func timelineSelectionTitle(_ title: String, in app: XCUIApplication) -> XCUIElement { + app.staticTexts.matching(NSPredicate(format: "label == %@ OR value == %@", title, title)).firstMatch + } + /// Selects the timeline bucket under a point with a click. The timeline's /// `DragGesture(minimumDistance: 0)` selects on press, so a click drives /// the same selection path as a scrub. XCTest's synthesized @@ -2096,6 +2170,18 @@ final class ChronoframeUITests: XCTestCase { app.buttons.matching(identifier: identifier).firstMatch } + @MainActor + private static func waitUntilDisabled(_ element: XCUIElement, timeout: TimeInterval = 5) -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while Date() < deadline { + if element.exists && !element.isEnabled { + return true + } + RunLoop.current.run(until: Date().addingTimeInterval(0.05)) + } + return element.exists && !element.isEnabled + } + @MainActor private static func waitUntilEnabled(_ element: XCUIElement, timeout: TimeInterval = 5) -> Bool { let deadline = Date().addingTimeInterval(timeout) @@ -2108,6 +2194,22 @@ final class ChronoframeUITests: XCTestCase { return element.exists && element.isEnabled } + /// True once the element's frame is the same across three samples 0.2s apart. + @MainActor + private static func waitUntilFrameSettles(_ element: XCUIElement, timeout: TimeInterval = 5) -> Bool { + let deadline = Date().addingTimeInterval(timeout) + var last = element.frame + var stableSamples = 0 + while Date() < deadline { + RunLoop.current.run(until: Date().addingTimeInterval(0.2)) + let frame = element.frame + stableSamples = (frame == last && !frame.isEmpty) ? stableSamples + 1 : 0 + if stableSamples >= 2 { return true } + last = frame + } + return false + } + private static func contentAnchorLabel(for scenario: Scenario) -> String? { switch scenario { case .setupIncompleteRun: