diff --git a/README.md b/README.md index 90d7470f..0c9e5d6e 100644 --- a/README.md +++ b/README.md @@ -82,12 +82,14 @@ The **History** tab keeps every run's reports and receipts. Reuse a past source, ![Deduplicate setup — a scan folder, recent folders with files removed and space saved, and detection presets.](docs/screenshots/dedupe-setup.jpg) -3. Review each group. Compare candidates side by side, choose what to **Keep**, and use **Accept & Next** to move through them. **Accept All Safe** clears the obvious exact copies for you. +3. Review each group. Compare candidates side by side, choose what to **Keep**, and use **Accept & Next** to move through them. **Accept Identical Copies** accepts, in one step, only the groups whose files are the same file byte for byte. Nearly identical groups go through **Quick Review**, and look-alikes are reviewed one by one. 4. Click **Move to Trash** to send the files you approved to the macOS Trash. ![Deduplicate review — two similar photos compared side by side, with keep and delete choices.](docs/screenshots/dedupe-compare.jpg) -Exact photo and video duplicates are matched by file content and can be accepted automatically. Similar-photo groups, bursts, RAW+JPEG pairs, and Live Photo pairs stay reviewable so you can make the final call. Visual matching for video transcodes and re-exports is available as an off-by-default option in **Settings → Deduplicate**; those video matches are always review-only. Before Trash, Chronoframe rechecks each planned file and preserves pair units when anything changed after the scan. +Exact photo and video duplicates are matched by file content, and groups of identical copies can be accepted in one step. Similar-photo groups, bursts, RAW+JPEG pairs, and Live Photo pairs stay reviewable so you can make the final call. Visual matching for video transcodes and re-exports is available as an off-by-default option in **Settings → Deduplicate**; those video matches are always review-only. Before Trash, Chronoframe rechecks each planned file and preserves pair units when anything changed after the scan. + +Chronoframe always suggests keeping one photo in every group. If a group you have accepted has every photo marked Delete, the screen says so and skips that group until you mark one Keep. Its photos stay even when their RAW+JPEG or Live Photo partners are being removed in another group. In the Mac App Store build, [what the free allowance covers in Deduplicate](docs/QUICK_START.md#if-your-reviewed-groups-are-more-than-the-free-allowance) is described in the Quick Start. ## Helpful Guides diff --git a/docs/FAQ.md b/docs/FAQ.md index 9de9ecd4..970ef7b4 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -112,6 +112,16 @@ A: Yes. Use the **Deduplicate** workspace: Visual video matching is off by default. Enable it in **Settings → Deduplicate** with the Balanced or Similar Shots preset. These groups are always review-only and never accepted automatically. +The lanes bar at the top of review starts with identical copies. **Accept Identical Copies** accepts, in one step, only groups whose files are the same file byte for byte. Nearly identical groups, still labelled Safe, go through **Quick Review**, where **Accept the Rest (N)** appears after the first group. Look-alikes and less certain groups are looked at one by one. Accepting only marks files; nothing moves to the Trash until you confirm **Move to Trash**. + +**Q: Does Deduplicate guarantee that a photo is kept from every group?** + +A: Yes. Chronoframe always suggests keeping one photo in every group. If a group you have accepted has every photo marked Delete, the screen shows a notice and skips that group until you mark one Keep. Its photos stay even when their RAW+JPEG or Live Photo partners are being removed in another group. Check the file count in the confirmation before you move anything to the Trash. + +**Q: What can I remove free in Deduplicate in the Mac App Store build?** + +A: When your reviewed groups hold more files than the free allowance has left, the footer says so. If at least one whole group fits, **Move N Files to Trash Free** moves whole groups, up to the limit, after the usual confirmation, and **Unlock to Remove All N** opens the unlock sheet. Your choices for the groups still waiting are saved and come back after the next scan, only for files that haven't changed. Restored choices are only a starting point. Nothing moves to the Trash until you confirm. + **Q: Will Deduplicate remove the edited versions Photos import saved?** A: No. An edited version is saved as `-edited.` beside the original, and Deduplicate never selects it on its own. It stays when its original is deleted, and the commit footer says how many edited versions were kept. It moves to the Trash only if you mark that exact file Delete. A file you named that way yourself, beside one with the same name, is protected too. diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md index 1c560193..44c80b7c 100644 --- a/docs/QUICK_START.md +++ b/docs/QUICK_START.md @@ -101,12 +101,28 @@ Use this when you want Chronoframe to find exact photo and video copies plus sim 2. Click **Choose Folder…** to pick the folder to scan, or reuse a recent one 3. Pick a **Detection** preset (**Exact copies**, **Balanced**, or **Similar shots**) and click **Start Scan** 4. Review each group — compare candidates side by side and choose what to keep -5. Click **Accept All Safe** to accept every group Chronoframe marks as a safe match, then click **Move to Trash** to remove the files you approved +5. Click **Accept Identical Copies** to accept the groups whose files are the same file, byte for byte, then click **Move to Trash** to remove the files you approved + +Review sorts the groups into three lanes: + +- **Identical copies.** Every file in the group is the same file, byte for byte. **Accept Identical Copies** accepts all of these groups in one step. +- **Nearly identical.** These groups are still labelled Safe, but the files are not the same byte for byte. **Quick Review** walks you through them one at a time. After the first group, **Accept the Rest (N)** appears, and it accepts every nearly identical group you have not reviewed yet. +- **Look-alikes and less certain groups.** You look at these one by one; **Quick Review** opens them too. + +Accepting only marks the files. Nothing moves to the Trash until you click **Move to Trash** and confirm. + +Chronoframe always suggests keeping one photo in every group. If a group you have accepted has every photo marked Delete, the screen says so and skips that group until you mark one photo Keep. Its photos stay even when their RAW+JPEG or Live Photo partners are being removed in another group. Chronoframe does not permanently delete files from Deduplicate. It sends selected files to the macOS Trash. Similar-photo, burst, RAW+JPEG, and Live Photo analysis applies to photos. Exact video copies are always detected, and an off-by-default setting can surface visually similar transcodes and re-exports for review; visual video matches are never auto-accepted. The commit summary and executor use the same content-verified plan. If a planned file or pair changes after the scan, Chronoframe leaves it untouched and asks you to scan again. +### If your reviewed groups are more than the free allowance + +This applies to the Mac App Store build while its free allowance is in use. When the groups you reviewed hold more files than the free allowance has left, the footer says how many duplicates you can remove free and how many your reviewed groups hold. If at least one whole group fits, **Move N Files to Trash Free** moves whole groups, up to the limit, after the usual confirmation, and **Unlock to Remove All N** opens the unlock sheet. When no free removals are left, the footer says so. + +After a free removal, the choices you made for the groups still waiting are saved. Scan the same folder again and they come back, only for files that have not changed. Restored choices are only a starting point, and nothing moves to the Trash until you confirm. + ## Tips - **Edit uncertain dates.** If a photo has an unknown date, fix it in Review and Chronoframe will use your correction. diff --git a/docs/SAFETY_AND_RECOVERY.md b/docs/SAFETY_AND_RECOVERY.md index b36ad276..28093387 100644 --- a/docs/SAFETY_AND_RECOVERY.md +++ b/docs/SAFETY_AND_RECOVERY.md @@ -175,8 +175,8 @@ folder. Deduplicate treats any file with that name beside a file with the same name (ignoring upper and lower case, and whatever the other file's extension is) as an edited version and protects it: -- It is never selected for the Trash by a group's suggestion or by Accept All, - and never pulled in because a RAW+JPEG or Live Photo partner, a sidecar, or its +- It is never selected for the Trash by a group's suggestion or by any of the + accept buttons, and never pulled in because a RAW+JPEG or Live Photo partner, a sidecar, or its original is being deleted. - Deleting the original leaves the edited version in place. The commit footer says how many edited versions stay (for example "2 edited versions kept"). @@ -248,7 +248,8 @@ expected content before anything moves to the Trash, exactly as described above. A restored choice is only a starting point. **When it is removed.** After a Deduplicate commit finishes for that folder, -its saved review is removed. Reverting a commit does not remove it, and +its saved review is removed, except after a free removal (see Free removal +below), which keeps it. Reverting a commit does not remove it, and choosing a different folder leaves each folder's save alone. To discard one yourself, open the Deduplicate start screen for that folder and choose **Discard Saved Review** on the "Pick up where you left off" card. The card @@ -256,6 +257,35 @@ appears when no paused review is open in the current session, and it also offers **Scan and Restore Review**. Discarding deletes only Chronoframe's saved review file; your photos are not touched. +### Review lanes, the keep suggestion and free removal + +Review sorts groups into three lanes. **Accept Identical Copies** accepts only +groups whose files are the same file, byte for byte, judged from the content +identities recorded in the scan; if the scan has no identity for a file, the +group is not treated as identical. Nearly identical groups, still labelled Safe, +go through **Quick Review**, where **Accept the Rest (N)** appears after the +first group. Look-alikes and less certain groups are looked at one by one. +Accepting only marks files; the plan, the confirmation and the content check +before anything moves to the Trash are unchanged. + +Chronoframe always suggests keeping one photo in every group. When every photo +in a reviewed group is marked Delete, the footer shows a notice and the planner +skips that group until one is marked Keep. The members of a skipped group stay +whichever route would remove them: pair expansion from another group does not +add them, and neither does a second group that lists the same files (INV-32). +Check the file count in the confirmation before you confirm. + +**Free removal (Mac App Store build).** When the reviewed groups hold more +files than the free allowance has left, the footer says how many duplicates can +be removed free. If at least one whole group fits, **Move N Files to Trash +Free** moves whole groups, up to the limit. +It uses the same planner, the same confirmation and the same executor as any +other commit, and it removes nothing the full reviewed plan would not. +**Unlock to Remove All N** opens the unlock sheet instead. After a free removal +the saved review is kept, so the choices for the groups still waiting come back +after the next scan under the rules above, only for files that have not +changed. + ## Library Guardian: Scrub, Mirror, Restore Library Guardian protects an already-organized library from silent bit rot. It diff --git a/docs/TECHNICAL.md b/docs/TECHNICAL.md index 0cfb33a3..75da99ef 100644 --- a/docs/TECHNICAL.md +++ b/docs/TECHNICAL.md @@ -350,7 +350,7 @@ mobile_backup: | `Cmd+,` | Open Settings | | `Cmd+?` | Open Chronoframe Help | -In the Deduplicate review, `←`/`→` move between photos in a group, `Return` confirms the group, `C` compares candidates, and `Space` opens Rapid Triage. +In the Deduplicate review, `←`/`→` move between photos in a group, `Return` confirms the group, `C` compares candidates, and `Space` previews the focused photo. ## Build From Source diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 715af633..9b5c89b5 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -159,7 +159,7 @@ If the app or Mac stopped unexpectedly, reconnect the destination drive before r **Solution:** - Make sure you've **selected keep/delete choices** for at least one group -- Click a group on the left and choose which items to keep and which to delete (or use **Accept All Safe** for the groups marked as safe matches) +- Click a group on the left and choose which items to keep and which to delete (or use **Accept Identical Copies** for groups of identical copies) - The **Move to Trash** button activates once at least one file is marked for removal ### Deduplicate says a file changed after the scan diff --git a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md index 84e46305..4c949344 100644 --- a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md +++ b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md @@ -1,6 +1,6 @@ # First-run experience — acceptance matrix -Status: M1 rows pass-auto at gate G1 (2026-11-28); M2 and M3 rows not built. Auto status values: todo, pass-auto, blocked. Owner status values: todo-owner, pass-owner, fail-owner, n/a. +Status: M1 rows pass-auto at gate G1 (2026-11-28); M2 rows pass-auto at gate G2 (2026-11-28); M3 rows not built. Auto status values: todo, pass-auto, blocked. Owner status values: todo-owner, pass-owner, fail-owner, n/a. | ID | Requirement (recommendation) | Automated coverage | Owner row | Auto status | Owner status | |---|---|---|---|---|---| @@ -9,9 +9,9 @@ Status: M1 rows pass-auto at gate G1 (2026-11-28); M2 and M3 rows not built. Aut | A-FRX-03 | The free limit is stated on the preview before any click, and the copy button is replaced by a free step and an unlock button when the plan is larger (rec 3) | RunWorkspaceModelTests (7 free-copy tests); AppStateTests/testRequestUnlockForPlanPresentsOrganizeRefusal, testDismissUnlockSheetClearsRequestedRefusal, testRetryAfterUnlockWithRequestedRefusalStartsNothing | H-FRX-2 | pass-auto | todo-owner | | A-FRX-04 | The unlock sheet names the person's outcome and says one-time, no subscription; the price is StoreKit's only (rec 3) | UnlockPresentationTests (6 new in WP-03); UnlockSheetLayoutTests/testPurchaseTermsLineIsShown; script/check_storekit_config_matches_policy.sh | H-FRX-2 | pass-auto | todo-owner | | A-FRX-05 | The free organize copy is one whole month of new photos, never exact copies, never more than the allowance, and is listed and confirmed before it runs (rec 5) | ChronoframeCoreFreeMonthBatchPlannerTests/*; FreeTestBatchPlannerTests (4 new); FreeMonthBatchOfferTests/*; SwiftOrganizerEngineIntegrationTests/testMonthRequestCopiesNothingAndReservesNothing, testConfirmedMonthBatchCopiesOnlyTheListedFiles, testConfirmedMonthBatchStillRefusedWhenAllowanceTooSmall; AppStateTests/testStartFreeMonthCopyRequestsAProposalForThatMonth | H-FRX-2 | pass-auto | todo-owner | -| A-FRX-06 | One click accepts only byte-identical groups; nearly identical groups go through Quick Review (rec 4) | ChronoframeCoreDeduplicateReviewLaneTests/*; DeduplicateSessionStoreTests (accept-by-lane, 5 new); DeduplicateReviewLanesTests (4 new); DeduplicateReviewViewsTests/testQuickReviewScopeIsUnreviewedGroupsOfLane, testAcceptTheRestOnlyForNearlyIdenticalAfterFirstGroup, testFooterAcceptCallsIdenticalLaneOnly | H-FRX-3 | todo | todo-owner | -| A-FRX-07 | The screen says Chronoframe always suggests keeping one photo per group, and tells the person when a fully marked group is being skipped (rec 4) | DeduplicateTests/testPlannerRefusesAllDelete (existing); DeduplicationPlannerPropertyTests/testPropertyNoClusterIsCompletelyEmptiedByThePlan (existing); DeduplicateSessionStoreTests/testFullyMarkedClusterIDs; DeduplicateReviewViewsTests/testFullyMarkedNoticeText | H-FRX-3 | todo | todo-owner | -| A-FRX-08 | Duplicates can be removed free in whole groups up to the allowance, through the normal planner and confirmation (rec 3) | ChronoframeCoreFreeDedupeBatchPlannerTests/*; DeduplicateSessionStoreTests (7 free-batch tests); UnlockPresentationTests (2 new in WP-13); AppStateTests (3 new); DeduplicateReviewViewsTests/testFreeRemovalLineAndButtonTitles, testConfirmationCountUsesPreparedPlan | H-FRX-4 | todo | todo-owner | +| A-FRX-06 | One click accepts only byte-identical groups; nearly identical groups go through Quick Review (rec 4) | ChronoframeCoreDeduplicateReviewLaneTests/*; DeduplicateSessionStoreTests (accept-by-lane, 5 new); DeduplicateReviewLanesTests (4 new); DeduplicateReviewViewsTests/testQuickReviewScopeIsUnreviewedGroupsOfLane, testAcceptTheRestOnlyForNearlyIdenticalAfterFirstGroup, testFooterAcceptCallsIdenticalLaneOnly | H-FRX-3 | pass-auto | todo-owner | +| A-FRX-07 | The screen says Chronoframe always suggests keeping one photo per group, and tells the person when a fully marked group is being skipped (rec 4) | DeduplicateTests/testPlannerRefusesAllDelete (existing); DeduplicationPlannerPropertyTests/testPropertyNoClusterIsCompletelyEmptiedByThePlan (existing); DeduplicateSessionStoreTests/testFullyMarkedClusterIDs; DeduplicateReviewViewsTests/testFullyMarkedNoticeText | H-FRX-3 | pass-auto | todo-owner | +| A-FRX-08 | Duplicates can be removed free in whole groups up to the allowance, through the normal planner and confirmation (rec 3) | ChronoframeCoreFreeDedupeBatchPlannerTests/*; DeduplicateSessionStoreTests (7 free-batch tests); UnlockPresentationTests (2 new in WP-13); AppStateTests (3 new); DeduplicateReviewViewsTests/testFreeRemovalLineAndButtonTitles, testConfirmationCountUsesPreparedPlan | H-FRX-4 | pass-auto | todo-owner | | A-FRX-09 | A person with nothing configured answers two questions and reaches the preview; everyone else keeps the full screen (rec 1) | GuidedSetupModelTests/*; AppStateTests/testGuidedSetupEligibleDefaultsTrue, testEveryExistingScenarioDisablesGuidedSetup; folder-access tests (4 new); SetupCoordinatorTests (2 new) | H-FRX-5 | todo | todo-owner | | A-FRX-10 | The destination step shows the folder's size against free space, labeled as an estimate, and never blocks (rec 1) | ChronoframeCoreFolderSizeEstimatorTests/*; GuidedSetupModelTests/testMeasureLineStates, testSpaceLineWarnsButNeverBlocks, testSpaceLineSaysEstimate | H-FRX-5 | todo | todo-owner | | A-FRX-11 | New people get Year/Month; anyone with prior use keeps their layout (rec 6, D-FRX-06) | PreferencesStoreTests (4 new) | H-FRX-7 | todo | todo-owner | diff --git a/docs/plan/first-run-experience/BLOCKED.md b/docs/plan/first-run-experience/BLOCKED.md index 6ceb6c65..960c22c9 100644 --- a/docs/plan/first-run-experience/BLOCKED.md +++ b/docs/plan/first-run-experience/BLOCKED.md @@ -1,5 +1,16 @@ # First-run experience — blocked items -Status: not started. No blocked items. +Status: B-1 has a fix built (see its Status line); only Nishith marks it resolved. Entry format: see "Blocked items" in `docs/plan/next-half/AGENT_RULES.md`. Only Nishith marks an item resolved. + +### B-1 — Planner can empty an all-Delete group through pair fan-out (pre-existing; confirmed in WP-11) +- **WP:** WP-11 (found), affects the wording WP-13 ships (C-13 notice) and owner row H-FRX-3. No FRX work package depends on it. +- **Command:** throwaway probe test against the unmodified `DeduplicationPlanner.plan` (removed afterwards; not committed), then confirmed by reading `ui/Sources/ChronoframeCore/DeduplicationPlanner.swift:107–114` and `:136–185`. +- **Error:** group Y = {y1, y2}, both Delete; group Z = {z3 Keep, z1 Delete, z2 Delete}; y1 paired with z1, y2 paired with z2. The plan is {z1, z2, y1, y2}. Step 3 skips Y (all Delete), step 4 emits z1 and z2, step 5 fans out to y1 and y2 because its guard only spares a partner whose effective decision is Keep. Every member of Y goes to the Trash. No existing test builds cross-group pairs (`DeduplicationPlannerPropertyTests.randomScenario` pairs only inside a cluster). +- **Real-world shape (Opus review, from code):** exact clusters group by file identity, so pairs cross clusters when the same RAW+JPEG (or Live Photo) folder was imported twice and a third copy of the JPEG exists without its RAW: Y = {A/1.CR2, B/1.CR2}, Z = {A/1.JPG, B/1.JPG, C/1.JPG}; keep C/1.JPG, mark the rest Delete → no CR2 survives. Y becomes all-Delete only through explicit Deletes on every member; suggestions always keep one. +- **Second path, read from code, not reproduced:** overlapping clusters. Exact E = {A/1.jpg, B/1.jpg} and a retained near-duplicate N = {A/1.jpg, B/1.jpg, A/1b.jpg} (`DeduplicateScanner.swift:422–426` keeps N because A/1b.jpg is not an exact member). Both copies Delete, A/1b.jpg Keep: E is skipped, N is not, N deletes both copies, E is emptied. Not checked: whether the store removes overlapping clusters before review. +- **Tried:** nothing in the planner. `DeduplicationPlanner.swift` is safety-critical and no contract names an edit to it (kickoff rule 5, D-FRX-11). The free removal batch cannot add to this: every batch item must be in the full plan with the same identity (C-11 step 4), so it can only repeat an emptying the full plan already contains. +- **Options:** 1) A separate, explicit planner change: in step 5, never fan out to a partner whose own cluster was skipped by the all-Delete rail (or re-run the rail after fan-out and drop the fan-out that empties a group), with a new tagged test and a cross-group-pair generator in the property test. 2) Leave the planner and change the C-13 notice so it does not promise the skip ("…Chronoframe skips a group when nothing in it is kept, unless its photos are paired with photos you are removing from another group"). 3) Leave both as they are. +- **Recommendation:** option 1 before `feature/first-run-duplicates` is merged, because the C-13 notice ("Chronoframe skips a group when nothing in it is kept") is untrue in this shape and the files do go to the Trash (recoverable, but not what the screen says). +- **Status:** fix built, awaiting the owner's mark. Option 1 done on `fix/dedupe-planner-rail-protects-fanout` (`2f8954f`, INV-32, issue #300) and merged into `feature/first-run-duplicates`; the second path reproduced at planner level and is fixed in the same commit. Evidence: `cf_swift.sh coverage` exit 0 (2518 passed, 0 failed; 96.17%), `guards origin/main` exit 0 (14), `xcode` exit 0, `git diff --check` exit 0; the new property test fails 44 times with the two guard lines switched off. diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index a6e931a0..c98fdc8d 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -20,7 +20,7 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-08 Supersedes first-ten-minutes.** `docs/plan/first-ten-minutes` is marked superseded in WP-00. Kept from it: estimates are labeled and rechecked (D-FTM-03); a space shortfall warns and never blocks, because the executor already pauses safely (D-FTM-02); Undo goes through the existing hash-checked revert (D-FTM-07). Dropped: the 25-file oldest-first batch (replaced by C-05), the Photos staging line, the Source/Destination Unavailable step states. - **D-FRX-09 Accounting is evidence-bound.** The "accounted for" sentence is shown only when the four categories add up to the files found; any disagreement shows the unbalanced wording (C-02). It never says or implies anything may be deleted from the source. - **D-FRX-10 Receipt path comes from the engine.** `SwiftOrganizerEngine` already matches the receipt by run ID; it publishes that path in the summary (C-03). `TransferExecutor` is not touched. -- **D-FRX-11 Keep promise (revised proposal).** The owner chose "confirm, don't block" on the planning session's statement that no engine rule keeps one photo per group. That statement was wrong: the planner already skips any group whose members are all Delete, with a property test (CONTRACTS fact 10). Removing that rail would weaken tested safety behavior, so this plan keeps it and makes it visible with the notice in C-13. The promise line is worded as what is certainly true, `Chronoframe always suggests keeping one photo in every group.`, because the rail covers direct deletes and pair fan-out runs after it (see known gaps). No planner change, no new invariant. If the owner wants a group to be removable in full, that is a separate, explicit product change. +- **D-FRX-11 Keep promise (approved 2026-11-29; superseded in part by D-FRX-119).** The owner chose "confirm, don't block" on the planning session's statement that no engine rule keeps one photo per group. That statement was wrong: the planner already skips any group whose members are all Delete, with a property test (CONTRACTS fact 10). Removing that rail would weaken tested safety behavior, so this plan keeps it and makes it visible with the notice in C-13. The promise line is worded as what is certainly true, `Chronoframe always suggests keeping one photo in every group.`, because the rail covers direct deletes and pair fan-out runs after it (see known gaps). No planner change, no new invariant. If the owner wants a group to be removable in full, that is a separate, explicit product change. - **D-FRX-12 Dedupe vocabulary stays.** Per the 2026-11-21 decision, Safe / Check / Risky, "Delete" and the Trash wording are unchanged. The one renamed control is "Accept All Safe" → "Accept Identical Copies", because its behavior narrows (D-FRX-05) and the old label would now be untrue. "Rapid Triage" in the Quick Review header becomes "Quick Review", the name every button already uses. - **D-FRX-13 Free month rules.** New photos and videos only, with their sidecars; exact copies and undated files are never in a free month. Suggested month: the newest that fits the remaining allowance; if none fits, the newest month in whole days. The refusal-driven sheet offers the same month batch, so there is one free-batch rule. The existing rule in `FreeTestBatchPlanner.swift` is kept in full: a month is only proposed; the sheet lists the files; the copy runs on the confirmed paths and identities through the existing selection. Pressing `Copy {Month Year} Free…` therefore costs one extra planning pass (cached hashes) before the confirmation appears. - **D-FRX-14 The free limit is shown before the click.** When a plan or a reviewed cleanup exceeds the remaining allowance, the primary button is the free step and a second button opens the unlock sheet. The refusal path remains as the safety net for cases the screen could not know. @@ -35,10 +35,10 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-23 No new UI-test files.** `ui/Xcode/UITests/` gets no new file (so `project.pbxproj` is untouched). If an existing UI test references a changed literal, the orchestrator edits that test and compiles it with `xcodebuild build-for-testing`; running the UI suite is an owner row. - **D-FRX-24 Invariants.** No new invariant. Tests are tagged: Undo `// AGENTS-INVARIANT: 8`; free dedupe batch `14` and `17`; free-batch saved review `29`; identical-lane and accept tests `6`; folder estimate symlink test `15`; preview/guided source read-only assertions `1`. -- **D-FRX-25 A free removal keeps the saved review (proposal).** Today a successful dedupe commit deletes the saved review. After a free batch that would throw away every choice the person made for the groups still waiting, exactly when they are deciding whether to unlock. C-12 skips that deletion for a free-batch commit only; the next scan restores under the unchanged INV-29 rules. This is the one edit to an existing branch of `DeduplicateSessionStore`. If the owner rejects it before kickoff: delete that bullet from C-12, delete `testFreeBatchCommitKeepsSavedReviewForNextScan` from WP-12, and change the C-13 summary sentence to `{deferred} more are waiting. Scan again to continue.` +- **D-FRX-25 A free removal keeps the saved review (approved 2026-11-29).** Today a successful dedupe commit deletes the saved review. After a free batch that would throw away every choice the person made for the groups still waiting, exactly when they are deciding whether to unlock. C-12 skips that deletion for a free-batch commit only; the next scan restores under the unchanged INV-29 rules. This is the one edit to an existing branch of `DeduplicateSessionStore`. If the owner rejects it before kickoff: delete that bullet from C-12, delete `testFreeBatchCommitKeepsSavedReviewForNextScan` from WP-12, and change the C-13 summary sentence to `{deferred} more are waiting. Scan again to continue.` ## Known gaps left alone (flagged, not fixed here) -- **Owner should look at this one.** `DeduplicationPlanner.plan` applies its all-Delete rail (step 3) before pair fan-out (step 5). If every member of a skipped group is the pair partner of a file being deleted in another group, fan-out might still remove all of them. Not confirmed, not reproduced, and not touched by this plan; it is why the promise line is worded carefully. +- **Owner should look at this one.** `DeduplicationPlanner.plan` applies its all-Delete rail (step 3) before pair fan-out (step 5). If every member of a skipped group is the pair partner of a file being deleted in another group, fan-out might still remove all of them. Not confirmed, not reproduced, and not touched by this plan; it is why the promise line is worded carefully. **Update 2026-11-28 (WP-11): confirmed and reproduced with the unmodified planner; see BLOCKED.md B-1. Still not touched by this plan.** - `OrganizeFolderIntent` uses `FolderStructure.default`, not the saved preference. - Changing the layout in Settings or in Choose Folders after a preview does not mark the preview stale. - The Options-menu count for the old "Accept All Safe" item could disagree with what it applied; the item is replaced in C-13. @@ -53,3 +53,10 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-105 Preview free-limit details (WP-04).** (a) The over-allowance line is implemented exactly as C-07 words it, so it reads "This plan has 18,412." with no "files" word (the spent line has it). (b) The hero primary-action enum gained `.freeMonthCopy` and `.unlockEverything`; a stale preview stays `.notMetered` and keeps the disabled Start Copying. (c) The free-limit line is the first row of the hero summary, drawn with `Text(verbatim:)` from a looked-up template. (d) `AppState` has an internal `organizeAllowanceRemaining` helper; `startFreeMonthCopy` does nothing when the allowance is nil or not positive, `requestUnlockForPlan` does nothing when it is nil. (e) `retryAfterUnlock` clears `requestedUnlockRefusal` right after its existing guard, so a stale requested refusal cannot reopen the sheet behind a run refusal. (f) `UITestScenario.preferredMainWindowSize` went from private to internal so the window-fit test can read it. (g) One string beyond the contract: the accessibility hint `Shows the files first. Nothing is copied until you confirm` on the free-month button; it restates C-07's rule for VoiceOver and is kept. (h) `testPurchaseTermsLineIsShown` asserts the sheet's internal `termsLine`; the drawing is covered by the unlock-sheet renders. (i) The `runPreviewOverAllowance` fixture skips the 120-file organize seed charge so the ledger is at 0 used, as C-08 says. - **D-FRX-106 Accounting line and Undo details (WP-05).** (a) `accountingLine` lives in `RunAccountingText.swift` as an extension, where C-02's code block puts it; `RunWorkspaceModel.swift` is unchanged. (b) Singular forms: counts that need their own verb are separate looked-up phrases (`1 is waiting for the next copy` / `%@ are waiting for the next copy`, and the same for "not in this plan yet" and "not accounted for in this copy"); where "Every one of the 1" or "All 1 … are" would be ungrammatical there is a `The 1 photo or video Chronoframe found is …` template. Plural output equals the C-02 sentences. (c) `notCopied > 0` is checked before the free-batch wording; equivalent to C-02's order because the free-batch case requires `notCopied == 0`. (d) No History refresh was added: `RunSessionStore.consume(.complete)` already reloads History. (e) `lastCopyUndoEntry` matches the `.auditReceipt` entry by file name and then by exact or symlink-resolved path, because History reports `/private/var/…` where the engine reports `/var/…`; stricter than "that path", never looser. Undo itself is `revertHistoryEntry` unchanged. (f) `Unlock to Copy the Rest` shows only for a finished free batch with `remainder > 0`, `notCopied == 0` and a known allowance (a request for 0 files would be meaningless). (g) Fixture `runCopyComplete`: its preflight mode is `.transfer` (Undo needs a transfer run) and it writes a placeholder `{}` receipt file inside its own temp destination, because a finished run re-reads History from disk. (h) The invariant-8 test uses a private recording engine in `AppStateTests.swift`; the App-target mock has no revert. - **D-FRX-107 Catalog details (WP-06).** (a) Core strings ship in both catalogs (the App catalog already carries a copy of every Core string for the single-target Xcode build), so `M1-app.json` repeats the Core entries. (b) `add_translated_keys.py` adds keys as `extractionState: manual`, and SwiftPM generates a Swift symbol for every manual key; `Undo This Copy…` collided with the existing `Undo this copy?` and `Copy %@ Free…` with `Copy %@ free`. The contract copy is kept and those two new App-catalog entries carry no `extractionState` (the state 1,283 existing keys already have), so no symbol is generated for them. No key was renamed or removed. (c) `%@ copied` already existed in the App catalog with German and was kept. +- **D-FRX-108 Free removal batch details (WP-11).** (a) `includedClusterIDs` lists the selected groups, in walk order, that own at least one item of the batch plan; a group accepted by the walk that loses nothing is not reported. (b) `limit <= 0` returns nil; the full plan is computed first, same result. (c) Lane order is built by explicit buckets (identical, nearly identical, look at each) in review order, not by sorting. (d) `FreeDedupeBatch` has no public initializer (contract shape). (e) The forced-Keep test adds a bystander group W so that limit 2 is below the full plan's count; the trap and the rejected `{y2}` candidate are the ones the plan describes. +- **D-FRX-109 Store details (WP-12).** (a) The `laneSummaries` recompute is a `didSet` on `approvedClusterIDs`: every required trigger (scan complete, saved review restored, any approval change including undo and redo) assigns that property after `summary`, `clusters` and the scan configuration are in place, so one line covers them all. (b) After a scan all three lanes have an entry (zeros when empty); before a scan or after `reset()` the dictionary is empty. (c) `acceptSuggestions(in:)` also requires `isAutomaticCommitEligible`, as `acceptAllSuggestions()` does (INV-06 fail-closed). (d) `fullyMarkedClusterIDs` leaves out a cluster with no members. (e) The free-batch flag is private, set only by `prepareFreeBatchCommitPlan`, cleared by the two existing prepare/discard functions, and read (not cleared) in the commit `.complete` arm; any later ordinary commit passes through `prepareReviewedCommitPlan()`, which clears it. (f) The offer cache key is decisions, approvals and `remaining` only, as C-12 says; cluster IDs are new per scan so it cannot survive a rescan. (g) An internal `freeBatchOfferComputationCount` exists so the cache test can observe it. (h) The undo names use `String(localized:bundle: .module)` like the existing one, so their catalog keys are Core keys. +- **D-FRX-110 TipsTests expectation (WP-13).** `ui/Tests/ChronoframeAppTests/TipsTests.swift:34` asserted the old tip message that C-13 replaces. The file was not in WP-13's owned list; it was added for that one expectation under D-FRX-20 (the `never selects uncertain matches` assertion and the test name are unchanged). Not logged in BLOCKED.md because the orchestrator could resolve it inside D-FRX-20. +- **D-FRX-111 Review UI details (WP-13).** (a) Singular templates added per the copy rule (`1 safe group is identical copies. Accept it now: %@, %@.`, `1 safe group is nearly identical. Look through it quickly.`, `1 group has every photo marked Delete. … Mark one Keep in it to include it.`, `Move 1 File to Trash Free`, `1 duplicate`). (b) The old `DeduplicateReviewLanes` initializer keeps its meaning with `identicalGroupCount = 0`; the lane initializer counts a group as safe only if the planner would auto-select it, whatever the closure says. (c) `Accept the Rest ({remaining})` counts and accepts every unreviewed nearly identical group, including ones skipped earlier in the walk; the number shown is the number accepted, and nothing reaches the Trash without the commit dialog. (d) Quick Review freezes its group list when it opens so accepting a group does not shift the walk. (e) `DeduplicateView.swift` edits outside the listed ranges, each needed by C-13: an observed `trialStatusStore`, `quickReviewLane` and `freeBatchDeferredCount` state, the `wantsFreeBatchConfirmation` reaction (`onChange` and `onAppear` on the footer), a defaulted `deferredFileCount` on `completedStatusCopy`, and removal of the now-unused `highCount` parameter. (f) A prepared free batch is discarded only by the dialog's Cancel button; every path that opens a confirmation dialog prepares a fresh plan first, so a dismissed, stale plan is never committed (same pattern as before this plan). (g) The "more are waiting" line is view state; if the view is rebuilt during the commit the line is lost (the saved review is not). (h) Accessibility labels and hints on the accept button and menu item now say "identical copies"; identifiers are unchanged. (i) The unlock sheet's dedupe action shows its detail line and no file list. (j) With a free-batch offer the destructive button carries `dedupeFreeBatchCommit` (as C-13 says), so `dedupeCommitButton` is absent in that one state. (k) The lanes bar is stacked vertically. +- **D-FRX-112 M2 docs (WP-14).** (a) Because B-1 is open, the docs do not say a fully marked group "is skipped" as a fact: all four say Chronoframe always suggests keeping one photo, that such a group is normally skipped, that this is not a guarantee, and to check RAW+JPEG and Live Photo pairs. The in-app notice keeps the C-13 wording. If the owner fixes the planner (B-1 option 1), these sentences can be simplified. (b) Two more documents named controls that no longer exist, so one phrase each was changed outside C-26's list: `docs/TROUBLESHOOTING.md` ("Accept All Safe" → "Accept Identical Copies for groups of identical copies") and `docs/TECHNICAL.md` ("`Space` opens Rapid Triage" was already untrue; it now says "`Space` previews the focused photo", which is what `ClusterDetailPane.swift:50–53` binds). (c) The docs review needed two rounds; round 2 left three one-sentence items, which the orchestrator applied itself with the reviewer's replacement text instead of a third round (WP-14 is an orchestrator work package; no code is involved). (d) The M2 strings add 29 App keys and 3 Core keys; `Accept identical copies` (accessibility label) carries no `extractionState` because its symbol would collide with `Accept Identical Copies` (same handling as D-FRX-107). +- **D-FRX-119 Planner fix for B-1 (approved 2026-11-29).** The owner confirmed D-FRX-11 and D-FRX-25 and asked for B-1 option 1. The fix is its own branch off `main`, `fix/dedupe-planner-rail-protects-fanout` (`2f8954f`, issue #300), merged into `feature/first-run-duplicates` with a merge commit (owner's choice; no history rewrite). The members of a group the all-Delete rail skipped are now protected from direct deletes and from pair fan-out; both B-1 routes (cross-group pairs, overlapping groups) reproduced as failing tests first. New invariant INV-32 in `AGENTS.md`. This replaces D-FRX-11's "No planner change, no new invariant" and D-FRX-112(a): the four docs now state the skip as a fact. +- **D-FRX-120 Review fixes after the PRs opened (2026-11-29).** Four automated review findings on #307 and #308, each reproduced as a failing test first. (a) `TrialRemaining.value` returns nil for `verificationUnavailable` and `unverified`, so the preview shows no spent-trial line and offers no purchase to someone who may already have paid; the gate's `purchaseUnconfirmed` path is unchanged. (b) The unlock sheet offers a requested month even when the plan has shrunk to exactly that month, and drops the "leaves N for later" detail line in that case; an offer nobody asked for is still withheld. (c) The sheet's free removal resumes a review that a refused commit paused, because the confirmation dialog lives on the review footer; nothing is prepared or moved before the dialog. (d) The Options menu's Quick Review opens the nearly identical lane while it has groups waiting, then the look-at-each lane. C-13 had it always open look-at-each, which left nearly identical unreachable when the lanes bar is compact. No new strings. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 5388572f..0debd2cc 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -1,6 +1,6 @@ # First-run experience — progress -Status: in progress. M1 gate G1 passed 2026-11-28; M2 next. +Status: in progress. Gates G1 and G2 passed 2026-11-28; M3 next. One open BLOCKED item (B-1, owner decision, blocks no work package). Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled", "Tested" and "Rendered" are recorded separately; "Verified in the running app" is never claimed here (owner rows). @@ -8,6 +8,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - Branch `feature/first-run-trust` cut from `origin/main` 3ca134a (#299 merged; `git show origin/main:AGENTS.md | grep -c "INV-31"` printed 1). - M1 anchor refresh (Explore, haiku, 2026-11-28): every fact 1–16 still true. Moved: fact 13 `FolderStructure.default` is at `EngineDomainModels.swift:332` (cited :325). Notes: the `"audit_receipt_"` literal is `auditReceiptPrefix` at `EngineDomainModels.swift:321` (stem helper still `TransferExecutor.swift:1425`); `"Unknown_Date"` is `namingRules.unknownDateDirectoryName` at `EngineDomainModels.swift:359`; `acceptAllHighConfidence()` is at `DeduplicateView.swift:717`. All WP-01 to WP-05 ranges resolve. CONTRACTS not edited. - Baseline on aa56f84: `cf_swift.sh build` exit 0; `cf_swift.sh suite` exit 0, 2513 test cases passed, 0 failed, 1 skipped. +- M2: branch `feature/first-run-duplicates` cut from `feature/first-run-trust` f461bfe. `cf_swift.sh build` exit 0. M2 anchor refresh (Explore, haiku): facts 9–12 still true. Moved: the `UnlockSheetAction` switch in `UnlockSheet.swift` is at :143–175 (cited ~133–165); in `UITestAppStateFactory.swift` the dedupe fixture is `sampleDeduplicateClusters()` at :728–785 (cited :606–653) and the dedupe scenario wiring is :192–224 (cited :167–199). `lastScanConfiguration` is at `DeduplicateSessionStore.swift:87`, outside WP-12's reference range. Callers: `acceptAllSuggestions()` at `DeduplicateView.swift:366` and `:761`; `acceptAllHighConfidence()` at `:717`. For G2 step 4: UI tests use identifiers `dedupeCommitButton`, `dedupeAcceptAllSuggestionsButton`, `dedupeCommitFooter`, the confirm button matched by "Move to Trash" (:1177), `staticTexts["96 of 100 duplicates left"]` (:1223), and A11yBaseline `deduplicateReviewWide`/`Compact` "0 groups reviewed · 12 still suggested". ## Work packages | WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | @@ -19,13 +20,13 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-04 | App: preview free limit and free month | done | build exit 0 | RunWorkspaceModel 26, AppState 44, UnlockSheetLayout 2, UITestWindowFit 8 tests exit 0; ScreenRenderEvidence exit 0 (4 skipped without marker) | approve (round 1) | 5a0dc9d | rendered: `m1-preview-over-allowance.png` shows the C-07 line, `Copy October 2026 Free…`, `Choose Another Month`, `Unlock to Copy Everything`, no Start Copying; D-FRX-105 | | WP-05 | App: accounted-for line, Undo, add folder | done | build exit 0 | RunAccountingText 9, RunWorkspaceModel 29, AppState 49, RunOutcomeAccuracy 14, Accessibility 8 tests exit 0 | approve (round 1) | 44ce018 | orchestrator read the AppState.swift and CurrentRunView.swift diffs: Undo is `revertHistoryEntry` unchanged, no new deletion path (INV-8 test tagged); rendered: `m1-copy-complete.png` shows the balanced line, `Undo This Copy…`, `Add Another Folder`; D-FRX-106 | | WP-06 | Docs and strings, M1 | done | build exit 0 | n/a (strings and docs; checked at G1) | German: changes required → 3 fixes applied; docs: changes required (round 1) → approve (round 2) | 1268aaf | 38 App keys + 9 Core keys added; D-FRX-107 | -| G1 | Gate, M1 | done | build exit 0; xcode exit 0; build-for-testing exit 0 | suite exit 0 (2601 passed, 0 failed); coverage exit 0 (96.16%) | n/a | (G1 commit) | guards origin/main exit 0 (14 of 14); German check exit 0; 4 renders checked | -| WP-10 | Branch and baseline, M2 | todo | | | n/a | | | -| WP-11 | Core: review lane, free removal batch | todo | | | | | safety-critical; extra opus review | -| WP-12 | AppCore: store lanes, accept by lane, batch plan | todo | | | | | orchestrator reads the full diff | -| WP-13 | App: three lanes, Quick Review, footer, free removal | todo | | | | | | -| WP-14 | Docs and strings, M2 | todo | | | | | | -| G2 | Gate, M2 | todo | | | n/a | | | +| G1 | Gate, M1 | done | build exit 0; xcode exit 0; build-for-testing exit 0 | suite exit 0 (2601 passed, 0 failed); coverage exit 0 (96.16%) | n/a | f461bfe | guards origin/main exit 0 (14 of 14); German check exit 0; 4 renders checked | +| WP-10 | Branch and baseline, M2 | done | build exit 0 | n/a | n/a | ef6dc69 | anchors recorded under Baseline | +| WP-11 | Core: review lane, free removal batch | done | build exit 0 | DeduplicateReviewLane 6, FreeDedupeBatchPlanner 13 tests exit 0 | cf-reviewer approve (round 1); Opus read-only review: batch cannot add a deletion, split a pair or sidecar unit, or empty a group the full plan does not | f559362 | orchestrator read both new files in full against C-10/C-11; planner, executor and models untouched; D-FRX-108; BLOCKED B-1 (pre-existing planner gap, confirmed) | +| WP-12 | AppCore: store lanes, accept by lane, batch plan | done | build exit 0 | DeduplicateSessionStoreTests 49 tests exit 0 | approve (round 1) | 89b21a8 | orchestrator read the full DeduplicateSessionStore.swift diff: every changed line traces to C-12 (recompute trigger; two flag resets; the three saved-review lines wrapped for a free-batch commit, D-FRX-25); `commitReviewed`, `acceptAllSuggestions()`, `acceptAllHighConfidence()` untouched; D-FRX-109 | +| WP-13 | App: three lanes, Quick Review, footer, free removal | done | build exit 0 | DeduplicateReviewLanes 15, DeduplicateReviewViews 10, DeduplicateStatusView 30, UnlockPresentation 21, UnlockSheetBatchOffer 14, AppState 54, Tips 4, UITestWindowFit 9, Accessibility 8 tests exit 0 | approve (round 1) | e321445 | orchestrator read the full DeduplicateView.swift diff: commit is reachable only through the two confirmation dialogs, each opened after a fresh prepare; no view calls `acceptAllSuggestions()`/`acceptAllHighConfidence()`; rendered: `m2-deduplicate-lanes.png` matches C-13; D-FRX-110, D-FRX-111 | +| WP-14 | Docs and strings, M2 | done | build exit 0 | n/a (strings and docs; checked at G2) | German: approve, no changes; docs: changes required (round 1), changes required (round 2, three one-sentence items applied by the orchestrator) | b4a1774 | 29 App keys + 3 Core keys; docs word the keep rule as "not a guarantee" because of B-1; D-FRX-112 | +| G2 | Gate, M2 | done | build exit 0; xcode exit 0; build-for-testing exit 0 | suite exit 0 (2654 passed, 0 failed); coverage exit 0 (96.17%) | n/a | (G2 commit) | guards feature/first-run-trust exit 0 (14 of 14); invariants exit 0; German check exit 0; 1 render checked | | WP-20 | Branch and baseline, M3 | todo | | | n/a | | lists FolderAccessServicing conformers | | WP-21 | Core and AppCore groundwork | todo | | | | | | | WP-22 | App: guided setup | todo | | | | | | @@ -39,6 +40,10 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-05 | ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift (`copyCompleteEngine`, fixture value, no test assertion) | discoveredCount 4_300 | discoveredCount 4_263 | C-08 | | WP-05 | ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift (`previewReviewEngine`, fixture value, no test assertion) | discoveredCount 84 | discoveredCount 72 | C-08 | | G1 | ui/Xcode/UITests/ChronoframeUITests.swift:545, :547 | "discovered: 84, planned: 42, …" | "discovered: 72, planned: 42, …" | C-08, D-FRX-23 | +| WP-13 | ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift:238 | acceptAllTitle (full) == "Accept All Safe" | == "Accept Identical Copies" | C-13 | +| WP-13 | ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift:239 | acceptAllTitle (compact) == "Accept Safe" | == "Accept Identical" | C-13 | +| WP-13 | ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift:256 | acceptAllTitle contains the Safe label | the identical-lane sentence contains the Safe label, case-insensitively | C-13 | +| WP-13 | ui/Tests/ChronoframeAppTests/TipsTests.swift:34 | old tip message "Safe groups are matches Chronoframe has verified. …" | C-13 tip message "Identical copies are the same file saved more than once. …" | C-13, D-FRX-110 | | G1 | ui/Xcode/UITests/A11yBaseline.json:48, :50 | "84, FOUND" | "72, FOUND" | C-08, D-FRX-23 | ## Renders checked @@ -47,6 +52,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | G1 | .tmp/frx-evidence/m1-preview-over-allowance.png | C-07 | matches: "You can copy 500 files free. This plan has 18,412. The newest month that fits is October 2026: 212 files."; buttons `Copy October 2026 Free…`, `Choose Another Month`, `Unlock to Copy Everything`; no Start Copying | | G1 | .tmp/frx-evidence/m1-copy-complete.png | C-02, C-04 | matches: "All 4,263 photos and videos Chronoframe found are accounted for: 4,200 copied, 63 already in your library."; `Undo This Copy…` beside `Open History`; add-folder text and `Add Another Folder` | | G1 | .tmp/frx-evidence/m1-unlock-organize.png | C-06 | matches: title "Organize all 250 files"; terms line "One-time purchase with Family Sharing. No subscription." under the message, secondary ink; price from the StoreKit stub only | +| G2 | .tmp/frx-evidence/m2-deduplicate-lanes.png | C-13 | matches: "4 safe groups are identical copies. Accept them together: 8 files, 19.2 MB." + `Accept Identical Copies`; "3 safe groups are nearly identical. Look through them quickly." + `Quick Review`; the unchanged look-alikes row + `Quick Review`; "Chronoframe always suggests keeping one photo in every group."; footer "You can remove 2 duplicates free. Your reviewed groups hold 4.", `Unlock to Remove All 4`, `Move 2 Files to Trash Free`; Safe / Check / Risky filter unchanged | | G1 | .tmp/frx-evidence/m1-unlock-dedupe.png | C-06 | matches: title "Remove all 25 duplicates"; same terms line | ## Log @@ -66,3 +72,18 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 2026-11-28 G1 commands (orchestrator): `cf_swift.sh suite` exit 0 (2601 test cases passed, 0 failed); `cf_swift.sh coverage` exit 0 (meaningful coverage 96.16%; RunAccounting 100%, FreeMonthBatchPlanner 99.2%); `cf_swift.sh guards origin/main` exit 0 (14 guards); `cf_swift.sh xcode` exit 0; `git diff --check` exit 0; `xcodebuild … SWIFT_EMIT_LOC_STRINGS=YES build` exit 0; `python3 script/check_german_localization.py --baseline-ref origin/main …` exit 0 (app 1764, core 327 German strings; zero missing keys); `xcodebuild … build-for-testing` exit 0; `cf_swift.sh test ScreenRenderEvidenceTests` with the marker exit 0 (4 PNGs). First suite/coverage attempt failed to build on a string-symbol collision; fixed in WP-06 (D-FRX-107) and rerun. - G1 step 4: grep of `ui/Xcode/UITests/ChronoframeUITests.swift` for M1's changed strings and identifiers found only the old fixture number (84); two literals there and two in `A11yBaseline.json` updated to 72. The `runCopyComplete` accessibility baseline was not regenerated (needs the UI suite; owner row H-FRX-8). - G1 PNGs sent to the owner. Rendered, not verified in the running app. +- 2026-11-28 WP-11 Done-when (orchestrator): `cf_swift.sh test ChronoframeCoreDeduplicateReviewLaneTests` exit 0 (6); `cf_swift.sh test ChronoframeCoreFreeDedupeBatchPlannerTests` exit 0 (13); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0. No strings, no existing assertions changed. +- WP-11 reviews. Orchestrator: read `DeduplicateReviewLane.swift` and `FreeDedupeBatchPlanner.swift` in full; the algorithm is C-11's five steps and nothing else, the plan returned is always a `DeduplicationPlanner.plan` result. cf-reviewer: approve; `expectedIdentity` is non-optional so an absent path cannot pass the subset check; plan paths are unique by construction. Opus (general-purpose, read-only): Q1 no (the only fields that can differ for the same path are `owningClusterID/Kind`, `pairOrigin`, `mutationUnitID`, `mediaKind`: receipt-only, same executor action); Q2 no (forcing Keep only adds Keeps among members; fan-out and sidecar guards are identical in both calls); Q3(a) no; Q3(b) yes, only by repeating an emptying the full plan already contains (B-1). +- For WP-12/WP-13 (from the Opus review): the batch plan must be the plan that is displayed, confirmed and committed. C-13 already moves both confirmation counts to `preparedCommitCount ?? reviewedDeletionPlan().count`; the reviewer checks that. +- 2026-11-28 WP-12 Done-when (orchestrator): `cf_swift.sh test DeduplicateSessionStoreTests` exit 0 (49); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0. Reviewer also ran `DeduplicateReviewPersistenceTests` exit 0 (20). No existing assertions changed. +- WP-12 strings for WP-14 (Core catalog, `Bundle.module`): `Accept Identical Copies`; `Accept Nearly Identical`. +- Noticed, not fixed: `acceptAllSuggestions()` (and so `acceptSuggestions(in:)`, which copies it) rebuilds `decisions` with `DedupeDecisions(byPath:)`, which drops any `pairKeepOverrides`. Pre-existing behaviour, kept identical on purpose. Reviewer notes: no test covers a free-batch commit followed by an ordinary commit on the same store (correct by trace); the free-batch flag is read at completion, so WP-13 must not allow a prepare call while a commit is running. +- 2026-11-28 WP-13 Done-when (orchestrator): `cf_swift.sh test` exit 0 for DeduplicateReviewLanesTests (15), DeduplicateReviewViewsTests (10), DeduplicateStatusViewTests (30), UnlockPresentationTests (21), UnlockSheetBatchOfferTests (14), AppStateTests (54), TipsTests (4), UITestWindowFitTests (9), AccessibilityTests (8), ScreenRenderEvidenceTests (5 run with marker, 5 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `git diff --check` exit 0. +- Noticed, not fixed (M2): `HelpView.swift:145` still says "Open comparison in Rapid Triage" (outside C-13); at 1180×820 the three lane rows plus the safeguard cards leave the group list about three rows tall; the footer status reads "4 files will be moved to Trash" beside `Move 2 Files to Trash Free` (the free line above explains the difference); the footer `Accept Identical Copies` button stays enabled when the identical lane is empty. +- 2026-11-28 WP-14: `add_translated_keys.py … Localizable.xcstrings … M2-app.json` exit 0 (added 29); `… LocalizableCore.xcstrings … M2-core.json` exit 0 (added 3); `cf_swift.sh build` exit 0; early German check: zero missing keys (app 1793, core 330). German review (cf-reviewer): approve, no changes. Docs: QUICK_START, FAQ, README, SAFETY_AND_RECOVERY, plus one phrase each in TROUBLESHOOTING and TECHNICAL (D-FRX-112); `git diff --check` exit 0. +- Noticed, not fixed (M2): `%@ more are waiting. Your choices are saved; scan again to continue.` has no singular form ("1 more are waiting"). The old undo name `Accept All Suggestions` and the keys `Accept All Safe`, `Accept Safe`, `Rapid Triage` stay in the catalogs (baseline keys are never removed). +- 2026-11-28 G2 commands (orchestrator): `cf_swift.sh suite` exit 0 (2654 passed, 0 failed); `cf_swift.sh coverage` exit 0 (96.17%; DeduplicateReviewLane 100%, FreeDedupeBatchPlanner 98.7%); `cf_swift.sh guards feature/first-run-trust` exit 0 (14 guards); `script/check_agents_invariants_have_tests.sh` exit 0 (30 invariants); `cf_swift.sh xcode` exit 0; `xcodebuild … SWIFT_EMIT_LOC_STRINGS=YES build` exit 0; `check_german_localization.py --baseline-ref origin/main …` exit 0 (app 1793, core 330; zero missing keys of 914 app / 287 core); `xcodebuild … build-for-testing` exit 0; `cf_swift.sh test ScreenRenderEvidenceTests` with the marker exit 0; `git diff --check` exit 0. +- G2 step 4: no literal in `ui/Xcode/UITests/ChronoframeUITests.swift` or `A11yBaseline.json` matches a string M2 changed (the dedupe UI tests use identifiers, all kept); nothing edited. In the existing wide and compact scenarios the reviewed plan stays under the 96 free removals left, so `dedupeCommitButton` is still the commit control there. +- G2 PNG sent to the owner. Rendered, not verified in the running app. +- 2026-11-29 after G3: owner confirmed D-FRX-11 and D-FRX-25 and asked for B-1 option 1 (D-FRX-119). `fix/dedupe-planner-rail-protects-fanout` `2f8954f` from `origin/main`: red first (`cf_swift.sh test DeduplicationPlannerGroupRailTests` exit 1, 6 failures), then `cf_swift.sh test DeduplicationPlanner` exit 0 (11 tests), `coverage` exit 0 (2518 passed; 96.17%), `guards origin/main` exit 0 (14), `xcode` exit 0, `git diff --check` exit 0. Merged into `feature/first-run-duplicates`; the "not a guarantee" sentences in QUICK_START, FAQ, README and SAFETY_AND_RECOVERY now state the skip as a fact. +- 2026-11-29: the planner fix changed two premise assertions in `ChronoframeCoreFreeDedupeBatchPlannerTests.testForcedKeepThatWouldUnskipAGroupStopsTheWalk` (`:266`, `:297`): the full plan and the Y+Z plan no longer contain `y1`, because a skipped group now stays whole. The trap the test covers (a forced Keep un-skips Y) and its `XCTAssertNil` are unchanged. `cf_swift.sh test ChronoframeCoreFreeDedupeBatchPlannerTests` exit 0 (13 tests). diff --git a/docs/plan/first-run-experience/strings/M2-app.json b/docs/plan/first-run-experience/strings/M2-app.json new file mode 100644 index 00000000..741e5ab4 --- /dev/null +++ b/docs/plan/first-run-experience/strings/M2-app.json @@ -0,0 +1,118 @@ +[ + { + "key": "Accept Identical", + "de": "Identische akzeptieren" + }, + { + "key": "Accept Identical Copies (%@)", + "de": "Identische Kopien akzeptieren (%@)" + }, + { + "key": "Accept identical copies", + "de": "Identische Kopien akzeptieren" + }, + { + "key": "Accept the Rest (%@)", + "de": "Rest akzeptieren (%@)" + }, + { + "key": "%@ safe groups are identical copies. Accept them together: %@, %@.", + "de": "%1$@ sichere Gruppen bestehen aus identischen Kopien. Akzeptiere sie gemeinsam: %2$@, %3$@." + }, + { + "key": "1 safe group is identical copies. Accept it now: %@, %@.", + "de": "1 sichere Gruppe besteht aus identischen Kopien. Du kannst sie jetzt akzeptieren: %1$@, %2$@." + }, + { + "key": "%@ safe groups are nearly identical. Look through them quickly.", + "de": "%@ sichere Gruppen sind nahezu identisch. Sieh sie kurz durch." + }, + { + "key": "1 safe group is nearly identical. Look through it quickly.", + "de": "1 sichere Gruppe ist nahezu identisch. Sieh sie kurz durch." + }, + { + "key": "%@ identical", + "de": "%@ identisch" + }, + { + "key": "%@ nearly identical", + "de": "%@ nahezu identisch" + }, + { + "key": "%@ to check", + "de": "%@ zu prüfen" + }, + { + "key": "Chronoframe always suggests keeping one photo in every group.", + "de": "Chronoframe schlägt immer vor, in jeder Gruppe ein Foto zu behalten." + }, + { + "key": "Keeps one file in every group of identical copies and marks the rest for the Trash", + "de": "Behält in jeder Gruppe identischer Kopien eine Datei und markiert den Rest für den Papierkorb" + }, + { + "key": "%@ groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them.", + "de": "In %@ Gruppen ist jedes Foto mit „Löschen“ markiert. Chronoframe überspringt eine Gruppe, wenn darin nichts behalten wird. Markiere in jeder ein Foto mit „Behalten“, um sie einzubeziehen." + }, + { + "key": "1 group has every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in it to include it.", + "de": "In 1 Gruppe ist jedes Foto mit „Löschen“ markiert. Chronoframe überspringt eine Gruppe, wenn darin nichts behalten wird. Markiere darin ein Foto mit „Behalten“, um sie einzubeziehen." + }, + { + "key": "Your free removals are used up.", + "de": "Deine kostenlosen Entfernungen sind aufgebraucht." + }, + { + "key": "You can remove %@ free. Your reviewed groups hold %@.", + "de": "Du kannst %1$@ kostenlos entfernen. Deine geprüften Gruppen enthalten %2$@." + }, + { + "key": "1 duplicate", + "de": "1 Duplikat" + }, + { + "key": "%@ duplicates", + "de": "%@ Duplikate" + }, + { + "key": "Move %@ Files to Trash Free", + "de": "%@ Dateien kostenlos in den Papierkorb legen" + }, + { + "key": "Move 1 File to Trash Free", + "de": "1 Datei kostenlos in den Papierkorb legen" + }, + { + "key": "Unlock to Remove All %@", + "de": "Freischalten, um alle %@ zu entfernen" + }, + { + "key": "%@ more are waiting. Your choices are saved; scan again to continue.", + "de": "%@ weitere warten. Deine Auswahl ist gespeichert; scanne erneut, um fortzufahren." + }, + { + "key": "Moves the files from whole groups to the Trash after confirmation", + "de": "Legt die Dateien ganzer Gruppen nach Bestätigung in den Papierkorb" + }, + { + "key": "Accept identical copies in one step", + "de": "Identische Kopien in einem Schritt akzeptieren" + }, + { + "key": "Identical copies are the same file saved more than once. Accepting them keeps one and marks the rest for the Trash. Chronoframe never selects uncertain matches for you.", + "de": "Identische Kopien sind dieselbe Datei, die mehrfach gespeichert wurde. Wenn du sie akzeptierst, bleibt eine erhalten und der Rest wird für den Papierkorb markiert. Chronoframe wählt unsichere Treffer nie für dich aus." + }, + { + "key": "Moves %@ from whole groups to the Trash now and leaves %@ for later.", + "de": "Legt jetzt %1$@ aus ganzen Gruppen in den Papierkorb und lässt %2$@ für später übrig." + }, + { + "key": "Accept Identical Copies", + "de": "Identische Kopien akzeptieren" + }, + { + "key": "Accept Nearly Identical", + "de": "Nahezu identische akzeptieren" + } +] diff --git a/docs/plan/first-run-experience/strings/M2-core.json b/docs/plan/first-run-experience/strings/M2-core.json new file mode 100644 index 00000000..1e19643b --- /dev/null +++ b/docs/plan/first-run-experience/strings/M2-core.json @@ -0,0 +1,14 @@ +[ + { + "key": "Moves %@ from whole groups to the Trash now and leaves %@ for later.", + "de": "Legt jetzt %1$@ aus ganzen Gruppen in den Papierkorb und lässt %2$@ für später übrig." + }, + { + "key": "Accept Identical Copies", + "de": "Identische Kopien akzeptieren" + }, + { + "key": "Accept Nearly Identical", + "de": "Nahezu identische akzeptieren" + } +] diff --git a/script/swift_meaningful_coverage.sh b/script/swift_meaningful_coverage.sh index 58c49a6b..dd140822 100755 --- a/script/swift_meaningful_coverage.sh +++ b/script/swift_meaningful_coverage.sh @@ -75,6 +75,8 @@ MEANINGFUL_BASENAMES=( BLAKE2bHasher RunAccounting FreeMonthBatchPlanner + DeduplicateReviewLane + FreeDedupeBatchPlanner CopyPlanBuilder DryRunPlanner EditedVariantDestinations diff --git a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift index e6c061a9..a961ad48 100644 --- a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift +++ b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift @@ -90,6 +90,10 @@ enum AccessibilityIdentifiers { static let dedupeLanes = "dedupe.lanes" static let dedupeLanesAcceptSafe = "dedupe.lanes.acceptSafe" static let dedupeLanesQuickReview = "dedupe.lanes.quickReview" + static let dedupeLanesQuickReviewNearlyIdentical = "dedupe.lanes.quickReviewNearlyIdentical" + static let quickReviewAcceptRest = "quickReview.acceptRest" + static let dedupeFreeBatchCommit = "dedupe.freeBatchCommit" + static let dedupeUnlockAll = "dedupe.unlockAll" static let dedupeMemberStrip = "dedupeMemberStrip" static let dedupeOpenRunHistoryButton = "dedupeOpenRunHistoryButton" static let dedupePausedScanSection = "dedupePausedScanSection" @@ -198,6 +202,7 @@ enum AccessibilityIdentifiers { dedupeReviewDetail, dedupeReviewSettingsButton, dedupeUseHistoryFolderButton, dedupeRestoredBanner, dedupeRestoredBannerDismiss, dedupeSavedReviewDiscard, dedupeSavedReviewResume, dedupeLanes, dedupeLanesAcceptSafe, dedupeLanesQuickReview, + dedupeLanesQuickReviewNearlyIdentical, quickReviewAcceptRest, dedupeFreeBatchCommit, dedupeUnlockAll, historyFilterControl, recoveryCenterSection, useHistoricalSourceButton, revealHistoricalSourceButton, receiptFileCount, receiptCloseButton, receiptItemList, receiptVerifyButton, activeProfileBadge, diff --git a/ui/Sources/ChronoframeApp/App/AppState.swift b/ui/Sources/ChronoframeApp/App/AppState.swift index c4fe278a..89964fac 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -551,6 +551,37 @@ final class AppState: ObservableObject { ) } + /// Open the unlock sheet for the reviewed duplicate groups on screen, without + /// removing anything (FRX C-13). Nothing was refused, so no store holds it. + func requestUnlockForDuplicates(requested: Int, remaining: Int) { + requestedUnlockRefusal = .allowanceSpent( + TrialRefusal(meter: .dedupe, requested: requested, remaining: remaining) + ) + } + + /// The free removal batch the sheet can offer: only for a spent dedupe allowance + /// that still has something left, and only when the reviewed plan is larger than + /// what is left (FRX C-13). + var offeredFreeDedupeBatch: FreeDedupeBatch? { + guard case let .allowanceSpent(details)? = unlockRefusal, + details.meter == .dedupe, + details.remaining > 0 else { return nil } + return deduplicateSessionStore.freeBatchOffer(remaining: details.remaining) + } + + /// The person chose the free removal in the sheet. Closes the sheet and asks the + /// review screen to open its confirmation dialog; nothing is moved to the Trash + /// until that dialog is confirmed. + func runOfferedFreeDedupeBatch() { + guard offeredFreeDedupeBatch != nil else { return } + deduplicateSessionStore.dismissRefusal() + requestedUnlockRefusal = nil + // A refused commit paused the review, and the dialog lives on the + // review footer. Does nothing when the review is already on screen. + deduplicateSessionStore.resumePausedReview() + deduplicateSessionStore.wantsFreeBatchConfirmation = true + } + /// A smaller run the remaining allowance covers, when one was offered /// alongside the refusal (free-trial step 5, T15). /// diff --git a/ui/Sources/ChronoframeApp/App/Tips.swift b/ui/Sources/ChronoframeApp/App/Tips.swift index 77b2b5c6..4c2d701a 100644 --- a/ui/Sources/ChronoframeApp/App/Tips.swift +++ b/ui/Sources/ChronoframeApp/App/Tips.swift @@ -14,8 +14,8 @@ enum TipCopy { } enum AcceptSafeSuggestions { - static let title = "Accept safe matches in one step" - static let message = "Safe groups are matches Chronoframe has verified. Accept them together and keep moving. Chronoframe never selects uncertain matches for you." + static let title = "Accept identical copies in one step" + static let message = "Identical copies are the same file saved more than once. Accepting them keeps one and marks the rest for the Trash. Chronoframe never selects uncertain matches for you." static let symbol = "checkmark.seal" } diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index 62e0d914..9a19e8f4 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -56,6 +56,8 @@ enum UITestAppStateFactory { let engine: MockOrganizerEngine let route: AppRoute var deduplicateSessionStore: DeduplicateSessionStore? = nil + /// Groups the scenario accepts once its scan has finished (the lanes fixture only). + var acceptedAfterScan: [DuplicateCluster] = [] var watchedSourcesStore: WatchedSourcesStore? = nil var photosImportStore: PhotosImportStore? = nil @@ -189,21 +191,26 @@ enum UITestAppStateFactory { engine = previewReviewEngine(sourcePath: setupStore.sourcePath, destinationPath: setupStore.destinationPath) route = .organize(.setup) - case .deduplicateReviewWide, .deduplicateReviewCompact: + case .deduplicateReviewWide, .deduplicateReviewCompact, .deduplicateReviewLanes: setupStore.destinationPath = "/Volumes/Archive/Chronoframe Library" historyStore = HistoryStore(destinationRoot: setupStore.destinationPath) engine = previewReviewEngine(sourcePath: "/Volumes/Card/April Session", destinationPath: setupStore.destinationPath) route = .deduplicate - let clusters = sampleDeduplicateClusters() + let lanesFixture = scenario == .deduplicateReviewLanes ? sampleDeduplicateLanesFixture() : nil + let clusters = lanesFixture?.clusters ?? sampleDeduplicateClusters() let deduplicateEngine = MockDeduplicateEngine( clusters: clusters, summary: DeduplicateSummary( - clusterCounts: [.burst: clusters.count], + clusterCounts: lanesFixture == nil + ? [.burst: clusters.count] + : [.exactDuplicate: 6, .nearDuplicate: 8], totalRecoverableBytes: clusters.reduce(Int64(0)) { $0 + $1.bytesIfPruned }, totalCandidatesScanned: clusters.reduce(0) { $0 + $1.members.count }, scanDuration: 4.2 - ) + ), + identityOverride: lanesFixture.map { fixture in { fixture.identitiesByPath[$0.path] } } ) + acceptedAfterScan = lanesFixture?.acceptedClusters ?? [] if ProcessInfo.processInfo.environment["CHRONOFRAME_UI_TEST_DEDUPE_REFUSAL"] == "1" { deduplicateEngine.commitErrorForPlan = { plan in TrialAuthorizationError(refusal: .allowanceSpent( @@ -285,6 +292,20 @@ enum UITestAppStateFactory { deduplicateSessionStore.startScan(configuration: preferencesStore.makeDeduplicateConfiguration( destinationPath: setupStore.destinationPath )) + if !acceptedAfterScan.isEmpty { + // Clusters arrive on the scan stream, so the acceptance waits for the review. + let accepted = acceptedAfterScan + Task { @MainActor in + var attempts = 0 + while deduplicateSessionStore.status != .readyToReview, attempts < 400 { + try? await Task.sleep(nanoseconds: 25_000_000) + attempts += 1 + } + for cluster in accepted { + deduplicateSessionStore.acceptSuggestionsForCluster(cluster) + } + } + } } return appState @@ -315,7 +336,9 @@ enum UITestAppStateFactory { ) } seedCharge( - ProcessInfo.processInfo.environment["CHRONOFRAME_UI_TEST_DEDUPE_REFUSAL"] == "1" ? 100 : 4, + scenario == .deduplicateReviewLanes + ? 98 + : (ProcessInfo.processInfo.environment["CHRONOFRAME_UI_TEST_DEDUPE_REFUSAL"] == "1" ? 100 : 4), meter: .dedupe, runID: "00000000-0000-0000-0000-000000000502", ledger: ledger, @@ -725,6 +748,56 @@ enum UITestAppStateFactory { return store } + /// FRX C-14: six exact groups of three files that share one identity (the first two + /// are accepted once the scan is in), three high-confidence near-duplicate groups and + /// five medium ones. With 98 of 100 free removals used, the two reviewed groups hold four + /// files against two remaining. + private static func sampleDeduplicateLanesFixture() -> ( + clusters: [DuplicateCluster], + identitiesByPath: [String: FileIdentity], + acceptedClusters: [DuplicateCluster] + ) { + var clusters: [DuplicateCluster] = [] + var identities: [String: FileIdentity] = [:] + let groups: [(name: String, kind: ClusterKind, confidence: ConfidenceLevel)] = + (1...6).map { ("exact-\($0)", .exactDuplicate, .high) } + + (1...3).map { ("nearly-\($0)", .nearDuplicate, .high) } + + (1...5).map { ("check-\($0)", .nearDuplicate, .medium) } + for (index, group) in groups.enumerated() { + let captureDate = Date(timeIntervalSinceReferenceDate: 763_948_800 + TimeInterval(index * 3_600)) + var members: [PhotoCandidate] = [] + for memberIndex in 0..<3 { + let size = group.kind == .exactDuplicate + ? Int64(2_400_000) + : Int64(memberIndex + 1) * 1_024_000 + let path = "/Volumes/Archive/Chronoframe Library/2012-08-\(String(format: "%02d", index + 1))_\(group.name)_\(memberIndex + 1).jpg" + members.append(PhotoCandidate( + path: path, + size: size, + modificationTime: 763_948_800, + captureDate: captureDate, + pixelWidth: 4032, + pixelHeight: 3024, + qualityScore: memberIndex == 0 ? 0.95 : 0.72 - Double(memberIndex) * 0.08, + sharpness: memberIndex == 0 ? 0.88 : 0.62, + faceScore: memberIndex == 0 ? 0.8 : 0.4 + )) + if group.kind == .exactDuplicate { + identities[path] = FileIdentity(size: size, digest: "lanes-fixture-\(group.name)") + } + } + clusters.append(DuplicateCluster( + id: UUID(uuidString: "00000000-0000-0000-0001-\(String(format: "%012d", index + 1))") ?? UUID(), + kind: group.kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: members.dropFirst().reduce(Int64(0)) { $0 + $1.size }, + annotation: ClusterAnnotation(confidence: group.confidence, matchReason: MatchReason(kind: group.kind)) + )) + } + return (clusters, identities, Array(clusters.prefix(2))) + } + private static func sampleDeduplicateClusters() -> [DuplicateCluster] { var clusters: [DuplicateCluster] = [] for index in 0..<12 { diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift index cac00894..0532a479 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift @@ -112,14 +112,19 @@ final class MockDeduplicateEngine: DeduplicateEngine { init( clusters: [DuplicateCluster] = [], summary: DeduplicateSummary = DeduplicateSummary(), - commitEvents: [DeduplicateCommitEvent] = [] + commitEvents: [DeduplicateCommitEvent] = [], + identityOverride: ((PhotoCandidate) -> FileIdentity?)? = nil ) { self.clustersToEmit = clusters var summary = summary if summary.scanSnapshot.identitiesByPath.isEmpty { summary.scanSnapshot = DeduplicateScanSnapshot(identitiesByPath: Dictionary( uniqueKeysWithValues: clusters.flatMap(\.members).map { member in - (member.path, FileIdentity(size: member.size, digest: Data(member.path.utf8).base64EncodedString())) + ( + member.path, + identityOverride?(member) + ?? FileIdentity(size: member.size, digest: Data(member.path.utf8).base64EncodedString()) + ) } )) } diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift index 6120ab71..f6d41661 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift @@ -22,6 +22,7 @@ enum UITestScenario: String, CaseIterable { case settingsDiagnostics case deduplicateReviewWide case deduplicateReviewCompact + case deduplicateReviewLanes static func current( environment: [String: String] = ProcessInfo.processInfo.environment, @@ -61,7 +62,7 @@ enum UITestScenario: String, CaseIterable { /// the audit never depends on StoreKit, signing, or a test account. var usesMeteredTrialUI: Bool { switch self { - case .runPreviewReview, .runPreviewOverAllowance, .settingsLicense, .deduplicateReviewWide, .deduplicateReviewCompact: + case .runPreviewReview, .runPreviewOverAllowance, .settingsLicense, .deduplicateReviewWide, .deduplicateReviewCompact, .deduplicateReviewLanes: return true default: return false @@ -76,7 +77,7 @@ enum UITestScenario: String, CaseIterable { return NSSize(width: 1360, height: 920) case .settingsSections, .settingsLayout, .settingsPerformance, .settingsDeduplicate, .settingsLicense, .settingsDiagnostics: return NSSize(width: 1360, height: 920) - case .deduplicateReviewWide: + case .deduplicateReviewWide, .deduplicateReviewLanes: return NSSize(width: 1180, height: 820) case .deduplicateReviewCompact: return NSSize(width: 900, height: 700) diff --git a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings index ddda9cf0..f5fa282a 100644 --- a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings +++ b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings @@ -214,6 +214,23 @@ } } }, + "%@ duplicates" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ Duplikate" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ duplicates" + } + } + } + }, "%@ edited photos will also be saved" : { "extractionState" : "manual", "localizations" : { @@ -265,6 +282,40 @@ } } }, + "%@ groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "In %@ Gruppen ist jedes Foto mit „Löschen“ markiert. Chronoframe überspringt eine Gruppe, wenn darin nichts behalten wird. Markiere in jeder ein Foto mit „Behalten“, um sie einzubeziehen." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them." + } + } + } + }, + "%@ identical" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ identisch" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ identical" + } + } + } + }, "%@ in identical extra copies (logical size, not space freed)" : { "extractionState" : "manual", "localizations" : { @@ -299,6 +350,40 @@ } } }, + "%@ more are waiting. Your choices are saved; scan again to continue." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ weitere warten. Deine Auswahl ist gespeichert; scanne erneut, um fortzufahren." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ more are waiting. Your choices are saved; scan again to continue." + } + } + } + }, + "%@ nearly identical" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ nahezu identisch" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ nearly identical" + } + } + } + }, "%@ of %@ reviewed" : { "comment" : "A step indicator showing the current step number and the total number of steps.", "isCommentAutoGenerated" : true, @@ -376,6 +461,40 @@ } } }, + "%@ safe groups are identical copies. Accept them together: %@, %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@ sichere Gruppen bestehen aus identischen Kopien. Akzeptiere sie gemeinsam: %2$@, %3$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ safe groups are identical copies. Accept them together: %@, %@." + } + } + } + }, + "%@ safe groups are nearly identical. Look through them quickly." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ sichere Gruppen sind nahezu identisch. Sieh sie kurz durch." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ safe groups are nearly identical. Look through them quickly." + } + } + } + }, "%@ sidecar files" : { "extractionState" : "manual", "localizations" : { @@ -410,6 +529,23 @@ } } }, + "%@ to check" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ zu prüfen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ to check" + } + } + } + }, "%@ · %@" : { "comment" : "A label that shows the date source and date confidence. The first argument is the title of the date source. The second argument is the title of the date confidence.", "isCommentAutoGenerated" : true, @@ -554,6 +690,23 @@ } } }, + "1 duplicate" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 Duplikat" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 duplicate" + } + } + } + }, "1 edited photo will also be saved" : { "extractionState" : "manual", "localizations" : { @@ -673,6 +826,23 @@ } } }, + "1 group has every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in it to include it." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "In 1 Gruppe ist jedes Foto mit „Löschen“ markiert. Chronoframe überspringt eine Gruppe, wenn darin nichts behalten wird. Markiere darin ein Foto mit „Behalten“, um sie einzubeziehen." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 group has every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in it to include it." + } + } + } + }, "1 group is a look-alike or less certain. Take a look." : { "extractionState" : "manual", "localizations" : { @@ -843,6 +1013,40 @@ } } }, + "1 safe group is identical copies. Accept it now: %@, %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 sichere Gruppe besteht aus identischen Kopien. Du kannst sie jetzt akzeptieren: %1$@, %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 safe group is identical copies. Accept it now: %@, %@." + } + } + } + }, + "1 safe group is nearly identical. Look through it quickly." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 sichere Gruppe ist nahezu identisch. Sieh sie kurz durch." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 safe group is nearly identical. Look through it quickly." + } + } + } + }, "1 safe match" : { "extractionState" : "manual", "localizations" : { @@ -1163,6 +1367,107 @@ } } }, + "Accept Identical" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identische akzeptieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept Identical" + } + } + } + }, + "Accept identical copies" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identische Kopien akzeptieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept identical copies" + } + } + } + }, + "Accept Identical Copies" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identische Kopien akzeptieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept Identical Copies" + } + } + } + }, + "Accept Identical Copies (%@)" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identische Kopien akzeptieren (%@)" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept Identical Copies (%@)" + } + } + } + }, + "Accept identical copies in one step" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identische Kopien in einem Schritt akzeptieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept identical copies in one step" + } + } + } + }, + "Accept Nearly Identical" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nahezu identische akzeptieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept Nearly Identical" + } + } + } + }, "Accept Safe" : { "extractionState" : "manual", "localizations" : { @@ -1286,6 +1591,23 @@ } } }, + "Accept the Rest (%@)" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rest akzeptieren (%@)" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Accept the Rest (%@)" + } + } + } + }, "Accepts the suggestion for every safe group" : { "extractionState" : "manual", "localizations" : { @@ -2502,6 +2824,23 @@ } } }, + "Chronoframe always suggests keeping one photo in every group." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe schlägt immer vor, in jeder Gruppe ein Foto zu behalten." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe always suggests keeping one photo in every group." + } + } + } + }, "Chronoframe could not finish. Your original files were left untouched." : { "extractionState" : "manual", "localizations" : { @@ -5127,6 +5466,23 @@ } } }, + "Identical copies are the same file saved more than once. Accepting them keeps one and marks the rest for the Trash. Chronoframe never selects uncertain matches for you." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identische Kopien sind dieselbe Datei, die mehrfach gespeichert wurde. Wenn du sie akzeptierst, bleibt eine erhalten und der Rest wird für den Papierkorb markiert. Chronoframe wählt unsichere Treffer nie für dich aus." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Identical copies are the same file saved more than once. Accepting them keeps one and marks the rest for the Trash. Chronoframe never selects uncertain matches for you." + } + } + } + }, "Imports the original photo or video. Edits made in Photos, such as crops and filters, are not included." : { "extractionState" : "manual", "localizations" : { @@ -5272,6 +5628,23 @@ } } }, + "Keeps one file in every group of identical copies and marks the rest for the Trash" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Behält in jeder Gruppe identischer Kopien eine Datei und markiert den Rest für den Papierkorb" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Keeps one file in every group of identical copies and marks the rest for the Trash" + } + } + } + }, "Keeps the suggested file in every safe group and marks the rest for the Trash" : { "extractionState" : "manual", "localizations" : { @@ -5587,6 +5960,40 @@ } } }, + "Move %@ Files to Trash Free" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ Dateien kostenlos in den Papierkorb legen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Move %@ Files to Trash Free" + } + } + } + }, + "Move 1 File to Trash Free" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 Datei kostenlos in den Papierkorb legen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Move 1 File to Trash Free" + } + } + } + }, "Move every file already in the destination into the layout selected above. Files are moved on the same volume (instant — no copy), originals are never deleted, and an existing file at the new location is never overwritten." : { "comment" : "A description of the reorganization process.", "isCommentAutoGenerated" : true, @@ -5652,6 +6059,40 @@ } } }, + "Moves %@ from whole groups to the Trash now and leaves %@ for later." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Legt jetzt %1$@ aus ganzen Gruppen in den Papierkorb und lässt %2$@ für später übrig." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Moves %@ from whole groups to the Trash now and leaves %@ for later." + } + } + } + }, + "Moves the files from whole groups to the Trash after confirmation" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Legt die Dateien ganzer Gruppen nach Bestätigung in den Papierkorb" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Moves the files from whole groups to the Trash after confirmation" + } + } + } + }, "Needs attention" : { "extractionState" : "manual", "localizations" : { @@ -9942,6 +10383,23 @@ } } }, + "Unlock to Remove All %@" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Freischalten, um alle %@ zu entfernen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unlock to Remove All %@" + } + } + } + }, "Untested" : { "comment" : "A badge that indicates that a test has not yet been run.", "isCommentAutoGenerated" : true, @@ -10571,6 +11029,23 @@ } } }, + "You can remove %@ free. Your reviewed groups hold %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Du kannst %1$@ kostenlos entfernen. Deine geprüften Gruppen enthalten %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "You can remove %@ free. Your reviewed groups hold %@." + } + } + } + }, "You changed some dates. Rebuild the preview so the copy matches your changes." : { "extractionState" : "manual", "localizations" : { @@ -10724,6 +11199,23 @@ } } }, + "Your free removals are used up." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Deine kostenlosen Entfernungen sind aufgebraucht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your free removals are used up." + } + } + } + }, "Your organized library already has everything it needs." : { "extractionState" : "manual", "localizations" : { diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift index 46f02660..01d5b3b6 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift @@ -1,21 +1,31 @@ +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif #if canImport(ChronoframeCore) import ChronoframeCore #endif import SwiftUI -/// Two lanes over the review list: groups Chronoframe can accept together -/// ("safe") and groups that need a look ("check"). A pure view over the store's -/// clusters; it decides nothing about what is accepted. +/// Three lanes over the review list: groups that are identical copies, +/// groups that are nearly identical (both "safe"), and groups that need a +/// look ("check"). A pure view over the store's clusters; it decides nothing +/// about what is accepted. /// /// A group counts as safe only when `DeduplicationPlanner.isAutomaticCommitEligible` /// says so, so a high-confidence group the planner refuses to auto-select /// (for example a perceptual video match) lands in the check lane. struct DeduplicateReviewLanes: Equatable { - /// Eligible and not yet reviewed. + /// Eligible and not yet reviewed: `identicalGroupCount + nearlyIdenticalGroupCount`. let safeGroupCount: Int /// Not eligible and not yet reviewed. let checkGroupCount: Int let reviewedGroupCount: Int + /// Eligible, not yet reviewed, and every member is the same file byte for byte. + let identicalGroupCount: Int + /// Eligible, not yet reviewed, and the files differ. + let nearlyIdenticalGroupCount: Int + /// True for the three-lane initializer, whose compact text names the lanes. + private let namesLanes: Bool init( clusters: [DuplicateCluster], @@ -37,6 +47,75 @@ struct DeduplicateReviewLanes: Equatable { safeGroupCount = safe checkGroupCount = check reviewedGroupCount = reviewed + // Without a lane the files are not known to be identical, so a safe group is + // counted as nearly identical (fail closed). + identicalGroupCount = 0 + nearlyIdenticalGroupCount = safe + namesLanes = false + } + + /// The three-lane initializer. A group is safe only if the planner would auto-select + /// it and `lane` places it in a safe lane; anything else is a group to check. + init( + clusters: [DuplicateCluster], + reviewedIDs: Set, + lane: (DuplicateCluster) -> DeduplicateReviewLane + ) { + var identical = 0 + var nearlyIdentical = 0 + var check = 0 + var reviewed = 0 + for cluster in clusters { + if reviewedIDs.contains(cluster.id) { + reviewed += 1 + } else if !DeduplicationPlanner.isAutomaticCommitEligible(cluster) { + check += 1 + } else { + switch lane(cluster) { + case .identical: identical += 1 + case .nearlyIdentical: nearlyIdentical += 1 + case .lookAtEach: check += 1 + } + } + } + identicalGroupCount = identical + nearlyIdenticalGroupCount = nearlyIdentical + safeGroupCount = identical + nearlyIdentical + checkGroupCount = check + reviewedGroupCount = reviewed + namesLanes = true + } + + /// The promise under the rows. Worded as what is certainly true (D-FRX-11). + static let promiseLine = "Chronoframe always suggests keeping one photo in every group." + + /// First row. Carries what accepting it would move, from the store's lane summary. + func identicalText(files: Int, bytes: Int64) -> String? { + guard identicalGroupCount > 0 else { return nil } + let fileText = files == 1 + ? String(localized: "1 file", bundle: .module) + : String(localized: "\(files.formatted()) files", bundle: .module) + let byteText = Self.byteCountFormatter.string(fromByteCount: bytes) + if identicalGroupCount == 1 { + return String(localized: "1 safe group is identical copies. Accept it now: \(fileText), \(byteText).", bundle: .module) + } + return String(localized: "\(identicalGroupCount.formatted()) safe groups are identical copies. Accept them together: \(fileText), \(byteText).", bundle: .module) + } + + /// Second row. + var nearlyIdenticalText: String? { + switch nearlyIdenticalGroupCount { + case ..<1: return nil + case 1: return String(localized: "1 safe group is nearly identical. Look through it quickly.", bundle: .module) + default: return String(localized: "\(nearlyIdenticalGroupCount.formatted()) safe groups are nearly identical. Look through them quickly.", bundle: .module) + } + } + + private static var byteCountFormatter: ByteCountFormatter { + let formatter = ByteCountFormatter() + formatter.allowedUnits = [.useMB, .useGB] + formatter.countStyle = .file + return formatter } var safeText: String? { @@ -63,6 +142,7 @@ struct DeduplicateReviewLanes: Equatable { /// One line for the stacked (narrow) layout, where a two-row bar with /// buttons would take the height the photo preview needs. var compactText: String? { + if namesLanes { return laneCompactText } var parts: [String] = [] if safeGroupCount == 1 { parts.append(String(localized: "1 safe match", bundle: .module)) @@ -80,19 +160,42 @@ struct DeduplicateReviewLanes: Equatable { } return parts.joined(separator: " · ") } + + /// `{n} identical · {m} nearly identical · {k} to check`, parts with 0 omitted. + private var laneCompactText: String? { + var parts: [String] = [] + if identicalGroupCount > 0 { + parts.append(String(localized: "\(identicalGroupCount.formatted()) identical", bundle: .module)) + } + if nearlyIdenticalGroupCount > 0 { + parts.append(String(localized: "\(nearlyIdenticalGroupCount.formatted()) nearly identical", bundle: .module)) + } + if checkGroupCount > 0 { + parts.append(String(localized: "\(checkGroupCount.formatted()) to check", bundle: .module)) + } + if parts.isEmpty { + return doneText == nil ? nil : String(localized: "Every group has been reviewed", bundle: .module) + } + return parts.joined(separator: " · ") + } } -/// Single-row band above the review body. The buttons only forward to the -/// caller: "Accept All Safe" is the store's `acceptAllSuggestions()` and -/// "Quick Review" opens the existing Quick Review sheet. +/// Band above the review body: one row per lane that has groups, and the keep +/// promise under them. The buttons only forward to the caller: "Accept Identical +/// Copies" is the store's `acceptSuggestions(in: .identical)`, and the two +/// "Quick Review" buttons open Quick Review over their lane. /// /// In the stacked layout the bar is one line of text with no buttons: the -/// commit footer already has Accept Safe and the Options menu has Quick Review. +/// commit footer already has Accept Identical and the Options menu has Quick Review. struct DeduplicateReviewLanesBar: View { let lanes: DeduplicateReviewLanes + /// Files and bytes the identical lane would move, from the store's lane summary. + var identicalFiles = 0 + var identicalBytes: Int64 = 0 var isCompact = false - let onAcceptSafe: () -> Void - let onQuickReview: () -> Void + let onAcceptIdentical: () -> Void + let onQuickReviewNearlyIdentical: () -> Void + let onQuickReviewLookAtEach: () -> Void var body: some View { if isCompact { @@ -118,19 +221,14 @@ struct DeduplicateReviewLanesBar: View { .accessibilityElement(children: .contain) .accessibilityIdentifier(AccessibilityIdentifiers.dedupeLanes) } - } else if lanes.safeText != nil || lanes.checkText != nil || lanes.doneText != nil { + } else if lanes.safeGroupCount > 0 || lanes.checkGroupCount > 0 || lanes.doneText != nil { VStack(spacing: 0) { - ViewThatFits(in: .horizontal) { - HStack(alignment: .center, spacing: DesignTokens.Spacing.lg) { - safeLane - checkLane - doneLane - } - VStack(alignment: .leading, spacing: DesignTokens.Spacing.sm) { - safeLane - checkLane - doneLane - } + VStack(alignment: .leading, spacing: DesignTokens.Spacing.sm) { + identicalLane + nearlyIdenticalLane + checkLane + doneLane + promiseLine } .padding(.horizontal, DesignTokens.Spacing.md) .padding(.vertical, DesignTokens.Spacing.sm) @@ -144,15 +242,15 @@ struct DeduplicateReviewLanesBar: View { } @ViewBuilder - private var safeLane: some View { - if let text = lanes.safeText { + private var identicalLane: some View { + if let text = lanes.identicalText(files: identicalFiles, bytes: identicalBytes) { HStack(spacing: DesignTokens.Spacing.sm) { Text(verbatim: text) .scaledFont(.label) .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) .fixedSize(horizontal: false, vertical: true) - Button("Accept All Safe") { - onAcceptSafe() + Button("Accept Identical Copies") { + onAcceptIdentical() } .buttonStyle(.borderedMicroDelight) .fixedSize() @@ -161,6 +259,24 @@ struct DeduplicateReviewLanesBar: View { } } + @ViewBuilder + private var nearlyIdenticalLane: some View { + if let text = lanes.nearlyIdenticalText { + HStack(spacing: DesignTokens.Spacing.sm) { + Text(verbatim: text) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .fixedSize(horizontal: false, vertical: true) + Button("Quick Review") { + onQuickReviewNearlyIdentical() + } + .buttonStyle(.borderedMicroDelight) + .fixedSize() + .accessibilityIdentifier(AccessibilityIdentifiers.dedupeLanesQuickReviewNearlyIdentical) + } + } + } + @ViewBuilder private var checkLane: some View { if let text = lanes.checkText { @@ -170,7 +286,7 @@ struct DeduplicateReviewLanesBar: View { .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) .fixedSize(horizontal: false, vertical: true) Button("Quick Review") { - onQuickReview() + onQuickReviewLookAtEach() } .buttonStyle(.borderedMicroDelight) .fixedSize() @@ -187,4 +303,95 @@ struct DeduplicateReviewLanesBar: View { .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) } } + + @ViewBuilder + private var promiseLine: some View { + if lanes.safeGroupCount > 0 || lanes.checkGroupCount > 0 { + Text(LocalizedStringKey(DeduplicateReviewLanes.promiseLine), bundle: .module) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } +} + +/// Copy and small decisions for the commit footer and Quick Review, kept out of +/// the views so they can be tested (FRX C-13). +enum DeduplicateFooterCopy { + static let acceptIdenticalHelp = "Keeps one file in every group of identical copies and marks the rest for the Trash" + + static func acceptIdenticalMenuTitle(groupCount: Int) -> String { + String(localized: "Accept Identical Copies (\(groupCount.formatted()))", bundle: .module) + } + + /// The lane the Options menu's Quick Review opens. The menu is the only way + /// in when the lanes bar is compact and shows no buttons, so it must reach + /// both lanes: nearly identical first while that lane has groups waiting + /// (it is the quick one), then the groups to look at one by one. + static func menuQuickReviewLane(nearlyIdenticalGroups: Int) -> DeduplicateReviewLane { + nearlyIdenticalGroups > 0 ? .nearlyIdentical : .lookAtEach + } + + /// The single place the footer, the lanes bar and the Options menu accept identical copies. + @MainActor + static func acceptIdenticalCopies(in store: DeduplicateSessionStore) { + store.acceptSuggestions(in: .identical) + } + + /// Reviewed groups whose every file is marked Delete are skipped by the planner. + static func fullyMarkedNotice(groupCount: Int) -> String? { + switch groupCount { + case ..<1: + return nil + case 1: + return String(localized: "1 group has every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in it to include it.", bundle: .module) + default: + return String(localized: "\(groupCount.formatted()) groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them.", bundle: .module) + } + } + + /// The notice as a suffix of a confirmation dialog's message. + static func dialogMessage(_ message: String, fullyMarkedGroupCount: Int) -> String { + guard let notice = fullyMarkedNotice(groupCount: fullyMarkedGroupCount) else { return message } + return message + " " + notice + } + + /// Whether the footer says the free allowance is short of the reviewed plan. + /// `remaining` is nil when the allowance does not apply or is not known. + static func showsFreeRemoval(remaining: Int?, reviewedCount: Int) -> Bool { + guard let remaining else { return false } + return reviewedCount > remaining + } + + static func freeRemovalLine(remaining: Int, reviewedCount: Int) -> String { + if remaining <= 0 { + return String(localized: "Your free removals are used up.", bundle: .module) + } + let removable = remaining == 1 + ? String(localized: "1 duplicate", bundle: .module) + : String(localized: "\(remaining.formatted()) duplicates", bundle: .module) + return String(localized: "You can remove \(removable) free. Your reviewed groups hold \(reviewedCount.formatted()).", bundle: .module) + } + + static func freeBatchCommitTitle(fileCount: Int) -> String { + fileCount == 1 + ? String(localized: "Move 1 File to Trash Free", bundle: .module) + : String(localized: "Move \(fileCount.formatted()) Files to Trash Free", bundle: .module) + } + + 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) + } + + /// The count both confirmation dialogs show: the frozen plan when one is + /// prepared (a free batch), otherwise what the reviewed groups would move. + @MainActor + static func confirmationFileCount(for store: DeduplicateSessionStore) -> Int { + store.preparedCommitCount ?? store.reviewedDeletionPlan().count + } } diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift index e94c62af..0cf9b86d 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift @@ -12,6 +12,8 @@ struct DeduplicateView: View { @ObservedObject var appState: AppState @ObservedObject private var sessionStore: DeduplicateSessionStore @ObservedObject private var preferencesStore: PreferencesStore + /// Read for the free removal footer; the footer must redraw when the allowance resolves. + @ObservedObject private var trialStatusStore: TrialStatusStore @StateObject private var thumbnailLoader = DedupeThumbnailLoader() @Environment(\.undoManager) private var undoManager @State private var showingComparisonInspector = false @@ -23,6 +25,10 @@ struct DeduplicateView: View { @State private var showingCommitConfirmation = false @State private var showingCommitReviewedConfirmation = false @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 @@ -35,6 +41,7 @@ struct DeduplicateView: View { self.appState = appState self._sessionStore = ObservedObject(wrappedValue: appState.deduplicateSessionStore) self._preferencesStore = ObservedObject(wrappedValue: appState.preferencesStore) + self._trialStatusStore = ObservedObject(wrappedValue: appState.trialStatusStore) } var body: some View { @@ -356,15 +363,19 @@ struct DeduplicateView: View { GeometryReader { geometry in let lanes = DeduplicateReviewLanes( clusters: sessionStore.clusters, - reviewedIDs: Set(sessionStore.reviewedClusters.map(\.id)) + reviewedIDs: Set(sessionStore.reviewedClusters.map(\.id)), + lane: sessionStore.lane(for:) ) VStack(spacing: 0) { restoredReviewBanner DeduplicateReviewLanesBar( lanes: lanes, + identicalFiles: sessionStore.laneSummaries[.identical]?.files ?? 0, + identicalBytes: sessionStore.laneSummaries[.identical]?.bytes ?? 0, isCompact: DeduplicateReviewLayout.mode(forWidth: geometry.size.width) == .compact, - onAcceptSafe: { sessionStore.acceptAllSuggestions() }, - onQuickReview: { showingRapidTriage = true } + onAcceptIdentical: { DeduplicateFooterCopy.acceptIdenticalCopies(in: sessionStore) }, + onQuickReviewNearlyIdentical: { openQuickReview(.nearlyIdentical) }, + onQuickReviewLookAtEach: { openQuickReview(.lookAtEach) } ) reviewBody(for: geometry.size) .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -516,6 +527,9 @@ struct DeduplicateView: View { let reviewedCount = sessionStore.reviewedClusters.count let unreviewedCount = max(0, sessionStore.clusters.count - reviewedCount) + let confirmationCount = DeduplicateFooterCopy.confirmationFileCount(for: sessionStore) + let fullyMarkedCount = sessionStore.fullyMarkedClusterIDs.count + let freeRemaining = dedupeAllowanceRemaining return VStack(alignment: .leading, spacing: 10) { TrustProofSurface(items: TrustProofModel.deduplicateSafetySummary( @@ -528,6 +542,13 @@ struct DeduplicateView: View { Divider() .foregroundStyle(DesignTokens.ColorSystem.hairline) + if let freeRemaining, DeduplicateFooterCopy.showsFreeRemoval(remaining: freeRemaining, reviewedCount: toDelete) { + Text(DeduplicateFooterCopy.freeRemovalLine(remaining: freeRemaining, reviewedCount: toDelete)) + .font(.callout) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .fixedSize(horizontal: false, vertical: true) + } + ViewThatFits(in: .horizontal) { commitFooterWide(toDelete: toDelete, bytes: bytes, hardDelete: hardDelete, editedVersionsKept: editedVersionsKept) commitFooterMedium(toDelete: toDelete, bytes: bytes, hardDelete: hardDelete, editedVersionsKept: editedVersionsKept) @@ -539,10 +560,16 @@ struct DeduplicateView: View { .padding(DesignTokens.Spacing.md) .frame(maxWidth: .infinity) .background(DesignTokens.ColorSystem.panel) + .onChange(of: sessionStore.wantsFreeBatchConfirmation) { _, _ in + handleFreeBatchConfirmationRequest() + } + .onAppear { + handleFreeBatchConfirmationRequest() + } .confirmationDialog( - toDelete == 1 + confirmationCount == 1 ? String(localized: "Move 1 file to Trash?", bundle: .module) - : String(localized: "Move \(String(toDelete)) files to Trash?", bundle: .module), + : String(localized: "Move \(String(confirmationCount)) files to Trash?", bundle: .module), isPresented: $showingCommitConfirmation ) { Button("Move to Trash", role: .destructive) { @@ -550,11 +577,15 @@ struct DeduplicateView: View { } Button("Cancel", role: .cancel) { sessionStore.discardPreparedCommitPlan() + freeBatchDeferredCount = nil } } message: { - Text(Self.trashCommitMessage( - byteCount: sessionStore.preparedCommitPlan?.totalBytes ?? bytes, - availableCapacity: deduplicateVolumeAvailableCapacity + Text(DeduplicateFooterCopy.dialogMessage( + Self.trashCommitMessage( + byteCount: sessionStore.preparedCommitPlan?.totalBytes ?? bytes, + availableCapacity: deduplicateVolumeAvailableCapacity + ), + fullyMarkedGroupCount: fullyMarkedCount )) } .confirmationDialog( @@ -566,18 +597,63 @@ struct DeduplicateView: View { } Button("Cancel", role: .cancel) { sessionStore.discardPreparedCommitPlan() + freeBatchDeferredCount = nil } } message: { - Text(String(localized: "Only groups you have fully reviewed will be affected. Unreviewed groups stay untouched. ", bundle: .module) + Self.trashCommitMessage( - byteCount: sessionStore.preparedCommitPlan?.totalBytes ?? bytes, - availableCapacity: deduplicateVolumeAvailableCapacity + Text(DeduplicateFooterCopy.dialogMessage( + String(localized: "Only groups you have fully reviewed will be affected. Unreviewed groups stay untouched. ", bundle: .module) + Self.trashCommitMessage( + byteCount: sessionStore.preparedCommitPlan?.totalBytes ?? bytes, + availableCapacity: deduplicateVolumeAvailableCapacity + ), + fullyMarkedGroupCount: fullyMarkedCount )) } } + /// Free removals left on the dedupe meter; nil when the allowance does not apply or is not known. + private var dedupeAllowanceRemaining: Int? { + TrialRemaining.value( + status: trialStatusStore.status, + meter: .dedupe, + isAppStoreChannel: appState.isAppStoreChannel + ) + } + + /// The free removal batch and the allowance it was cut from, when the reviewed + /// plan is larger than what is left and a whole-group batch fits. + private func freeBatchFooterOffer(toDelete: Int) -> (remaining: Int, batch: FreeDedupeBatch)? { + guard let remaining = dedupeAllowanceRemaining, + DeduplicateFooterCopy.showsFreeRemoval(remaining: remaining, reviewedCount: toDelete), + let batch = sessionStore.freeBatchOffer(remaining: remaining) else { return nil } + return (remaining, batch) + } + + /// 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. + 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 + showingCommitConfirmation = true + } + + /// The unlock sheet's "Move … Free" asks the store for a confirmation; the dialog opens here. + private func handleFreeBatchConfirmationRequest() { + guard sessionStore.wantsFreeBatchConfirmation else { return } + sessionStore.wantsFreeBatchConfirmation = false + guard let remaining = dedupeAllowanceRemaining else { return } + openFreeBatchConfirmation(remaining: remaining) + } + + private func openQuickReview(_ lane: DeduplicateReviewLane) { + quickReviewLane = lane + showingRapidTriage = true + } + private var reviewedCommitDialogTitle: String { - let plan = sessionStore.preparedCommitPlan ?? sessionStore.reviewedDeletionPlan() - let count = plan.count + let count = DeduplicateFooterCopy.confirmationFileCount(for: sessionStore) let reviewed = sessionStore.reviewedClusters.count if count == 0 { return String(localized: "No deletions in reviewed groups", bundle: .module) @@ -651,6 +727,12 @@ struct DeduplicateView: View { .font(.caption) .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) .lineLimit(1) + if let notice = DeduplicateFooterCopy.fullyMarkedNotice(groupCount: sessionStore.fullyMarkedClusterIDs.count) { + Text(notice) + .font(.caption) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .fixedSize(horizontal: false, vertical: true) + } } } @@ -659,12 +741,11 @@ struct DeduplicateView: View { toDelete: Int, density: CommitFooterButtonDensity ) -> some View { - let highCount = sessionStore.triageBuckets[.high]?.count ?? 0 switch density { case .full: VStack(alignment: .trailing, spacing: DesignTokens.Spacing.xs) { HStack(spacing: DesignTokens.Spacing.sm) { - commitFooterSecondaryButtons(highCount: highCount, density: density) + commitFooterSecondaryButtons(density: density) } .fixedSize(horizontal: true, vertical: false) @@ -677,7 +758,7 @@ struct DeduplicateView: View { case .compact: VStack(alignment: .trailing, spacing: DesignTokens.Spacing.xs) { HStack(spacing: DesignTokens.Spacing.xs) { - commitFooterSecondaryButtons(highCount: highCount, density: density) + commitFooterSecondaryButtons(density: density) } .fixedSize(horizontal: true, vertical: false) @@ -691,7 +772,6 @@ struct DeduplicateView: View { @ViewBuilder private func commitFooterSecondaryButtons( - highCount: Int, density: CommitFooterButtonDensity ) -> some View { Menu { @@ -708,18 +788,21 @@ struct DeduplicateView: View { Divider() Button("Quick Review") { - showingRapidTriage = true + openQuickReview(DeduplicateFooterCopy.menuQuickReviewLane( + nearlyIdenticalGroups: sessionStore.laneSummaries[.nearlyIdentical]?.groups ?? 0 + )) } .accessibilityIdentifier(AccessibilityIdentifiers.dedupeRapidTriageButton) - if highCount > 0 { - Button("Accept All Safe (\(highCount))") { - sessionStore.acceptAllHighConfidence() + let identicalGroups = sessionStore.laneSummaries[.identical]?.groups ?? 0 + if identicalGroups > 0 { + Button(DeduplicateFooterCopy.acceptIdenticalMenuTitle(groupCount: identicalGroups)) { + DeduplicateFooterCopy.acceptIdenticalCopies(in: sessionStore) } .keyboardShortcut("h", modifiers: [.command, .shift]) - .accessibilityLabel("Accept all safe groups") + .accessibilityLabel("Accept identical copies") .accessibilityIdentifier(AccessibilityIdentifiers.dedupeAcceptHighConfidenceButton) - .accessibilityHint("Accepts the suggestion for every safe group") + .accessibilityHint(Text(LocalizedStringKey(DeduplicateFooterCopy.acceptIdenticalHelp), bundle: .module)) .popoverTip(AcceptSafeSuggestionsTip(), arrowEdge: .bottom) } @@ -730,6 +813,7 @@ 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) @@ -743,10 +827,16 @@ struct DeduplicateView: View { hint: "Change folder, adjust settings, quick review, or commit reviewed duplicate groups." ) .sheet(isPresented: $showingRapidTriage) { - let reviewClusters = sessionStore.clusters.filter { !DeduplicationPlanner.isAutomaticCommitEligible($0) } + let reviewClusters = QuickReviewScope.clusters( + in: quickReviewLane, + from: sessionStore.clusters, + reviewedIDs: sessionStore.approvedClusterIDs, + laneOf: sessionStore.lane(for:) + ) RapidTriageView( sessionStore: sessionStore, thumbnailLoader: thumbnailLoader, + lane: quickReviewLane, clustersToReview: reviewClusters ) } @@ -758,33 +848,55 @@ struct DeduplicateView: View { density: CommitFooterButtonDensity ) -> some View { Button(density.acceptAllTitle) { - sessionStore.acceptAllSuggestions() + DeduplicateFooterCopy.acceptIdenticalCopies(in: sessionStore) } .keyboardShortcut(.return, modifiers: [.command, .shift]) .buttonStyle(.borderedMicroDelight) .fixedSize() - .accessibilityLabel("Accept all safe groups") + .help(Text(LocalizedStringKey(DeduplicateFooterCopy.acceptIdenticalHelp), bundle: .module)) + .accessibilityLabel("Accept identical copies") .accessibilityIdentifier(AccessibilityIdentifiers.dedupeAcceptAllSuggestionsButton) - .accessibilityHint("Keeps the suggested file in every safe group and marks the rest for the Trash") + .accessibilityHint(Text(LocalizedStringKey(DeduplicateFooterCopy.acceptIdenticalHelp), bundle: .module)) Spacer().frame(width: DesignTokens.Spacing.lg) - Button(density.commitTitle(fileCount: toDelete), role: .destructive) { - sessionStore.prepareReviewedCommitPlan() - showingCommitConfirmation = true + if let free = freeBatchFooterOffer(toDelete: toDelete) { + Button(DeduplicateFooterCopy.unlockAllTitle(count: toDelete)) { + appState.requestUnlockForDuplicates(requested: toDelete, remaining: free.remaining) + } + .buttonStyle(.borderedMicroDelight) + .fixedSize() + .disabled(sessionStore.status == .committing) + .accessibilityIdentifier(AccessibilityIdentifiers.dedupeUnlockAll) + + Button(DeduplicateFooterCopy.freeBatchCommitTitle(fileCount: free.batch.plan.count), role: .destructive) { + openFreeBatchConfirmation(remaining: free.remaining) + } + .keyboardShortcut(.return, modifiers: .command) + .buttonStyle(.prominentMicroDelight(role: .destructive)) + .fixedSize() + .disabled(sessionStore.status == .committing) + .accessibilityIdentifier(AccessibilityIdentifiers.dedupeFreeBatchCommit) + .accessibilityHint("Moves the files from whole groups to the Trash after confirmation") + } else { + Button(density.commitTitle(fileCount: toDelete), role: .destructive) { + sessionStore.prepareReviewedCommitPlan() + freeBatchDeferredCount = nil + showingCommitConfirmation = true + } + .keyboardShortcut(.return, modifiers: .command) + .buttonStyle(.prominentMicroDelight(role: .destructive)) + .fixedSize() + .disabled(toDelete == 0 || sessionStore.status == .committing) + .accessibilityIdentifier(AccessibilityIdentifiers.dedupeCommitButton) + .accessibilityHint("Moves the selected files to the Trash after confirmation") } - .keyboardShortcut(.return, modifiers: .command) - .buttonStyle(.prominentMicroDelight(role: .destructive)) - .fixedSize() - .disabled(toDelete == 0 || sessionStore.status == .committing) - .accessibilityIdentifier(AccessibilityIdentifiers.dedupeCommitButton) - .accessibilityHint("Moves the selected files to the Trash after confirmation") } // MARK: - Completed private var completedView: some View { - let copy = Self.completedStatusCopy(for: sessionStore.commitSummary) + let copy = Self.completedStatusCopy(for: sessionStore.commitSummary, deferredFileCount: freeBatchDeferredCount) return DeduplicateStatusView( style: .success, title: "Deduplicate complete", @@ -1122,7 +1234,7 @@ extension DeduplicateView { return String(localized: "≈ \(formattedBytes) recoverable", bundle: .module) } - static func completedStatusCopy(for summary: DeduplicateCommitSummary?) -> DeduplicateStatusCopy { + static func completedStatusCopy(for summary: DeduplicateCommitSummary?, deferredFileCount: Int? = nil) -> DeduplicateStatusCopy { guard let summary else { return DeduplicateStatusCopy(message: nil, warning: nil) } @@ -1133,8 +1245,11 @@ extension DeduplicateView { let failed = summary.failedCount == 1 ? String(localized: "1 item failed — see History for details.", bundle: .module) : String(localized: "\(summary.failedCount) items failed — see History for details.", bundle: .module) + let recovered = String(localized: "\(moved) · \(statusByteCountFormatter.string(fromByteCount: summary.bytesReclaimed)) recoverable", bundle: .module) return DeduplicateStatusCopy( - message: String(localized: "\(moved) · \(statusByteCountFormatter.string(fromByteCount: summary.bytesReclaimed)) recoverable", bundle: .module), + message: (deferredFileCount ?? 0) > 0 + ? recovered + "\n" + DeduplicateFooterCopy.waitingLine(deferredFileCount: deferredFileCount ?? 0) + : recovered, warning: summary.failedCount > 0 ? failed : nil @@ -1214,8 +1329,8 @@ enum CommitFooterButtonDensity { var acceptAllTitle: String { switch self { - case .full: return String(localized: "Accept All Safe", bundle: .module) - case .compact: return String(localized: "Accept Safe", bundle: .module) + case .full: return String(localized: "Accept Identical Copies", bundle: .module) + case .compact: return String(localized: "Accept Identical", bundle: .module) } } diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift index ad105b6b..7162b67f 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift @@ -3,6 +3,31 @@ import ChronoframeAppCore #endif import SwiftUI +/// Which groups Quick Review walks through, and when it offers to accept the rest. +/// Pure, so the rules are tested without a view (FRX C-13). +enum QuickReviewScope { + /// The unreviewed groups of one lane, in review order. + static func clusters( + in lane: DeduplicateReviewLane, + from clusters: [DuplicateCluster], + reviewedIDs: Set, + laneOf: (DuplicateCluster) -> DeduplicateReviewLane + ) -> [DuplicateCluster] { + clusters.filter { !reviewedIDs.contains($0.id) && laneOf($0) == lane } + } + + /// The number on "Accept the Rest": only for nearly identical groups, only once + /// the person has passed at least one group, and only while groups remain. + static func acceptTheRestCount(lane: DeduplicateReviewLane, currentIndex: Int, remainingInLane: Int) -> Int? { + guard lane == .nearlyIdentical, currentIndex >= 1, remainingInLane > 0 else { return nil } + return remainingInLane + } + + static func acceptTheRestTitle(remaining: Int) -> String { + String(localized: "Accept the Rest (\(remaining.formatted()))", bundle: .module) + } +} + struct RapidTriageView: View { @ObservedObject var sessionStore: DeduplicateSessionStore @ObservedObject var thumbnailLoader: DedupeThumbnailLoader @@ -12,7 +37,23 @@ struct RapidTriageView: View { @Environment(\.dismiss) private var dismiss @Environment(\.accessibilityReduceMotion) private var reduceMotion - var clustersToReview: [DuplicateCluster] + let lane: DeduplicateReviewLane + /// The groups to walk through, fixed when Quick Review opens: accepting a + /// group takes it out of the store's unreviewed set, and the list under the + /// person's position must not shift. + @State private var clustersToReview: [DuplicateCluster] + + init( + sessionStore: DeduplicateSessionStore, + thumbnailLoader: DedupeThumbnailLoader, + lane: DeduplicateReviewLane, + clustersToReview: [DuplicateCluster] + ) { + self.sessionStore = sessionStore + self.thumbnailLoader = thumbnailLoader + self.lane = lane + self._clustersToReview = State(initialValue: clustersToReview) + } private var currentCluster: DuplicateCluster? { guard currentIndex < clustersToReview.count else { return nil } @@ -61,7 +102,7 @@ struct RapidTriageView: View { private var header: some View { VStack(spacing: 6) { HStack { - Text("Rapid Triage") + Text("Quick Review") .font(.headline) Spacer() Text("\(currentIndex) of \(clustersToReview.count) reviewed") @@ -240,6 +281,13 @@ struct RapidTriageView: View { .buttonStyle(.borderedProminent) .keyboardShortcut(.return, modifiers: []) + if currentCluster != nil, let remaining = acceptTheRestCount { + Button(QuickReviewScope.acceptTheRestTitle(remaining: remaining)) { + acceptTheRest() + } + .accessibilityIdentifier(AccessibilityIdentifiers.quickReviewAcceptRest) + } + // Stacked `.keyboardShortcut` modifiers on a single Button // collapse to the last one wins, so the right-arrow binding // used to be silently dropped. Use an invisible second @@ -280,6 +328,23 @@ struct RapidTriageView: View { advance() } + /// Groups still unreviewed in this lane: exactly what "Accept the Rest" accepts. + private var acceptTheRestCount: Int? { + QuickReviewScope.acceptTheRestCount( + lane: lane, + currentIndex: currentIndex, + remainingInLane: sessionStore.laneSummaries[lane]?.groups ?? 0 + ) + } + + /// Accepts the suggestion for every group still unreviewed in the nearly identical + /// lane, then shows the completion screen. Nothing is moved to the Trash here. + private func acceptTheRest() { + sessionStore.acceptSuggestions(in: .nearlyIdentical) + dragOffset = .zero + currentIndex = clustersToReview.count + } + private func skipCurrent() { advance() } diff --git a/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift b/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift index c17de2cf..95fff7b2 100644 --- a/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift +++ b/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift @@ -31,6 +31,10 @@ struct UnlockSheet: View { /// Run the batch shown above the buttons. The caller re-runs preflight and /// planning, then copies only the files this sheet listed. var onRunFreeTestBatch: () -> Void = {} + /// The free removal of whole duplicate groups, when a dedupe refusal has one (FRX C-13). + var offeredDedupeBatch: FreeDedupeBatch? + /// Closes the sheet and asks the review screen to confirm the removal; moves nothing itself. + var onRunFreeDedupeBatch: () -> Void = {} let onDismiss: () -> Void /// Local, because `loadProduct()` publishes only its result. "Still @@ -45,7 +49,8 @@ struct UnlockSheet: View { isLoadingProduct: isLoadingProduct, isPurchasing: entitlementStore.isPurchasing, isRestoring: entitlementStore.isRestoring, - offeredBatch: offeredBatch + offeredBatch: offeredBatch, + offeredDedupeBatch: offeredDedupeBatch.map { (fileCount: $0.plan.count, deferredCount: $0.deferredFileCount) } ) } @@ -55,8 +60,17 @@ struct UnlockSheet: View { model.actions.first { if case .runFreeTestBatch = $0 { return true } else { return false } } } + private var dedupeBatchAction: UnlockSheetAction? { + model.actions.first { if case .runFreeDedupeBatch = $0 { return true } else { return false } } + } + private var buttonRowActions: [UnlockSheetAction] { - model.actions.filter { if case .runFreeTestBatch = $0 { return false } else { return true } } + model.actions.filter { + switch $0 { + case .runFreeTestBatch, .runFreeDedupeBatch: return false + default: return true + } + } } /// The one-line purchase terms the model chose for this refusal, if any. @@ -94,6 +108,9 @@ struct UnlockSheet: View { if let batchAction, let detail = model.batchDetail, let batch = offeredBatch { Divider() freeTestBatchOffer(action: batchAction, detail: detail, batch: batch) + } else if let dedupeBatchAction, let detail = model.batchDetail { + Divider() + freeDedupeBatchOffer(action: dedupeBatchAction, detail: detail) } Divider() @@ -171,6 +188,10 @@ struct UnlockSheet: View { // Rendered by `freeTestBatchOffer`, which shows the files first. EmptyView() + case .runFreeDedupeBatch: + // Rendered by `freeDedupeBatchOffer`, above the buttons. + EmptyView() + case .dismiss: Button("Not Now", role: .cancel) { onDismiss() @@ -225,6 +246,25 @@ struct UnlockSheet: View { } } + /// The free removal. The groups are listed on the review screen, and its usual + /// confirmation comes before anything is moved; pressing this only goes there. + @ViewBuilder + private func freeDedupeBatchOffer(action: UnlockSheetAction, detail: String) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(detail) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .fixedSize(horizontal: false, vertical: true) + + if case let .runFreeDedupeBatch(fileCount, _) = action { + Button(DeduplicateFooterCopy.freeBatchCommitTitle(fileCount: fileCount)) { + onRunFreeDedupeBatch() + } + .disabled(!model.isBatchEnabled) + .accessibilityIdentifier("unlockSheet.runDedupeBatch") + } + } + } + func purchase() async { onBeforeUnlock() await entitlementStore.purchase() diff --git a/ui/Sources/ChronoframeApp/Views/RootSplitView.swift b/ui/Sources/ChronoframeApp/Views/RootSplitView.swift index 0c3f51db..3230ef34 100644 --- a/ui/Sources/ChronoframeApp/Views/RootSplitView.swift +++ b/ui/Sources/ChronoframeApp/Views/RootSplitView.swift @@ -117,6 +117,8 @@ struct RootSplitView: View { offeredBatch: appState.offeredFreeTestBatch, onUnlocked: { Task { await appState.retryAfterUnlock() } }, onRunFreeTestBatch: { Task { await appState.runOfferedFreeTestBatch() } }, + offeredDedupeBatch: appState.offeredFreeDedupeBatch, + onRunFreeDedupeBatch: { appState.runOfferedFreeDedupeBatch() }, onDismiss: { appState.dismissUnlockSheet() } ) } diff --git a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings index 80f542cf..f0936d09 100644 --- a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings +++ b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings @@ -390,6 +390,40 @@ } } }, + "Accept Identical Copies": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Identische Kopien akzeptieren" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Accept Identical Copies" + } + } + } + }, + "Accept Nearly Identical": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Nahezu identische akzeptieren" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Accept Nearly Identical" + } + } + } + }, "Accept Suggestion": { "extractionState": "manual", "localizations": { @@ -2297,6 +2331,23 @@ } } }, + "Moves %@ from whole groups to the Trash now and leaves %@ for later.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Legt jetzt %1$@ aus ganzen Gruppen in den Papierkorb und lässt %2$@ für später übrig." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Moves %@ from whole groups to the Trash now and leaves %@ for later." + } + } + } + }, "Needs folders": { "extractionState": "manual", "localizations": { diff --git a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift index 6cddc18f..6470ad8a 100644 --- a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift +++ b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift @@ -26,6 +26,9 @@ public enum UnlockSheetAction: Equatable, Sendable { /// (free-trial step 5, T15). Carries the counts so the button can name /// them; the sheet also shows the exact files before this runs anything. case runFreeTestBatch(fileCount: Int, deferredCount: Int) + /// Move only whole duplicate groups the remaining allowance covers, instead of + /// unlocking (FRX C-13). The review screen shows its usual confirmation first. + case runFreeDedupeBatch(fileCount: Int, deferredCount: Int) case dismiss } @@ -87,13 +90,16 @@ public struct UnlockSheetModel: Equatable, Sendable { /// which is the difference between a spinner and a Retry button. /// - offeredBatch: a smaller run the remaining allowance covers, when the /// engine could honestly propose one. + /// - offeredDedupeBatch: the free removal of whole duplicate groups, offered + /// only against a spent dedupe allowance (FRX C-13). public static func make( refusal: TrialAuthorizationRefusal? = nil, product: StoreProductInfo?, isLoadingProduct: Bool, isPurchasing: Bool, isRestoring: Bool, - offeredBatch: FreeTestBatch? = nil + offeredBatch: FreeTestBatch? = nil, + offeredDedupeBatch: (fileCount: Int, deferredCount: Int)? = nil ) -> UnlockSheetModel { let busy = isPurchasing || isRestoring let batch = Self.offerableBatch(offeredBatch, refusal: refusal) @@ -107,12 +113,16 @@ public struct UnlockSheetModel: Equatable, Sendable { ?? Self.title(for: refusal) let message = requestedMonth.map { Self.requestedMonthMessage(includedCount: $0.batch.includedCount) } ?? Self.message(for: refusal) + let dedupeBatch = Self.offerableDedupeBatch(offeredDedupeBatch, refusal: refusal) let batchAction: [UnlockSheetAction] = batch.map { [.runFreeTestBatch(fileCount: $0.includedCount, deferredCount: $0.deferredCount)] + } ?? dedupeBatch.map { + [.runFreeDedupeBatch(fileCount: $0.fileCount, deferredCount: $0.deferredCount)] } ?? [] let leadingBatchAction = requestedMonth == nil ? [] : batchAction let trailingBatchAction = requestedMonth == nil ? batchAction : [] let batchDetail = batch.flatMap { $0.coversWholePlan ? nil : Self.batchDetail($0) } + ?? dedupeBatch.map(Self.dedupeBatchDetail) let purchaseTermsLine = Self.purchaseTermsLine(for: refusal) // Never offer a purchase this customer may not need. `purchaseUnconfirmed` @@ -197,6 +207,24 @@ public struct UnlockSheetModel: Equatable, Sendable { return batch } + /// The dedupe batch is only offerable against a spent dedupe allowance, and only + /// when it removes something. An organize refusal never carries one. + private static func offerableDedupeBatch( + _ batch: (fileCount: Int, deferredCount: Int)?, + refusal: TrialAuthorizationRefusal? + ) -> (fileCount: Int, deferredCount: Int)? { + guard case let .allowanceSpent(details) = refusal, + details.meter == .dedupe, + let batch, + batch.fileCount > 0 else { return nil } + return batch + } + + private static func dedupeBatchDetail(_ batch: (fileCount: Int, deferredCount: Int)) -> String { + let files = CoreL10n.files(batch.fileCount) + return CoreL10n.text("Moves \(files) from whole groups to the Trash now and leaves \(batch.deferredCount.formatted()) for later.") + } + private static func batchDetail(_ batch: FreeTestBatch) -> String { let files = CoreL10n.files(batch.includedCount) if let monthKey = batch.monthKey { diff --git a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift index ef46014d..fd5922d2 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift @@ -4,6 +4,14 @@ import ChronoframeCore import Combine import Foundation +/// What is still waiting in one review lane: unreviewed groups, and the files +/// and bytes the planner would remove if the suggestions were accepted. +public struct DeduplicateLaneSummary: Equatable, Sendable { + public let groups: Int + public let files: Int + public let bytes: Int64 +} + @MainActor public final class DeduplicateSessionStore: ObservableObject { public enum Status: Sendable, Equatable { @@ -42,7 +50,11 @@ public final class DeduplicateSessionStore: ObservableObject { @Published public private(set) var preparedCommitPlan: DeduplicationPlan? @Published public private(set) var runHistory: [DeduplicateFolderHistoryRecord] @Published public var decisions: DedupeDecisions = DedupeDecisions() - @Published public var approvedClusterIDs: Set = [] + @Published public var approvedClusterIDs: Set = [] { + didSet { recomputeLaneSummaries() } + } + @Published public private(set) var laneSummaries: [DeduplicateReviewLane: DeduplicateLaneSummary] = [:] + @Published public var wantsFreeBatchConfirmation: Bool = false /// 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:)`. @@ -85,6 +97,16 @@ public final class DeduplicateSessionStore: ObservableObject { /// agree on which pair-as-unit toggles + similarity thresholds were /// in effect when the clusters were produced. private var lastScanConfiguration: DeduplicateConfiguration? + /// True while the prepared commit plan is a free removal batch. + private var preparedPlanIsFreeBatch = false + private var freeBatchOfferCache: ( + decisions: DedupeDecisions, + approvedClusterIDs: Set, + remaining: Int, + offer: FreeDedupeBatch? + )? + /// Counts planner runs behind `freeBatchOffer(remaining:)`; lets tests see the cache hold. + private(set) var freeBatchOfferComputationCount = 0 /// True while an `engine.revert(...)` stream is being consumed. /// `consumeCommit`'s `.complete` arm uses this to land in /// `.reverted` instead of `.completed`. @@ -178,11 +200,50 @@ public final class DeduplicateSessionStore: ObservableObject { public func prepareReviewedCommitPlan() -> DeduplicationPlan { let plan = reviewedDeletionPlan() preparedCommitPlan = plan + preparedPlanIsFreeBatch = false return plan } public func discardPreparedCommitPlan() { preparedCommitPlan = nil + preparedPlanIsFreeBatch = false + } + + /// File count of the frozen plan the confirmation dialog shows. + public var preparedCommitCount: Int? { + preparedCommitPlan?.count + } + + /// The free removal batch for the reviewed groups, or nil when the whole + /// reviewed plan fits in `remaining`. Cached: the footer asks on every render. + public func freeBatchOffer(remaining: Int) -> FreeDedupeBatch? { + guard let configuration = lastScanConfiguration else { return nil } + if let cache = freeBatchOfferCache, + cache.remaining == remaining, + cache.decisions == decisions, + cache.approvedClusterIDs == approvedClusterIDs { + return cache.offer + } + freeBatchOfferComputationCount += 1 + let offer = FreeDedupeBatchPlanner.batch( + decisions: decisions, + reviewedClusters: reviewedClusters, + configuration: configuration, + snapshot: summary?.scanSnapshot ?? DeduplicateScanSnapshot(), + limit: remaining + ) + freeBatchOfferCache = (decisions, approvedClusterIDs, remaining, offer) + return offer + } + + /// Freezes the free removal batch as the prepared commit plan. Nil, and no + /// change, when there is no offer. + @discardableResult + public func prepareFreeBatchCommitPlan(remaining: Int) -> DeduplicationPlan? { + guard let offer = freeBatchOffer(remaining: remaining) else { return nil } + preparedCommitPlan = offer.plan + preparedPlanIsFreeBatch = true + return offer.plan } /// Commits delete decisions for reviewed clusters only; unreviewed clusters @@ -505,6 +566,51 @@ public final class DeduplicateSessionStore: ObservableObject { 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. + public func acceptSuggestions(in lane: DeduplicateReviewLane) { + let actionName: String + switch lane { + case .lookAtEach: + return + case .identical: + actionName = String(localized: "Accept Identical Copies", bundle: Bundle.module) + case .nearlyIdentical: + actionName = String(localized: "Accept Nearly Identical", bundle: Bundle.module) + } + let laneClusters = clusters.filter { + DeduplicationPlanner.isAutomaticCommitEligible($0) + && !approvedClusterIDs.contains($0.id) + && self.lane(for: $0) == lane + } + guard !laneClusters.isEmpty else { return } + let oldDecisions = decisions + let oldApproved = approvedClusterIDs + var byPath = decisions.byPath + for (path, decision) in suggestedDecisions(for: laneClusters).byPath { + byPath[path] = decision + } + decisions = DedupeDecisions(byPath: byPath) + approvedClusterIDs.formUnion(laneClusters.map(\.id)) + registerUndo( + oldDecisions: oldDecisions, + oldApproved: oldApproved, + actionName: actionName + ) + scheduleSave() + } + + /// Reviewed groups in which every member is marked Delete. + public var fullyMarkedClusterIDs: Set { + Set(reviewedClusters.filter { cluster in + !cluster.members.isEmpty && cluster.members.allSatisfy { decisions.byPath[$0.path] == .delete } + }.map(\.id)) + } + // MARK: - Confidence Triage public var triageBuckets: [ConfidenceLevel: [DuplicateCluster]] { @@ -760,9 +866,11 @@ public final class DeduplicateSessionStore: ObservableObject { summary: summary, completedAt: Date() ) - reviewSnapshotStore.remove(folderPath: destinationPath) - restoredReview = nil - savedReviewForCurrentFolder = nil + if !preparedPlanIsFreeBatch { + reviewSnapshotStore.remove(folderPath: destinationPath) + restoredReview = nil + savedReviewForCurrentFolder = nil + } } status = isHandlingRevert ? .reverted : .completed isHandlingRevert = false @@ -772,6 +880,30 @@ public final class DeduplicateSessionStore: ObservableObject { } } + private func recomputeLaneSummaries() { + guard let configuration = lastScanConfiguration else { + laneSummaries = [:] + return + } + let snapshot = summary?.scanSnapshot ?? DeduplicateScanSnapshot() + var unreviewedByLane: [DeduplicateReviewLane: [DuplicateCluster]] = [:] + for cluster in clusters where !approvedClusterIDs.contains(cluster.id) { + unreviewedByLane[DeduplicateReviewLane.lane(for: cluster, snapshot: snapshot), default: []].append(cluster) + } + var result: [DeduplicateReviewLane: DeduplicateLaneSummary] = [:] + for lane in DeduplicateReviewLane.allCases { + let laneClusters = unreviewedByLane[lane] ?? [] + let plan = DeduplicationPlanner.plan( + decisions: suggestedDecisions(for: laneClusters), + clusters: laneClusters, + configuration: configuration, + snapshot: snapshot + ) + result[lane] = DeduplicateLaneSummary(groups: laneClusters.count, files: plan.count, bytes: plan.totalBytes) + } + laneSummaries = result + } + private func applySuggestionsToDecisions() -> DedupeDecisions { var byPath = decisions.byPath for (path, decision) in automaticDecisions(for: clusters).byPath where byPath[path] == nil { diff --git a/ui/Sources/ChronoframeCore/DeduplicateReviewLane.swift b/ui/Sources/ChronoframeCore/DeduplicateReviewLane.swift new file mode 100644 index 00000000..eea89fea --- /dev/null +++ b/ui/Sources/ChronoframeCore/DeduplicateReviewLane.swift @@ -0,0 +1,38 @@ +import Foundation + +/// Which review lane a duplicate group belongs to. Pure and read-only: it +/// classifies a cluster against an immutable scan snapshot and never changes +/// what `DeduplicationPlanner` would delete. +public enum DeduplicateReviewLane: String, Sendable, CaseIterable { + /// Every member is the same file, byte for byte. + case identical + /// Auto-eligible, but the files differ. + case nearlyIdentical + /// Not auto-eligible. + case lookAtEach + + public static func lane(for cluster: DuplicateCluster, snapshot: DeduplicateScanSnapshot) -> DeduplicateReviewLane { + guard DeduplicationPlanner.isAutomaticCommitEligible(cluster) else { + return .lookAtEach + } + guard cluster.kind == .exactDuplicate else { + return .nearlyIdentical + } + // Fail closed: an exact group counts as identical only when the scan + // recorded an identity for every member and all of them match. + guard cluster.members.count >= 2 else { + return .lookAtEach + } + var firstIdentity: FileIdentity? + for member in cluster.members { + guard let identity = snapshot.identitiesByPath[member.path] else { + return .lookAtEach + } + if let firstIdentity, firstIdentity != identity { + return .lookAtEach + } + firstIdentity = identity + } + return .identical + } +} diff --git a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift new file mode 100644 index 00000000..43b7a48c --- /dev/null +++ b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift @@ -0,0 +1,92 @@ +import Foundation + +/// A whole-group slice of a reviewed removal plan that fits the free dedupe +/// allowance. `plan` is always a `DeduplicationPlanner.plan` result. +public struct FreeDedupeBatch: Sendable { + public let plan: DeduplicationPlan + public let includedClusterIDs: [UUID] + /// `fullPlan.count − plan.count`. + public let deferredFileCount: Int +} + +/// Chooses which reviewed groups can be removed free, then asks the planner +/// for the plan with every other group forced to Keep. Items are never +/// filtered or assembled by hand, so pair, sidecar and edited-variant rules +/// all still apply. +public enum FreeDedupeBatchPlanner { + public static func batch( + decisions: DedupeDecisions, + reviewedClusters: [DuplicateCluster], + configuration: DeduplicateConfiguration, + snapshot: DeduplicateScanSnapshot, + limit: Int + ) -> FreeDedupeBatch? { + // 1. The person's full reviewed plan. + let full = DeduplicationPlanner.plan( + decisions: decisions, + clusters: reviewedClusters, + configuration: configuration, + snapshot: snapshot + ) + guard limit > 0, full.count > limit else { return nil } + let fullIdentities = Dictionary( + full.items.map { ($0.path, $0.expectedIdentity) }, + uniquingKeysWith: { first, _ in first } + ) + + // 2. Identical groups first, then nearly identical, then the rest; + // review order is kept within a lane. + let lanes = reviewedClusters.map { DeduplicateReviewLane.lane(for: $0, snapshot: snapshot) } + var ordered: [DuplicateCluster] = [] + for lane in [DeduplicateReviewLane.identical, .nearlyIdentical, .lookAtEach] { + for (index, cluster) in reviewedClusters.enumerated() where lanes[index] == lane { + ordered.append(cluster) + } + } + + // 3 and 4. Grow the selection one group at a time. Forcing Keep is not + // monotone (pair Keep-wins can carry a Keep into another group and + // un-skip a group the all-Delete rail skipped), so a candidate is + // accepted only if it fits and deletes nothing the full plan does not. + var selected: Set = [] + var selectedOrder: [UUID] = [] + var accepted: DeduplicationPlan? + for cluster in ordered { + var trial = selected + trial.insert(cluster.id) + + var candidateDecisions = decisions + var byPath = decisions.byPath + for other in reviewedClusters where !trial.contains(other.id) { + for member in other.members { + byPath[member.path] = .keep + } + } + candidateDecisions.byPath = byPath + + let candidate = DeduplicationPlanner.plan( + decisions: candidateDecisions, + clusters: reviewedClusters, + configuration: configuration, + snapshot: snapshot + ) + let withinFullPlan = candidate.items.allSatisfy { item in + fullIdentities[item.path] == item.expectedIdentity + } + guard candidate.count <= limit, withinFullPlan else { break } + + accepted = candidate + selected = trial + selectedOrder.append(cluster.id) + } + + // 5. + guard let plan = accepted, !plan.items.isEmpty else { return nil } + let owners = Set(plan.items.map(\.owningClusterID)) + return FreeDedupeBatch( + plan: plan, + includedClusterIDs: selectedOrder.filter { owners.contains($0) }, + deferredFileCount: full.count - plan.count + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreDeduplicateReviewLaneTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreDeduplicateReviewLaneTests.swift new file mode 100644 index 00000000..4682c240 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreDeduplicateReviewLaneTests.swift @@ -0,0 +1,132 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +final class ChronoframeCoreDeduplicateReviewLaneTests: XCTestCase { + private let shared = FileIdentity(size: 4_000, digest: "shared-digest") + + func testIneligibleClusterIsLookAtEach() { + // Medium confidence is never auto-eligible, even when the cluster is + // exact and every identity matches. + let cluster = makeCluster(kind: .exactDuplicate, confidence: .medium, paths: ["/a/1.jpg", "/a/2.jpg"]) + let snapshot = DeduplicateScanSnapshot(identitiesByPath: [ + "/a/1.jpg": shared, + "/a/2.jpg": shared, + ]) + XCTAssertFalse(DeduplicationPlanner.isAutomaticCommitEligible(cluster)) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: snapshot), .lookAtEach) + + // A cluster with no annotation defaults to medium and is also ineligible. + let unannotated = DuplicateCluster( + kind: .exactDuplicate, + members: [candidate("/b/1.jpg"), candidate("/b/2.jpg")], + suggestedKeeperIDs: ["/b/1.jpg"], + bytesIfPruned: 0 + ) + XCTAssertEqual(DeduplicateReviewLane.lane(for: unannotated, snapshot: snapshot), .lookAtEach) + } + + // AGENTS-INVARIANT: 6 + func testExactClusterWithEqualIdentitiesIsIdentical() { + let cluster = makeCluster( + kind: .exactDuplicate, + confidence: .high, + paths: ["/a/1.jpg", "/a/2.jpg", "/a/3.jpg"] + ) + let snapshot = DeduplicateScanSnapshot(identitiesByPath: [ + "/a/1.jpg": shared, + "/a/2.jpg": shared, + "/a/3.jpg": shared, + ]) + XCTAssertTrue(DeduplicationPlanner.isAutomaticCommitEligible(cluster)) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: snapshot), .identical) + } + + func testExactClusterMissingAnIdentityFailsClosed() { + let cluster = makeCluster( + kind: .exactDuplicate, + confidence: .high, + paths: ["/a/1.jpg", "/a/2.jpg", "/a/3.jpg"] + ) + let snapshot = DeduplicateScanSnapshot(identitiesByPath: [ + "/a/1.jpg": shared, + "/a/2.jpg": shared, + ]) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: snapshot), .lookAtEach) + + let emptySnapshot = DeduplicateScanSnapshot() + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: emptySnapshot), .lookAtEach) + } + + func testExactClusterWithDifferingIdentitiesFailsClosed() { + let cluster = makeCluster(kind: .exactDuplicate, confidence: .high, paths: ["/a/1.jpg", "/a/2.jpg"]) + let differentDigest = DeduplicateScanSnapshot(identitiesByPath: [ + "/a/1.jpg": shared, + "/a/2.jpg": FileIdentity(size: 4_000, digest: "other-digest"), + ]) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: differentDigest), .lookAtEach) + + let differentSize = DeduplicateScanSnapshot(identitiesByPath: [ + "/a/1.jpg": shared, + "/a/2.jpg": FileIdentity(size: 4_001, digest: "shared-digest"), + ]) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: differentSize), .lookAtEach) + + // An exact cluster with a single member never counts as identical. + let single = makeCluster(kind: .exactDuplicate, confidence: .high, paths: ["/a/1.jpg"]) + let singleSnapshot = DeduplicateScanSnapshot(identitiesByPath: ["/a/1.jpg": shared]) + XCTAssertEqual(DeduplicateReviewLane.lane(for: single, snapshot: singleSnapshot), .lookAtEach) + } + + func testHighConfidenceNearDuplicateIsNearlyIdentical() { + // Equal identities do not matter for a non-exact cluster. + let snapshot = DeduplicateScanSnapshot(identitiesByPath: [ + "/a/1.jpg": shared, + "/a/2.jpg": shared, + ]) + for kind in [ClusterKind.nearDuplicate, .burst] { + let cluster = makeCluster(kind: kind, confidence: .high, paths: ["/a/1.jpg", "/a/2.jpg"]) + XCTAssertTrue(DeduplicationPlanner.isAutomaticCommitEligible(cluster)) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: snapshot), .nearlyIdentical, "\(kind)") + } + } + + // AGENTS-INVARIANT: 6 + func testNonExactVideoClusterIsLookAtEach() { + // A perceptual video cluster is never auto-eligible, even if an + // annotation bug marked it high confidence. + let cluster = makeCluster( + kind: .nearDuplicate, + confidence: .high, + paths: ["/v/1.mov", "/v/2.mov"], + mediaKind: .video + ) + let snapshot = DeduplicateScanSnapshot(identitiesByPath: [ + "/v/1.mov": shared, + "/v/2.mov": shared, + ]) + XCTAssertFalse(DeduplicationPlanner.isAutomaticCommitEligible(cluster)) + XCTAssertEqual(DeduplicateReviewLane.lane(for: cluster, snapshot: snapshot), .lookAtEach) + } + + // MARK: Fixtures + + private func candidate(_ path: String, mediaKind: MediaKind = .photo) -> PhotoCandidate { + PhotoCandidate(path: path, size: 4_000, modificationTime: 0, mediaKind: mediaKind) + } + + private func makeCluster( + kind: ClusterKind, + confidence: ConfidenceLevel, + paths: [String], + mediaKind: MediaKind = .photo + ) -> DuplicateCluster { + DuplicateCluster( + kind: kind, + members: paths.map { candidate($0, mediaKind: mediaKind) }, + suggestedKeeperIDs: [paths[0]], + bytesIfPruned: 0, + annotation: ClusterAnnotation(confidence: confidence, matchReason: MatchReason(kind: kind)) + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift new file mode 100644 index 00000000..2aafe4e7 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift @@ -0,0 +1,547 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { + + // MARK: Nil cases + + func testNilWhenWholePlanFits() { + var fixture = Fixture() + fixture.addGroup("a", deletes: 2, lane: .lookAtEach) + fixture.addGroup("b", deletes: 1, lane: .lookAtEach) + let full = fixture.fullPlan() + XCTAssertEqual(full.count, 3) + + XCTAssertNil(fixture.batch(limit: 3), "a limit equal to the whole plan needs no batch") + XCTAssertNil(fixture.batch(limit: 100)) + XCTAssertNotNil(fixture.batch(limit: 2), "one file short of the whole plan must offer a batch") + } + + func testNilWhenLimitIsZero() { + var fixture = Fixture() + fixture.addGroup("a", deletes: 2, lane: .identical) + fixture.addGroup("b", deletes: 2, lane: .identical) + XCTAssertGreaterThan(fixture.fullPlan().count, 0) + + XCTAssertNil(fixture.batch(limit: 0)) + XCTAssertNil(fixture.batch(limit: -5)) + } + + // MARK: Limit and ordering + + func testBatchNeverExceedsLimit() { + var fixture = Fixture() + fixture.addGroup("a", deletes: 2, lane: .identical) + fixture.addGroup("b", deletes: 3, lane: .nearlyIdentical) + fixture.addGroup("c", deletes: 1, lane: .lookAtEach) + fixture.addGroup("d", deletes: 2, lane: .lookAtEach) + let full = fixture.fullPlan() + XCTAssertEqual(full.count, 8) + + for limit in 1..] = [:] + var configuration = DeduplicateConfiguration( + destinationPath: "/fx", + timeWindowSeconds: 30, + similarityThreshold: 0.9, + dhashHammingThreshold: 5, + treatRawJpegPairsAsUnit: true, + treatLivePhotoPairsAsUnit: true + ) + + /// Adds a group of `deletes + 1` photos: `keep.jpg` is Keep, `d1.jpg`... are Delete. + /// `customize` may adjust the members (pairs, sidecars) before the cluster is built. + @discardableResult + mutating func addGroup( + _ prefix: String, + deletes: Int, + lane: DeduplicateReviewLane, + customize: (inout [PhotoCandidate]) -> Void = { _ in } + ) -> DuplicateCluster { + var members = [PhotoCandidate(path: "/fx/\(prefix)/keep.jpg", size: 1_000, modificationTime: 0)] + for index in 1...max(1, deletes) { + members.append(PhotoCandidate(path: "/fx/\(prefix)/d\(index).jpg", size: 1_000, modificationTime: 0)) + } + customize(&members) + let cluster = Fixture.makeCluster(members: members, lane: lane) + clusters.append(cluster) + for (index, member) in members.enumerated() { + decisions.byPath[member.path] = index == 0 ? .keep : .delete + } + return cluster + } + + static func makeCluster(members: [PhotoCandidate], lane: DeduplicateReviewLane) -> DuplicateCluster { + let kind: ClusterKind + let confidence: ConfidenceLevel + switch lane { + case .identical: (kind, confidence) = (.exactDuplicate, .high) + case .nearlyIdentical: (kind, confidence) = (.nearDuplicate, .high) + case .lookAtEach: (kind, confidence) = (.nearDuplicate, .medium) + } + return DuplicateCluster( + kind: kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 0, + annotation: ClusterAnnotation(confidence: confidence, matchReason: MatchReason(kind: kind)) + ) + } + + /// Every file the scan saw has an identity. Members of an exact cluster + /// share one; everything else is unique by path. + var snapshot: DeduplicateScanSnapshot { + var identities: [String: FileIdentity] = [:] + for cluster in clusters { + for member in cluster.members { + let digest = cluster.kind == .exactDuplicate ? "exact-\(cluster.id.uuidString)" : "path-\(member.path)" + identities[member.path] = FileIdentity(size: member.size, digest: digest) + } + } + for member in clusters.flatMap(\.members) { + for extra in [member.pairedPath].compactMap({ $0 }) + member.sidecarPaths where identities[extra] == nil { + identities[extra] = FileIdentity(size: 500, digest: "path-\(extra)") + } + } + return DeduplicateScanSnapshot(identitiesByPath: identities, sidecarOwners: sidecarOwners) + } + + func fullPlan() -> DeduplicationPlan { + DeduplicationPlanner.plan( + decisions: decisions, + clusters: clusters, + configuration: configuration, + snapshot: snapshot + ) + } + + func batch(limit: Int) -> FreeDedupeBatch? { + FreeDedupeBatchPlanner.batch( + decisions: decisions, + reviewedClusters: clusters, + configuration: configuration, + snapshot: snapshot, + limit: limit + ) + } +} + +private extension DuplicateCluster { + /// Paths of every member except the first (the Keep in `Fixture.addGroup`). + var deletePaths: Set { Set(members.dropFirst().map(\.path)) } +} + +private func randomFixture(prng: inout FreeBatchPRNG) -> Fixture { + var fixture = Fixture() + fixture.configuration.treatRawJpegPairsAsUnit = prng.bool() + fixture.configuration.treatLivePhotoPairsAsUnit = prng.bool() + + let clusterCount = prng.intInRange(2...6) + var membersByCluster: [[PhotoCandidate]] = [] + var lanes: [DeduplicateReviewLane] = [] + for clusterIndex in 0.. = [] + for _ in 0..= 2, prng.bool() { + let a = prng.intInRange(0...(clusterCount - 1)) + var b = prng.intInRange(0...(clusterCount - 1)) + if a == b { b = (b + 1) % clusterCount } + let ai = prng.intInRange(0...(membersByCluster[a].count - 1)) + let bi = prng.intInRange(0...(membersByCluster[b].count - 1)) + let sidecar = "/fx/shared\(a)_\(b).xmp" + membersByCluster[a][ai].sidecarPaths = [sidecar] + membersByCluster[b][bi].sidecarPaths = [sidecar] + fixture.sidecarOwners[sidecar] = [membersByCluster[a][ai].path, membersByCluster[b][bi].path] + } + + for clusterIndex in 0.. UInt64 { + state ^= state >> 12 + state ^= state << 25 + state ^= state >> 27 + return state &* 0x2545_F491_4F6C_DD1D + } + + mutating func intInRange(_ range: ClosedRange) -> Int { + let span = UInt64(range.upperBound - range.lowerBound + 1) + return range.lowerBound + Int(next() % span) + } + + mutating func bool() -> Bool { + next() & 1 == 1 + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift index 987abba3..a5a633b8 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift @@ -1363,4 +1363,449 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.decisions.byPath[file2.path], DedupeDecision.delete) XCTAssertFalse(store.approvedClusterIDs.contains(clusterID)) } + + // MARK: - Review lanes, accept by lane and the free batch (FRX WP-12) + + private func laneCluster( + _ name: String, + lane: DeduplicateReviewLane, + deletes: Int = 1, + size: Int64 = 100 + ) -> DuplicateCluster { + var members = [PhotoCandidate(path: "/dest/\(name)/keep.jpg", size: size, modificationTime: 0)] + for index in 1...deletes { + members.append(PhotoCandidate(path: "/dest/\(name)/d\(index).jpg", size: size, modificationTime: 0)) + } + let kind: ClusterKind + let confidence: ConfidenceLevel + switch lane { + case .identical: (kind, confidence) = (.exactDuplicate, .high) + case .nearlyIdentical: (kind, confidence) = (.nearDuplicate, .high) + case .lookAtEach: (kind, confidence) = (.nearDuplicate, .medium) + } + return DuplicateCluster( + kind: kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: Int64(deletes) * size, + annotation: ClusterAnnotation(confidence: confidence, matchReason: MatchReason(kind: kind)) + ) + } + + /// Members of an exact group share one identity; everything else is unique by path. + private func laneSnapshot( + _ clusters: [DuplicateCluster], + overriding: [String: FileIdentity] = [:] + ) -> DeduplicateScanSnapshot { + var identities: [String: FileIdentity] = [:] + for cluster in clusters { + for member in cluster.members { + let digest = cluster.kind == .exactDuplicate ? "exact-\(cluster.id.uuidString)" : "path-\(member.path)" + identities[member.path] = FileIdentity(size: member.size, digest: digest) + } + } + identities.merge(overriding) { _, explicit in explicit } + return DeduplicateScanSnapshot(identitiesByPath: identities) + } + + @MainActor + private func laneEngine( + _ clusters: [DuplicateCluster], + commitEvents: [DeduplicateCommitEvent] = [] + ) -> MockDeduplicateEngine { + MockDeduplicateEngine( + clusters: clusters, + summary: DeduplicateSummary(scanSnapshot: laneSnapshot(clusters)), + commitEvents: commitEvents + ) + } + + @MainActor + private func laneStore( + engine: MockDeduplicateEngine, + snapshotStore: InMemoryDeduplicateReviewSnapshotStore = InMemoryDeduplicateReviewSnapshotStore() + ) -> DeduplicateSessionStore { + let suiteName = "DeduplicateSessionStoreTests-\(UUID().uuidString)" + let isolatedDefaults = UserDefaults(suiteName: suiteName) ?? .standard + isolatedDefaults.removePersistentDomain(forName: suiteName) + addTeardownBlock { isolatedDefaults.removePersistentDomain(forName: suiteName) } + return DeduplicateSessionStore( + engine: engine, + runHistoryStore: UserDefaultsDeduplicateRunHistoryStore(defaults: isolatedDefaults), + reviewSnapshotStore: snapshotStore, + saveDebounceNanoseconds: 60_000_000_000 + ) + } + + @MainActor + private func scannedLaneStore( + _ clusters: [DuplicateCluster], + commitEvents: [DeduplicateCommitEvent] = [], + snapshotStore: InMemoryDeduplicateReviewSnapshotStore = InMemoryDeduplicateReviewSnapshotStore() + ) async -> (store: DeduplicateSessionStore, engine: MockDeduplicateEngine) { + let engine = laneEngine(clusters, commitEvents: commitEvents) + let store = laneStore(engine: engine, snapshotStore: snapshotStore) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + return (store, engine) + } + + @MainActor + private func pumpRunLoop(timeout: TimeInterval = 3, until condition: () -> Bool) -> Bool { + let deadline = Date().addingTimeInterval(timeout) + while !condition(), Date() < deadline { + RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.01)) + } + return condition() + } + + @MainActor + func testLaneSummariesCountUnreviewedGroupsFilesAndBytes() async throws { + let sameA = laneCluster("sameA", lane: .identical, deletes: 2) + let sameB = laneCluster("sameB", lane: .identical, deletes: 1) + let nearly = laneCluster("nearly", lane: .nearlyIdentical, deletes: 1) + let look = laneCluster("look", lane: .lookAtEach, deletes: 3) + let (store, _) = await scannedLaneStore([sameA, sameB, nearly, look]) + + XCTAssertEqual(store.lane(for: sameA), .identical) + XCTAssertEqual(store.lane(for: nearly), .nearlyIdentical) + XCTAssertEqual(store.lane(for: look), .lookAtEach) + XCTAssertEqual(store.laneSummaries[.identical], DeduplicateLaneSummary(groups: 2, files: 3, bytes: 300)) + XCTAssertEqual(store.laneSummaries[.nearlyIdentical], DeduplicateLaneSummary(groups: 1, files: 1, bytes: 100)) + XCTAssertEqual(store.laneSummaries[.lookAtEach], DeduplicateLaneSummary(groups: 1, files: 3, bytes: 300)) + + // A reviewed group no longer counts as waiting. + store.approveCluster(sameA.id) + XCTAssertEqual(store.laneSummaries[.identical], DeduplicateLaneSummary(groups: 1, files: 1, bytes: 100)) + XCTAssertEqual(store.laneSummaries[.lookAtEach], DeduplicateLaneSummary(groups: 1, files: 3, bytes: 300)) + } + + @MainActor + func testLaneSummariesUpdateAfterAccept() async throws { + let same = laneCluster("same", lane: .identical, deletes: 2) + let nearly = laneCluster("nearly", lane: .nearlyIdentical, deletes: 1) + let (store, _) = await scannedLaneStore([same, nearly]) + XCTAssertEqual(store.laneSummaries[.identical]?.groups, 1) + + store.acceptSuggestions(in: .identical) + + XCTAssertEqual(store.laneSummaries[.identical], DeduplicateLaneSummary(groups: 0, files: 0, bytes: 0)) + XCTAssertEqual(store.laneSummaries[.nearlyIdentical], DeduplicateLaneSummary(groups: 1, files: 1, bytes: 100)) + } + + @MainActor + // AGENTS-INVARIANT: 6 + func testAcceptIdenticalApprovesOnlyIdenticalGroups() async throws { + let same = laneCluster("same", lane: .identical, deletes: 2) + let nearly = laneCluster("nearly", lane: .nearlyIdentical, deletes: 1) + let look = laneCluster("look", lane: .lookAtEach, deletes: 1) + let (store, _) = await scannedLaneStore([same, nearly, look]) + + store.acceptSuggestions(in: .identical) + + XCTAssertEqual(store.approvedClusterIDs, [same.id]) + XCTAssertEqual(store.decisions.byPath["/dest/same/keep.jpg"], .keep) + XCTAssertEqual(store.decisions.byPath["/dest/same/d1.jpg"], .delete) + XCTAssertEqual(store.decisions.byPath["/dest/same/d2.jpg"], .delete) + let reviewedPaths = Set(store.reviewedDeletionPlan().items.map(\.path)) + XCTAssertEqual(reviewedPaths, ["/dest/same/d1.jpg", "/dest/same/d2.jpg"]) + XCTAssertFalse(store.approvedClusterIDs.contains(nearly.id), "A nearly identical group stays review-only") + XCTAssertFalse(store.approvedClusterIDs.contains(look.id), "A group to look at stays review-only") + } + + @MainActor + func testAcceptNearlyIdenticalLeavesOtherLanesAlone() async throws { + let same = laneCluster("same", lane: .identical, deletes: 1) + let nearly = laneCluster("nearly", lane: .nearlyIdentical, deletes: 2) + let look = laneCluster("look", lane: .lookAtEach, deletes: 1) + let (store, _) = await scannedLaneStore([same, nearly, look]) + let decisionsBefore = store.decisions + + store.acceptSuggestions(in: .nearlyIdentical) + + XCTAssertEqual(store.approvedClusterIDs, [nearly.id]) + XCTAssertEqual(store.decisions, decisionsBefore, "Suggestions were already in place; accepting only approves the group") + XCTAssertEqual(store.laneSummaries[.identical]?.groups, 1) + XCTAssertEqual(store.laneSummaries[.lookAtEach]?.groups, 1) + XCTAssertEqual(store.laneSummaries[.nearlyIdentical]?.groups, 0) + } + + @MainActor + func testAcceptLookAtEachDoesNothing() async throws { + let look = laneCluster("look", lane: .lookAtEach, deletes: 1) + let same = laneCluster("same", lane: .identical, deletes: 1) + let (store, _) = await scannedLaneStore([look, same]) + let decisionsBefore = store.decisions + let undoManager = UndoManager() + store.undoManager = undoManager + + store.acceptSuggestions(in: .lookAtEach) + + XCTAssertEqual(store.decisions, decisionsBefore) + XCTAssertTrue(store.approvedClusterIDs.isEmpty) + XCTAssertFalse(undoManager.canUndo, "Nothing was accepted, so there is nothing to undo") + } + + @MainActor + func testAcceptInLaneSkipsReviewedGroups() async throws { + let first = laneCluster("first", lane: .identical, deletes: 1) + let second = laneCluster("second", lane: .identical, deletes: 1) + let (store, _) = await scannedLaneStore([first, second]) + // The person already flipped the first group's keeper. + store.setDecision(.delete, forPath: "/dest/first/keep.jpg") + store.setDecision(.keep, forPath: "/dest/first/d1.jpg") + XCTAssertEqual(store.approvedClusterIDs, [first.id]) + + store.acceptSuggestions(in: .identical) + + XCTAssertEqual(store.decisions.byPath["/dest/first/keep.jpg"], .delete, "A reviewed group keeps its own choice") + XCTAssertEqual(store.decisions.byPath["/dest/first/d1.jpg"], .keep) + XCTAssertEqual(store.approvedClusterIDs, [first.id, second.id]) + XCTAssertEqual(store.decisions.byPath["/dest/second/keep.jpg"], .keep) + XCTAssertEqual(store.decisions.byPath["/dest/second/d1.jpg"], .delete) + } + + @MainActor + func testAcceptInLaneIsUndoable() { + // Synchronous on purpose: UndoManager inside an async XCTest method + // crashes the Swift task allocator. The run loop is pumped instead. + let same = laneCluster("same", lane: .identical, deletes: 1) + let nearly = laneCluster("nearly", lane: .nearlyIdentical, deletes: 1) + let engine = laneEngine([same, nearly]) + let store = laneStore(engine: engine) + let undoManager = UndoManager() + undoManager.groupsByEvent = false + store.undoManager = undoManager + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + XCTAssertTrue(pumpRunLoop { store.status == .readyToReview }) + let decisionsBefore = store.decisions + + undoManager.beginUndoGrouping() + store.acceptSuggestions(in: .identical) + undoManager.endUndoGrouping() + XCTAssertEqual(store.approvedClusterIDs, [same.id]) + XCTAssertEqual(undoManager.undoActionName, "Accept Identical Copies") + + undoManager.undo() + XCTAssertTrue(store.approvedClusterIDs.isEmpty) + XCTAssertEqual(store.decisions, decisionsBefore) + XCTAssertEqual(store.laneSummaries[.identical]?.groups, 1, "Undo puts the group back in its lane") + + undoManager.redo() + XCTAssertEqual(store.approvedClusterIDs, [same.id]) + + undoManager.beginUndoGrouping() + store.acceptSuggestions(in: .nearlyIdentical) + undoManager.endUndoGrouping() + XCTAssertEqual(undoManager.undoActionName, "Accept Nearly Identical") + XCTAssertEqual(store.approvedClusterIDs, [same.id, nearly.id]) + } + + @MainActor + func testFullyMarkedClusterIDs() async throws { + let marked = laneCluster("marked", lane: .identical, deletes: 2) + let suggested = laneCluster("suggested", lane: .identical, deletes: 1) + let unreviewed = laneCluster("unreviewed", lane: .lookAtEach, deletes: 1) + let (store, _) = await scannedLaneStore([marked, suggested, unreviewed]) + XCTAssertTrue(store.fullyMarkedClusterIDs.isEmpty) + + store.deleteAllInCluster(marked) + store.acceptSuggestionsForCluster(suggested) + // Every member marked Delete, but the group was never reviewed. + var byPath = store.decisions.byPath + for member in unreviewed.members { byPath[member.path] = .delete } + store.decisions = DedupeDecisions(byPath: byPath) + + XCTAssertEqual(store.fullyMarkedClusterIDs, [marked.id]) + } + + @MainActor + func testFreeBatchOfferNilWhenPlanFits() 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.acceptSuggestions(in: .identical) + XCTAssertEqual(store.reviewedDeletionPlan().count, 2) + + XCTAssertNil(store.freeBatchOffer(remaining: 2), "A plan that fits needs no batch") + XCTAssertNil(store.freeBatchOffer(remaining: 100)) + XCTAssertNotNil(store.freeBatchOffer(remaining: 1)) + + let withoutScan = laneStore(engine: laneEngine([])) + XCTAssertNil(withoutScan.freeBatchOffer(remaining: 1), "No scan configuration means no offer") + } + + @MainActor + func testPrepareFreeBatchCommitPlanFreezesBatchPlan() async throws { + let first = laneCluster("first", lane: .identical, deletes: 2) + let second = laneCluster("second", lane: .identical, deletes: 2) + let (store, _) = await scannedLaneStore([first, second]) + store.acceptSuggestions(in: .identical) + XCTAssertEqual(store.reviewedDeletionPlan().count, 4) + + XCTAssertNil(store.prepareFreeBatchCommitPlan(remaining: 100), "A plan that fits has no batch") + XCTAssertNil(store.preparedCommitPlan, "No offer, no change") + + let offer = try XCTUnwrap(store.freeBatchOffer(remaining: 2)) + let prepared = try XCTUnwrap(store.prepareFreeBatchCommitPlan(remaining: 2)) + + XCTAssertEqual(prepared, offer.plan) + XCTAssertEqual(store.preparedCommitPlan, offer.plan) + XCTAssertEqual(prepared.count, 2) + XCTAssertEqual(offer.deferredFileCount, 2) + XCTAssertEqual(Set(prepared.items.map(\.path)), ["/dest/first/d1.jpg", "/dest/first/d2.jpg"]) + } + + @MainActor + func testCommitAfterFreeBatchPassesOnlyBatchItemsToEngine() async throws { + let first = laneCluster("first", lane: .identical, deletes: 2) + let second = laneCluster("second", lane: .identical, deletes: 2) + let (store, engine) = await scannedLaneStore([first, second]) + store.acceptSuggestions(in: .identical) + let prepared = try XCTUnwrap(store.prepareFreeBatchCommitPlan(remaining: 2)) + + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + + let commitPlan = try XCTUnwrap(engine.lastCommitPlan) + XCTAssertEqual(commitPlan, prepared, "The engine commits the frozen batch, not a re-derived plan") + XCTAssertEqual(commitPlan.count, 2) + XCTAssertTrue(commitPlan.items.allSatisfy { $0.path.hasPrefix("/dest/first/") }) + XCTAssertNil(store.preparedCommitPlan) + } + + @MainActor + func testPreparedCommitCountFollowsThePreparedPlan() async throws { + let first = laneCluster("first", lane: .identical, deletes: 2) + let second = laneCluster("second", lane: .identical, deletes: 2) + let (store, _) = await scannedLaneStore([first, second]) + store.acceptSuggestions(in: .identical) + XCTAssertNil(store.preparedCommitCount) + + store.prepareReviewedCommitPlan() + XCTAssertEqual(store.preparedCommitCount, 4) + + store.prepareFreeBatchCommitPlan(remaining: 2) + XCTAssertEqual(store.preparedCommitCount, 2) + + store.discardPreparedCommitPlan() + XCTAssertNil(store.preparedCommitCount) + + store.prepareFreeBatchCommitPlan(remaining: 2) + store.prepareReviewedCommitPlan() + XCTAssertEqual(store.preparedCommitCount, 4, "An ordinary prepare replaces a prepared batch") + } + + @MainActor + func testFreeBatchOfferIsCachedUntilDecisionsChange() async throws { + let first = laneCluster("first", lane: .identical, deletes: 2) + let second = laneCluster("second", lane: .identical, deletes: 2) + let (store, _) = await scannedLaneStore([first, second]) + store.acceptSuggestions(in: .identical) + let baseline = store.freeBatchOfferComputationCount + + let firstOffer = try XCTUnwrap(store.freeBatchOffer(remaining: 2)) + XCTAssertEqual(store.freeBatchOfferComputationCount, baseline + 1) + let secondOffer = try XCTUnwrap(store.freeBatchOffer(remaining: 2)) + XCTAssertEqual(store.freeBatchOfferComputationCount, baseline + 1, "The footer asks on every render") + XCTAssertEqual(firstOffer.plan, secondOffer.plan) + + _ = store.freeBatchOffer(remaining: 3) + XCTAssertEqual(store.freeBatchOfferComputationCount, baseline + 2, "A new allowance recomputes") + + store.setDecision(.keep, forPath: "/dest/second/d1.jpg") + _ = store.freeBatchOffer(remaining: 3) + XCTAssertEqual(store.freeBatchOfferComputationCount, baseline + 3, "A changed decision recomputes") + _ = store.freeBatchOffer(remaining: 3) + XCTAssertEqual(store.freeBatchOfferComputationCount, baseline + 3) + + store.approvedClusterIDs.remove(second.id) + _ = store.freeBatchOffer(remaining: 3) + XCTAssertEqual(store.freeBatchOfferComputationCount, baseline + 4, "A changed approval recomputes") + } + + /// Free-batch commit helper: two identical groups, one accepted batch, one deferred. + @MainActor + private func commitFreeBatchThenRescan( + snapshotStore: InMemoryDeduplicateReviewSnapshotStore, + free: Bool + ) async throws -> (store: DeduplicateSessionStore, engine: MockDeduplicateEngine, deferred: DuplicateCluster, changed: DuplicateCluster) { + let batched = laneCluster("batched", lane: .identical, deletes: 2) + let deferred = laneCluster("deferred", lane: .identical, deletes: 2) + let changed = laneCluster("changed", lane: .nearlyIdentical, deletes: 1) + let summary = DeduplicateCommitSummary(deletedCount: 2, failedCount: 0, bytesReclaimed: 200, receiptPath: nil, hardDelete: false) + let (store, engine) = await scannedLaneStore( + [batched, deferred, changed], + commitEvents: [.complete(summary)], + snapshotStore: snapshotStore + ) + store.refreshSavedReview(folderPath: "/dest") + store.acceptSuggestions(in: .identical) + store.acceptSuggestions(in: .nearlyIdentical) + // A choice the person made on purpose: keep the second file of a deferred group. + store.setDecision(.delete, forPath: "/dest/deferred/keep.jpg") + store.setDecision(.keep, forPath: "/dest/deferred/d1.jpg") + store.setDecision(.delete, forPath: "/dest/changed/keep.jpg") + store.setDecision(.keep, forPath: "/dest/changed/d1.jpg") + if free { + // Remaining allowance fits the first group only. + XCTAssertNotNil(store.prepareFreeBatchCommitPlan(remaining: 2)) + } else { + store.prepareReviewedCommitPlan() + } + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let completed = await waitForCondition { store.status == .completed } + XCTAssertTrue(completed) + return (store, engine, deferred, changed) + } + + @MainActor + // AGENTS-INVARIANT: 29 + func testFreeBatchCommitKeepsSavedReviewForNextScan() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let (store, engine, deferred, changed) = try await commitFreeBatchThenRescan(snapshotStore: snapshotStore, free: true) + + XCTAssertEqual(engine.lastCommitPlan?.count, 2) + XCTAssertTrue(snapshotStore.removals.isEmpty, "A free removal keeps the saved review") + XCTAssertNotNil(snapshotStore.load(folderPath: "/dest")) + XCTAssertNotNil(store.savedReviewForCurrentFolder) + + // The next scan: the batched group is gone (moved to the Trash) and one + // file of the "changed" group no longer has the identity that was saved. + let changedNow = changed + engine.clustersToEmit = [deferred, changedNow] + let moved = laneSnapshot([deferred, changedNow], overriding: [ + "/dest/changed/d1.jpg": FileIdentity(size: 100, digest: "edited-after-review"), + ]) + engine.summary = DeduplicateSummary(scanSnapshot: moved) + let commitCallsBefore = engine.lastCommitPlan + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + + // Unchanged file: the saved choice returns. + XCTAssertEqual(store.decisions.byPath["/dest/deferred/keep.jpg"], .delete) + XCTAssertEqual(store.decisions.byPath["/dest/deferred/d1.jpg"], .keep) + XCTAssertTrue(store.approvedClusterIDs.contains(deferred.id)) + // Changed file: its saved Keep is dropped and the fresh suggestion applies. + XCTAssertEqual(store.decisions.byPath["/dest/changed/d1.jpg"], .delete) + XCTAssertFalse(store.approvedClusterIDs.contains(changed.id), "A group whose files changed needs another look") + XCTAssertGreaterThan(store.restoredReview?.droppedDecisionCount ?? 0, 0) + // Restoring never builds a plan or approves a commit. + XCTAssertNil(store.preparedCommitPlan) + XCTAssertNil(store.preparedCommitCount) + XCTAssertFalse(store.wantsFreeBatchConfirmation) + XCTAssertEqual(engine.lastCommitPlan, commitCallsBefore, "Restoring committed nothing") + } + + @MainActor + func testOrdinaryCommitStillRemovesSavedReview() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let (store, _, _, _) = try await commitFreeBatchThenRescan(snapshotStore: snapshotStore, free: false) + + XCTAssertEqual(snapshotStore.removals, ["/dest"]) + XCTAssertNil(snapshotStore.load(folderPath: "/dest")) + XCTAssertNil(store.savedReviewForCurrentFolder) + XCTAssertNil(store.restoredReview) + } } diff --git a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift index aaef3270..9083835a 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift @@ -337,6 +337,106 @@ final class UnlockPresentationTests: XCTestCase { ) } + // MARK: - Free removal batch on a dedupe refusal (FRX C-13) + + private func dedupeSpent(requested: Int = 40, remaining: Int = 3) -> TrialAuthorizationRefusal { + .allowanceSpent(TrialRefusal(meter: .dedupe, requested: requested, remaining: remaining)) + } + + func testDedupeRefusalOffersFreeBatchAction() { + let offered = UnlockSheetModel.make( + refusal: dedupeSpent(), + product: product, + isLoadingProduct: false, + isPurchasing: false, + isRestoring: false, + offeredDedupeBatch: (fileCount: 3, deferredCount: 37) + ) + // Where the organize batch action sits: below unlock and restore, above dismiss. + XCTAssertEqual(offered.actions, [ + .buy(displayName: product.displayName, displayPrice: "£14.99"), + .restore, + .runFreeDedupeBatch(fileCount: 3, deferredCount: 37), + .dismiss, + ]) + XCTAssertEqual(offered.batchDetail, "Moves 3 files from whole groups to the Trash now and leaves 37 for later.") + XCTAssertTrue(offered.isBatchEnabled) + + let single = UnlockSheetModel.make( + refusal: dedupeSpent(), + product: product, + isLoadingProduct: false, + isPurchasing: false, + isRestoring: false, + offeredDedupeBatch: (fileCount: 1, deferredCount: 1_200) + ) + XCTAssertEqual(single.batchDetail, "Moves 1 file from whole groups to the Trash now and leaves \(1_200.formatted()) for later.") + + // While the price loads the free step still stands; a purchase in flight disables it. + let loading = UnlockSheetModel.make( + refusal: dedupeSpent(), + product: nil, + isLoadingProduct: true, + isPurchasing: false, + isRestoring: false, + offeredDedupeBatch: (fileCount: 3, deferredCount: 37) + ) + XCTAssertEqual(loading.actions, [.runFreeDedupeBatch(fileCount: 3, deferredCount: 37), .dismiss]) + let purchasing = UnlockSheetModel.make( + refusal: dedupeSpent(), + product: product, + isLoadingProduct: false, + isPurchasing: true, + isRestoring: false, + offeredDedupeBatch: (fileCount: 3, deferredCount: 37) + ) + XCTAssertFalse(purchasing.isBatchEnabled) + + // A dedupe batch is only ever offered against a spent dedupe allowance. + let organizeRefusal = UnlockSheetModel.make( + refusal: spent(remaining: 3), + product: product, + isLoadingProduct: false, + isPurchasing: false, + isRestoring: false, + offeredDedupeBatch: (fileCount: 3, deferredCount: 37) + ) + XCTAssertFalse(organizeRefusal.actions.contains(.runFreeDedupeBatch(fileCount: 3, deferredCount: 37))) + let unconfirmed = UnlockSheetModel.make( + refusal: .purchaseUnconfirmed(TrialRefusal(meter: .dedupe, requested: 4, remaining: 2)), + product: product, + isLoadingProduct: false, + isPurchasing: false, + isRestoring: false, + offeredDedupeBatch: (fileCount: 3, deferredCount: 37) + ) + XCTAssertEqual(unconfirmed.actions, [.restore, .dismiss]) + let nothingToRun = UnlockSheetModel.make( + refusal: dedupeSpent(), + product: product, + isLoadingProduct: false, + isPurchasing: false, + isRestoring: false, + offeredDedupeBatch: (fileCount: 0, deferredCount: 37) + ) + XCTAssertNil(nothingToRun.batchDetail) + } + + func testNoDedupeBatchActionWithoutOffer() { + let withoutOffer = UnlockSheetModel.make( + refusal: dedupeSpent(), + product: product, + isLoadingProduct: false, + isPurchasing: false, + isRestoring: false + ) + XCTAssertEqual(withoutOffer.actions, [ + .buy(displayName: product.displayName, displayPrice: "£14.99"), .restore, .dismiss, + ]) + XCTAssertNil(withoutOffer.batchDetail) + XCTAssertEqual(withoutOffer.title, "Remove all 40 duplicates") + } + // MARK: - Busy /// While StoreKit is working the view disables its buttons from this flag diff --git a/ui/Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift b/ui/Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift index b3dee0b5..7729b9ad 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift @@ -82,6 +82,7 @@ final class UnlockSheetBatchOfferTests: XCTestCase { case .buy: return "buy" case .restore: return "restore" case .runFreeTestBatch: return "batch" + case .runFreeDedupeBatch: return "dedupeBatch" case .retryProductLoad: return "retry" case .dismiss: return "dismiss" } diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index 95e85e86..8079f421 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -1113,7 +1113,8 @@ final class AppStateTests: XCTestCase { @MainActor private func makeMeteredState( harness: AppStateHarness, - organizeUsed: Int = 0 + organizeUsed: Int = 0, + deduplicateSessionStore: DeduplicateSessionStore? = nil ) -> AppState { let accountKey = "frx-wp04-account" let ledger = InMemoryTrialLedger() @@ -1133,7 +1134,7 @@ final class AppStateTests: XCTestCase { runLogStore: harness.runLogStore, historyStore: harness.historyStore, runSessionStore: harness.runSessionStore, - deduplicateSessionStore: harness.deduplicateSessionStore, + deduplicateSessionStore: deduplicateSessionStore ?? harness.deduplicateSessionStore, photosImportStore: PhotosImportStore( access: AppStatePhotosAccessStub(), catalog: AppStatePhotosCatalogStub(), @@ -1241,6 +1242,198 @@ final class AppStateTests: XCTestCase { ) } + // MARK: - Free removal batch (FRX C-13) + + /// A store of its own, so no saved review lands in the user's Application Support. + @MainActor + private func scannedDedupeStore( + _ clusters: [DuplicateCluster], + engine: MockDeduplicateEngine + ) async throws -> DeduplicateSessionStore { + engine.clustersToEmit = clusters + // Members of an exact group share one identity, which is what makes the group identical. + var identities: [String: FileIdentity] = [:] + for cluster in clusters { + for member in cluster.members { + identities[member.path] = FileIdentity(size: member.size, digest: "exact-\(cluster.id.uuidString)") + } + } + engine.summary = DeduplicateSummary(scanSnapshot: DeduplicateScanSnapshot(identitiesByPath: identities)) + let suiteName = "AppStateTests-dedupe-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent("AppStateTests-dedupe-\(UUID().uuidString)", isDirectory: true) + addTeardownBlock { + defaults.removePersistentDomain(forName: suiteName) + try? FileManager.default.removeItem(at: directory) + } + let store = DeduplicateSessionStore( + engine: engine, + runHistoryStore: UserDefaultsDeduplicateRunHistoryStore(defaults: defaults), + reviewSnapshotStore: DeduplicateReviewFileSnapshotStore(directory: directory), + saveDebounceNanoseconds: 60_000_000_000 + ) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/tmp/destination")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + return store + } + + /// Two exact groups of three files each: reviewing both makes a four-file plan. + @MainActor + private func twoExactGroups() -> [DuplicateCluster] { + (1...2).map { index in + let members = [ + PhotoCandidate(path: "/tmp/destination/g\(index)/keep.jpg", size: 100, modificationTime: 0), + PhotoCandidate(path: "/tmp/destination/g\(index)/d1.jpg", size: 100, modificationTime: 0), + PhotoCandidate(path: "/tmp/destination/g\(index)/d2.jpg", size: 100, modificationTime: 0), + ] + return DuplicateCluster( + kind: .exactDuplicate, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 200, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) + ) + } + } + + @MainActor + func testDeduplicateReviewLanesScenarioSeedsThreeLanesAndAnOverAllowancePlan() async throws { + let state = UITestAppStateFactory.make(scenario: .deduplicateReviewLanes) + let store = state.deduplicateSessionStore + let ready = await waitForCondition(timeoutNanoseconds: 3_000_000_000) { + store.status == .readyToReview && store.approvedClusterIDs.count == 2 + } + XCTAssertTrue(ready) + + XCTAssertTrue(state.isAppStoreChannel) + XCTAssertEqual(state.trialStatusStore.status.remaining(for: .dedupe), 2) + XCTAssertEqual(store.clusters.count, 14) + XCTAssertEqual(store.approvedClusterIDs.count, 2, "The first two exact groups are accepted") + XCTAssertEqual(store.laneSummaries[.identical]?.groups, 4) + XCTAssertEqual(store.laneSummaries[.nearlyIdentical]?.groups, 3) + XCTAssertEqual(store.laneSummaries[.lookAtEach]?.groups, 5) + XCTAssertEqual(store.reviewedDeletionPlan().count, 4, "Two reviewed groups of three keep one each") + XCTAssertEqual(store.freeBatchOffer(remaining: 2)?.plan.count, 2) + } + + @MainActor + func testRequestUnlockForDuplicatesPresentsDedupeRefusal() { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness) + XCTAssertNil(state.unlockRefusal) + + state.requestUnlockForDuplicates(requested: 4, remaining: 2) + + let expected = TrialAuthorizationRefusal.allowanceSpent( + TrialRefusal(meter: .dedupe, requested: 4, remaining: 2) + ) + XCTAssertEqual(state.requestedUnlockRefusal, expected) + XCTAssertEqual(state.unlockRefusal, expected) + XCTAssertFalse(harness.deduplicateSessionStore.isWorking, "Presenting the sheet starts nothing") + XCTAssertEqual(harness.deduplicateEngine.commitCallCount, 0) + + state.dismissUnlockSheet() + XCTAssertNil(state.unlockRefusal) + } + + @MainActor + func testOfferedFreeDedupeBatchOnlyForAllowanceSpentWithRemaining() async throws { + let harness = AppStateHarness() + let store = try await scannedDedupeStore(twoExactGroups(), engine: harness.deduplicateEngine) + store.acceptSuggestions(in: .identical) + XCTAssertEqual(store.reviewedDeletionPlan().count, 4) + let state = makeMeteredState(harness: harness, deduplicateSessionStore: store) + + XCTAssertNil(state.offeredFreeDedupeBatch, "No refusal, no offer") + + state.requestUnlockForDuplicates(requested: 4, remaining: 2) + let offer = try XCTUnwrap(state.offeredFreeDedupeBatch) + XCTAssertEqual(offer.plan.count, 2) + XCTAssertEqual(offer.deferredFileCount, 2) + XCTAssertEqual(offer.plan, store.freeBatchOffer(remaining: 2)?.plan) + + state.requestUnlockForDuplicates(requested: 4, remaining: 0) + XCTAssertNil(state.offeredFreeDedupeBatch, "Nothing is left to spend") + + state.requestUnlockForDuplicates(requested: 4, remaining: 100) + XCTAssertNil(state.offeredFreeDedupeBatch, "A plan that fits needs no batch") + + state.requestUnlockForPlan(requested: 4) + XCTAssertNil(state.offeredFreeDedupeBatch, "An organize refusal never offers a removal batch") + } + + @MainActor + func testOfferedFreeDedupeBatchFollowsARefusedCommit() async throws { + let harness = AppStateHarness() + harness.deduplicateEngine.commitError = TrialAuthorizationError(refusal: .allowanceSpent( + TrialRefusal(meter: .dedupe, requested: 4, remaining: 2) + )) + let store = try await scannedDedupeStore(twoExactGroups(), engine: harness.deduplicateEngine) + store.acceptSuggestions(in: .identical) + let state = makeMeteredState(harness: harness, deduplicateSessionStore: store) + + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/tmp/destination")) + let refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + + XCTAssertEqual(state.offeredFreeDedupeBatch?.plan.count, 2) + } + + /// A refused commit leaves the review paused, and the confirmation dialog + /// lives on the review footer. The sheet's free removal has to bring the + /// review back, or the button would close the sheet onto an idle screen. + @MainActor + func testRunOfferedFreeDedupeBatchResumesAReviewTheRefusalPaused() async throws { + let harness = AppStateHarness() + harness.deduplicateEngine.commitError = TrialAuthorizationError(refusal: .allowanceSpent( + TrialRefusal(meter: .dedupe, requested: 4, remaining: 2) + )) + let store = try await scannedDedupeStore(twoExactGroups(), engine: harness.deduplicateEngine) + store.acceptSuggestions(in: .identical) + let state = makeMeteredState(harness: harness, deduplicateSessionStore: store) + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/tmp/destination")) + let refused = await waitForCondition { store.lastRefusal != nil } + XCTAssertTrue(refused) + XCTAssertEqual(store.status, .idle, "premise: the refusal paused the review") + let commitsSoFar = harness.deduplicateEngine.commitCallCount + + state.runOfferedFreeDedupeBatch() + + XCTAssertEqual(store.status, .readyToReview, "The review, and its confirmation dialog, are back on screen") + XCTAssertTrue(store.wantsFreeBatchConfirmation) + XCTAssertNil(state.unlockRefusal, "The sheet closes") + XCTAssertEqual(harness.deduplicateEngine.commitCallCount, commitsSoFar, "Nothing is committed without that dialog") + XCTAssertNil(store.preparedCommitPlan) + XCTAssertEqual(store.reviewedDeletionPlan().count, 4, "The reviewed choices are untouched") + } + + @MainActor + func testRunOfferedFreeDedupeBatchAsksForConfirmationOnly() async throws { + let harness = AppStateHarness() + let store = try await scannedDedupeStore(twoExactGroups(), engine: harness.deduplicateEngine) + store.acceptSuggestions(in: .identical) + let state = makeMeteredState(harness: harness, deduplicateSessionStore: store) + + // No offer, nothing happens. + state.runOfferedFreeDedupeBatch() + XCTAssertFalse(store.wantsFreeBatchConfirmation) + + state.requestUnlockForDuplicates(requested: 4, remaining: 2) + XCTAssertNotNil(state.unlockRefusal) + + state.runOfferedFreeDedupeBatch() + + XCTAssertNil(state.unlockRefusal, "The sheet closes") + XCTAssertTrue(store.wantsFreeBatchConfirmation, "The review screen opens its confirmation dialog") + XCTAssertEqual(harness.deduplicateEngine.commitCallCount, 0, "Nothing is committed without that dialog") + XCTAssertNil(harness.deduplicateEngine.lastCommitPlan) + XCTAssertEqual(store.status, .readyToReview) + XCTAssertNil(store.preparedCommitPlan, "The batch is frozen by the dialog, not here") + XCTAssertEqual(store.reviewedDeletionPlan().count, 4, "The reviewed choices are untouched") + } + @MainActor func testDismissUnlockSheetClearsRequestedRefusal() { let harness = AppStateHarness() diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewLanesTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewLanesTests.swift index 07e8c509..3fd4775d 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewLanesTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewLanesTests.swift @@ -223,4 +223,119 @@ final class DeduplicateReviewLanesTests: XCTestCase { XCTAssertEqual(AccessibilityIdentifiers.dedupeLanesAcceptSafe, "dedupe.lanes.acceptSafe") XCTAssertEqual(AccessibilityIdentifiers.dedupeLanesQuickReview, "dedupe.lanes.quickReview") } + + // MARK: - Three lanes (FRX C-13) + + /// Reviewed groups first, then the lane each remaining group belongs to. + private func threeLaneFixture() -> (clusters: [DuplicateCluster], reviewed: Set, lane: (DuplicateCluster) -> DeduplicateReviewLane) { + let identical = [eligible("i1"), eligible("i2")] + let nearly = [eligible("n1"), eligible("n2"), eligible("n3")] + let look = [uncertain("l1"), uncertain("l2"), uncertain("l3"), uncertain("l4")] + let reviewedIdentical = eligible("ri") + var laneByID: [DuplicateCluster.ID: DeduplicateReviewLane] = [reviewedIdentical.id: .identical] + identical.forEach { laneByID[$0.id] = .identical } + nearly.forEach { laneByID[$0.id] = .nearlyIdentical } + look.forEach { laneByID[$0.id] = .lookAtEach } + return ( + identical + nearly + look + [reviewedIdentical], + [reviewedIdentical.id], + { laneByID[$0.id] ?? .lookAtEach } + ) + } + + func testIdenticalAndNearlyIdenticalCountsSumToSafe() { + let fixture = threeLaneFixture() + let lanes = DeduplicateReviewLanes(clusters: fixture.clusters, reviewedIDs: fixture.reviewed, lane: fixture.lane) + + XCTAssertEqual(lanes.identicalGroupCount, 2, "A reviewed group leaves its lane") + XCTAssertEqual(lanes.nearlyIdenticalGroupCount, 3) + XCTAssertEqual(lanes.safeGroupCount, lanes.identicalGroupCount + lanes.nearlyIdenticalGroupCount) + XCTAssertEqual(lanes.checkGroupCount, 4) + XCTAssertEqual(lanes.reviewedGroupCount, 1) + + // A group the planner refuses to auto-select is never counted in a safe lane, + // even if the lane closure were to claim it. + let trap = highButNotEligible("trap") + let guarded = DeduplicateReviewLanes(clusters: [trap], reviewedIDs: []) { _ in .identical } + XCTAssertEqual(guarded.safeGroupCount, 0) + XCTAssertEqual(guarded.identicalGroupCount, 0) + XCTAssertEqual(guarded.checkGroupCount, 1) + } + + func testIdenticalSentenceCarriesFilesAndBytes() { + let fixture = threeLaneFixture() + let lanes = DeduplicateReviewLanes(clusters: fixture.clusters, reviewedIDs: fixture.reviewed, lane: fixture.lane) + let formatter = ByteCountFormatter() + formatter.allowedUnits = [.useMB, .useGB] + formatter.countStyle = .file + let bytes: Int64 = 5_000_000 + + XCTAssertEqual( + lanes.identicalText(files: 6, bytes: bytes), + "2 safe groups are identical copies. Accept them together: 6 files, \(formatter.string(fromByteCount: bytes))." + ) + XCTAssertEqual( + lanes.nearlyIdenticalText, + "3 safe groups are nearly identical. Look through them quickly." + ) + + let one = DeduplicateReviewLanes(clusters: [eligible("a")], reviewedIDs: []) { _ in .identical } + XCTAssertEqual( + one.identicalText(files: 1, bytes: bytes), + "1 safe group is identical copies. Accept it now: 1 file, \(formatter.string(fromByteCount: bytes))." + ) + let oneNearly = DeduplicateReviewLanes(clusters: [eligible("a")], reviewedIDs: []) { _ in .nearlyIdentical } + XCTAssertEqual(oneNearly.nearlyIdenticalText, "1 safe group is nearly identical. Look through it quickly.") + + let thousands = DeduplicateReviewLanes( + clusters: (0..<1_200).map { eligible("g\($0)") }, + reviewedIDs: [] + ) { _ in .identical } + XCTAssertEqual( + thousands.identicalText(files: 2_400, bytes: bytes), + "\(1_200.formatted()) safe groups are identical copies. Accept them together: \(2_400.formatted()) files, \(formatter.string(fromByteCount: bytes))." + ) + + // The identical-lane sentence still says "safe", the word the Safe tier uses (D-FRX-12). + XCTAssertTrue(lanes.identicalText(files: 6, bytes: bytes)?.localizedCaseInsensitiveContains("safe") == true) + } + + func testRowsWithZeroGroupsAreOmitted() { + let onlyLook = DeduplicateReviewLanes(clusters: [uncertain("a"), uncertain("b")], reviewedIDs: []) { _ in .lookAtEach } + XCTAssertNil(onlyLook.identicalText(files: 0, bytes: 0)) + XCTAssertNil(onlyLook.nearlyIdenticalText) + XCTAssertEqual(onlyLook.checkText, "2 groups are look-alikes or less certain. Look at each one.") + + let onlyIdentical = DeduplicateReviewLanes(clusters: [eligible("a")], reviewedIDs: []) { _ in .identical } + XCTAssertNotNil(onlyIdentical.identicalText(files: 1, bytes: 10_000_000)) + XCTAssertNil(onlyIdentical.nearlyIdenticalText) + XCTAssertNil(onlyIdentical.checkText) + + let reviewedOne = eligible("r") + let everythingReviewed = DeduplicateReviewLanes(clusters: [reviewedOne], reviewedIDs: [reviewedOne.id]) { _ in .identical } + XCTAssertNil(everythingReviewed.identicalText(files: 0, bytes: 0)) + + XCTAssertEqual( + DeduplicateReviewLanes.promiseLine, + "Chronoframe always suggests keeping one photo in every group." + ) + } + + func testCompactTextListsThreeLanes() { + let fixture = threeLaneFixture() + let all = DeduplicateReviewLanes(clusters: fixture.clusters, reviewedIDs: fixture.reviewed, lane: fixture.lane) + XCTAssertEqual(all.compactText, "\(2.formatted()) identical · \(3.formatted()) nearly identical · \(4.formatted()) to check") + + let noNearly = DeduplicateReviewLanes( + clusters: [eligible("a"), uncertain("b")], reviewedIDs: [] + ) { $0.members.first?.path.contains("/dest/a") == true ? .identical : .lookAtEach } + XCTAssertEqual(noNearly.compactText, "1 identical · 1 to check") + + let onlyNearly = DeduplicateReviewLanes(clusters: [eligible("a")], reviewedIDs: []) { _ in .nearlyIdentical } + XCTAssertEqual(onlyNearly.compactText, "1 nearly identical") + + let finished = eligible("f") + let done = DeduplicateReviewLanes(clusters: [finished], reviewedIDs: [finished.id]) { _ in .identical } + XCTAssertEqual(done.compactText, "Every group has been reviewed") + } } diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift index 8fd49c1c..2ed92ac8 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift @@ -1,6 +1,9 @@ import Foundation import SwiftUI import XCTest +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif @testable import ChronoframeApp @testable import ChronoframeCore @@ -214,4 +217,236 @@ final class DeduplicateReviewViewsTests: XCTestCase { } } } + + // MARK: - Quick Review, footer and free removal (FRX C-13) + + private func laneCluster(_ name: String, lane: DeduplicateReviewLane, deletes: Int = 1) -> DuplicateCluster { + var members = [PhotoCandidate(path: "/dest/\(name)/keep.jpg", size: 100, modificationTime: 0)] + for index in 1...deletes { + members.append(PhotoCandidate(path: "/dest/\(name)/d\(index).jpg", size: 100, modificationTime: 0)) + } + let kind: ClusterKind = lane == .identical ? .exactDuplicate : .nearDuplicate + let confidence: ConfidenceLevel = lane == .lookAtEach ? .medium : .high + return DuplicateCluster( + kind: kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: Int64(deletes) * 100, + annotation: ClusterAnnotation(confidence: confidence, matchReason: MatchReason(kind: kind)) + ) + } + + /// Members of an exact group share one identity; everything else is unique by path. + private func scannedStore(_ clusters: [DuplicateCluster]) async throws -> DeduplicateSessionStore { + var identities: [String: FileIdentity] = [:] + for cluster in clusters { + for member in cluster.members { + let digest = cluster.kind == .exactDuplicate ? "exact-\(cluster.id.uuidString)" : "path-\(member.path)" + identities[member.path] = FileIdentity(size: member.size, digest: digest) + } + } + let engine = MockDeduplicateEngine() + engine.clustersToEmit = clusters + engine.summary = DeduplicateSummary(scanSnapshot: DeduplicateScanSnapshot(identitiesByPath: identities)) + let suiteName = "DeduplicateReviewViewsTests-\(UUID().uuidString)" + let defaults = try XCTUnwrap(UserDefaults(suiteName: suiteName)) + defaults.removePersistentDomain(forName: suiteName) + let snapshotDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("DeduplicateReviewViewsTests-\(UUID().uuidString)", isDirectory: true) + addTeardownBlock { + defaults.removePersistentDomain(forName: suiteName) + try? FileManager.default.removeItem(at: snapshotDirectory) + } + let store = DeduplicateSessionStore( + engine: engine, + runHistoryStore: UserDefaultsDeduplicateRunHistoryStore(defaults: defaults), + reviewSnapshotStore: DeduplicateReviewFileSnapshotStore(directory: snapshotDirectory), + saveDebounceNanoseconds: 60_000_000_000 + ) + store.startScan(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let ready = await waitForCondition { store.status == .readyToReview } + XCTAssertTrue(ready) + return store + } + + func testQuickReviewScopeIsUnreviewedGroupsOfLane() async throws { + let identical = laneCluster("identical", lane: .identical) + let nearlyDone = laneCluster("nearlyDone", lane: .nearlyIdentical) + let nearlyOne = laneCluster("nearlyOne", lane: .nearlyIdentical) + let nearlyTwo = laneCluster("nearlyTwo", lane: .nearlyIdentical) + let lookOne = laneCluster("lookOne", lane: .lookAtEach) + let lookDone = laneCluster("lookDone", lane: .lookAtEach) + let store = try await scannedStore([identical, nearlyDone, nearlyOne, lookOne, nearlyTwo, lookDone]) + store.acceptSuggestionsForCluster(nearlyDone) + store.acceptSuggestionsForCluster(lookDone) + + func scope(_ lane: DeduplicateReviewLane) -> [DuplicateCluster.ID] { + QuickReviewScope.clusters( + in: lane, + from: store.clusters, + reviewedIDs: store.approvedClusterIDs, + laneOf: store.lane(for:) + ).map(\.id) + } + XCTAssertEqual(scope(.nearlyIdentical), [nearlyOne.id, nearlyTwo.id], "Reviewed groups are left out, order is kept") + XCTAssertEqual(scope(.lookAtEach), [lookOne.id]) + XCTAssertEqual(scope(.identical), [identical.id]) + } + + func testAcceptTheRestOnlyForNearlyIdenticalAfterFirstGroup() { + XCTAssertNil(QuickReviewScope.acceptTheRestCount(lane: .nearlyIdentical, currentIndex: 0, remainingInLane: 5), + "Not before the person has passed a group") + XCTAssertEqual(QuickReviewScope.acceptTheRestCount(lane: .nearlyIdentical, currentIndex: 1, remainingInLane: 5), 5) + XCTAssertEqual(QuickReviewScope.acceptTheRestCount(lane: .nearlyIdentical, currentIndex: 4, remainingInLane: 1), 1) + XCTAssertNil(QuickReviewScope.acceptTheRestCount(lane: .nearlyIdentical, currentIndex: 2, remainingInLane: 0), + "Not when no group remains") + XCTAssertNil(QuickReviewScope.acceptTheRestCount(lane: .lookAtEach, currentIndex: 3, remainingInLane: 5)) + XCTAssertNil(QuickReviewScope.acceptTheRestCount(lane: .identical, currentIndex: 3, remainingInLane: 5)) + + XCTAssertEqual(QuickReviewScope.acceptTheRestTitle(remaining: 5), "Accept the Rest (5)") + XCTAssertEqual(QuickReviewScope.acceptTheRestTitle(remaining: 1_200), "Accept the Rest (\(1_200.formatted()))") + XCTAssertEqual(AccessibilityIdentifiers.quickReviewAcceptRest, "quickReview.acceptRest") + } + + func testFullyMarkedNoticeText() { + XCTAssertNil(DeduplicateFooterCopy.fullyMarkedNotice(groupCount: 0)) + XCTAssertEqual( + DeduplicateFooterCopy.fullyMarkedNotice(groupCount: 3), + "3 groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them." + ) + XCTAssertEqual( + DeduplicateFooterCopy.fullyMarkedNotice(groupCount: 1), + "1 group has every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in it to include it." + ) + XCTAssertEqual( + DeduplicateFooterCopy.fullyMarkedNotice(groupCount: 1_200)?.prefix(30), + "\(1_200.formatted()) groups have every photo marked Delete.".prefix(30) + ) + XCTAssertEqual( + DeduplicateFooterCopy.dialogMessage("Files will move.", fullyMarkedGroupCount: 0), + "Files will move." + ) + XCTAssertEqual( + DeduplicateFooterCopy.dialogMessage("Files will move.", fullyMarkedGroupCount: 2), + "Files will move. 2 groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them." + ) + } + + func testFreeRemovalLineAndButtonTitles() { + XCTAssertEqual( + DeduplicateFooterCopy.freeRemovalLine(remaining: 2, reviewedCount: 4), + "You can remove 2 duplicates free. Your reviewed groups hold 4." + ) + XCTAssertEqual( + DeduplicateFooterCopy.freeRemovalLine(remaining: 1, reviewedCount: 4), + "You can remove 1 duplicate free. Your reviewed groups hold 4." + ) + XCTAssertEqual( + DeduplicateFooterCopy.freeRemovalLine(remaining: 0, reviewedCount: 4), + "Your free removals are used up." + ) + XCTAssertEqual( + DeduplicateFooterCopy.freeRemovalLine(remaining: 20, reviewedCount: 1_200), + "You can remove 20 duplicates free. Your reviewed groups hold \(1_200.formatted())." + ) + XCTAssertEqual(DeduplicateFooterCopy.freeBatchCommitTitle(fileCount: 2), "Move 2 Files to Trash Free") + XCTAssertEqual(DeduplicateFooterCopy.freeBatchCommitTitle(fileCount: 1), "Move 1 File to Trash Free") + XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 4), "Unlock to Remove All 4") + XCTAssertEqual(DeduplicateFooterCopy.unlockAllTitle(count: 1_200), "Unlock to Remove All \(1_200.formatted())") + + // The line appears only when the allowance applies and the reviewed plan exceeds it. + XCTAssertTrue(DeduplicateFooterCopy.showsFreeRemoval(remaining: 2, reviewedCount: 4)) + XCTAssertTrue(DeduplicateFooterCopy.showsFreeRemoval(remaining: 0, reviewedCount: 1)) + XCTAssertFalse(DeduplicateFooterCopy.showsFreeRemoval(remaining: 4, reviewedCount: 4)) + XCTAssertFalse(DeduplicateFooterCopy.showsFreeRemoval(remaining: 5, reviewedCount: 4)) + XCTAssertFalse(DeduplicateFooterCopy.showsFreeRemoval(remaining: nil, reviewedCount: 4)) + XCTAssertFalse(DeduplicateFooterCopy.showsFreeRemoval(remaining: 0, reviewedCount: 0)) + + // After a free removal the summary says what is still waiting. + let summary = DeduplicateCommitSummary(deletedCount: 2, failedCount: 0, bytesReclaimed: 10_000_000, receiptPath: nil, hardDelete: false) + XCTAssertEqual( + DeduplicateView.completedStatusCopy(for: summary, deferredFileCount: 2).message, + (DeduplicateView.completedStatusCopy(for: summary).message ?? "") + + "\n2 more are waiting. Your choices are saved; scan again to continue." + ) + XCTAssertEqual( + DeduplicateFooterCopy.waitingLine(deferredFileCount: 1_200), + "\(1_200.formatted()) more are waiting. Your choices are saved; scan again to continue." + ) + XCTAssertNil(DeduplicateView.completedStatusCopy(for: summary, deferredFileCount: nil).message?.range(of: "waiting")) + XCTAssertNil(DeduplicateView.completedStatusCopy(for: summary, deferredFileCount: 0).message?.range(of: "waiting")) + } + + func testFooterAcceptCallsIdenticalLaneOnly() async throws { + let identicalOne = laneCluster("identicalOne", lane: .identical) + let identicalTwo = laneCluster("identicalTwo", lane: .identical) + let nearly = laneCluster("nearly", lane: .nearlyIdentical) + let look = laneCluster("look", lane: .lookAtEach) + let store = try await scannedStore([identicalOne, nearly, identicalTwo, look]) + + DeduplicateFooterCopy.acceptIdenticalCopies(in: store) + + XCTAssertEqual(store.approvedClusterIDs, [identicalOne.id, identicalTwo.id]) + XCTAssertFalse(store.approvedClusterIDs.contains(nearly.id), "Nearly identical groups go through Quick Review") + XCTAssertFalse(store.approvedClusterIDs.contains(look.id)) + + XCTAssertEqual(CommitFooterButtonDensity.full.acceptAllTitle, "Accept Identical Copies") + XCTAssertEqual(CommitFooterButtonDensity.compact.acceptAllTitle, "Accept Identical") + XCTAssertEqual( + DeduplicateFooterCopy.acceptIdenticalMenuTitle(groupCount: 3), + "Accept Identical Copies (3)" + ) + XCTAssertEqual( + DeduplicateFooterCopy.acceptIdenticalHelp, + "Keeps one file in every group of identical copies and marks the rest for the Trash" + ) + } + + func testConfirmationCountUsesPreparedPlan() 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) + + XCTAssertEqual(DeduplicateFooterCopy.confirmationFileCount(for: store), 4, "No prepared plan: the reviewed plan") + + XCTAssertNotNil(store.prepareFreeBatchCommitPlan(remaining: 2)) + XCTAssertEqual( + DeduplicateFooterCopy.confirmationFileCount(for: store), 2, + "A free batch is confirmed with the batch's number" + ) + XCTAssertEqual(store.reviewedDeletionPlan().count, 4) + + store.discardPreparedCommitPlan() + XCTAssertEqual(DeduplicateFooterCopy.confirmationFileCount(for: store), 4, "Cancelling discards the batch") + } + + func testNewDedupeIdentifiersAreRegistered() { + let identifiers = [ + AccessibilityIdentifiers.dedupeLanesQuickReviewNearlyIdentical, + AccessibilityIdentifiers.quickReviewAcceptRest, + AccessibilityIdentifiers.dedupeFreeBatchCommit, + AccessibilityIdentifiers.dedupeUnlockAll, + ] + XCTAssertEqual(identifiers, [ + "dedupe.lanes.quickReviewNearlyIdentical", + "quickReview.acceptRest", + "dedupe.freeBatchCommit", + "dedupe.unlockAll", + ]) + for id in identifiers { + XCTAssertTrue(AccessibilityIdentifiers.all.contains(id), id) + } + // Existing identifiers stay on their controls (D-FRX-19). + XCTAssertEqual(AccessibilityIdentifiers.dedupeLanesAcceptSafe, "dedupe.lanes.acceptSafe") + XCTAssertEqual(AccessibilityIdentifiers.dedupeLanesQuickReview, "dedupe.lanes.quickReview") + } + + /// With the lanes bar compact the Options menu is the only way into Quick + /// Review, so it must not open a lane with nothing waiting while another has groups. + func testMenuQuickReviewOpensNearlyIdenticalWhileThatLaneHasGroups() { + XCTAssertEqual(DeduplicateFooterCopy.menuQuickReviewLane(nearlyIdenticalGroups: 3), .nearlyIdentical) + XCTAssertEqual(DeduplicateFooterCopy.menuQuickReviewLane(nearlyIdenticalGroups: 1), .nearlyIdentical) + XCTAssertEqual(DeduplicateFooterCopy.menuQuickReviewLane(nearlyIdenticalGroups: 0), .lookAtEach) + } } diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift index 5cda6079..4e940d92 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift @@ -235,8 +235,8 @@ final class DeduplicateStatusViewTests: XCTestCase { } func testBulkAcceptLabelMatchesHighConfidenceOnlyBehavior() { - XCTAssertEqual(CommitFooterButtonDensity.full.acceptAllTitle, "Accept All Safe") - XCTAssertEqual(CommitFooterButtonDensity.compact.acceptAllTitle, "Accept Safe") + XCTAssertEqual(CommitFooterButtonDensity.full.acceptAllTitle, "Accept Identical Copies") + XCTAssertEqual(CommitFooterButtonDensity.compact.acceptAllTitle, "Accept Identical") } /// One confidence vocabulary across the review surface: the filter tabs @@ -252,8 +252,25 @@ final class DeduplicateStatusViewTests: XCTestCase { XCTAssertEqual(MatchReasonFormatter.confidenceLabel(.medium), DedupeClusterConfidenceFilter.medium.label) XCTAssertEqual(MatchReasonFormatter.confidenceLabel(.low), DedupeClusterConfidenceFilter.low.label) + // FRX C-13: the button now says "Identical", so the sentence beside it + // carries the Safe word that links it to the Safe tab. + let identicalLane = DeduplicateReviewLanes( + clusters: [DuplicateCluster( + kind: .exactDuplicate, + members: [ + PhotoCandidate(path: "/dest/a.jpg", size: 1, modificationTime: 0), + PhotoCandidate(path: "/dest/b.jpg", size: 1, modificationTime: 0), + ], + suggestedKeeperIDs: [], + bytesIfPruned: 1, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: .exactDuplicate)) + )], + reviewedIDs: [] + ) { _ in .identical } + let identicalSentence = identicalLane.identicalText(files: 1, bytes: 1_000_000) ?? "" XCTAssertTrue( - CommitFooterButtonDensity.full.acceptAllTitle.contains(DedupeClusterConfidenceFilter.high.label) + identicalSentence.localizedCaseInsensitiveContains(DedupeClusterConfidenceFilter.high.label), + identicalSentence ) } diff --git a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift index 46d0919b..48ba4096 100644 --- a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift +++ b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift @@ -90,6 +90,17 @@ final class ScreenRenderEvidenceTests: XCTestCase { assertWritten("m1-unlock-dedupe") } + func testRenderDeduplicateLanes() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .deduplicateReviewLanes) + try await render( + RootSplitView(appState: appState), + name: "m2-deduplicate-lanes", + size: NSSize(width: 1180, height: 820) + ) + assertWritten("m2-deduplicate-lanes") + } + private func makeEntitlementStore() async -> EntitlementStore { let store = EntitlementStore( storeKit: EvidenceStore(), diff --git a/ui/Tests/ChronoframeAppTests/TipsTests.swift b/ui/Tests/ChronoframeAppTests/TipsTests.swift index dba29638..b02cae0e 100644 --- a/ui/Tests/ChronoframeAppTests/TipsTests.swift +++ b/ui/Tests/ChronoframeAppTests/TipsTests.swift @@ -31,7 +31,7 @@ final class TipsTests: XCTestCase { ) XCTAssertEqual( TipCopy.AcceptSafeSuggestions.message, - "Safe groups are matches Chronoframe has verified. Accept them together and keep moving. Chronoframe never selects uncertain matches for you." + "Identical copies are the same file saved more than once. Accepting them keeps one and marks the rest for the Trash. Chronoframe never selects uncertain matches for you." ) } diff --git a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift index 87680168..ec1a7b35 100644 --- a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift +++ b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift @@ -51,6 +51,24 @@ final class UITestWindowFitTests: XCTestCase { XCTAssertEqual(pinned.maxY, visible.maxY) } + func testDeduplicateReviewLanesScenarioIsMeteredAndSizedLikeTheWideReview() { + let scenario = UITestScenario.deduplicateReviewLanes + XCTAssertEqual(UITestScenario(rawValue: "deduplicateReviewLanes"), scenario) + XCTAssertTrue(scenario.usesMeteredTrialUI) + XCTAssertFalse(scenario.opensSettingsOnLaunch) + XCTAssertEqual(scenario.preferredMainWindowSize, UITestScenario.deduplicateReviewWide.preferredMainWindowSize) + XCTAssertEqual(scenario.preferredMainWindowSize, NSSize(width: 1180, height: 820)) + + // On a small runner display it shrinks to fit like every other main-window scenario. + let size = UITestScenario.fittedContentSize( + preferred: scenario.preferredMainWindowSize, chrome: chrome, + visible: NSSize(width: 1024, height: 690), minimum: minimum + ) + XCTAssertLessThanOrEqual(size.width, 1024 - chrome.width) + XCTAssertLessThanOrEqual(size.height, 690 - chrome.height) + XCTAssertGreaterThanOrEqual(size.height, minimum.height) + } + func testOverAllowancePreviewScenarioIsMeteredAndSizedLikeThePreviewScenario() { let scenario = UITestScenario.runPreviewOverAllowance XCTAssertEqual(UITestScenario(rawValue: "runPreviewOverAllowance"), scenario)