From a09eca6b7fb0d59c637bfa080114cc5eb5e81843 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sat, 28 Nov 2026 17:45:19 -0800 Subject: [PATCH 01/30] FRX WP-00: plan folder Co-Authored-By: Claude Fable 5.2 --- .../first-run-experience/ACCEPTANCE_MATRIX.md | 20 + docs/plan/first-run-experience/BLOCKED.md | 5 + docs/plan/first-run-experience/CONTRACTS.md | 484 ++++++++++++++++++ docs/plan/first-run-experience/DECISIONS.md | 48 ++ .../first-run-experience/EVIDENCE_LEDGER.md | 14 + .../IMPLEMENTATION_PLAN.md | 190 +++++++ .../ORCHESTRATOR_KICKOFF.md | 71 +++ docs/plan/first-run-experience/PROGRESS.md | 42 ++ .../bin/add_translated_keys.py | 82 +++ 9 files changed, 956 insertions(+) create mode 100644 docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md create mode 100644 docs/plan/first-run-experience/BLOCKED.md create mode 100644 docs/plan/first-run-experience/CONTRACTS.md create mode 100644 docs/plan/first-run-experience/DECISIONS.md create mode 100644 docs/plan/first-run-experience/EVIDENCE_LEDGER.md create mode 100644 docs/plan/first-run-experience/IMPLEMENTATION_PLAN.md create mode 100644 docs/plan/first-run-experience/ORCHESTRATOR_KICKOFF.md create mode 100644 docs/plan/first-run-experience/PROGRESS.md create mode 100644 docs/plan/first-run-experience/bin/add_translated_keys.py diff --git a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md new file mode 100644 index 00000000..74e39ce7 --- /dev/null +++ b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md @@ -0,0 +1,20 @@ +# First-run experience — acceptance matrix + +Status: not started. No row is 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 | +|---|---|---|---|---|---| +| A-FRX-01 | Preview and completion say whether every file found is accounted for, and never claim it when the numbers disagree (rec 2) | ChronoframeCoreRunAccountingTests/*; RunAccountingTextTests/*; RunWorkspaceModelTests/testAccountingLineOnlyForReadyPreviewAndFinishedCopy, testCopyCompleteAndPreviewFixturesAreBalanced | H-FRX-1 | todo | todo-owner | +| A-FRX-02 | The completion screen can undo that copy through the hash-checked revert (rec 2) | SwiftOrganizerEngineIntegrationTests/testTransferSummaryCarriesReceiptPath; AppStateTests/testLastCopyUndoEntryMatchesReceiptPath, testNoUndoEntryWithoutReceiptPath, testUndoLastCopyRevertsThatReceiptOnly | H-FRX-1 | todo | todo-owner | +| 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 | todo | 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 | todo | 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 | 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 | 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-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 | +| A-FRX-12 | The ready preview shows photos without a click, the folder picture with real counts, and the technical panels behind Details (rec 6) | histogram tests (2 new); RunTimelinePresentationTests (3 new); LayoutPictureModelTests/*; RunWorkspaceModelTests/testRunningPreviewMessageSaysOnlyReading | H-FRX-6 | todo | todo-owner | +| A-FRX-13 | Every new string ships in German; no baseline key is lost | script/check_german_localization.py at G1, G2, G3 | — | todo | n/a | +| A-FRX-14 | No safety invariant is weakened; source folders and the Photos library stay read-only | script/check_agents_invariants_have_tests.sh; cf_swift.sh guards; tagged tests (INV 1, 6, 8, 14, 15, 17, 29) | — | todo | n/a | diff --git a/docs/plan/first-run-experience/BLOCKED.md b/docs/plan/first-run-experience/BLOCKED.md new file mode 100644 index 00000000..6ceb6c65 --- /dev/null +++ b/docs/plan/first-run-experience/BLOCKED.md @@ -0,0 +1,5 @@ +# First-run experience — blocked items + +Status: not started. No blocked items. + +Entry format: see "Blocked items" in `docs/plan/next-half/AGENT_RULES.md`. Only Nishith marks an item resolved. diff --git a/docs/plan/first-run-experience/CONTRACTS.md b/docs/plan/first-run-experience/CONTRACTS.md new file mode 100644 index 00000000..6a138a4f --- /dev/null +++ b/docs/plan/first-run-experience/CONTRACTS.md @@ -0,0 +1,484 @@ +# First-run experience — contracts + +Status: approved, not started. Prepared 2026-11-28 from the six onboarding recommendations Nishith approved that day. Anchors below were read on `feature/edit-preservation-impl` at 40317b6 (PR #299); WP-00 refreshes them on `main` after #299 merges. If a line moved, search for the quoted declaration. + +Plan prefix `FRX`. Read `docs/plan/next-half/AGENT_RULES.md` first, then `DECISIONS.md`. + +Goal: a person with tens of thousands of photos, no technical vocabulary and a fear of losing one picture gets from first launch to a verified first result without a surprise. Three milestones, each its own stacked branch (D-FRX-01): + +- **M1 Trust and paywall** (`feature/first-run-trust`): "every photo is accounted for", Undo on the completion screen, no-surprise free limit, a free whole month, unlock sheet that names the outcome. +- **M2 Duplicates** (`feature/first-run-duplicates`): identical copies first, Quick Review for nearly identical, the keep promise made visible, a free removal step in whole groups. +- **M3 Guided first job** (`feature/first-run-guided`): two plain questions before the first preview, Year/Month for new people, photos and the folder picture on the preview. + +Copy rule for every string in this file: implement it exactly; use the existing plural pattern of the file you are in for the singular form (`1 photo or video`, `1 file`, `1 group`); numbers are formatted with `.formatted()`; byte counts with the formatter the file already uses. No string is looked up after interpolation (CLAUDE.md "Localization"). + +## Facts this design rests on (verified 2026-11-28) + +1. `RunMetrics` (`ChronoframeCore/RunModels.swift:189–290`) carries `discoveredCount` (media only), `plannedCount` (= new + exact copies + sidecar companions), `alreadyInDestinationCount`, `duplicateCount`, `hashErrorCount`, `copiedCount`, `failedCount`, `skippedCount`, `plannedCompanionCount`, `copiedCompanionCount`, `dateHistogram`. Every discovered media file lands in exactly one of new / exact copy / already there / unreadable (`DryRunPlanner.swift:194–325`), but nothing states or tests that the four add up to `discoveredCount`. +2. Preview headline: `RunPreviewHeadline` (`Views/Run/RunPreviewHeadline.swift:9–121`), shown by `RunWorkspaceModel.heroState` `.dryRunFinished` (`RunWorkspaceModel.swift:307–316`) and `RunPreviewSummarySection` (`RunSectionViews.swift:260–315`). Completion: `.finished` (`RunWorkspaceModel.swift:334–356`), `RunOutcomeSummaryCard` (`CurrentRunView.swift:123–180`), which offers only "Open History". +3. The organize receipt is `audit_receipt__.json` in `/.organize_logs` (`TransferExecutor.swift:1425–1450`). The run ID is not in `RunSummary` or `RunArtifactPaths` (`RunModels.swift:292–312`). The only lookup is the private scan inside `SwiftOrganizerEngine.copiedCompanionCount` (`SwiftOrganizerEngine.swift:1349–1372`). +4. Undo exists only in History: `AppState.revertHistoryEntry(_:)` (`AppState.swift:933`) → `HistoryCoordinator.revertHistoryEntry` (`HistoryCoordinator.swift:49–83`) → `RunSessionStore.requestRevert`; confirmation copy "Undo this copy?" (`RunHistoryView.swift:161–180`). No test calls `revertHistoryEntry`. +5. Free allowance: `TrialAllowanceCaps.standard` = 500 organize files, 100 dedupe files (`TrialAllowance.swift:41–45`). The organize meter counts `result.transferCount`, exact copies and companions included (`SwiftOrganizerEngine.swift:886–893`). Debug and non-App-Store builds use `UnrestrictedTrialAuthorizer` and show no allowance; UI-test scenarios in `usesMeteredTrialUI` inject a metered one. +6. The free organize batch is offered only after a refusal: `TrialAuthorizationError.offeringFreeTestBatch(_:plannedTransfers:)` (`TrialAuthorizer.swift:84–96`), built by `FreeTestBatchPlanner.batch(from:limit:)` (`FreeTestBatchPlanner.swift:124–148`): earliest `dateBucket` first, exact copies and companions included. `DryRunPlanningResult.reduced(to:)` (`:153–203`) applies a `FreeTestBatchSelection`. Planned transfers are not kept by any store after a preview. The file's header states a deliberate rule this plan keeps: a reduced plan is proposed, displayed in full and confirmed, and what runs is exactly what was confirmed (paths and identities), never a re-derived set. +7. `PlannedTransfer.dateBucket` is `"yyyy-MM-dd"` or `"Unknown_Date"` (`MediaDateResolver.swift:124–163`). The histogram is monthly, key `"yyyy-MM"` or `"Unknown"`; it counts owners only, meaning new files and exact copies but not sidecar companions (`DryRunPlanner.swift:474–475`), and carries up to 4 `samplePaths` (`CopyPlanBuilder.swift:270–296`). Exact copies are written under `/Duplicate/…`, not in the month folders. Selecting a bar in `RunTimelineView` (`:41`, `:114–117`) already shows those samples; nothing is selected by default. +8. Unlock sheet: `UnlockSheetModel.make` (`UnlockPresentation.swift:82–229`), title "Unlock Chronoframe" for every refusal; "one-time … No subscription." appears only in the no-refusal message (`:200`). Presented by `RootSplitView.swift:103–120` from `runSessionStore.lastRefusal ?? deduplicateSessionStore.lastRefusal`. Price text is StoreKit's `displayPrice` only. +9. Dedupe: `ClusterKind.exactDuplicate` clusters are one `FileIdentity` group by construction (`DuplicateClusterer.swift:162–182`); identities live in `DeduplicateSummary.scanSnapshot.identitiesByPath`. `DeduplicationPlanner.isAutomaticCommitEligible` (`DeduplicationPlanner.swift:293–306`) is true for any high-confidence cluster that is not a non-exact video cluster, so "safe" includes near-duplicate and burst photo clusters. +10. **The planner already skips a group whose members are all Delete**: step 3 of `DeduplicationPlanner.plan` (`:107–114`), with `DeduplicateTests/testPlannerRefusesAllDelete` and `DeduplicationPlannerPropertyTests/testPropertyNoClusterIsCompletelyEmptiedByThePlan`. The skip is silent: no view says so. Pair fan-out (step 5, `:136–185`) runs after that rail, so the rule is about direct deletes; whether fan-out can still empty a skipped group is unverified (DECISIONS, known gaps). +11. Dedupe UI: lanes `DeduplicateReviewLanes` (`Views/Deduplicate/DeduplicateReviewLanes.swift`), built at `DeduplicateView.swift:357–368`; Quick Review is `RapidTriageView`, presented at `DeduplicateView.swift:745–752` over every non-eligible cluster, header text "Rapid Triage" (`RapidTriageView.swift:64`). The footer accept button and the lanes button both call `acceptAllSuggestions()`; the Options menu calls `acceptAllHighConfidence()` (`DeduplicateView.swift:716`). +12. The dedupe trial gate is in the engine (`DeduplicateEngine.swift:204–215`), counts `plan.items.count` (pair partners and sidecars included). `commitReviewed` (`DeduplicateSessionStore.swift:190–236`) commits `preparedCommitPlan` when one is set and saves the review first. A refusal leaves the review paused and intact. A **successful** commit deletes the saved review (`:757–766`, `reviewSnapshotStore.remove`). The first confirmation dialog takes its count from `reviewedDeletionPlan()` (`DeduplicateView.swift:511–545`), not from `preparedCommitPlan`. +13. Folder layout is one global preference: `PreferencesStore.folderStructure` (`PreferencesStore.swift:98`, default applied at `:196–197`, persisted only on change). `FolderStructure.default` is `.yyyyMMDD` (`EngineDomainModels.swift:325`), used by the CLI and App Intents. A transfer always re-plans with the current preference (`SwiftOrganizerEngine.swift:721–741`). +14. Folder picker: `FolderAccessServicing.chooseFolder(startingAt:prompt:)` opens at the **parent** of the given path (`FolderAccessService.swift:148–180`) and resolves home with `FileManager.default.homeDirectoryForCurrentUser`, which is the container in a sandboxed build. `AppState.folderAccessService` is private (`AppState.swift:52`). The protocol already has one requirement with a protocol-extension default (`:112–116`). `SetupCoordinator.selectSourceFolder` (`:210`) and `selectDestinationFolder` (`:483`) validate and persist bookmarks. First route is `.organize(.setup)` (`AppState.swift:220`). `@AppStorage("didOnboard")` (`SetupView.swift:13`) reads `UserDefaults.standard`. +15. Free space: `PhotosExportExecutor.liveFreeSpace(at:)` (`PhotosExportExecutor.swift:216`) is the one public helper. No preview byte total exists. +16. `ui/Xcode/UITests/ChronoframeUITests.swift` contains none of these literals: "Unlock Chronoframe", "Accept All Safe", "Rapid Triage", "safe match", "Copy complete", "2019/07/14". + +--- + +# Milestone 1 — Trust and paywall + +## C-00 Render evidence harness — `ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift` (WP-01, new) + +`@MainActor final class ScreenRenderEvidenceTests: XCTestCase`. Each test builds an `AppState` with `UITestAppStateFactory.make(scenario:)`, hosts one view in an offscreen window and writes a PNG. Every test starts with `try XCTSkipUnless(FileManager.default.fileExists(atPath: evidenceDirectory + "/.enabled"))`, where `evidenceDirectory` is `/.tmp/frx-evidence` derived from `#filePath`. CI never has the marker, so CI skips. + +```swift +private func render(_ view: V, name: String, size: NSSize = NSSize(width: 1360, height: 920)) async throws { + let hosting = NSHostingView(rootView: view + .frame(width: size.width, height: size.height) + .background(Color(nsColor: .windowBackgroundColor))) + let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.borderless], backing: .buffered, defer: false) + window.contentView = hosting + hosting.layoutSubtreeIfNeeded() + try await Task.sleep(nanoseconds: 1_500_000_000) + let bitmap = try XCTUnwrap(hosting.bitmapImageRepForCachingDisplay(in: hosting.bounds)) + hosting.cacheDisplay(in: hosting.bounds, to: bitmap) + let data = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) + try data.write(to: URL(fileURLWithPath: evidenceDirectory).appendingPathComponent(name + ".png")) +} +``` +M1 tests: `testRenderPreviewOverAllowance` (scenario C-08), `testRenderCopyComplete` (`runCopyComplete`), `testRenderUnlockSheetOrganize`, `testRenderUnlockSheetDedupe` (the sheet built directly with stub clients, as `UnlockSheetLayoutTests` does). Later milestones add tests to this class. The tests assert only that a file was written. Renders are evidence for the orchestrator to look at, never a pass/fail check, and are not committed. + +## C-01 Accounting numbers — `ui/Sources/ChronoframeCore/RunAccounting.swift` (WP-02, new, pure) + +```swift +public struct RunAccounting: Equatable, Sendable { + public let found: Int // metrics.discoveredCount + public let new: Int // max(0, plannedCount − duplicateCount − plannedCompanionCount) + public let extraCopies: Int // duplicateCount + public let alreadyThere: Int // alreadyInDestinationCount + public let unreadable: Int // hashErrorCount + public let copiedMedia: Int // max(0, copiedCount − copiedCompanionCount); 0 for a preview + public let notCopied: Int // finished only: max(0, (new + extraCopies) − copiedMedia); 0 for a preview + /// found − (new + extraCopies + alreadyThere + unreadable). Zero means every file found is listed. + public let remainder: Int + public var isBalanced: Bool { remainder == 0 } + + public static func preview(_ metrics: RunMetrics) -> RunAccounting + public static func finished(_ metrics: RunMetrics) -> RunAccounting +} +``` +No rounding, no clamping of `remainder` (a negative remainder is a real disagreement and must show as unbalanced). + +## C-02 Accounting sentence — `ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift` (WP-05, new) + +```swift +enum RunAccountingText { + static func previewLine(_ a: RunAccounting) -> String? // nil when a.found == 0 + static func finishedLine(_ a: RunAccounting, isFreeBatch: Bool) -> String? // nil when a.found == 0 +} +extension RunWorkspaceModel { + /// previewLine for `.dryRunFinished` with a non-stale preview; finishedLine for `.finished`; nil for every other status + /// (nothing to copy, reverted, reorganized, failed, running). + var accountingLine: String? { get } +} +``` +Preview, shown as the first line of `RunPreviewSummarySection` above the existing exception rows: +- balanced: `Every one of the {found} photos and videos Chronoframe found is listed below.` +- not balanced: `Chronoframe found {found} photos and videos, and {abs(remainder)} are not in this plan yet. Rebuild the preview before copying.` + +Finished, shown as the first line of `RunOutcomeSummaryCard`. Parts are joined with ", " and a part is omitted when its number is 0: +- balanced and `notCopied == 0`: `All {found} photos and videos Chronoframe found are accounted for: {copiedMedia} copied, {alreadyThere} already in your library, {unreadable} could not be read.` +- free batch (`isFreeBatch`, `remainder > 0`, `notCopied == 0`): `Chronoframe found {found} photos and videos. This free copy handled {found − remainder}; {remainder} are waiting for the next copy.` +- `notCopied > 0`: `{notCopied} planned photos and videos were not copied. Your originals were not changed. See Problems.` +- any other unbalanced case: `Chronoframe found {found} photos and videos, and {abs(remainder)} are not accounted for in this copy. Open History for the full record.` + +Never the words "safe to delete" or any statement about what may be removed from the source. `isFreeBatch` is `summary.copiedBatchSourcePaths != nil`. + +## C-03 Receipt path in the run summary (WP-02, WP-03) + +`RunArtifactPaths` (`RunModels.swift:292`) gains `public var receiptPath: String?`, last init parameter, default `nil` (synthesized `Codable` keeps older data decodable). + +`SwiftOrganizerEngine`: move the directory scan at `:1356–1364` into +```swift +nonisolated static func receiptURL(runID: UUID, logsDirectoryPath: String?) -> URL? +``` +(same rule: name has the audit-receipt prefix, ends `.json`, contains `runID.uuidString`; last when sorted). `copiedCompanionCount` calls it. The transfer `.complete` summary (`:999–1024`) passes `executionResult.artifacts` with `receiptPath` set from it. `TransferExecutor` is not edited. + +## C-04 Undo on the completion screen (WP-05) + +`AppState`: +```swift +var lastCopyUndoEntry: RunHistoryEntry? { get } // status .finished, mode .transfer, receiptPath non-nil, + // and historyStore.entries has an .auditReceipt entry with that path +func undoLastCopy() // guard let entry = lastCopyUndoEntry; revertHistoryEntry(entry) +``` +If History has not picked the receipt up when the run finishes, refresh History once on completion using the call the run-completion handler already uses. No new deletion path: Undo is `revertHistoryEntry` unchanged (INV-08). + +`RunOutcomeSummaryCard`: beside "Open History", a button `Undo This Copy…` (identifier `runOutcomeUndoCopy`), shown only when `lastCopyUndoEntry != nil`. It opens a confirmation dialog with the same title, message and button strings History uses (`RunHistoryView.swift:161–180`; reuse the identical literals so the catalog keys are shared). When there is no entry the existing sentence pointing to History stays as it is. + +Below the buttons, for `.finished` only: text `Have more photos somewhere else? Add that folder next. Photos already in your library are skipped.` and button `Add Another Folder` (identifier `runOutcomeAddFolder`) → `appState.navigate(to: .organize(.setup))`. + +## C-05 Free whole month — Core (WP-02) + +The rule in `FreeTestBatchPlanner.swift:3–18` stands: a free batch is proposed, displayed in full and confirmed, and what runs is the confirmed paths and identities. A month is therefore only ever a **proposal**; the copy itself uses the existing identity selection, unchanged. + +`ui/Sources/ChronoframeCore/FreeMonthBatchPlanner.swift` (new, pure): +```swift +public struct FreeMonthOption: Equatable, Sendable, Identifiable { + public var id: String { key } + public let key: String // "yyyy-MM" + public let fileCount: Int // that month's new photos and videos plus their sidecars + public let fits: Bool // fileCount <= remaining +} + +public enum FreeMonthBatchPlanner { + /// "2026-10-14" → "2026-10". nil for the unknown-date bucket or anything that is not yyyy-MM-dd. + public static func monthKey(forDateBucket bucket: String) -> String? + /// Month key → new files that land in that month: owners with isDuplicate == false plus their companions. + /// Exact copies and undated files are never counted. + public static func newFilesByMonth(for result: DryRunPlanningResult) -> [String: Int] + /// Newest month first. Empty when remaining <= 0. + public static func options(newFilesByMonth: [String: Int], remaining: Int) -> [FreeMonthOption] + /// The newest option that fits; when none fits, the newest option (a partial month). + public static func suggestedOption(_ options: [FreeMonthOption]) -> FreeMonthOption? + /// The transfers a free copy of `monthKey` would run, never more than `limit`. + public static func select(from result: DryRunPlanningResult, monthKey: String, limit: Int) -> [PlannedTransfer] +} +``` +`select` rules: owners are transfers with no entry in `result.companionOwners`, `isDuplicate == false`, and a matching month key, in `FreeTestBatchPlanner.inBatchOrder`. An owner always travels with every companion transfer that names it in `companionOwners`. If the whole month is within `limit`, take all of it. Otherwise take whole days (`dateBucket`) in ascending order while the running total stays within `limit`; if the first day alone exceeds `limit`, take owners of that day in order while they fit. `limit <= 0` → empty. + +`FreeTestBatchPlanner.swift` (edit; both additions go in the struct bodies, not in extensions): +```swift +public struct FreeMonthRequest: Equatable, Sendable { + public let key: String + public let limit: Int // the remaining allowance the screen showed + public init(key: String, limit: Int) +} +// in FreeTestBatchSelection: +public let monthRequest: FreeMonthRequest? // nil from the existing initializer +public init(requestingMonth request: FreeMonthRequest) // confirmedIdentities is empty +// in FreeTestBatch (existing init gains two defaulted parameters): +public let monthKey: String? // default nil +public let wasRequested: Bool // default false; true when the person asked for this month +``` +A requesting selection confirms nothing, so `apply(to:)` returns `[]` for it and `reduced(to:)` would keep nothing: if the engine branch in C-06 were ever missed, the result is "nothing copied". `apply`, `reduced(to:)`, `count`, `isEmpty` and `missingSourcePaths` are not edited. + +`RunMetrics` gains `public var newFilesByMonth: [String: Int]` (default `[:]`, decoded with `decodeIfPresent` wherever the type decodes by hand). + +## C-06 Free whole month — engine and sheet (WP-03) + +`TrialAuthorizer.swift` gains two builders beside `offeringFreeTestBatch` (which stays, uncalled by the engine): +```swift +/// Refusal path. Same conditions as offeringFreeTestBatch; the batch is the suggested month. +static func offeringFreeMonthBatch(_ error: TrialAuthorizationError, result: DryRunPlanningResult) -> TrialAuthorizationError +/// Request path. The person asked to see a free copy of one month. Nothing has been authorized or copied. +static func proposingFreeMonth(_ request: FreeMonthRequest, result: DryRunPlanningResult) -> TrialAuthorizationError +``` +Both build `FreeTestBatch(included: FreeMonthBatchPlanner.select(from: result, monthKey:, limit:), deferredCount: result.transferCount − included.count, monthKey:, wasRequested:)`. +- `offeringFreeMonthBatch`: month = `suggestedOption` over `newFilesByMonth(for: result)` with `remaining = refusal.remaining`; `wasRequested: false`. No offer when there is no option, the batch is empty or it covers the whole plan. +- `proposingFreeMonth`: month = `request.key`, `limit = request.limit`, `wasRequested: true`; when that month now selects nothing, fall back to the suggested month; when that is empty too, no batch. The error's refusal is `.allowanceSpent(TrialRefusal(meter: .organize, requested: result.transferCount, remaining: request.limit))`. + +`SwiftOrganizerEngine.startTransfer`: +- preview metrics (`:535–544`) set `newFilesByMonth: FreeMonthBatchPlanner.newFilesByMonth(for: result)`; +- directly after planning and the zero-transfer branches, before `plan.reduced(to:)` (`:757`) and before `authorizeTransfer`: `if let request = batch?.monthRequest { throw TrialAuthorizationError.proposingFreeMonth(request, result: result) }`. Nothing is reserved, queued or written on this path beyond what a preview already writes; +- the refusal at `:894–903` calls `offeringFreeMonthBatch` instead of `offeringFreeTestBatch`. +The confirmed copy is the existing path untouched: the sheet lists the batch, `AppState.runOfferedFreeTestBatch()` passes `batch.selection` (paths and identities), and the real authorization runs on that count. + +`ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift` (new): +```swift +public enum TrialRemaining { + /// nil when not the App Store channel, unlocked, loading, unknown or unavailable. + public static func value(status: TrialStatus, meter: TrialMeter, isAppStoreChannel: Bool) -> Int? +} +``` + +`UnlockPresentation.swift`: +- titles for `.allowanceSpent`: organize `Organize all {requested} files`, dedupe `Remove all {requested} duplicates`. Other titles unchanged. +- `UnlockSheetModel` gains `let purchaseTermsLine: String?` (defaulted in its init): `One-time purchase with Family Sharing. No subscription.` for `.allowanceSpent` and `.requiresUnlock`; nil for `.purchaseUnconfirmed` and for no refusal (that message already says it). +- batch detail when `offeredBatch.monthKey` is non-nil: `Copies {Month Year} now, {files}, and leaves {deferred} for later.` (`{Month Year}` from the key with the `MMMMyyyy` template in the current locale). The earliest-first sentences stay for a batch without a month. +- when `offeredBatch?.wasRequested == true` (the person asked for the free copy): title `Copy {Month Year} free`; message `These {included} new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.`; the batch action comes **first** in `actions`, then buy, restore, dismiss. + +`UnlockSheet.swift`: render `purchaseTermsLine` directly under the message, secondary ink, no badge. + +Price text is still only `displayPrice` from StoreKit. No number or currency is written in code or copy. + +## C-07 Preview tells the truth about the free limit (WP-04) + +`RunWorkspaceContext` gains `var organizeAllowanceRemaining: Int?` (nil = not metered or unknown), filled in `CurrentRunView` from `TrialRemaining.value(status: appState.trialStatusStore.status, meter: .organize, isAppStoreChannel: appState.isAppStoreChannel)`; the `RunWorkspaceModel` store initializer takes it as a defaulted parameter. + +```swift +enum RunFreeCopyState: Equatable { + case notMetered + case fits(remaining: Int) + case overAllowance(remaining: Int, planned: Int, options: [FreeMonthOption], suggested: FreeMonthOption?) + case spent(planned: Int) +} +extension RunWorkspaceModel { var freeCopyState: RunFreeCopyState { get } } +``` +Evaluated only for `.dryRunFinished` with `plannedCount > 0` and a non-stale preview; `.notMetered` otherwise. `planned` is `metrics.plannedCount`; options come from `metrics.newFilesByMonth`. + +Hero for `.dryRunFinished` (the hero's primary-action enum gains the cases it needs; its switch in `RunSectionViews.swift` is in the same work package): +- `.notMetered`, `.fits`: unchanged. +- `.overAllowance`: an extra line under the headline, `You can copy {remaining} files free. This plan has {planned}.` followed, when there is a suggested option, by `The newest month that fits is {Month Year}: {fileCount} files.` (partial month: `{Month Year} is larger than that, so the free copy takes its first days.`). Primary button `Copy {Month Year} Free…`, identifier `runFreeMonthCopy`. A menu button `Choose Another Month`, identifier `runFreeMonthMenu`, lists every option as `{Month Year} · {fileCount} files`; an option that does not fit is disabled unless it is the suggested one. Second button `Unlock to Copy Everything`, identifier `runUnlockEverything`. "Start Copying" is not shown in this state. With no options (nothing dated and new): only the first line and `Unlock to Copy Everything`. +- `.spent`: line `Your free copies are used up. This plan has {planned} files.` and the single button `Unlock to Copy Everything`. + +`AppState`: +```swift +@Published private(set) var requestedUnlockRefusal: TrialAuthorizationRefusal? +/// Asks the engine to propose a free copy of that month. Copies nothing; the sheet that follows lists the files (C-06). +func startFreeMonthCopy(_ option: FreeMonthOption) async // runCoordinator.startTransfer(batch: + // FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: option.key, limit: remaining))) +func requestUnlockForPlan(requested: Int? = nil) // requestedUnlockRefusal = .allowanceSpent(TrialRefusal(meter: .organize, + // requested: requested ?? metrics.plannedCount, remaining: remaining)) +``` +`unlockRefusal` (`AppState.swift:512`) and the private copy in `RootSplitView.swift:22–24` become `runSessionStore.lastRefusal ?? deduplicateSessionStore.lastRefusal ?? requestedUnlockRefusal` (`RootSplitView` reads the published AppState value). `dismissUnlockSheet()` also clears `requestedUnlockRefusal`. `retryAfterUnlock()`: when only `requestedUnlockRefusal` is set, clear it and start nothing (the person presses Start Copying, now shown). + +After a free copy finishes, `RunOutcomeSummaryCard` shows the C-02 free-batch line and, when `organizeAllowanceRemaining != nil`, the button `Unlock to Copy the Rest` (identifier `runOutcomeUnlockRest`) → `requestUnlockForPlan(requested: accounting.remainder)`. + +## C-08 Fixtures for M1 renders (WP-04, WP-05) + +WP-04: `UITestScenario` gains `runPreviewOverAllowance` (metered; added to `usesMeteredTrialUI` and `preferredMainWindowSize`). `UITestAppStateFactory` builds it like `runPreviewReview` with preview metrics `discoveredCount 18_475, plannedCount 18_412, alreadyInDestinationCount 63, duplicateCount 1_204`, a histogram of at least 14 months ending `2026-10`, and `newFilesByMonth` with `"2026-10": 212, "2026-09": 148, "2026-08": 734`, the organize ledger at 0 used. + +WP-05: the two existing fixtures do not add up, so they would render the unbalanced wording. Change only `discoveredCount`: `runCopyComplete` 4300 → 4263 (4163 new + 37 exact copies + 63 already there) and `runPreviewReview` 84 → 72 (35 + 7 + 29 + 1 unreadable). `runCopyComplete` also gets `artifacts.receiptPath` set to a fixture path and one `.auditReceipt` entry with that path seeded in its History store, so the Undo button renders. Any test or UI test that asserts the old two numbers is updated under D-FRX-20 (UI tests by the orchestrator at G1). + +--- + +# Milestone 2 — Duplicates + +Wording rule for M2 (D-FRX-12): the Safe / Check / Risky labels, "Delete", "Keep" and "Trash" stay exactly as they are. Only the strings named below change. + +## C-10 Review lane — `ui/Sources/ChronoframeCore/DeduplicateReviewLane.swift` (WP-11, new, pure) + +```swift +public enum DeduplicateReviewLane: String, Sendable, CaseIterable { + case identical // every member is the same file, byte for byte + case nearlyIdentical // auto-eligible, but the files differ + case lookAtEach // not auto-eligible + + public static func lane(for cluster: DuplicateCluster, snapshot: DeduplicateScanSnapshot) -> DeduplicateReviewLane +} +``` +Rule, in order: not `DeduplicationPlanner.isAutomaticCommitEligible(cluster)` → `.lookAtEach`. `kind == .exactDuplicate`, at least two members, every member has an entry in `snapshot.identitiesByPath` and all those identities are equal → `.identical`. `kind == .exactDuplicate` but the identity check fails → `.lookAtEach` (fail closed). Otherwise → `.nearlyIdentical`. `DeduplicationPlanner.swift` is not edited. + +## C-11 Free removal batch — `ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift` (WP-11, new, pure, safety-critical) + +```swift +public struct FreeDedupeBatch: Sendable { + public let plan: DeduplicationPlan + public let includedClusterIDs: [UUID] + public let deferredFileCount: Int // fullPlan.count − plan.count +} + +public enum FreeDedupeBatchPlanner { + public static func batch( + decisions: DedupeDecisions, + reviewedClusters: [DuplicateCluster], + configuration: DeduplicateConfiguration, + snapshot: DeduplicateScanSnapshot, + limit: Int + ) -> FreeDedupeBatch? +} +``` +Algorithm, and nothing else: +1. `full = DeduplicationPlanner.plan(decisions:clusters: reviewedClusters, configuration:snapshot:)`. Return nil when `limit <= 0` or `full.count <= limit`. +2. Order `reviewedClusters` by lane (`identical`, then `nearlyIdentical`, then `lookAtEach`), stable within a lane. +3. Walk that order. For each cluster, copy `decisions` and replace only its `byPath` (so `pairKeepOverrides` is preserved) with a map in which every member path of every reviewed cluster that is **not** selected-so-far-plus-this-one is forced to `.keep`; call `DeduplicationPlanner.plan` over **all** `reviewedClusters` with it. +4. Accept the candidate plan only if **both** hold: its `count <= limit`, and every one of its items is in `full` with the same `path` and the same `expectedIdentity`. If either fails, stop the walk; the last accepted plan is the answer. +5. Return nil when no candidate was accepted or the accepted plan is empty. + +The batch plan is always a `DeduplicationPlanner.plan` result; items are never filtered or assembled by hand. Forcing Keep is **not** monotone: pair Keep-wins (step 2 of the planner) can carry a forced Keep into another group and un-skip a group the all-Delete rail had skipped, which would add a deletion the full plan does not have. Step 4's subset check is what guarantees the batch never deletes anything the person's full reviewed plan would not; the walk fails closed. + +## C-12 Store additions — `ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift` (WP-12) + +```swift +public struct DeduplicateLaneSummary: Equatable, Sendable { public let groups: Int; public let files: Int; public let bytes: Int64 } + +@Published public private(set) var laneSummaries: [DeduplicateReviewLane: DeduplicateLaneSummary] +@Published public var wantsFreeBatchConfirmation: Bool + +public func lane(for cluster: DuplicateCluster) -> DeduplicateReviewLane +public func acceptSuggestions(in lane: DeduplicateReviewLane) +public var fullyMarkedClusterIDs: Set { get } +public func freeBatchOffer(remaining: Int) -> FreeDedupeBatch? +@discardableResult public func prepareFreeBatchCommitPlan(remaining: Int) -> DeduplicationPlan? +public var preparedCommitCount: Int? { get } // preparedCommitPlan?.count +``` +- `laneSummaries`: per lane, the **unreviewed** clusters in it; `files` and `bytes` are the count and total bytes of `DeduplicationPlanner.plan(decisions: suggestedDecisions(for: those clusters), clusters: those clusters, …)`. Recomputed when a scan completes, when a saved review is restored and whenever `approvedClusterIDs` changes. +- `acceptSuggestions(in:)`: `.lookAtEach` does nothing. For the other two it does exactly what `acceptAllSuggestions()` does (`:478–506`), restricted to unreviewed clusters whose lane matches; undo names `Accept Identical Copies` and `Accept Nearly Identical`. `acceptAllSuggestions()` and `acceptAllHighConfidence()` stay as they are with their tests; no view calls them after this plan. +- `fullyMarkedClusterIDs`: reviewed clusters in which every member's decision in `decisions.byPath` is `.delete`. +- `freeBatchOffer(remaining:)`: `FreeDedupeBatchPlanner.batch` over `decisions`, `reviewedClusters`, `lastScanConfiguration` and the scan snapshot; nil without a scan configuration. The result is cached and recomputed only when `decisions`, `approvedClusterIDs` or `remaining` change, because the footer asks on every render. +- `prepareFreeBatchCommitPlan(remaining:)`: sets `preparedCommitPlan` to the offer's plan, remembers that the prepared plan is a free batch, and returns it; nil (and no change) when there is no offer. `prepareReviewedCommitPlan()` and `discardPreparedCommitPlan()` clear that memory. `commitReviewed` is unchanged and commits the frozen plan. +- One existing branch changes (D-FRX-25): in the `.complete` handler (`:757–766`), when the committed plan was a free batch, the three lines that drop the saved review (`reviewSnapshotStore.remove`, `restoredReview = nil`, `savedReviewForCurrentFolder = nil`) are skipped. The saved review was written before the commit; the next scan restores it under the unchanged INV-29 rules, so choices for the files just moved to the Trash drop out and the rest come back. Every other line of that handler is untouched. + +## C-13 Review UI (WP-13) + +`DeduplicateReviewLanes` keeps its existing initializer and `safeGroupCount`, `checkGroupCount`, `reviewedGroupCount` with their current meaning (the tests in `DeduplicateReviewLanesTests.swift` stay untouched). It gains `identicalGroupCount`, `nearlyIdenticalGroupCount` and a second initializer `init(clusters:reviewedIDs:lane:)` taking `lane: (DuplicateCluster) -> DeduplicateReviewLane`, for which `safeGroupCount == identicalGroupCount + nearlyIdenticalGroupCount`. The view uses the second initializer with `sessionStore.lane(for:)`. + +Lanes bar, three rows in this order (a row with 0 groups is omitted): +- identical: `{n} safe groups are identical copies. Accept them together: {files} files, {bytes}.` Button `Accept Identical Copies` → `acceptSuggestions(in: .identical)`. Keeps the existing identifier `dedupeLanesAcceptSafe`. +- nearly identical: `{n} safe groups are nearly identical. Look through them quickly.` Button `Quick Review` (new identifier `dedupeLanesQuickReviewNearlyIdentical`) → Quick Review over that lane. +- look at each: the existing check sentence unchanged, existing `Quick Review` button and identifier → Quick Review over that lane. +- one line under the rows, secondary ink: `Chronoframe always suggests keeping one photo in every group.` +Compact text: `{n} identical · {m} nearly identical · {k} to check` (parts with 0 omitted). + +Quick Review (`RapidTriageView`): new inputs `lane: DeduplicateReviewLane` and `clustersToReview` = the **unreviewed** clusters in that lane. Header text becomes `Quick Review`. For `.nearlyIdentical` only: once `currentIndex >= 1` and groups remain, a button `Accept the Rest ({remaining})` (identifier `quickReviewAcceptRest`) → `acceptSuggestions(in: .nearlyIdentical)` and show the existing completion screen. The Options-menu "Quick Review" opens the `.lookAtEach` lane. + +Commit footer: +- the accept button title becomes `Accept Identical Copies` (compact: `Accept Identical`), calls `acceptSuggestions(in: .identical)`, help text `Keeps one file in every group of identical copies and marks the rest for the Trash`. `DeduplicateStatusViewTests.swift:238–239` and `:256` assert the old titles and that the title contains the Safe label; under D-FRX-20 the first two take the new titles and the third asserts that the identical-lane sentence contains the Safe label, case-insensitively; +- the Options-menu item becomes `Accept Identical Copies ({identical groups})`, same action; +- when `fullyMarkedClusterIDs` is not empty, a line in the footer status and as a suffix of both confirmation-dialog messages: `{n} groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them.` +- both confirmation dialogs take their file count from `sessionStore.preparedCommitCount ?? reviewedDeletionPlan().count`, so a free batch is confirmed with the batch's number; +- `Tips.swift:17–18`: title `Accept identical copies in one step`, 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.` + +Free removal, when `TrialRemaining.value(… meter: .dedupe …)` is non-nil and the reviewed plan's count exceeds it: +- a line above the footer buttons: `You can remove {remaining} duplicates free. Your reviewed groups hold {count}.` (`remaining == 0`: `Your free removals are used up.`); +- when `freeBatchOffer(remaining:)` is non-nil the destructive button becomes `Move {k} Files to Trash Free` (identifier `dedupeFreeBatchCommit`): it calls `prepareFreeBatchCommitPlan(remaining:)` and opens the existing first confirmation dialog; and a second button `Unlock to Remove All {count}` (identifier `dedupeUnlockAll`) → `appState.requestUnlockForDuplicates(requested:remaining:)`, which sets `requestedUnlockRefusal` with meter `.dedupe`; +- without an offer the footer is unchanged apart from the line. +After a free batch commit the summary adds: `{deferred} more are waiting. Your choices are saved; scan again to continue.` + +Unlock sheet on a dedupe refusal (all of this is WP-13, so the enum case and both of its exhaustive switches change together): `UnlockSheetAction` gains `runFreeDedupeBatch(fileCount: Int, deferredCount: Int)`; `UnlockSheetModel.make` gains `offeredDedupeBatch: (fileCount: Int, deferredCount: Int)? = nil`, placed where the organize batch action is placed; label `Move {k} Files to Trash Free`, detail `Moves {k} files from whole groups to the Trash now and leaves {deferred} for later.` The switches at `UnlockSheet.swift:~133–165` and `UnlockSheetBatchOfferTests.swift:81–88` get the new arm. `AppState.offeredFreeDedupeBatch` is `freeBatchOffer(remaining:)` when the dedupe refusal is `.allowanceSpent` with `remaining > 0`; `AppState.runOfferedFreeDedupeBatch()` dismisses the refusal and sets `wantsFreeBatchConfirmation = true`; `DeduplicateView` reacts by preparing the batch plan and opening the same confirmation dialog. Nothing is moved to the Trash without that dialog. + +## C-14 Fixture for M2 renders (WP-13) + +`UITestScenario.deduplicateReviewLanes` (metered, 1180×820): 6 `.exactDuplicate` clusters of 3 members (annotation `.high`, members sharing one `FileIdentity` in the mock snapshot), the first 2 of them approved by the factory with `acceptSuggestionsForCluster`; 3 `.nearDuplicate` clusters with `.high`; 5 `.nearDuplicate` with `.medium`; the dedupe ledger at 98 used, so the reviewed plan (4 files) exceeds the 2 remaining and the free-removal footer renders. `MockDeduplicateEngine` gets an optional per-path identity override for this scenario only; the existing scenarios keep their current identities. + +--- + +# Milestone 3 — Guided first job + +## C-20 Folder size estimate — `ui/Sources/ChronoframeCore/FolderSizeEstimator.swift` (WP-21, new, read-only) + +```swift +public struct FolderSizeEstimate: Equatable, Sendable { + public let fileCount: Int + public let totalBytes: Int64 + public let isComplete: Bool // false when cancelled or any entry could not be read +} +public enum FolderSizeEstimator { + public static func estimate(root: URL, isCancelled: @Sendable () -> Bool = { false }) -> FolderSizeEstimate? +} +``` +Regular files only, by `FileManager` enumerator with `.skipsHiddenFiles` and `.skipsPackageDescendants`; symbolic links are skipped, never followed (INV-15); nothing is opened, created or modified. Checks `isCancelled` every 500 entries. nil when the root cannot be enumerated at all. It counts every regular file, so copy says "files", never "photos". + +## C-21 Year/Month for new people — `ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift:196–197` (WP-21) + +When no `folderStructure` value is stored: `.yyyyMMDD` if the defaults show prior use (a non-empty `lastManualDestinationPath`, `lastManualSourcePath` or `manualSourceItemPaths`, or any key with the `bookmark.` or `history.destination.` prefix), otherwise `.yyyyMM`. The resolved value is written once so it never flips later. A stored value is never changed. `FolderStructure.default`, the CLI and App Intents are not edited. `UITestAppStateFactory` sets `.yyyyMMDD` explicitly for every existing scenario so their screens do not change. + +## C-22 Opening the picker at a place — `FolderAccessService.swift` (WP-21) + +`FolderAccessServicing` gains +```swift +@MainActor func chooseFolder(openingAt directory: URL, prompt: String) -> URL? +``` +with a protocol-extension default that forwards to `chooseFolder(startingAt: directory.path, prompt:)` (the pattern at `:112–116`), so test conformers need no edit. `FolderAccessService` implements it for real: `panel.directoryURL` is `directory` when it exists on a local volume, otherwise the fallback `initialPanelDirectoryURL` uses for an empty path. `MockFolderAccessService` records the directory and returns its canned folder. + +Also new there: `public static func realHomeDirectoryURL() -> URL`, the home directory from the password database (`getpwuid(getuid())`), falling back to `FileManager.default.homeDirectoryForCurrentUser`. In a sandboxed build the latter is the app's container; the guided places must open in the person's real Pictures, Desktop and Downloads. The person still confirms the folder in the panel; no entitlement changes. + +## C-23 Guided setup (WP-22) + +`ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift` (new): +```swift +enum GuidedSetupStep: Equatable { case source, destination } +enum GuidedSourcePlace: String, CaseIterable { case pictures, desktop, downloads, externalDrive, other } +enum GuidedSourceKind: Equatable { case folder, applePhotos } + +struct GuidedSetupGateInputs: Equatable { + var isEligible: Bool // AppState.guidedSetupEligible + var didOnboard: Bool + var sourcePath: String + var sourceItemCount: Int + var destinationPath: String + var hasHistory: Bool + var hasProfiles: Bool +} +enum GuidedSetupGate { static func shouldShow(_ inputs: GuidedSetupGateInputs) -> Bool } // eligible, not onboarded, everything else empty/false + +struct GuidedSetupModel: Equatable { + var step: GuidedSetupStep + var sourceKind: GuidedSourceKind + var sourcePath: String + var destinationPath: String + var isMeasuring: Bool + var estimate: FolderSizeEstimate? + var destinationFreeBytes: Int64? + + var title: String + var body: String + var measureLine: String? + var spaceLine: String? + var spaceIsWarning: Bool + var primaryTitle: String + var canContinue: Bool + static func startingDirectory(for place: GuidedSourcePlace, home: URL) -> URL? // Pictures, Desktop, Downloads under home; /Volumes; nil for .other +} +``` +`AppState` gains `let guidedSetupEligible: Bool` (init parameter, default `true`; `UITestAppStateFactory` passes `false` for every scenario except the new `guidedFirstRun`) and, because its folder service is private: +```swift +/// Opens the picker at `directory` (nil: the default start) and, when a folder is chosen, makes it the one source folder. True when chosen. +@discardableResult func chooseSourceFolder(openingAt directory: URL?) async -> Bool +``` +which calls a new `SetupCoordinator.chooseSourceFolder(openingAt: URL?) async -> Bool` (`chooseFolder(openingAt:prompt: "Choose This Folder")`, or `chooseFolder(startingAt: nil, prompt:)` for nil, then the existing `selectSourceFolder`). Like the other AppState wrappers it first calls `runCoordinator.invalidateWatchedImportContext()`. + +`GuidedSetupView.swift` (new) is shown by `SetupView` in place of its current content while `GuidedSetupGate.shouldShow` is true; `.navigationTitle("Choose Folders")` stays. One question per step, single column, native controls, no illustration. + +Step `source`: +- title `Where are most of your photos?` +- body `Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted.` +- buttons `Pictures Folder`, `Desktop`, `Downloads`, `An External Drive`, `Somewhere Else…` (identifiers `guided.source.`): each calls `appState.chooseSourceFolder(openingAt: GuidedSetupModel.startingDirectory(for: place, home: FolderAccessService.realHomeDirectoryURL()))`; a chosen folder moves to step `destination`. The home directory is the person's real home (C-22), never the sandbox container. +- link `My photos are in the Apple Photos app` (identifier `guided.source.applePhotos`) → `sourceKind = .applePhotos`, step `destination`. + +Step `destination`: +- title `Where should the organized copy go?` +- body, folder: `Chronoframe builds a new, organized copy there. Your originals stay exactly where they are.` Apple Photos: `Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed.` +- measure line (folder only): `Measuring your folder…`; complete `Your folder holds about {size} in {count} files.`; incomplete `Your folder holds at least {size}.`; nil `Chronoframe could not measure this folder. Space is checked again before copying.` The estimate runs off the main actor and is cancelled when the step is left. +- button `Choose a Folder…` (identifier `guided.destination.choose`) → `appState.chooseDestinationFolder()` unchanged, including its conflict handling. +- space line once a destination is set, free bytes from `PhotosExportExecutor.liveFreeSpace(at:)`: unknown `Free space on this drive is unknown.`; free below the estimate (warning tone, never blocking) `{free} free here, and your folder holds about {size}. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out.`; otherwise `{free} free here. That is enough for about {size} (estimate, checked again when the copy starts).`; Apple Photos or no estimate: `{free} free here.` +- primary, folder: `Look at My Photos` (identifier `guided.start`) → `didOnboard = true`, `await appState.startPreview()`. Under it: `Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read.` Apple Photos: `Choose Photos to Copy` → `didOnboard = true`, `appState.navigate(to: .photos)`. +- `Back` returns to step `source`. + +Every step has the link `Use the full setup screen` (identifier `guided.useFullSetup`) → `didOnboard = true`. + +`UITestScenario.guidedFirstRun` (1180×820, route `.organize(.setup)`, empty stores, `guidedSetupEligible: true`). Because `@AppStorage("didOnboard")` reads `UserDefaults.standard`, `GuidedSetupView` and `SetupView` take the flag through a binding the render test can supply; production passes the `@AppStorage` binding. + +## C-24 Reading reassurance (WP-23) + +`RunWorkspaceModel.heroState` for a running preview: the message gains the sentence `Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.` Nothing else in that state changes. + +## C-25 Photos and the folder picture on the preview (WP-21 Core part, WP-23) + +Core, `CopyPlanBuilder.dateHistogram(from:namingRules:)` (`:270–296`): `samplePathLimit` becomes 12, and a bucket's samples are taken from transfers with `isDuplicate == false` first, then from exact copies only if fewer than 12 were found. Counts are unchanged. + +`RunTimelineView`: when the preview is ready and nothing is selected, select the newest dated bucket (never `Unknown`) once, so its photos are visible on arrival. The selected-bucket panel shows `{Month Year}: {count} photos and videos`, the sample thumbnails (up to 12, existing loader) and the caption `A sample from this month.` + +`ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift` (new, pure): +```swift +struct LayoutPictureCard: Equatable, Identifiable { + var id: FolderStructure { structure } + let structure: FolderStructure + let title: String // FolderLayoutPresentation.title(structure) + let lines: [String] // real folders, newest first, at most 6 lines, e.g. "2026/", " 10/ · 212", " 09/ · 148" + let footer: String // .yyyy "{years} folders"; .yyyyMM "{months} folders"; .yyyyMMDD "One folder for each day" + let isSelected: Bool +} +enum LayoutPictureModel { + static let offered: [FolderStructure] = [.yyyyMM, .yyyyMMDD, .yyyy] + static func cards(newFilesByMonth: [String: Int], selected: FolderStructure) -> [LayoutPictureCard] +} +``` +Folder names follow `FolderLayoutPresentation.exampleRelativePath` (numeric month folders). Counts come from `metrics.newFilesByMonth` (new files that land in that month folder, sidecars included), not from the histogram, whose counts include exact copies that go to the Duplicate folder. Undated files are left out. For `.yyyyMMDD` the lines show months with a third-level line ` one folder per day`. When `newFilesByMonth` is empty the section is not shown. + +`RunLayoutPictureSection.swift` (new), shown on the ready preview under the timeline: title `How your library will be arranged`, the three cards as selectable buttons (identifiers `layoutPicture.`), caption `You can change this later with Reorganize, which needs the unlock.` and, when `metrics.duplicateCount > 0`, a second caption `{duplicateCount} exact copies go to a separate Duplicate folder.` Selecting a different card sets `preferencesStore.folderStructure` and calls `await appState.startPreview()`; disabled while a run is in progress. When the current layout is `.yyyyMonEvent` or `.flat`, the section shows one line instead of cards: `Layout: {title}. Change it in Settings.` + +`RunWorkspaceShell` overview tab (`RunSectionViews.swift:410–423`): for `.dryRunFinished` only, `RunSnapshotPanel` and `RunArtifactsPanel` sit inside a `DisclosureGroup("Details")` that starts collapsed (identifier `runDetailsDisclosure`). Every other status is unchanged. + +## C-26 Documentation (WP-06, WP-14, WP-24) + +`docs/QUICK_START.md`, `docs/FAQ.md`, `README.md` and `docs/SAFETY_AND_RECOVERY.md` describe only what a milestone built: the accounted-for line and Undo button; the free month and what the free allowance covers; identical-first review and the keep rule; the two-question start and the Year/Month default for new people. No claim about speed beyond the existing "5 to 15 minutes" wording. No "safe to delete" wording. diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md new file mode 100644 index 00000000..13fc0f6c --- /dev/null +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -0,0 +1,48 @@ +# First-run experience — decisions + +Status: approved by Nishith 2026-11-28 unless a decision says "revised proposal". Not started. + +Prefix `FRX`. Runtime decisions are appended as `D-FRX-1NN`. + +## Tie-break rule for new gaps +Keep every invariant; fewest changed lines; copy the named reference pattern; when a number cannot be known, say "unknown" or "about", never a guess; when unsure whether a first-time person needs to see something, leave it behind Details. Log the choice as `D-FRX-1NN` and continue. + +## Owner answers (2026-11-28) +- **D-FRX-01 Branches.** Three stacked branches, one per milestone: `feature/first-run-trust` from `main`, `feature/first-run-duplicates` from the first, `feature/first-run-guided` from the second. `main` must already contain PR #299 (edit preservation); WP-00 checks that `AGENTS.md` on `main` has an `INV-31` bullet and stops if it does not. Never push, never open a pull request. +- **D-FRX-02 Plan author.** This folder was written in the planning session; the orchestrator builds from it and does not redesign. +- **D-FRX-03 Photo lookup is out.** "Drop an original, see where its copy went" stays with `docs/plan/find-and-account`. This plan builds the accounted-for sentence and Undo only. +- **D-FRX-04 Purchase-surface exception.** Recommendations 3 and 5 change what the unlock sheet says and which free batch is offered. That is the only exception to "never edit purchase code" in `AGENT_RULES.md`, and it covers exactly: `UnlockPresentation.swift` (titles, terms line, batch detail, the dedupe batch action), `UnlockSheet.swift` (rendering those), `TrialAuthorizer.swift` (adding `offeringFreeMonthBatch` and `proposingFreeMonth` only), the new `TrialRemaining.swift`, and `FreeTestBatchPlanner.swift`. Still forbidden: `Chronoframe.storekit`, product IDs, prices, the caps in `TrialAllowance.swift`, `StoreKitClient`, the entitlement and ledger code, any authorizer decision, and every `*Capability.isEnabled` value. +- **D-FRX-05 Nearly identical groups.** One click only for identical copies. Nearly identical groups go through Quick Review; "Accept the Rest" appears there after the person has passed at least one group. +- **D-FRX-06 Default layout.** Year/Month for new people only (C-21). Anyone with prior use keeps Year/Month/Day. +- **D-FRX-07 Preview size.** The small version: photos visible on arrival, the folder picture with real counts, technical panels behind Details. The full browsable library is not built. + +## Design decisions made while planning +- **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-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. +- **D-FRX-15 Free removal is whole groups through the planner.** The free dedupe batch is a `DeduplicationPlanner.plan` result with the left-out groups forced to Keep (C-11). No item filtering, no executor change, the normal confirmation dialog. +- **D-FRX-16 Guided setup is two questions, then the normal screens.** It replaces the Choose Folders content only for a person with nothing configured, hands off to Preview & Copy, and is always skippable. The preview, copy and completion screens are the same for everyone. This reverses "no new wizard" from the first-ten-minutes plan, approved 2026-11-28. +- **D-FRX-17 Scan time wording.** The copy reuses the range already published in `docs/TROUBLESHOOTING.md` ("5 to 15 minutes" for a very large collection). No new speed claim; the owner row H-FRX-6 checks it on a release build. +- **D-FRX-18 Changing layout from the picture re-runs the preview.** No re-map function exists in Core and none is added; the second pass reuses cached hashes. +- **D-FRX-19 Identifiers are never renamed or removed.** New controls get new identifiers; a control whose label changes keeps its identifier. +- **D-FRX-20 Existing tests whose expectation changes.** Where a contract changes behavior an existing test asserts (unlock titles, lane sentences, the default layout of fresh defaults, the hero message of a running preview, histogram sample counts), the implementer updates that assertion to the contract value and lists each one, with file and line, in its report; the reviewer checks each against the contract. No test is deleted, skipped or weakened for any other reason. +- **D-FRX-21 Strings.** Each milestone's last work package adds every new string to both catalogs with German, using `bin/add_translated_keys.py` in this folder. The orchestrator writes the German in the informal "du" voice the catalog already uses; a cf-reviewer checks it. Baseline keys are never removed. +- **D-FRX-22 Evidence renders.** Screens are rendered offscreen from fixture states into `.tmp/frx-evidence/` (C-00) and looked at by the orchestrator. That is "rendered", reported separately from "verified in the running app", which stays an owner row. +- **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.` + +## 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. +- `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. +- `acceptAllSuggestions()` and `acceptAllHighConfidence()` have no caller after M2; removing them is a follow-up. +- "never hard-deletes them" in `SharedViews.swift:895` is jargon; rewording it is the owner's call under D-FRX-12. + +## Runtime decisions diff --git a/docs/plan/first-run-experience/EVIDENCE_LEDGER.md b/docs/plan/first-run-experience/EVIDENCE_LEDGER.md new file mode 100644 index 00000000..ca600f29 --- /dev/null +++ b/docs/plan/first-run-experience/EVIDENCE_LEDGER.md @@ -0,0 +1,14 @@ +# First-run experience — evidence ledger (owner rows) + +Status: not started. No row is run. Only Nishith records a result. The allowance, the unlock sheet and the free steps appear only in a Mac App Store build (`MAS_BUILD`); a Debug build is unmetered and shows none of them. + +| Row | What to run | Pass when | Status | Evidence | +|---|---|---|---|---| +| H-FRX-1 | MAS build, clean macOS user account. Organize a 300-file folder that contains about 20 exact copies into an empty folder. Then press Undo This Copy… and confirm | The preview and the completion screen each show the accounted-for line and the numbers add up to the files in the folder; Undo removes exactly the copies and the allowance returns to 500; the source folder is unchanged | todo-owner | screenshots | +| H-FRX-2 | Same account. Preview a folder of more than 500 new files spread over several months | The preview states the free limit before any click; the suggested month is the newest that fits; pressing the free button lists the files and copies nothing until you confirm; the copy holds only that month's new files and no exact copies; "Unlock to Copy Everything" opens the sheet titled with the file count, with the one-time line and the StoreKit price; Not Now changes nothing | todo-owner | screenshots | +| H-FRX-3 | Deduplicate a folder with exact copies, near-identical bursts and look-alikes | "Accept Identical Copies" approves only groups of byte-identical files; nearly identical groups open in Quick Review and "Accept the Rest" appears after the first group; marking every photo in a group Delete shows the notice and that group is still whole after Move to Trash (also try it with RAW+JPEG or Live Photo pairs spread over two groups; see the known gap in DECISIONS) | todo-owner | screenshots | +| H-FRX-4 | MAS build with more than 100 reviewed duplicates | The footer states the free limit; "Move N Files to Trash Free" asks for confirmation, moves whole groups only and never more than the allowance; after the next scan the choices for the groups still waiting are restored and nothing is pre-approved; History can put the files back | todo-owner | screenshots | +| H-FRX-5 | Clean account, first launch | Choose Folders shows the two questions; each place button opens the picker at that place; the destination step shows the folder size and the drive's free space; a drive that is too small warns and still lets you continue; "Use the full setup screen" shows the old screen and the questions never return | todo-owner | screenshots | +| H-FRX-6 | Release or MAS build, a real collection of at least 20,000 files | The reading step says nothing is being copied; the time taken is inside the "5 to 15 minutes" wording or the wording is corrected (D-FRX-17); the ready preview shows photos from the newest month, the folder picture matches the folders the copy then makes | todo-owner | timing note, screenshots | +| H-FRX-7 | Your own account (existing preferences, layout never changed), updated build | The layout is still Year/Month/Day; a new copy lands beside the existing day folders | todo-owner | screenshot | +| H-FRX-8 | VoiceOver through the two questions, the over-allowance preview, the completion card, the three lanes and Quick Review; then the Xcode UI-test suite | Every new status and button is read with its name; the UI-test suite passes | todo-owner | note | diff --git a/docs/plan/first-run-experience/IMPLEMENTATION_PLAN.md b/docs/plan/first-run-experience/IMPLEMENTATION_PLAN.md new file mode 100644 index 00000000..a5b4dd61 --- /dev/null +++ b/docs/plan/first-run-experience/IMPLEMENTATION_PLAN.md @@ -0,0 +1,190 @@ +# First-run experience — implementation plan + +Status: approved, not started. Prepared 2026-11-28. Prefix `FRX`. Read first: `docs/plan/next-half/AGENT_RULES.md`, `CONTRACTS.md`, `DECISIONS.md`. + +## Run order +M1: WP-00 → WP-01 → WP-02 → WP-03 → WP-04 → WP-05 → WP-06 → G1. +M2: WP-10 → WP-11 → WP-12 → WP-13 → WP-14 → G2. +M3: WP-20 → WP-21 → WP-22 → WP-23 → WP-24 → G3. +One work package at a time (SwiftPM shares one build directory). A milestone whose gate fails does not block the write-up of the ones before it, but the next milestone does not start until the gate passes or its failure is logged in `BLOCKED.md` and is unrelated to the next milestone's files. + +## Rules for every implementation work package +- **Model:** cf-implementer, then cf-reviewer. Paths are under `ui/Sources/` and `ui/Tests/` unless they start with `docs/` or `script/`. +- Core test classes live in `ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreTests.swift`; AppCore tests in `ui/Tests/ChronoframeAppCoreTests/`; App tests in `ui/Tests/ChronoframeAppTests/`. App test classes are `@MainActor`. +- Where an acceptance bullet needs logic that lives in a SwiftUI view, the implementer puts that logic in a small internal pure helper beside the view and tests the helper. +- Existing assertions may change only under D-FRX-20, each listed in the report. +- Every new control gets an identifier in `AccessibilityIdentifiers.swift` and in its `all` list; no identifier is renamed (D-FRX-19). +- New user-facing strings are written as literals in code. The implementer lists every new or changed string, with its file, at the end of its report; the orchestrator collects them for the milestone's strings work package. +- **Done when**, for every WP: its named test classes exit 0, `cf_swift.sh build` exits 0, `git diff --check` exits 0, plus any extra command the WP names. + +--- + +# Milestone 1 — Trust and paywall (`feature/first-run-trust`) + +## WP-00 — Branch, plan folder, baseline (orchestrator) +1. `git status --short` shows no modified tracked file. `git fetch origin main`. +2. `git show origin/main:AGENTS.md | grep -c "INV-31"` prints 1 or more. If it prints 0, PR #299 is not merged: stop (listed stop condition). +3. `git switch -c feature/first-run-trust origin/main`. +4. Commit this plan folder as it is: `git add docs/plan/first-run-experience` → `FRX WP-00: plan folder`. +5. Mark `docs/plan/first-ten-minutes/` superseded: change the `Status:` line of each of its seven files to `Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built.`; in `docs/plan/next-half/README.md` change row 5's status cell to the same sentence and add a row for this plan. Commit `FRX WP-00: supersede first-ten-minutes`. +6. Anchor refresh: brief one Explore agent (model haiku) to check every `file:line` in CONTRACTS "Facts" and every "Read for reference" range in M1 against the working tree and return only the ones that moved, with the new line. Record the moves in `PROGRESS.md` under Baseline. Do not edit CONTRACTS for a moved line; edit it only if a fact is no longer true, and log that as a runtime decision. +7. `cf_swift.sh build`, `cf_swift.sh suite`. Done when both exit 0; record the test count. + +## WP-01 — Render evidence harness +- **Owned paths:** `Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift` (new). +- **Read for reference:** `ChronoframeApp/App/UITesting/UITestAppStateFactory.swift:30–60, :213–260`; `Tests/ChronoframeAppTests/UnlockSheetLayoutTests.swift` (how the sheet is built with stub clients); `ChronoframeApp/Views/RootSplitView.swift:137–156`. +- **Contracts:** C-00. **Decisions:** D-FRX-22. +- **Acceptance:** `testRenderCopyComplete`, `testRenderUnlockSheetOrganize`, `testRenderUnlockSheetDedupe`; each skips without the marker file and writes one PNG with it. +- **Done when:** `cf_swift.sh test ScreenRenderEvidenceTests` exits 0 without the marker (3 skipped); the orchestrator then creates `.tmp/frx-evidence/.enabled`, reruns, and finds 3 PNG files. + +## WP-02 — Core: accounting, free month, model fields +- **Owned paths:** `ChronoframeCore/RunAccounting.swift` (new), `ChronoframeCore/FreeMonthBatchPlanner.swift` (new), `ChronoframeCore/FreeTestBatchPlanner.swift`, `ChronoframeCore/RunModels.swift` (`RunArtifactPaths.receiptPath`, `RunMetrics.newFilesByMonth` only), `Tests/ChronoframeAppCoreTests/ChronoframeCoreRunAccountingTests.swift` (new), `Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeMonthBatchPlannerTests.swift` (new), `Tests/ChronoframeAppCoreTests/FreeTestBatchPlannerTests.swift`. +- **Read for reference:** `FreeTestBatchPlanner.swift:20–205`; `RunModels.swift:155–312`; `EngineDomainModels.swift:273–293`; `CopyPlanBuilder.swift:28–45, :435–449`; `DryRunPlanner.swift:3–81`. +- **Contracts:** C-01, C-03 (model field), C-05. **Decisions:** D-FRX-09, D-FRX-13. +- **Acceptance:** + - `ChronoframeCoreRunAccountingTests`: `testPreviewBalancedWhenCategoriesSumToFound`, `testPreviewNewExcludesCopiesAndCompanions`, `testPreviewRemainderIsSignedWhenCountsDisagree`, `testFinishedCopiedMediaExcludesCompanions`, `testFinishedNotCopiedWhenFewerCopiedThanPlanned`, `testFreeBatchLeavesPositiveRemainder`, `testRunArtifactPathsDecodesWithoutReceiptPath`, `testRunMetricsDecodesWithoutNewFilesByMonth`. + - `ChronoframeCoreFreeMonthBatchPlannerTests`: `testMonthKeyFromDateBucket`, `testMonthKeyNilForUnknownDate`, `testMonthCountsExcludeExactCopiesAndUndated`, `testMonthCountsIncludeCompanionsOfNewFiles`, `testOptionsNewestFirstWithFits`, `testOptionsEmptyWhenNothingRemains`, `testSuggestedOptionIsNewestThatFits`, `testSuggestedOptionFallsBackToNewestMonth`, `testSelectWholeMonthWhenItFits`, `testSelectWholeDaysWhenMonthTooLarge`, `testSelectWithinFirstDayWhenDayTooLarge`, `testSelectNeverExceedsLimit`, `testSelectKeepsCompanionsWithOwners`, `testSelectNeverIncludesExactCopies`. + - `FreeTestBatchPlannerTests` (added): `testMonthRequestSelectionAppliesToNothing`, `testReducedToMonthRequestKeepsNothing`, `testBatchDefaultsHaveNoMonthAndAreNotRequested`, `testIdentitySelectionBehaviourUnchanged`. + +## WP-03 — AppCore: engine, offer, unlock presentation +- **Owned paths:** `ChronoframeAppCore/Services/SwiftOrganizerEngine.swift` (the receipt lookup at `:1349–1372`, the preview metrics at `:535–544`, the transfer summary at `:999–1024`, the refusal at `:894–903`, the one early branch before `:757`; nothing else), `ChronoframeAppCore/Services/TrialAuthorizer.swift` (add `offeringFreeMonthBatch` and `proposingFreeMonth` only), `ChronoframeAppCore/Services/TrialRemaining.swift` (new), `ChronoframeAppCore/Services/UnlockPresentation.swift`, `Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift` (new), `Tests/ChronoframeAppCoreTests/FreeMonthBatchOfferTests.swift` (new), `Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift`, `Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift`, `Tests/ChronoframeAppCoreTests/FreeTestBatchOfferTests.swift`, `Tests/ChronoframeAppCoreTests/FreeTestBatchRunTests.swift`, `Tests/ChronoframeAppCoreTests/SwiftOrganizerEngineIntegrationTests.swift`. +- **Read for reference:** the engine ranges above; `TrialAuthorizer.swift:25–135`; `UnlockPresentation.swift:15–229`; `TrialStatusStore.swift:29–60`; `TrialIndicatorPresentation.swift:48–84`. +- **Contracts:** C-03 (engine), C-06. **Decisions:** D-FRX-04, D-FRX-10, D-FRX-13, D-FRX-20. Read `FreeTestBatchPlanner.swift:1–18` first: that rule is not negotiable. +- **Extra review:** the orchestrator reads the full diff of `SwiftOrganizerEngine.swift` and `TrialAuthorizer.swift` and confirms the month-request branch can reach neither `authorizeTransfer` nor the job queue. +- **Acceptance:** + - `TrialRemainingTests`: `testNilWhenNotAppStoreChannel`, `testNilWhenUnlocked`, `testNilWhenUnknownOrLoading`, `testRemainingForEachMeter`. + - `FreeMonthBatchOfferTests`: `testRefusalOffersNewestMonthThatFits`, `testOfferNeverContainsExactCopies`, `testNoOfferWhenNothingDatedAndNew`, `testNoOfferWhenNothingRemains`, `testOfferedBatchCarriesMonthKey`, `testRequestedMonthIsProposedAsRequested`, `testRequestedMonthFallsBackToSuggestedWhenEmpty`. + - `UnlockPresentationTests`: `testAllowanceSpentOrganizeTitleNamesFileCount`, `testAllowanceSpentDedupeTitleNamesDuplicateCount`, `testPurchaseTermsLineForAllowanceSpentAndRequiresUnlock`, `testNoPurchaseTermsLineForUnconfirmedPurchaseOrVoluntaryUnlock`, `testRequestedMonthTitleAndMessage`, `testRequestedMonthPutsFreeCopyFirst`. + - `UnlockSheetBatchOfferTests`: `testMonthBatchDetailNamesMonth`. + - `SwiftOrganizerEngineIntegrationTests`: `testPreviewMetricsCarryNewFilesByMonth`, `testTransferSummaryCarriesReceiptPath`, `testMonthRequestCopiesNothingAndReservesNothing` (no media file appears in the destination, no receipt is written, the authorizer double records no call), `testConfirmedMonthBatchCopiesOnlyTheListedFiles` (`// AGENTS-INVARIANT: 1`: runs the offered batch's `selection`; also asserts every source file is byte-for-byte unchanged), `testConfirmedMonthBatchStillRefusedWhenAllowanceTooSmall`. +- **Done when:** the named classes exit 0; `script/check_authorizer_has_no_default.sh` and `script/check_storekit_config_matches_policy.sh` exit 0. + +## WP-04 — App: preview shows the free limit and the free month +- **Owned paths:** `ChronoframeApp/Views/Run/RunWorkspaceModel.swift`, `ChronoframeApp/Views/Run/RunSectionViews.swift` (hero actions for `.dryRunFinished`), `ChronoframeApp/Views/Run/CurrentRunView.swift` (model construction), `ChronoframeApp/App/AppState.swift` (`requestedUnlockRefusal`, `startFreeMonthCopy`, `requestUnlockForPlan`, `unlockRefusal`, `dismissUnlockSheet`, `retryAfterUnlock`), `ChronoframeApp/Views/RootSplitView.swift` (`:22–24` only), `ChronoframeApp/Views/Purchase/UnlockSheet.swift` (terms line), `ChronoframeApp/App/AccessibilityIdentifiers.swift`, `ChronoframeApp/App/UITesting/UITestScenario.swift`, `ChronoframeApp/App/UITesting/UITestAppStateFactory.swift`, `Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift`, `Tests/ChronoframeAppTests/AppStateTests.swift`, `Tests/ChronoframeAppTests/UnlockSheetLayoutTests.swift`, `Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift`, `Tests/ChronoframeAppTests/UITestWindowFitTests.swift`. +- **Read for reference:** `RunWorkspaceModel.swift:99–232, :300–360`; `RunSectionViews.swift:110–192`; `CurrentRunView.swift:37–60, :93–110`; `AppState.swift:505–580`; `RootSplitView.swift:14–30, :98–126`; `UnlockSheet.swift:41–76, :130–215`; `UITestScenario.swift:4–110`; `UITestAppStateFactory.swift:62–200, :277–309, :388–420`. +- **Contracts:** C-07, C-08, C-06 (sheet rendering). **Decisions:** D-FRX-04, D-FRX-14, D-FRX-19. +- **Acceptance:** + - `RunWorkspaceModelTests`: `testFreeCopyStateNotMeteredWithoutAllowance`, `testFreeCopyStateFitsWhenPlanWithinAllowance`, `testFreeCopyStateOverAllowanceSuggestsNewestFittingMonth`, `testFreeCopyStateSpentWhenNothingRemains`, `testFreeCopyStateNotOfferedForStalePreview`, `testOverAllowanceHeroHidesStartCopying`, `testOverAllowanceLineNamesBothNumbersAndTheSuggestedMonth`. + - `AppStateTests`: `testStartFreeMonthCopyRequestsAProposalForThatMonth`, `testRequestUnlockForPlanPresentsOrganizeRefusal`, `testDismissUnlockSheetClearsRequestedRefusal`, `testRetryAfterUnlockWithRequestedRefusalStartsNothing`. + - `UnlockSheetLayoutTests`: `testPurchaseTermsLineIsShown`. + - `ScreenRenderEvidenceTests`: `testRenderPreviewOverAllowance`. +- **Done when:** the named classes exit 0; `script/check_no_raw_animations.sh` and `script/check_detail_views_set_navigation_title.sh` exit 0. + +## WP-05 — App: accounted-for line, Undo, add another folder +- **Owned paths:** `ChronoframeApp/Views/Run/RunAccountingText.swift` (new), `ChronoframeApp/Views/Run/RunWorkspaceModel.swift` (`accountingLine` only), `ChronoframeApp/Views/Run/RunSectionViews.swift` (`RunPreviewSummarySection` first line only), `ChronoframeApp/Views/Run/CurrentRunView.swift` (`RunOutcomeSummaryCard`), `ChronoframeApp/App/AppState.swift` (`lastCopyUndoEntry`, `undoLastCopy`), `ChronoframeApp/App/AccessibilityIdentifiers.swift`, `ChronoframeApp/App/UITesting/UITestAppStateFactory.swift` (the two fixture corrections in C-08), `Tests/ChronoframeAppTests/RunAccountingTextTests.swift` (new), `Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift`, `Tests/ChronoframeAppTests/AppStateTests.swift`, `Tests/ChronoframeAppTests/RunOutcomeAccuracyTests.swift`, and any other test file that asserts the two old fixture numbers (named in the report). +- **Read for reference:** `RunSectionViews.swift:260–315`; `CurrentRunView.swift:93–180`; `AppState.swift:925–940`; `HistoryCoordinator.swift:49–94`; `RunHistoryView.swift:155–182`; `RunSessionStore.swift:257–310`; `ProfileModels.swift:33–113`. +- **Contracts:** C-02, C-04, C-07 (last paragraph), C-08 (WP-05 part). **Decisions:** D-FRX-09, D-FRX-20, D-FRX-24. +- **Acceptance:** + - `RunAccountingTextTests`: `testPreviewBalancedLine`, `testPreviewUnbalancedLineNamesTheGap`, `testPreviewNilWhenNothingFound`, `testFinishedBalancedLineOmitsZeroParts`, `testFinishedFreeBatchLine`, `testFinishedNotCopiedLine`, `testFinishedUnbalancedLine`, `testNoLineEverSaysSafeToDelete`. + - `RunWorkspaceModelTests`: `testAccountingLineOnlyForReadyPreviewAndFinishedCopy` (nil for nothing-to-copy, reverted, reorganized, failed and running), `testCopyCompleteAndPreviewFixturesAreBalanced`. + - `AppStateTests`: `testLastCopyUndoEntryMatchesReceiptPath`, `testNoUndoEntryWithoutReceiptPath`, `testNoUndoEntryForPreviewOrRevertRuns`, `testUndoLastCopyRevertsThatReceiptOnly` (`// AGENTS-INVARIANT: 8`: the harness asserts `requestRevert` receives exactly that receipt URL and nothing else is deleted). +- **Done when:** the named classes exit 0; `script/check_agents_invariants_have_tests.sh` exits 0. + +## WP-06 — Docs and strings for M1 (orchestrator) +1. Collect the new and changed strings from the WP-02 to WP-05 reports. Write `docs/plan/first-run-experience/strings/M1-app.json` and `M1-core.json` (format in `bin/add_translated_keys.py`), German in the "du" voice the catalogs use. Brief a cf-reviewer to check the German against the English for meaning, placeholders and tone; apply its corrections. +2. `python3 docs/plan/first-run-experience/bin/add_translated_keys.py ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings docs/plan/first-run-experience/strings/M1-app.json`, and the same for `ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings` with `M1-core.json`. +3. Docs per C-26 (cf-implementer, owned paths `docs/QUICK_START.md`, `docs/FAQ.md`, `README.md`, `docs/SAFETY_AND_RECOVERY.md`; the reviewer confirms every claim against the code). +4. Commit `FRX WP-06: strings and docs`. + +## Gate G1 (orchestrator) +1. Add `RunAccounting FreeMonthBatchPlanner` to `MEANINGFUL_BASENAMES` in `script/swift_meaningful_coverage.sh`. +2. `cf_swift.sh suite`; `cf_swift.sh coverage`; `cf_swift.sh guards origin/main`; `cf_swift.sh xcode`; `git diff --check`. +3. German: the two commands under "Localization" in `CLAUDE.md` (the `SWIFT_EMIT_LOC_STRINGS=YES` build, then `script/check_german_localization.py --baseline-ref origin/main …`). +4. UI-test literals: `grep -n` in `ui/Xcode/UITests/ChronoframeUITests.swift` for every string and identifier M1 changed. For each hit, edit that test to the contract value and run `xcodebuild -project ui/Chronoframe.xcodeproj -scheme Chronoframe -derivedDataPath .tmp/ChronoframeDerivedData -destination "platform=macOS,arch=arm64" CODE_SIGNING_ALLOWED=NO build-for-testing` (D-FRX-23). +5. Renders: with `.tmp/frx-evidence/.enabled` present, `cf_swift.sh test ScreenRenderEvidenceTests`; open each PNG and check the copy and layout against C-02, C-04, C-06, C-07; record each file and what was checked in `PROGRESS.md`; send the PNGs to the owner. +6. Commit `FRX G1: gate`. +- **Pass when:** every command exits 0 and every M1 row of `ACCEPTANCE_MATRIX.md` is `pass-auto`; owner rows stay `todo-owner`. + +--- + +# Milestone 2 — Duplicates (`feature/first-run-duplicates`) + +## WP-10 — Branch and baseline (orchestrator) +`git switch -c feature/first-run-duplicates feature/first-run-trust`. Anchor refresh for M2 as in WP-00 step 6. `cf_swift.sh build`. Done when it exits 0. + +## WP-11 — Core: review lane and free removal batch (safety-critical) +- **Owned paths:** `ChronoframeCore/DeduplicateReviewLane.swift` (new), `ChronoframeCore/FreeDedupeBatchPlanner.swift` (new), `Tests/ChronoframeAppCoreTests/ChronoframeCoreDeduplicateReviewLaneTests.swift` (new), `Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift` (new). `DeduplicationPlanner.swift`, `DeduplicateExecutor.swift` and `DeduplicateModels.swift` are read-only. +- **Read for reference:** `DeduplicationPlanner.swift:25–325`; `DeduplicateModels.swift:196–379, :460–474, :559–591, :659–725`; `ClusterAnnotation.swift:5–8, :148–154`; `Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift` (fixture builders and the property style). +- **Contracts:** C-10, C-11. **Decisions:** D-FRX-05, D-FRX-11, D-FRX-15, D-FRX-24. +- **Acceptance:** + - `ChronoframeCoreDeduplicateReviewLaneTests`: `testIneligibleClusterIsLookAtEach`, `testExactClusterWithEqualIdentitiesIsIdentical` (`// AGENTS-INVARIANT: 6`), `testExactClusterMissingAnIdentityFailsClosed`, `testExactClusterWithDifferingIdentitiesFailsClosed`, `testHighConfidenceNearDuplicateIsNearlyIdentical`, `testNonExactVideoClusterIsLookAtEach` (`// AGENTS-INVARIANT: 6`). + - `ChronoframeCoreFreeDedupeBatchPlannerTests`: `testNilWhenWholePlanFits`, `testNilWhenLimitIsZero`, `testBatchNeverExceedsLimit`, `testIdenticalGroupsAreTakenFirst`, `testStopsAtFirstGroupThatDoesNotFit`, `testBatchPlanIsSubsetOfFullPlanWithSameIdentities` (`// AGENTS-INVARIANT: 17`), `testPairPartnerInLeftOutGroupKeepsBothHalves` (`// AGENTS-INVARIANT: 14`), `testSharedSidecarSurvivesWhenAnOwnerIsLeftOut` (`// AGENTS-INVARIANT: 14`), `testNoGroupIsEmptiedByTheBatch`, `testDeferredCountIsFullMinusBatch`, `testPairKeepOverridesArePreserved`, `testForcedKeepThatWouldUnskipAGroupStopsTheWalk` (group Y: y1 and y2 both Delete, y1 paired with z1; group Z: z1 Delete, z2 Keep; the full plan is {z1, y1}; with Z left out the planner would return {y2}, which is not in the full plan, so that candidate is rejected), `testPropertyRandomReviewsNeverExceedLimitOrLeaveTheFullPlan` (seeded, at least 200 cases). +- **Extra review:** after cf-reviewer approves, the orchestrator reads both new files in full and briefs one independent read-only reviewer (general-purpose agent, model opus) with the two files, C-10, C-11 and the planner, asking only: can the batch ever contain a deletion the full plan does not, split a pair or sidecar unit, or empty a group. Record both reviews in `PROGRESS.md`. +- **Done when:** both classes exit 0; `script/check_agents_invariants_have_tests.sh` exits 0. + +## WP-12 — AppCore: store lanes, accept by lane, free batch plan +- **Owned paths:** `ChronoframeAppCore/Stores/DeduplicateSessionStore.swift` (the additions in C-12; existing code is edited only to trigger the `laneSummaries` recompute, to clear the free-batch memory in `prepareReviewedCommitPlan`/`discardPreparedCommitPlan`, and for the one `.complete` change C-12 names), `Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift`. +- **Read for reference:** `DeduplicateSessionStore.swift:40–75, :130–240, :395–545, :686–720, :775–781`; `UnlockPresentation.swift:15–153`; `DeduplicateEngine.swift:177–274`. +- **Contracts:** C-12. **Decisions:** D-FRX-05, D-FRX-15, D-FRX-25. +- **Acceptance:** + - `DeduplicateSessionStoreTests`: `testLaneSummariesCountUnreviewedGroupsFilesAndBytes`, `testLaneSummariesUpdateAfterAccept`, `testAcceptIdenticalApprovesOnlyIdenticalGroups` (`// AGENTS-INVARIANT: 6`), `testAcceptNearlyIdenticalLeavesOtherLanesAlone`, `testAcceptLookAtEachDoesNothing`, `testAcceptInLaneSkipsReviewedGroups`, `testAcceptInLaneIsUndoable`, `testFullyMarkedClusterIDs`, `testFreeBatchOfferNilWhenPlanFits`, `testPrepareFreeBatchCommitPlanFreezesBatchPlan`, `testCommitAfterFreeBatchPassesOnlyBatchItemsToEngine`, `testPreparedCommitCountFollowsThePreparedPlan`, `testFreeBatchOfferIsCachedUntilDecisionsChange`, `testFreeBatchCommitKeepsSavedReviewForNextScan` (`// AGENTS-INVARIANT: 29`: after the commit and a rescan, a saved choice returns only for a file whose identity is unchanged, and nothing is pre-approved for commit), `testOrdinaryCommitStillRemovesSavedReview`. +- **Extra review:** the orchestrator reads the full diff of `DeduplicateSessionStore.swift` and confirms every changed line traces to C-12. +- **Done when:** the class exits 0; `script/check_agents_invariants_have_tests.sh` exits 0. + +## WP-13 — App: three lanes, Quick Review scope, footer, free removal +- **Owned paths:** `ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift`, `ChronoframeApp/Views/Deduplicate/DeduplicateView.swift` (lanes construction `:357–368`, footer `:510–782`, the Quick Review sheet `:745–752`, the title helpers `:1215–1246`, the commit-summary line; nothing else), `ChronoframeApp/Views/Deduplicate/RapidTriageView.swift`, `ChronoframeApp/App/Tips.swift` (`:17–18`), `ChronoframeApp/App/AppState.swift` (`requestUnlockForDuplicates`, `offeredFreeDedupeBatch`, `runOfferedFreeDedupeBatch`), `ChronoframeApp/Views/RootSplitView.swift` (the sheet's new arguments), `ChronoframeApp/Views/Purchase/UnlockSheet.swift` (the dedupe batch action), `ChronoframeAppCore/Services/UnlockPresentation.swift` (`runFreeDedupeBatch`, `offeredDedupeBatch`), `ChronoframeApp/App/AccessibilityIdentifiers.swift`, `ChronoframeApp/App/UITesting/UITestScenario.swift`, `ChronoframeApp/App/UITesting/UITestAppStateFactory.swift`, `ChronoframeApp/App/UITesting/UITestDoubles.swift`, `Tests/ChronoframeAppTests/DeduplicateReviewLanesTests.swift`, `Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift`, `Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift`, `Tests/ChronoframeAppTests/AppStateTests.swift`, `Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift`, `Tests/ChronoframeAppTests/UITestWindowFitTests.swift`, `Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift`, `Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift`. +- **Read for reference:** `DeduplicateReviewLanes.swift` (whole file); `DeduplicateView.swift:340–370, :505–790, :1090–1250`; `RapidTriageView.swift:6–120, :210–309`; `UITestAppStateFactory.swift:167–199, :259–309, :606–653`; `UITestDoubles.swift:103–143`. +- **Contracts:** C-13, C-14. **Decisions:** D-FRX-04, D-FRX-05, D-FRX-11, D-FRX-12, D-FRX-14, D-FRX-19, D-FRX-20. +- **Acceptance:** + - `DeduplicateReviewLanesTests`: `testIdenticalAndNearlyIdenticalCountsSumToSafe`, `testIdenticalSentenceCarriesFilesAndBytes`, `testRowsWithZeroGroupsAreOmitted`, `testCompactTextListsThreeLanes`; the existing tests in this file still pass unedited. + - `DeduplicateReviewViewsTests`: `testQuickReviewScopeIsUnreviewedGroupsOfLane`, `testAcceptTheRestOnlyForNearlyIdenticalAfterFirstGroup`, `testFullyMarkedNoticeText`, `testFreeRemovalLineAndButtonTitles`, `testFooterAcceptCallsIdenticalLaneOnly`, `testConfirmationCountUsesPreparedPlan`. + - `UnlockPresentationTests`: `testDedupeRefusalOffersFreeBatchAction`, `testNoDedupeBatchActionWithoutOffer`. + - `DeduplicateStatusViewTests`: the three assertions C-13 names, changed as it says. + - `AppStateTests`: `testRequestUnlockForDuplicatesPresentsDedupeRefusal`, `testOfferedFreeDedupeBatchOnlyForAllowanceSpentWithRemaining`, `testRunOfferedFreeDedupeBatchAsksForConfirmationOnly` (asserts the engine's `commit` was not called). + - `ScreenRenderEvidenceTests`: `testRenderDeduplicateLanes`. +- **Done when:** the named classes exit 0; `script/check_no_raw_animations.sh` exits 0. + +## WP-14 — Docs and strings for M2 (orchestrator) +As WP-06 with `strings/M2-app.json` and `M2-core.json`. Commit `FRX WP-14: strings and docs`. + +## Gate G2 (orchestrator) +As G1 with: basenames `DeduplicateReviewLane FreeDedupeBatchPlanner`; `cf_swift.sh guards feature/first-run-trust`; renders checked against C-13; additionally `script/check_agents_invariants_have_tests.sh`. Commit `FRX G2: gate`. + +--- + +# Milestone 3 — Guided first job (`feature/first-run-guided`) + +## WP-20 — Branch and baseline (orchestrator) +`git switch -c feature/first-run-guided feature/first-run-duplicates`. Anchor refresh for M3. `cf_swift.sh build`. Done when it exits 0. + +## WP-21 — Core and AppCore groundwork +- **Owned paths:** `ChronoframeCore/FolderSizeEstimator.swift` (new), `ChronoframeCore/CopyPlanBuilder.swift` (`dateHistogram(from:namingRules:)` `:270–296` only), `ChronoframeAppCore/Stores/PreferencesStore.swift` (`:196–197` only), `ChronoframeAppCore/Services/FolderAccessService.swift` (the new requirement, its protocol-extension default, the real implementation, `realHomeDirectoryURL`), `ChronoframeApp/App/UITesting/UITestAppStateFactory.swift` (explicit `.yyyyMMDD` for existing scenarios), `ChronoframeApp/App/UITesting/UITestDoubles.swift`, `Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift` (new), `Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift`, the existing test file that covers `CopyPlanBuilder.dateHistogram` and the one that covers `FolderAccessService.initialPanelDirectoryURL` (both named in the report). +- **Read for reference:** `CopyPlanBuilder.swift:262–325`; `PreferencesStore.swift:75–100, :190–275`; `FolderAccessService.swift:93–200`; `MediaDiscovery.swift` (the skip rules only). +- **Contracts:** C-20, C-21, C-22, C-25 (Core part). **Decisions:** D-FRX-06, D-FRX-20, D-FRX-24. +- **Acceptance:** + - `ChronoframeCoreFolderSizeEstimatorTests`: `testCountsRegularFilesAndBytes`, `testSkipsSymlinksWithoutFollowing` (`// AGENTS-INVARIANT: 15`), `testSkipsHiddenFilesAndPackages`, `testNilForUnreadableRoot`, `testIncompleteWhenCancelled`, `testCreatesAndModifiesNothing` (`// AGENTS-INVARIANT: 1`). + - Histogram: `testHistogramSamplesPreferNewFilesUpToTwelve`, `testHistogramCountsUnchangedBySampleRule`. + - `PreferencesStoreTests`: `testFreshDefaultsUseYearMonth`, `testPriorUseWithoutStoredLayoutKeepsYearMonthDay`, `testStoredLayoutIsNeverChanged`, `testResolvedLayoutIsWrittenOnce`. + - Folder access: `testOpeningAtExistingLocalFolderStartsThere`, `testOpeningAtMissingFolderFallsBack`, `testProtocolDefaultForwardsToStartingAt`, `testRealHomeDirectoryIsNotInsideAContainer`. +- **Done when:** the named classes exit 0. + +## WP-22 — App: guided setup +- **Owned paths:** `ChronoframeApp/Views/Setup/GuidedSetupModel.swift` (new), `ChronoframeApp/Views/Setup/GuidedSetupView.swift` (new), `ChronoframeApp/Views/Setup/SetupView.swift` (the gate and the `didOnboard` binding only), `ChronoframeApp/App/AppState.swift` (`guidedSetupEligible`, `chooseSourceFolder(openingAt:)`), `ChronoframeApp/App/Coordinators/SetupCoordinator.swift` (`chooseSourceFolder(openingAt:)` only), `ChronoframeApp/App/UITesting/UITestScenario.swift`, `ChronoframeApp/App/UITesting/UITestAppStateFactory.swift`, `ChronoframeApp/App/AccessibilityIdentifiers.swift`, `Tests/ChronoframeAppTests/GuidedSetupModelTests.swift` (new), `Tests/ChronoframeAppTests/SetupCoordinatorTests.swift`, `Tests/ChronoframeAppTests/AppStateTests.swift`, `Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift`, `Tests/ChronoframeAppTests/UITestWindowFitTests.swift`. +- **Read for reference:** `SetupView.swift:7–200`; `SetupSectionViews.swift:52–110, :233–260, :400–470`; `AppState.swift:178–260, :380–430, :456–470`; `SetupCoordinator.swift:210–230, :472–505`; `OnboardingCard.swift`; `Motion.swift:57–90`; `PhotosExportExecutor.swift:201–220`. +- **Contracts:** C-23. **Decisions:** D-FRX-08, D-FRX-16, D-FRX-17, D-FRX-19. +- **Acceptance:** + - `GuidedSetupModelTests`: `testGateShowsOnlyForUntouchedEligibleState`, `testGateHiddenAfterOnboardOrAnyConfiguredPath`, `testGateHiddenWithHistoryOrProfiles`, `testSourceStepCopy`, `testDestinationStepCopyForFolderAndApplePhotos`, `testMeasureLineStates`, `testSpaceLineWarnsButNeverBlocks`, `testSpaceLineSaysEstimate`, `testStartingDirectoryForEachPlace`, `testCanContinueNeedsDestination`. + - `SetupCoordinatorTests`: `testChooseSourceFolderOpeningAtSelectsThatFolder`, `testChooseSourceFolderCancelledChangesNothing`. + - `AppStateTests`: `testGuidedSetupEligibleDefaultsTrue`, `testEveryExistingScenarioDisablesGuidedSetup`. + - `ScreenRenderEvidenceTests`: `testRenderGuidedSource`, `testRenderGuidedDestination`. +- **Done when:** the named classes exit 0; `script/check_no_raw_animations.sh` and `script/check_detail_views_set_navigation_title.sh` exit 0. + +## WP-23 — App: photos and the folder picture on the preview +- **Owned paths:** `ChronoframeApp/Views/Run/RunWorkspaceModel.swift` (the running-preview message only), `ChronoframeApp/Views/Run/RunTimelineView.swift`, `ChronoframeApp/Views/Run/LayoutPictureModel.swift` (new), `ChronoframeApp/Views/Run/RunLayoutPictureSection.swift` (new), `ChronoframeApp/Views/Run/RunSectionViews.swift` (the overview tab `:410–423` only), `ChronoframeApp/Views/Run/CurrentRunView.swift` (placing the section), `ChronoframeApp/App/AccessibilityIdentifiers.swift`, `Tests/ChronoframeAppTests/LayoutPictureModelTests.swift` (new), `Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift`, `Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift`, `Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift`. +- **Read for reference:** `RunTimelineView.swift:16–135`; `InteractiveTimelineView.swift:11–110`; `FolderLayoutPresentation.swift` (whole file); `RunSectionViews.swift:396–456`; `DedupeThumbnailLoader.swift:11–90`. +- **Contracts:** C-24, C-25 (App part). **Decisions:** D-FRX-07, D-FRX-18, D-FRX-20. +- **Acceptance:** + - `LayoutPictureModelTests`: `testCardsForThreeDateLayouts`, `testLinesUseNewFilesByMonthNewestFirst`, `testNoCardsWithoutMonthCounts`, `testFooterCounts`, `testSelectedCardMatchesPreference`, `testAtMostSixLines`. + - `RunWorkspaceModelTests`: `testRunningPreviewMessageSaysOnlyReading`. + - `RunTimelinePresentationTests`: `testDefaultSelectionIsNewestDatedBucket`, `testNoDefaultSelectionWithoutDatedBuckets`, `testSelectedBucketTitle`. + - `ScreenRenderEvidenceTests`: `testRenderPreviewWithPhotosAndLayout`. +- **Done when:** the named classes exit 0; `script/check_no_raw_animations.sh` exits 0. + +## WP-24 — Docs and strings for M3 (orchestrator) +As WP-06 with `strings/M3-app.json` and `M3-core.json`; set this plan's row in `docs/plan/next-half/README.md` to "built, not merged". Commit `FRX WP-24: strings and docs`. + +## Gate G3 — final (orchestrator) +As G1 with: basename `FolderSizeEstimator`; `cf_swift.sh guards feature/first-run-duplicates`; renders checked against C-23 and C-25. Then, from `feature/first-run-guided`, run the whole of gate steps 2 and 3 once more against `origin/main` (`cf_swift.sh guards origin/main`) so the stack is known good as one change. Commit `FRX G3: final gate`. + +## Owner handoff +Rows H-FRX-1 to H-FRX-8 in `EVIDENCE_LEDGER.md`. No agent marks them. diff --git a/docs/plan/first-run-experience/ORCHESTRATOR_KICKOFF.md b/docs/plan/first-run-experience/ORCHESTRATOR_KICKOFF.md new file mode 100644 index 00000000..083e9fda --- /dev/null +++ b/docs/plan/first-run-experience/ORCHESTRATOR_KICKOFF.md @@ -0,0 +1,71 @@ +# First-run experience — orchestrator kickoff + +Status: ready to run once PR #299 is on `main`. This plan has three stacked branches, so it uses its own kickoff instead of `docs/plan/next-half/ORCHESTRATOR_KICKOFF.md`. One orchestrator at a time in this checkout. + +## Before you start (owner, once) + +1. PR #299 (edit preservation, INV-31) is merged to `main` and `git fetch origin main` has run. +2. `git status` shows no modified tracked files. The untracked `docs/plan/first-run-experience/` folder is expected; WP-00 commits it. +3. Read `DECISIONS.md` D-FRX-04 (which purchase-surface files may change), D-FRX-11 (the keep promise, a revised proposal), D-FRX-12 (the one renamed dedupe button) and D-FRX-25 (a free removal keeps the saved review, a proposal with its removal steps). Edit them now if you disagree; the orchestrator will not ask. +4. `.claude/agents/` holds `cf-implementer.md`, `cf-reviewer.md` and `cf-data-entry.md` (copy from `docs/plan/next-half/claude-config/agents/` if not). +5. Add these to the `allow` list in `.claude/settings.json` so the run does not stop for approval: + ```json + "Bash(git switch -c feature/first-run-trust origin/main)", + "Bash(git switch -c feature/first-run-duplicates feature/first-run-trust)", + "Bash(git switch -c feature/first-run-guided feature/first-run-duplicates)", + "Bash(git switch feature/first-run-trust)", + "Bash(git switch feature/first-run-duplicates)", + "Bash(git switch feature/first-run-guided)", + "Bash(git show origin/main:AGENTS.md*)", + "Bash(python3 docs/plan/first-run-experience/bin/add_translated_keys.py *)", + "Bash(python3 script/check_german_localization.py *)", + "Bash(grep *)" + ``` +6. Open Claude Code in `/Users/nishithnand/Code/Chronoframe`, choose Fable, set the permission mode to accept edits (or auto), and paste the kickoff prompt. + +## Kickoff prompt + +```text +You are the orchestrator for the Chronoframe plan in docs/plan/first-run-experience (prefix FRX). It implements six approved onboarding recommendations as three milestones on three stacked branches. Work unattended until the final gate is done or every remaining work package is blocked. Do not ask me questions. The design is decided: build what the contracts say, and do not redesign. + +READ FIRST, in this order: docs/plan/next-half/AGENT_RULES.md, then in docs/plan/first-run-experience: IMPLEMENTATION_PLAN.md, CONTRACTS.md, DECISIONS.md, PROGRESS.md, BLOCKED.md, ACCEPTANCE_MATRIX.md, EVIDENCE_LEDGER.md. The root AGENTS.md (safety invariants) and CLAUDE.md win on any conflict. DECISIONS.md D-FRX-04 is my approved exception to the "purchase code" line in AGENT_RULES.md, for exactly the files it lists and nothing else. + +WHO DOES WHAT. Spend your own tokens on judgment and delegate the rest: +- You: WP-00, WP-10, WP-20, the strings parts of WP-06, WP-14 and WP-24 (you write the German), every gate, reading safety-critical diffs, looking at the rendered screens, runtime decisions, the final report. +- cf-implementer (Sonnet): every implementation work package, one at a time. +- cf-reviewer (Sonnet): every finished work package, and the German strings. +- cf-data-entry (Haiku): rows in PROGRESS.md, ACCEPTANCE_MATRIX.md and the "Existing assertions changed" table, from facts you give it. +- Explore agent with model haiku: the anchor refresh at the start of each milestone, and any "where is X" search. +- One general-purpose agent with model opus, read-only: the extra review WP-11 asks for. Nothing else uses Opus. +Never run two agents that build or test at the same time: SwiftPM shares one build directory. + +PROCEDURE. +1. Do WP-00 yourself exactly as written. If `git show origin/main:AGENTS.md | grep -c "INV-31"` prints 0, stop and tell me PR #299 is not merged. +2. Run the work packages strictly in the plan's run order. For each implementation WP: + a. Mark it in-progress in PROGRESS.md. + b. Brief cf-implementer with: PLAN_DIR docs/plan/first-run-experience, the WP ID, its owned paths, the contract and decision IDs it cites, its acceptance test names, its Done-when commands, and any anchors that moved in the refresh. Tell it to read AGENT_RULES.md first and to end its report with every new or changed user-facing string and every existing assertion it changed (D-FRX-20). + c. Brief cf-reviewer on the same WP. On "changes required", send the blocking findings back to the same implementer (continue it, do not start a new one) and review again. Two failed review rounds: log BLOCKED.md and move to the next WP that does not depend on it. + d. For WP-03, WP-11 and WP-12, and any diff that touches a file AGENT_RULES.md calls safety-critical, read the full diff yourself and confirm every changed line traces to a contract item. Record that in PROGRESS.md. WP-11 also gets the Opus review it describes. + e. Run the WP's Done-when commands yourself. Record each command and its exit code in PROGRESS.md. + f. Log every ambiguity the implementer resolved as a runtime decision D-FRX-1NN in DECISIONS.md, using the tie-break rule at its top. + g. Commit only that WP's owned paths plus the plan files you updated: git add ; git commit -m "FRX : ". Never git add -A or git add . +3. Run each gate yourself exactly as written, including looking at every rendered PNG against the contract copy and sending me the PNGs. A render is "rendered", not "verified in the running app". +4. Keep PROGRESS.md current after every step. After any context compaction, re-read AGENT_RULES.md, PROGRESS.md and BLOCKED.md before anything else, run git status and git log --oneline -15, and continue from the first WP that is not done. +5. If an approach fails twice or a contract fact turns out wrong, stop patching: re-read the code, write the corrected fact and your choice as a runtime decision, then continue. If the correction would weaken a safety invariant, change a file D-FRX-04 forbids, or need a planner or executor edit the contracts do not name, log it in BLOCKED.md instead and move on. + +NEVER: git push; open a pull request; git reset --hard, git clean, git stash, git restore, git checkout -- <path>; sudo; worktrees; touch untracked files you did not create (other than committing this plan folder in WP-00); edit Chronoframe.storekit, product IDs, prices, the allowance caps, StoreKit, entitlement or ledger code; change any *Capability.isEnabled value; edit project.pbxproj or add a file under ui/Xcode/UITests; rename or remove an accessibility identifier or a string-catalog key; delete, skip or weaken a test; mark an owner row; ask to control the app or the screen. + +STOP ONLY WHEN: gate G3 is done; or every remaining WP depends on an open BLOCKED.md item; or WP-00 cannot proceed (INV-31 missing on main, modified tracked files, or the branch cannot be created). + +FINAL MESSAGE, in this order: per milestone the branch name and its commits (hash and title); each gate's commands with exit codes; per WP "compiled", "tested" and "rendered" reported separately; every runtime decision in one line each; every existing assertion you changed; open BLOCKED.md items with your recommendation; anything you noticed and did not fix; then the owner checklist from EVIDENCE_LEDGER.md. Lead with what is not done. +``` + +## Resume prompt + +```text +You are resuming as the orchestrator for the Chronoframe plan in docs/plan/first-run-experience (prefix FRX). Do not ask me questions. +Read docs/plan/next-half/AGENT_RULES.md, then PROGRESS.md and BLOCKED.md in the plan folder, then the kickoff prompt in ORCHESTRATOR_KICKOFF.md (its roles, procedure, never-list and stop conditions all still apply), then the plan, contracts and decisions for the next work package. +Run git status, git branch --show-current and git log --oneline -15 and reconcile them with PROGRESS.md: a WP whose commit exists is done; a WP marked in-progress without a commit restarts from its acceptance tests (keep files already in its owned paths and let the implementer continue from them). Switch to the branch of the milestone you are resuming; never create a milestone branch that already exists. +BLOCKED.md items I marked "resolved" unblock their WPs. +Continue from the first WP that is not done, through gate G3, and finish with the same final message. +``` diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md new file mode 100644 index 00000000..e17b12b1 --- /dev/null +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -0,0 +1,42 @@ +# First-run experience — progress + +Status: not started. Every work package is `todo`. + +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). + +## Baseline +(WP-00: branch point, test count, anchors that moved) + +## Work packages +| WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | +|---|---|---|---|---|---|---|---| +| WP-00 | Branch, plan folder, baseline | todo | | | n/a | | stops if INV-31 is not on main | +| WP-01 | Render evidence harness | todo | | | | | | +| WP-02 | Core: accounting, free month, model fields | todo | | | | | | +| WP-03 | AppCore: engine, offer, unlock presentation | todo | | | | | D-FRX-04 files only | +| WP-04 | App: preview free limit and free month | todo | | | | | | +| WP-05 | App: accounted-for line, Undo, add folder | todo | | | | | INV-8 tag on the undo test | +| WP-06 | Docs and strings, M1 | todo | | | | | | +| G1 | Gate, M1 | todo | | | n/a | | | +| 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 | | | +| 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 | | | | | | +| WP-23 | App: photos and folder picture on the preview | todo | | | | | | +| WP-24 | Docs and strings, M3 | todo | | | | | | +| G3 | Final gate | todo | | | n/a | | | + +## Existing assertions changed (D-FRX-20) +| WP | Test file:line | Old expectation | New expectation | Contract | +|---|---|---|---|---| + +## Renders checked +| Gate | File | Checked against | Result | +|---|---|---|---| + +## Log diff --git a/docs/plan/first-run-experience/bin/add_translated_keys.py b/docs/plan/first-run-experience/bin/add_translated_keys.py new file mode 100644 index 00000000..f697bc55 --- /dev/null +++ b/docs/plan/first-run-experience/bin/add_translated_keys.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python3 +"""Add keys with English and German values to an Xcode String Catalog. + +usage: add_translated_keys.py <catalog.xcstrings> <strings.json> [--allow-reformat] + +strings.json: a JSON array of {"key": "<English string exactly as in code>", "de": "<German>"}. +- A key that is missing is added with extractionState "manual", an English stringUnit equal + to the key and a German stringUnit, both "translated". +- A key that exists without German gets the German stringUnit added. +- A key that already has German is left untouched (reported as "kept"). +- Nothing is ever deleted or renamed. +Refuses an entry whose printf placeholders (%@, %lld, %1$@ ...) differ between key and German. +Keeps the file's own JSON layout (Xcode's "key" : value or Python's "key": value, detected by +round-trip) and its key order: a new key is inserted before the first existing key that sorts +after it, case-insensitively. Refuses to write if neither layout reproduces the untouched file +byte for byte (so the diff stays limited to the new keys), unless --allow-reformat is given. +Prints counts and exits 0 on success. +""" +import json, re, sys + +args = [a for a in sys.argv[1:] if not a.startswith("--")] +allow_reformat = "--allow-reformat" in sys.argv[1:] +if len(args) != 2: + sys.exit(__doc__) +catalog_path, strings_path = args + +PLACEHOLDER = re.compile(r"%(?:\d+\$)?(?:@|lld|ld|d|f|\.\d+f|s)") + + +def dump(obj, separators): + return json.dumps(obj, ensure_ascii=False, indent=2, separators=separators) + "\n" + + +def kinds(text): + return sorted(re.sub(r"\d+\$", "", p) for p in PLACEHOLDER.findall(text)) + + +with open(catalog_path, encoding="utf-8") as f: + original = f.read() +catalog = json.loads(original) +layout = next((s for s in ((",", " : "), (",", ": ")) if dump(catalog, s) == original), None) +if layout is None and not allow_reformat: + sys.exit( + f"refusing to write {catalog_path}: this script's JSON layout differs from the file's, " + "so the whole file would be rewritten. Re-run with --allow-reformat only if that is intended." + ) + +with open(strings_path, encoding="utf-8") as f: + entries = json.load(f) + +strings = catalog.setdefault("strings", {}) +added = filled = kept = 0 +for entry in entries: + key, german = entry["key"], entry["de"] + if not key or not german: + sys.exit(f"empty key or German value: {entry!r}") + if kinds(key) != kinds(german): + sys.exit(f"placeholder mismatch for key {key!r}: German is {german!r}") + unit = {"stringUnit": {"state": "translated", "value": german}} + if key not in strings: + value = { + "extractionState": "manual", + "localizations": { + "de": unit, + "en": {"stringUnit": {"state": "translated", "value": key}}, + }, + } + items = list(strings.items()) + index = next((i for i, (k, _) in enumerate(items) if k.casefold() > key.casefold()), len(items)) + items.insert(index, (key, value)) + strings.clear() + strings.update(items) + added += 1 + elif "de" not in strings[key].get("localizations", {}): + strings[key].setdefault("localizations", {})["de"] = unit + filled += 1 + else: + kept += 1 + +with open(catalog_path, "w", encoding="utf-8") as f: + f.write(dump(catalog, layout or (",", " : "))) +print(f"{catalog_path}: added {added}, German filled {filled}, kept {kept}") From aa56f84e23a74ce13d1bc41e0b4e75f24db012de Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 17:45:27 -0800 Subject: [PATCH 02/30] FRX WP-00: supersede first-ten-minutes Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-ten-minutes/ACCEPTANCE_MATRIX.md | 2 +- docs/plan/first-ten-minutes/BLOCKED.md | 2 +- docs/plan/first-ten-minutes/CONTRACTS.md | 2 +- docs/plan/first-ten-minutes/DECISIONS.md | 2 +- docs/plan/first-ten-minutes/EVIDENCE_LEDGER.md | 2 +- docs/plan/first-ten-minutes/IMPLEMENTATION_PLAN.md | 2 +- docs/plan/first-ten-minutes/PROGRESS.md | 2 +- docs/plan/next-half/README.md | 3 ++- 8 files changed, 9 insertions(+), 8 deletions(-) diff --git a/docs/plan/first-ten-minutes/ACCEPTANCE_MATRIX.md b/docs/plan/first-ten-minutes/ACCEPTANCE_MATRIX.md index 9ace3582..44d8e463 100644 --- a/docs/plan/first-ten-minutes/ACCEPTANCE_MATRIX.md +++ b/docs/plan/first-ten-minutes/ACCEPTANCE_MATRIX.md @@ -1,6 +1,6 @@ # First ten minutes — acceptance matrix -Status: not started (verified 2026-11-22 on main 8308aac: `git grep` finds no `RunPreflightAssessment`, `PreflightService`, `FirstRunTestBatch` or `RunProofModel` in `ui/`). No row is built. +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | ID | Requirement (Round 3 #5) | Automated coverage | Hardware row | Auto status | Hardware status | |---|---|---|---|---|---| diff --git a/docs/plan/first-ten-minutes/BLOCKED.md b/docs/plan/first-ten-minutes/BLOCKED.md index 17d97b38..7d8e07a8 100644 --- a/docs/plan/first-ten-minutes/BLOCKED.md +++ b/docs/plan/first-ten-minutes/BLOCKED.md @@ -1,5 +1,5 @@ # First ten minutes — blocked items -Status: not started. No blocked items. +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. Entry format: see "Blocked items" in `docs/plan/next-half/AGENT_RULES.md`. Only Nishith marks an item resolved. diff --git a/docs/plan/first-ten-minutes/CONTRACTS.md b/docs/plan/first-ten-minutes/CONTRACTS.md index fe637402..797e888d 100644 --- a/docs/plan/first-ten-minutes/CONTRACTS.md +++ b/docs/plan/first-ten-minutes/CONTRACTS.md @@ -1,6 +1,6 @@ # First ten minutes — contracts -Status: not started (verified 2026-11-22 on main 8308aac: `git grep` finds no `RunPreflightAssessment`, `PreflightService`, `FirstRunTestBatch` or `RunProofModel` in `ui/`). References and UI names below were refreshed against that commit after clear-path (#269, #274), free-space reservation (#265), run-outcome accuracy (#282) and presentation accuracy (#281); the contracts themselves are unchanged except where a `Stale since` note says so. UI names: the Setup tab is now Choose Folders, the Run tab is Preview & Copy, the copy button is "Start Copying" (was "Start Transfer") and the preview button "Preview Plan". +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. Plan prefix `FTM`. Read `docs/plan/next-half/AGENT_RULES.md` first. Line numbers were refreshed against `main` at 8308aac (2026-11-22); if a line moved, search for the quoted declaration. diff --git a/docs/plan/first-ten-minutes/DECISIONS.md b/docs/plan/first-ten-minutes/DECISIONS.md index 8055e129..eff3df25 100644 --- a/docs/plan/first-ten-minutes/DECISIONS.md +++ b/docs/plan/first-ten-minutes/DECISIONS.md @@ -1,6 +1,6 @@ # First ten minutes — decisions -Status: not started (verified 2026-11-22 on main 8308aac: `git grep` finds no `RunPreflightAssessment`, `PreflightService`, `FirstRunTestBatch` or `RunProofModel` in `ui/`). Intact. D-FTM-01 names the base branch; edit it before running (see its note). +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. Prefix `FTM`. Runtime decisions appended as `D-FTM-1NN`. diff --git a/docs/plan/first-ten-minutes/EVIDENCE_LEDGER.md b/docs/plan/first-ten-minutes/EVIDENCE_LEDGER.md index 032188fa..3adcc7a5 100644 --- a/docs/plan/first-ten-minutes/EVIDENCE_LEDGER.md +++ b/docs/plan/first-ten-minutes/EVIDENCE_LEDGER.md @@ -1,6 +1,6 @@ # First ten minutes — evidence ledger (owner rows) -Status: not started (verified 2026-11-22 on main 8308aac: `git grep` finds no `RunPreflightAssessment`, `PreflightService`, `FirstRunTestBatch` or `RunProofModel` in `ui/`). No row is run. +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | Row | What to run | Pass when | Status | Evidence | |---|---|---|---|---| diff --git a/docs/plan/first-ten-minutes/IMPLEMENTATION_PLAN.md b/docs/plan/first-ten-minutes/IMPLEMENTATION_PLAN.md index 9af49f1d..1af97a26 100644 --- a/docs/plan/first-ten-minutes/IMPLEMENTATION_PLAN.md +++ b/docs/plan/first-ten-minutes/IMPLEMENTATION_PLAN.md @@ -1,6 +1,6 @@ # First ten minutes — implementation plan -Status: not started (verified 2026-11-22 on main 8308aac: `git grep` finds no `RunPreflightAssessment`, `PreflightService`, `FirstRunTestBatch` or `RunProofModel` in `ui/`). Line references and UI names refreshed 2026-11-22 after clear-path (#269, #274), #265, #282 and #281; `photos-import-resume` (#268, #270), `dedupe-persistence` (#267) and `nas-v1`/`nas-public` (#266) are on `main`. Proposal prepared 2026-11-07. Prefix `FTM`. Read first: `docs/plan/next-half/AGENT_RULES.md`, `CONTRACTS.md`, `DECISIONS.md`. +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. ## Run order WP-00 → WP-01 → WP-02 → G1 → WP-03 → WP-04 → WP-05 → WP-06 → WP-07 → G2. diff --git a/docs/plan/first-ten-minutes/PROGRESS.md b/docs/plan/first-ten-minutes/PROGRESS.md index 86dbc3b0..8a42b489 100644 --- a/docs/plan/first-ten-minutes/PROGRESS.md +++ b/docs/plan/first-ten-minutes/PROGRESS.md @@ -1,6 +1,6 @@ # First ten minutes — progress -Status: not started (verified 2026-11-22 on main 8308aac: `git grep` finds no `RunPreflightAssessment`, `PreflightService`, `FirstRunTestBatch` or `RunProofModel` in `ui/`). Every WP is `todo`. +Status: superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. Prefix `FTM`. Status values: todo, in-progress, review, done, blocked. diff --git a/docs/plan/next-half/README.md b/docs/plan/next-half/README.md index 5bd1fe53..5b741d8a 100644 --- a/docs/plan/next-half/README.md +++ b/docs/plan/next-half/README.md @@ -13,7 +13,8 @@ Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as | 3 | [`photos-import-resume/`](../photos-import-resume/) | `feature/photos-import-resume` | `main` after #2 merges | `PIR` | 3 — visible, cancellable, resumable Photos import | shipped in #268 | | 3a | [`clear-path/`](../clear-path/) | `feature/clear-path` | `feature/photos-import-resume` (stacked, D-CLP-01) | `CLP` | UX review 2026-11-12 — plain-language Organize and Deduplicate flow, several folders at once | shipped in #269, follow-up #274 | | 4 | [`find-and-account/`](../find-and-account/) | `feature/find-and-account` | `main` after #3 merges | `FAA` | 4 — item-level reconciliation and original-name lookup | not started | -| 5 | [`first-ten-minutes/`](../first-ten-minutes/) | `feature/first-ten-minutes` | `main` after #4 merges | `FTM` | 5 — preflight, free batch, proof | not started | +| 5 | [`first-ten-minutes/`](../first-ten-minutes/) | `feature/first-ten-minutes` | `main` after #4 merges | `FTM` | 5 — preflight, free batch, proof | superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | +| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | in progress, not merged | Each plan is self-contained: `CONTRACTS.md`, `DECISIONS.md`, `IMPLEMENTATION_PLAN.md`, `PROGRESS.md`, `ACCEPTANCE_MATRIX.md`, `BLOCKED.md`, `EVIDENCE_LEDGER.md`. Shared files live here: [`AGENT_RULES.md`](AGENT_RULES.md), [`bin/cf_swift.sh`](bin/cf_swift.sh), [`ORCHESTRATOR_KICKOFF.md`](ORCHESTRATOR_KICKOFF.md), [`claude-config/`](claude-config/) (install into the gitignored `.claude/`). From f5f8d8044ba1ba55b5d50ff0ed519aaff194e725 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 17:48:49 -0800 Subject: [PATCH 03/30] FRX WP-00: baseline Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/PROGRESS.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index e17b12b1..1c758f10 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -1,17 +1,19 @@ # First-run experience — progress -Status: not started. Every work package is `todo`. +Status: in progress (M1). 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). ## Baseline -(WP-00: branch point, test count, anchors that moved) +- 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. ## Work packages | WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | |---|---|---|---|---|---|---|---| -| WP-00 | Branch, plan folder, baseline | todo | | | n/a | | stops if INV-31 is not on main | -| WP-01 | Render evidence harness | todo | | | | | | +| WP-00 | Branch, plan folder, baseline | done | build exit 0 | suite exit 0 (2513 passed) | n/a | a09eca6, aa56f84 | INV-31 on main: 1 | +| WP-01 | Render evidence harness | in-progress | | | | | | | WP-02 | Core: accounting, free month, model fields | todo | | | | | | | WP-03 | AppCore: engine, offer, unlock presentation | todo | | | | | D-FRX-04 files only | | WP-04 | App: preview free limit and free month | todo | | | | | | From fb09f36b2fe2d25bff95eb489cd00748b494360b Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 17:50:50 -0800 Subject: [PATCH 04/30] FRX WP-01: Render evidence harness Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 5 +- .../ScreenRenderEvidenceTests.swift | 109 ++++++++++++++++++ 3 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 13fc0f6c..472ae10c 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -46,3 +46,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - "never hard-deletes them" in `SharedViews.swift:895` is jargon; rewording it is the owner's call under D-FRX-12. ## Runtime decisions +- **D-FRX-101 Sheet render size and fixture numbers (WP-01).** C-00 gives no size for the unlock-sheet renders and no refusal numbers. The sheet tests render at 460×560 (the sheet is 420 wide in `UnlockSheetLayoutTests`) with refusals `.allowanceSpent` organize 250/0 and dedupe 25/0. Evidence-only values; nothing in production reads them. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 1c758f10..bcc9b346 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -13,8 +13,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | |---|---|---|---|---|---|---|---| | WP-00 | Branch, plan folder, baseline | done | build exit 0 | suite exit 0 (2513 passed) | n/a | a09eca6, aa56f84 | INV-31 on main: 1 | -| WP-01 | Render evidence harness | in-progress | | | | | | -| WP-02 | Core: accounting, free month, model fields | todo | | | | | | +| WP-01 | Render evidence harness | done | build exit 0 | `test ScreenRenderEvidenceTests` exit 0 (3 skipped without marker; 3 run, 3 PNGs with marker) | approve (round 1) | (this commit) | rendered: harness produces non-blank PNGs; D-FRX-101 | +| WP-02 | Core: accounting, free month, model fields | in-progress | | | | | | | WP-03 | AppCore: engine, offer, unlock presentation | todo | | | | | D-FRX-04 files only | | WP-04 | App: preview free limit and free month | todo | | | | | | | WP-05 | App: accounted-for line, Undo, add folder | todo | | | | | INV-8 tag on the undo test | @@ -42,3 +42,4 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled |---|---|---|---| ## Log +- 2026-11-28 WP-01 Done-when (orchestrator): `cf_swift.sh test ScreenRenderEvidenceTests` exit 0 without marker (3 skipped); with `.tmp/frx-evidence/.enabled` exit 0, 3 PNGs (`m1-copy-complete`, `m1-unlock-organize`, `m1-unlock-dedupe`); `cf_swift.sh build` exit 0; `git diff --check` exit 0. Marker removed afterwards. diff --git a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift new file mode 100644 index 00000000..478db396 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift @@ -0,0 +1,109 @@ +import AppKit +import SwiftUI +import XCTest +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +@testable import ChronoframeApp + +/// Offscreen renders of screens from fixture states, for the orchestrator to look +/// at (D-FRX-22). They assert only that a file was written and are never a +/// pass/fail check on appearance. Without `.tmp/frx-evidence/.enabled` every test +/// skips, so CI skips. Output is not committed. +@MainActor +final class ScreenRenderEvidenceTests: XCTestCase { + /// `<repo root>/.tmp/frx-evidence`, derived from this file's path: + /// `<repo root>/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift`. + private var evidenceDirectory: String { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + .appendingPathComponent(".tmp/frx-evidence") + .path + } + + private func requireEvidenceMarker() throws { + try XCTSkipUnless(FileManager.default.fileExists(atPath: evidenceDirectory + "/.enabled")) + } + + private func render<V: View>(_ view: V, name: String, size: NSSize = NSSize(width: 1360, height: 920)) async throws { + let hosting = NSHostingView(rootView: view + .frame(width: size.width, height: size.height) + .background(Color(nsColor: .windowBackgroundColor))) + let window = NSWindow(contentRect: NSRect(origin: .zero, size: size), styleMask: [.borderless], backing: .buffered, defer: false) + window.contentView = hosting + hosting.layoutSubtreeIfNeeded() + try await Task.sleep(nanoseconds: 1_500_000_000) + let bitmap = try XCTUnwrap(hosting.bitmapImageRepForCachingDisplay(in: hosting.bounds)) + hosting.cacheDisplay(in: hosting.bounds, to: bitmap) + let data = try XCTUnwrap(bitmap.representation(using: .png, properties: [:])) + try data.write(to: URL(fileURLWithPath: evidenceDirectory).appendingPathComponent(name + ".png")) + } + + private func assertWritten(_ name: String, file: StaticString = #filePath, line: UInt = #line) { + let path = evidenceDirectory + "/" + name + ".png" + XCTAssertTrue(FileManager.default.fileExists(atPath: path), "Expected \(path) to be written", file: file, line: line) + } + + func testRenderCopyComplete() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .runCopyComplete) + try await render(RootSplitView(appState: appState), name: "m1-copy-complete") + assertWritten("m1-copy-complete") + } + + func testRenderUnlockSheetOrganize() async throws { + try requireEvidenceMarker() + let store = await makeEntitlementStore() + try await render( + UnlockSheet( + refusal: .allowanceSpent(TrialRefusal(meter: .organize, requested: 250, remaining: 0)), + entitlementStore: store, onUnlocked: {}, onDismiss: {} + ), + name: "m1-unlock-organize", size: NSSize(width: 460, height: 560) + ) + assertWritten("m1-unlock-organize") + } + + func testRenderUnlockSheetDedupe() async throws { + try requireEvidenceMarker() + let store = await makeEntitlementStore() + try await render( + UnlockSheet( + refusal: .allowanceSpent(TrialRefusal(meter: .dedupe, requested: 25, remaining: 0)), + entitlementStore: store, onUnlocked: {}, onDismiss: {} + ), + name: "m1-unlock-dedupe", size: NSSize(width: 460, height: 560) + ) + assertWritten("m1-unlock-dedupe") + } + + private func makeEntitlementStore() async -> EntitlementStore { + let store = EntitlementStore( + storeKit: EvidenceStore(), + appTransactionClient: EvidenceTransaction(), + defaults: .standard + ) + await store.loadProduct() + return store + } +} + +private struct EvidenceStore: StoreKitClient { + func product(for productID: String) async -> StoreProductInfo? { + StoreProductInfo(productID: productID, displayName: "Chronoframe Unlock", displayPrice: "$14.99") + } + func ownedProducts() async -> Result<[OwnedProduct], EntitlementLookupFailure> { .success([]) } + func purchase(productID: String) async -> PurchaseOutcome { .userCancelled } + func sync() async throws {} + func transactionUpdates() -> AsyncStream<Void> { AsyncStream { $0.finish() } } +} + +private struct EvidenceTransaction: AppTransactionClient { + func appTransaction() async -> Result<AppTransactionInfo, EntitlementLookupFailure> { .failure(.unavailable) } +} From 682f714b28fee6585f4adbc12e4fdcd37b9ae136 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 17:55:38 -0800 Subject: [PATCH 05/30] FRX WP-02: Core: accounting, free month, model fields Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 7 +- .../FreeMonthBatchPlanner.swift | 152 +++++++++++ .../FreeTestBatchPlanner.swift | 41 ++- .../ChronoframeCore/RunAccounting.swift | 53 ++++ ui/Sources/ChronoframeCore/RunModels.swift | 16 +- ...oframeCoreFreeMonthBatchPlannerTests.swift | 245 ++++++++++++++++++ .../ChronoframeCoreRunAccountingTests.swift | 145 +++++++++++ .../FreeTestBatchPlannerTests.swift | 67 +++++ 9 files changed, 720 insertions(+), 7 deletions(-) create mode 100644 ui/Sources/ChronoframeCore/FreeMonthBatchPlanner.swift create mode 100644 ui/Sources/ChronoframeCore/RunAccounting.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeMonthBatchPlannerTests.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreRunAccountingTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 472ae10c..36b31f53 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -47,3 +47,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh ## Runtime decisions - **D-FRX-101 Sheet render size and fixture numbers (WP-01).** C-00 gives no size for the unlock-sheet renders and no refusal numbers. The sheet tests render at 460×560 (the sheet is 420 wide in `UnlockSheetLayoutTests`) with refusals `.allowanceSpent` organize 250/0 and dedupe 25/0. Evidence-only values; nothing in production reads them. +- **D-FRX-102 Free-month planner details (WP-02).** (a) `monthKey(forDateBucket:)` is strict: exactly `yyyy-MM-dd` in ASCII digits with month 01–12 and day 01–31, otherwise nil. (b) A companion counts toward, and travels with, its owner's month whatever its own `dateBucket`; a companion whose owner is an exact copy or is not in the plan is not counted. (c) When a month is too large, `select` stops at the first day that does not fit (it never skips ahead to a smaller later day); within a too-large first day it stops at the first owner unit that does not fit. (d) `options` leaves out a month whose count is 0. All four are the narrowest reading of C-05; none widens what a free copy can contain. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index bcc9b346..4bb07d32 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -13,9 +13,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | |---|---|---|---|---|---|---|---| | WP-00 | Branch, plan folder, baseline | done | build exit 0 | suite exit 0 (2513 passed) | n/a | a09eca6, aa56f84 | INV-31 on main: 1 | -| WP-01 | Render evidence harness | done | build exit 0 | `test ScreenRenderEvidenceTests` exit 0 (3 skipped without marker; 3 run, 3 PNGs with marker) | approve (round 1) | (this commit) | rendered: harness produces non-blank PNGs; D-FRX-101 | -| WP-02 | Core: accounting, free month, model fields | in-progress | | | | | | -| WP-03 | AppCore: engine, offer, unlock presentation | todo | | | | | D-FRX-04 files only | +| WP-01 | Render evidence harness | done | build exit 0 | `test ScreenRenderEvidenceTests` exit 0 (3 skipped without marker; 3 run, 3 PNGs with marker) | approve (round 1) | fb09f36 | rendered: harness produces non-blank PNGs; D-FRX-101 | +| WP-02 | Core: accounting, free month, model fields | done | build exit 0 | RunAccounting 8, FreeMonthBatchPlanner 14, FreeTestBatchPlanner 19 tests, all exit 0 | approve (round 1) | (WP-02 commit) | orchestrator read the FreeTestBatchPlanner.swift and RunModels.swift diffs: additions only; D-FRX-102 | +| WP-03 | AppCore: engine, offer, unlock presentation | in-progress | | | | | D-FRX-04 files only | | WP-04 | App: preview free limit and free month | todo | | | | | | | WP-05 | App: accounted-for line, Undo, add folder | todo | | | | | INV-8 tag on the undo test | | WP-06 | Docs and strings, M1 | todo | | | | | | @@ -43,3 +43,4 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled ## Log - 2026-11-28 WP-01 Done-when (orchestrator): `cf_swift.sh test ScreenRenderEvidenceTests` exit 0 without marker (3 skipped); with `.tmp/frx-evidence/.enabled` exit 0, 3 PNGs (`m1-copy-complete`, `m1-unlock-organize`, `m1-unlock-dedupe`); `cf_swift.sh build` exit 0; `git diff --check` exit 0. Marker removed afterwards. +- 2026-11-28 WP-02 Done-when (orchestrator): `cf_swift.sh test ChronoframeCoreRunAccountingTests` exit 0 (8 tests); `cf_swift.sh test ChronoframeCoreFreeMonthBatchPlannerTests` exit 0 (14); `cf_swift.sh test FreeTestBatchPlannerTests` exit 0 (19); `cf_swift.sh build` exit 0; `git diff --check` exit 0. No user-facing strings, no existing assertions changed. diff --git a/ui/Sources/ChronoframeCore/FreeMonthBatchPlanner.swift b/ui/Sources/ChronoframeCore/FreeMonthBatchPlanner.swift new file mode 100644 index 00000000..be738ab8 --- /dev/null +++ b/ui/Sources/ChronoframeCore/FreeMonthBatchPlanner.swift @@ -0,0 +1,152 @@ +import Foundation + +// MARK: - The free whole month (FRX C-05, D-FRX-13) +// +// A month is only ever a *proposal*. Nothing here runs a copy: `select` names +// the transfers a free copy of a month would run, and the sheet then lists +// them and the copy runs on the confirmed paths and identities through +// `FreeTestBatchSelection`, as `FreeTestBatchPlanner.swift` requires. A month +// is never re-derived at run time. +// +// New photos and videos only, with their sidecars. Exact copies are written +// under `Duplicate/`, not in the month folders, and undated files have no month, +// so neither is ever part of a free month. + +/// One month a person could copy for free. +public struct FreeMonthOption: Equatable, Sendable, Identifiable { + public var id: String { key } + /// `"yyyy-MM"`. + public let key: String + /// That month's new photos and videos plus their sidecars. + public let fileCount: Int + /// `fileCount <= remaining`. + public let fits: Bool +} + +public enum FreeMonthBatchPlanner { + /// `"2026-10-14"` → `"2026-10"`. Nil for the unknown-date bucket or anything + /// that is not `yyyy-MM-dd`. + public static func monthKey(forDateBucket bucket: String) -> String? { + let parts = bucket.split(separator: "-", omittingEmptySubsequences: false) + guard parts.count == 3, + parts[0].count == 4, parts[1].count == 2, parts[2].count == 2, + parts.allSatisfy({ $0.allSatisfy { $0.isASCII && $0.isNumber } }), + let month = Int(parts[1]), (1...12).contains(month), + let day = Int(parts[2]), (1...31).contains(day) + else { return nil } + return "\(parts[0])-\(parts[1])" + } + + /// Month key → new files that land in that month: owners with + /// `isDuplicate == false` plus their companions. Exact copies and undated + /// files are never counted. + public static func newFilesByMonth(for result: DryRunPlanningResult) -> [String: Int] { + var counts: [String: Int] = [:] + for unit in newOwnerUnits(in: result) { + counts[unit.monthKey, default: 0] += unit.size + } + return counts + } + + /// Newest month first. Empty when `remaining <= 0`. + public static func options(newFilesByMonth: [String: Int], remaining: Int) -> [FreeMonthOption] { + guard remaining > 0 else { return [] } + return newFilesByMonth + .filter { $0.value > 0 } + .sorted { $0.key > $1.key } + .map { FreeMonthOption(key: $0.key, fileCount: $0.value, fits: $0.value <= remaining) } + } + + /// The newest option that fits; when none fits, the newest option (a + /// partial month). + public static func suggestedOption(_ options: [FreeMonthOption]) -> FreeMonthOption? { + options.first(where: \.fits) ?? options.first + } + + /// The transfers a free copy of `monthKey` would run, never more than + /// `limit`. + /// + /// Owners are transfers with no entry in `result.companionOwners`, + /// `isDuplicate == false` and a matching month key. An owner always travels + /// with every companion that names it. The whole month when it is within + /// `limit`; otherwise whole days in ascending order while the running total + /// stays within `limit`; if the first day alone exceeds `limit`, owners of + /// that day in order while they fit. + public static func select( + from result: DryRunPlanningResult, + monthKey: String, + limit: Int + ) -> [PlannedTransfer] { + guard limit > 0 else { return [] } + + let monthUnits = newOwnerUnits(in: result).filter { $0.monthKey == monthKey } + let unitsByOwner = Dictionary(monthUnits.map { ($0.owner.sourcePath, $0) }, uniquingKeysWith: { first, _ in first }) + let units = FreeTestBatchPlanner.inBatchOrder(monthUnits.map(\.owner)).compactMap { unitsByOwner[$0.sourcePath] } + let total = units.reduce(0) { $0 + $1.size } + + let chosen: [OwnerUnit] + if total <= limit { + chosen = units + } else { + var days: [(bucket: String, units: [OwnerUnit])] = [] + for unit in units { + if days.last?.bucket == unit.owner.dateBucket { + days[days.count - 1].units.append(unit) + } else { + days.append((unit.owner.dateBucket, [unit])) + } + } + + var taken: [OwnerUnit] = [] + var running = 0 + for day in days { + let daySize = day.units.reduce(0) { $0 + $1.size } + guard running + daySize <= limit else { break } + taken.append(contentsOf: day.units) + running += daySize + } + + if taken.isEmpty, let firstDay = days.first { + for unit in firstDay.units { + guard running + unit.size <= limit else { break } + taken.append(unit) + running += unit.size + } + } + chosen = taken + } + + return FreeTestBatchPlanner.inBatchOrder(chosen.flatMap { [$0.owner] + $0.companions }) + } + + // MARK: - Owners and their companions + + private struct OwnerUnit { + let owner: PlannedTransfer + let companions: [PlannedTransfer] + let monthKey: String + var size: Int { 1 + companions.count } + } + + /// Every new, dated owner with the companions that name it. + private static func newOwnerUnits(in result: DryRunPlanningResult) -> [OwnerUnit] { + let transfers = result.copyPlan.transfers + var companionsByOwner: [String: [PlannedTransfer]] = [:] + for transfer in transfers { + guard let owner = result.companionOwners[transfer.sourcePath] else { continue } + companionsByOwner[owner, default: []].append(transfer) + } + + return transfers.compactMap { transfer in + guard result.companionOwners[transfer.sourcePath] == nil, + !transfer.isDuplicate, + let key = monthKey(forDateBucket: transfer.dateBucket) + else { return nil } + return OwnerUnit( + owner: transfer, + companions: companionsByOwner[transfer.sourcePath] ?? [], + monthKey: key + ) + } + } +} diff --git a/ui/Sources/ChronoframeCore/FreeTestBatchPlanner.swift b/ui/Sources/ChronoframeCore/FreeTestBatchPlanner.swift index 81fb3e5c..a2344cbd 100644 --- a/ui/Sources/ChronoframeCore/FreeTestBatchPlanner.swift +++ b/ui/Sources/ChronoframeCore/FreeTestBatchPlanner.swift @@ -30,9 +30,23 @@ public struct FreeTestBatch: Equatable, Sendable { /// again as new work. public let deferredCount: Int - public init(included: [PlannedTransfer], deferredCount: Int) { + /// `"yyyy-MM"` when the batch is a whole (or partial) month; nil otherwise. + public let monthKey: String? + + /// True when the person asked for this month, as opposed to the batch being + /// the one suggested. + public let wasRequested: Bool + + public init( + included: [PlannedTransfer], + deferredCount: Int, + monthKey: String? = nil, + wasRequested: Bool = false + ) { self.included = included self.deferredCount = deferredCount + self.monthKey = monthKey + self.wasRequested = wasRequested } public var includedCount: Int { included.count } @@ -62,6 +76,19 @@ public struct FreeTestBatch: Equatable, Sendable { } } +/// A person's request for one month, made before any file list is confirmed. +public struct FreeMonthRequest: Equatable, Sendable { + /// `"yyyy-MM"`. + public let key: String + /// The remaining allowance the screen showed. + public let limit: Int + + public init(key: String, limit: Int) { + self.key = key + self.limit = limit + } +} + /// Exactly which files a confirmed batch may copy. /// /// Keyed by source path **and** the content identity confirmed at that path, so @@ -84,8 +111,20 @@ public struct FreeTestBatchSelection: Equatable, Sendable { /// Source path to the identity that path had when the batch was confirmed. public let confirmedIdentities: [String: FileIdentity] + /// Set only by `init(requestingMonth:)`; nil from the existing initializer. + public let monthRequest: FreeMonthRequest? + public init(confirmedIdentities: [String: FileIdentity]) { self.confirmedIdentities = confirmedIdentities + self.monthRequest = nil + } + + /// A request, not a confirmation. `confirmedIdentities` is empty, so + /// `apply(to:)` returns nothing and `reduced(to:)` keeps nothing: if the + /// engine branch that answers a request were ever missed, nothing is copied. + public init(requestingMonth request: FreeMonthRequest) { + self.confirmedIdentities = [:] + self.monthRequest = request } public var count: Int { confirmedIdentities.count } diff --git a/ui/Sources/ChronoframeCore/RunAccounting.swift b/ui/Sources/ChronoframeCore/RunAccounting.swift new file mode 100644 index 00000000..74ee1b51 --- /dev/null +++ b/ui/Sources/ChronoframeCore/RunAccounting.swift @@ -0,0 +1,53 @@ +import Foundation + +/// The numbers behind "every photo is accounted for" (FRX C-01, D-FRX-09). +/// +/// Every discovered media file lands in exactly one of: new, exact copy, +/// already in the destination, or unreadable. `remainder` is what is left of +/// `found` after those four, so zero means every file found is listed. It is +/// never rounded or clamped: a negative remainder is a real disagreement and +/// must read as unbalanced. +public struct RunAccounting: Equatable, Sendable { + /// `metrics.discoveredCount`. + public let found: Int + /// `max(0, plannedCount - duplicateCount - plannedCompanionCount)`. + public let new: Int + /// `duplicateCount`. + public let extraCopies: Int + /// `alreadyInDestinationCount`. + public let alreadyThere: Int + /// `hashErrorCount`. + public let unreadable: Int + /// `max(0, copiedCount - copiedCompanionCount)`; 0 for a preview. + public let copiedMedia: Int + /// Finished only: `max(0, (new + extraCopies) - copiedMedia)`; 0 for a preview. + public let notCopied: Int + /// `found - (new + extraCopies + alreadyThere + unreadable)`. Zero means + /// every file found is listed. + public let remainder: Int + + public var isBalanced: Bool { remainder == 0 } + + private init(metrics: RunMetrics, isFinished: Bool) { + let new = max(0, metrics.plannedCount - metrics.duplicateCount - metrics.plannedCompanionCount) + let copiedMedia = isFinished ? max(0, metrics.copiedCount - metrics.copiedCompanionCount) : 0 + + self.found = metrics.discoveredCount + self.new = new + self.extraCopies = metrics.duplicateCount + self.alreadyThere = metrics.alreadyInDestinationCount + self.unreadable = metrics.hashErrorCount + self.copiedMedia = copiedMedia + self.notCopied = isFinished ? max(0, (new + metrics.duplicateCount) - copiedMedia) : 0 + self.remainder = metrics.discoveredCount + - (new + metrics.duplicateCount + metrics.alreadyInDestinationCount + metrics.hashErrorCount) + } + + public static func preview(_ metrics: RunMetrics) -> RunAccounting { + RunAccounting(metrics: metrics, isFinished: false) + } + + public static func finished(_ metrics: RunMetrics) -> RunAccounting { + RunAccounting(metrics: metrics, isFinished: true) + } +} diff --git a/ui/Sources/ChronoframeCore/RunModels.swift b/ui/Sources/ChronoframeCore/RunModels.swift index c2c8202d..092ae1af 100644 --- a/ui/Sources/ChronoframeCore/RunModels.swift +++ b/ui/Sources/ChronoframeCore/RunModels.swift @@ -210,6 +210,9 @@ public struct RunMetrics: Equatable, Codable, Sendable { public var copiedCompanionCount: Int /// Companions the plan did not copy (no single owner, name taken, unreadable). public var unresolvedCompanionCount: Int + /// New photos and videos (with their sidecars) per `"yyyy-MM"` month; exact + /// copies and undated files are not counted. Empty when not computed. + public var newFilesByMonth: [String: Int] public init( discoveredCount: Int = 0, @@ -231,7 +234,8 @@ public struct RunMetrics: Equatable, Codable, Sendable { dateHistogram: [DateHistogramBucket] = [], plannedCompanionCount: Int = 0, copiedCompanionCount: Int = 0, - unresolvedCompanionCount: Int = 0 + unresolvedCompanionCount: Int = 0, + newFilesByMonth: [String: Int] = [:] ) { self.discoveredCount = discoveredCount self.plannedCount = plannedCount @@ -253,6 +257,7 @@ public struct RunMetrics: Equatable, Codable, Sendable { self.plannedCompanionCount = plannedCompanionCount self.copiedCompanionCount = copiedCompanionCount self.unresolvedCompanionCount = unresolvedCompanionCount + self.newFilesByMonth = newFilesByMonth } private enum CodingKeys: String, CodingKey { @@ -261,7 +266,8 @@ public struct RunMetrics: Equatable, Codable, Sendable { speedMBps, etaSeconds, revertedCount, skippedCount, missingCount, movedCount, dateHistogram, - plannedCompanionCount, copiedCompanionCount, unresolvedCompanionCount + plannedCompanionCount, copiedCompanionCount, unresolvedCompanionCount, + newFilesByMonth } public init(from decoder: Decoder) throws { @@ -286,6 +292,7 @@ public struct RunMetrics: Equatable, Codable, Sendable { self.plannedCompanionCount = try c.decodeIfPresent(Int.self, forKey: .plannedCompanionCount) ?? 0 self.copiedCompanionCount = try c.decodeIfPresent(Int.self, forKey: .copiedCompanionCount) ?? 0 self.unresolvedCompanionCount = try c.decodeIfPresent(Int.self, forKey: .unresolvedCompanionCount) ?? 0 + self.newFilesByMonth = try c.decodeIfPresent([String: Int].self, forKey: .newFilesByMonth) ?? [:] } } @@ -295,19 +302,22 @@ public struct RunArtifactPaths: Equatable, Codable, Sendable { public var previewReviewPath: String? public var logFilePath: String? public var logsDirectoryPath: String? + public var receiptPath: String? public init( destinationRoot: String = "", reportPath: String? = nil, previewReviewPath: String? = nil, logFilePath: String? = nil, - logsDirectoryPath: String? = nil + logsDirectoryPath: String? = nil, + receiptPath: String? = nil ) { self.destinationRoot = destinationRoot self.reportPath = reportPath self.previewReviewPath = previewReviewPath self.logFilePath = logFilePath self.logsDirectoryPath = logsDirectoryPath + self.receiptPath = receiptPath } } diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeMonthBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeMonthBatchPlannerTests.swift new file mode 100644 index 00000000..e38f4efa --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeMonthBatchPlannerTests.swift @@ -0,0 +1,245 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +/// Covers the free whole month planner (FRX C-05, D-FRX-13): a month is only +/// ever a proposal, and it never includes exact copies or undated files. +final class ChronoframeCoreFreeMonthBatchPlannerTests: XCTestCase { + private func transfer( + _ name: String, + bucket: String, + isDuplicate: Bool = false + ) -> PlannedTransfer { + PlannedTransfer( + sourcePath: "/Volumes/Card/\(name)", + destinationPath: "/Volumes/Archive/\(bucket)/\(name)", + identity: FileIdentity(size: Int64(name.count), digest: "digest-\(name)"), + dateBucket: bucket, + isDuplicate: isDuplicate + ) + } + + private func result( + _ transfers: [PlannedTransfer], + companionOwners: [String: String] = [:] + ) -> DryRunPlanningResult { + DryRunPlanningResult( + discoveredSourceCount: transfers.count, + destinationIndexedCount: 0, + sourceHashedCount: transfers.count, + copyPlan: CopyPlanResult( + transfers: transfers, + counts: CopyPlanCounts(newCount: transfers.filter { !$0.isDuplicate }.count), + warningMessages: [], + sequenceState: SequenceCounterState() + ), + companionOwners: companionOwners + ) + } + + /// `count` new photos on each of the given days of one month. + private func photos(_ prefix: String, day: String, count: Int) -> [PlannedTransfer] { + (0..<count).map { transfer("\(prefix)-\($0).jpg", bucket: day) } + } + + // MARK: - Month keys + + func testMonthKeyFromDateBucket() { + XCTAssertEqual(FreeMonthBatchPlanner.monthKey(forDateBucket: "2026-10-14"), "2026-10") + XCTAssertEqual(FreeMonthBatchPlanner.monthKey(forDateBucket: "1999-01-01"), "1999-01") + } + + func testMonthKeyNilForUnknownDate() { + XCTAssertNil(FreeMonthBatchPlanner.monthKey(forDateBucket: "Unknown_Date")) + XCTAssertNil(FreeMonthBatchPlanner.monthKey(forDateBucket: "")) + XCTAssertNil(FreeMonthBatchPlanner.monthKey(forDateBucket: "2026-10")) + XCTAssertNil(FreeMonthBatchPlanner.monthKey(forDateBucket: "2026/10/14")) + XCTAssertNil(FreeMonthBatchPlanner.monthKey(forDateBucket: "2026-1a-14")) + } + + // MARK: - Counting + + func testMonthCountsExcludeExactCopiesAndUndated() { + let plan = result([ + transfer("a.jpg", bucket: "2026-10-01"), + transfer("b.jpg", bucket: "2026-10-02"), + transfer("copy.jpg", bucket: "2026-10-02", isDuplicate: true), + transfer("c.jpg", bucket: "2026-09-30"), + transfer("undated.jpg", bucket: "Unknown_Date"), + ]) + + XCTAssertEqual( + FreeMonthBatchPlanner.newFilesByMonth(for: plan), + ["2026-10": 2, "2026-09": 1] + ) + } + + func testMonthCountsIncludeCompanionsOfNewFiles() { + let owner = transfer("a.jpg", bucket: "2026-10-01") + let companion = transfer("a.xmp", bucket: "2026-10-01") + let copy = transfer("copy.jpg", bucket: "2026-10-03", isDuplicate: true) + let copyCompanion = transfer("copy.xmp", bucket: "2026-10-03") + let plan = result( + [owner, companion, copy, copyCompanion], + companionOwners: [ + companion.sourcePath: owner.sourcePath, + copyCompanion.sourcePath: copy.sourcePath, + ] + ) + + XCTAssertEqual( + FreeMonthBatchPlanner.newFilesByMonth(for: plan), + ["2026-10": 2], + "the new photo and its sidecar count; an exact copy and its sidecar do not" + ) + } + + // MARK: - Options + + func testOptionsNewestFirstWithFits() { + let options = FreeMonthBatchPlanner.options( + newFilesByMonth: ["2026-08": 40, "2026-10": 600, "2026-09": 120], + remaining: 150 + ) + + XCTAssertEqual(options.map(\.key), ["2026-10", "2026-09", "2026-08"]) + XCTAssertEqual(options.map(\.fileCount), [600, 120, 40]) + XCTAssertEqual(options.map(\.fits), [false, true, true]) + XCTAssertEqual(options.first?.id, "2026-10") + } + + func testOptionsEmptyWhenNothingRemains() { + XCTAssertTrue(FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 5], remaining: 0).isEmpty) + XCTAssertTrue(FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 5], remaining: -3).isEmpty) + } + + func testSuggestedOptionIsNewestThatFits() { + let options = FreeMonthBatchPlanner.options( + newFilesByMonth: ["2026-08": 40, "2026-10": 600, "2026-09": 120], + remaining: 150 + ) + + XCTAssertEqual(FreeMonthBatchPlanner.suggestedOption(options)?.key, "2026-09") + } + + func testSuggestedOptionFallsBackToNewestMonth() { + let options = FreeMonthBatchPlanner.options( + newFilesByMonth: ["2026-08": 400, "2026-10": 600], + remaining: 150 + ) + + let suggested = FreeMonthBatchPlanner.suggestedOption(options) + + XCTAssertEqual(suggested?.key, "2026-10") + XCTAssertEqual(suggested?.fits, false) + XCTAssertNil(FreeMonthBatchPlanner.suggestedOption([])) + } + + // MARK: - Selecting + + func testSelectWholeMonthWhenItFits() { + let plan = result( + photos("oct1", day: "2026-10-01", count: 3) + + photos("oct2", day: "2026-10-02", count: 2) + + photos("sep", day: "2026-09-30", count: 4) + ) + + let selected = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 5) + + XCTAssertEqual(selected.count, 5) + XCTAssertTrue(selected.allSatisfy { $0.dateBucket.hasPrefix("2026-10") }) + XCTAssertEqual(selected, FreeTestBatchPlanner.inBatchOrder(selected), "in batch order") + } + + func testSelectWholeDaysWhenMonthTooLarge() { + let plan = result( + photos("d1", day: "2026-10-01", count: 3) + + photos("d2", day: "2026-10-02", count: 3) + + photos("d3", day: "2026-10-03", count: 3) + ) + + let selected = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 7) + + XCTAssertEqual(selected.count, 6, "days 1 and 2 fit whole; day 3 would pass the limit") + XCTAssertEqual(Set(selected.map(\.dateBucket)), ["2026-10-01", "2026-10-02"]) + } + + func testSelectWithinFirstDayWhenDayTooLarge() { + let plan = result( + photos("d1", day: "2026-10-01", count: 10) + + photos("d2", day: "2026-10-02", count: 2) + ) + + let selected = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 4) + + XCTAssertEqual(selected.count, 4) + XCTAssertEqual(Set(selected.map(\.dateBucket)), ["2026-10-01"]) + XCTAssertEqual( + selected.map(\.sourcePath), + (0..<4).map { "/Volumes/Card/d1-\($0).jpg" }, + "the first owners of that day in path order" + ) + } + + func testSelectNeverExceedsLimit() { + let plan = result( + photos("a", day: "2026-10-01", count: 5) + + photos("b", day: "2026-10-02", count: 7) + + photos("c", day: "2026-10-09", count: 1) + ) + + for limit in -1...20 { + let selected = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: limit) + XCTAssertLessThanOrEqual(selected.count, max(0, limit), "limit \(limit)") + } + XCTAssertTrue(FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 0).isEmpty) + XCTAssertTrue(FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-11", limit: 20).isEmpty) + } + + func testSelectKeepsCompanionsWithOwners() { + // Day 1: two owners, each with a sidecar (4 files). Day 2: one owner. + let a = transfer("a.jpg", bucket: "2026-10-01") + let aSidecar = transfer("a.xmp", bucket: "2026-10-01") + let b = transfer("b.jpg", bucket: "2026-10-01") + let bSidecar = transfer("b.xmp", bucket: "2026-10-01") + let c = transfer("c.jpg", bucket: "2026-10-02") + let plan = result( + [a, aSidecar, b, bSidecar, c], + companionOwners: [ + aSidecar.sourcePath: a.sourcePath, + bSidecar.sourcePath: b.sourcePath, + ] + ) + + // Limit 3 cannot hold day 1 whole (4), so owners are taken in order while + // they fit: a with its sidecar (2); b with its sidecar would make 4. + let selected = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 3) + + XCTAssertEqual(Set(selected.map(\.sourcePath)), [a.sourcePath, aSidecar.sourcePath]) + + let whole = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 5) + XCTAssertEqual(whole.count, 5) + + let daysOnly = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 4) + XCTAssertEqual( + Set(daysOnly.map(\.sourcePath)), + [a.sourcePath, aSidecar.sourcePath, b.sourcePath, bSidecar.sourcePath] + ) + } + + func testSelectNeverIncludesExactCopies() { + let plan = result( + photos("new", day: "2026-10-01", count: 2) + [ + transfer("copy-1.jpg", bucket: "2026-10-01", isDuplicate: true), + transfer("copy-2.jpg", bucket: "2026-10-02", isDuplicate: true), + transfer("undated.jpg", bucket: "Unknown_Date"), + ] + ) + + let selected = FreeMonthBatchPlanner.select(from: plan, monthKey: "2026-10", limit: 50) + + XCTAssertEqual(selected.count, 2) + XCTAssertFalse(selected.contains { $0.isDuplicate }) + XCTAssertFalse(selected.contains { $0.dateBucket == "Unknown_Date" }) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreRunAccountingTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreRunAccountingTests.swift new file mode 100644 index 00000000..c9e1caba --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreRunAccountingTests.swift @@ -0,0 +1,145 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +/// Covers the "every photo is accounted for" numbers (FRX C-01) and the two +/// model fields that WP-02 adds so older stored data keeps decoding (C-03, C-05). +final class ChronoframeCoreRunAccountingTests: XCTestCase { + /// 10 found = 5 new + 2 exact copies + 2 already there + 1 unreadable, and + /// one sidecar companion that rides along in `plannedCount`. + private func balancedMetrics() -> RunMetrics { + RunMetrics( + discoveredCount: 10, + plannedCount: 8, + alreadyInDestinationCount: 2, + duplicateCount: 2, + hashErrorCount: 1, + plannedCompanionCount: 1 + ) + } + + func testPreviewBalancedWhenCategoriesSumToFound() { + let accounting = RunAccounting.preview(balancedMetrics()) + + XCTAssertEqual(accounting.found, 10) + XCTAssertEqual(accounting.new, 5) + XCTAssertEqual(accounting.extraCopies, 2) + XCTAssertEqual(accounting.alreadyThere, 2) + XCTAssertEqual(accounting.unreadable, 1) + XCTAssertEqual(accounting.remainder, 0) + XCTAssertTrue(accounting.isBalanced) + XCTAssertEqual(accounting.copiedMedia, 0, "a preview has copied nothing") + XCTAssertEqual(accounting.notCopied, 0, "a preview has no not-copied count") + } + + func testPreviewNewExcludesCopiesAndCompanions() { + let metrics = RunMetrics( + discoveredCount: 3, + plannedCount: 10, + duplicateCount: 4, + plannedCompanionCount: 3 + ) + + XCTAssertEqual(RunAccounting.preview(metrics).new, 3, "10 planned - 4 copies - 3 companions") + + // Never negative, even when the counts contradict each other. + let contradictory = RunMetrics(plannedCount: 2, duplicateCount: 4, plannedCompanionCount: 3) + XCTAssertEqual(RunAccounting.preview(contradictory).new, 0) + } + + func testPreviewRemainderIsSignedWhenCountsDisagree() { + var tooFew = balancedMetrics() + tooFew.discoveredCount = 13 + let positive = RunAccounting.preview(tooFew) + XCTAssertEqual(positive.remainder, 3) + XCTAssertFalse(positive.isBalanced) + + var tooMany = balancedMetrics() + tooMany.discoveredCount = 8 + let negative = RunAccounting.preview(tooMany) + XCTAssertEqual(negative.remainder, -2, "a negative remainder is a real disagreement and is not clamped") + XCTAssertFalse(negative.isBalanced) + } + + func testFinishedCopiedMediaExcludesCompanions() { + var metrics = balancedMetrics() + metrics.copiedCount = 8 + metrics.copiedCompanionCount = 1 + + let accounting = RunAccounting.finished(metrics) + + XCTAssertEqual(accounting.copiedMedia, 7, "8 copied - 1 companion") + XCTAssertEqual(accounting.notCopied, 0) + XCTAssertEqual(accounting.remainder, 0) + XCTAssertTrue(accounting.isBalanced) + } + + func testFinishedNotCopiedWhenFewerCopiedThanPlanned() { + var metrics = balancedMetrics() + metrics.copiedCount = 5 + metrics.copiedCompanionCount = 1 + + let accounting = RunAccounting.finished(metrics) + + XCTAssertEqual(accounting.copiedMedia, 4) + XCTAssertEqual(accounting.notCopied, 3, "(5 new + 2 copies) - 4 copied") + + // More copied than planned never goes negative. + var extra = balancedMetrics() + extra.copiedCount = 20 + XCTAssertEqual(RunAccounting.finished(extra).notCopied, 0) + } + + /// A free batch reduces the plan but not what discovery found, so the sum + /// falls short of `found` and the difference is what is left for later. + func testFreeBatchLeavesPositiveRemainder() { + let metrics = RunMetrics( + discoveredCount: 1_000, + plannedCount: 500, + alreadyInDestinationCount: 100, + duplicateCount: 0, + hashErrorCount: 0, + copiedCount: 500, + plannedCompanionCount: 0, + copiedCompanionCount: 0 + ) + + let accounting = RunAccounting.finished(metrics) + + XCTAssertEqual(accounting.remainder, 400) + XCTAssertFalse(accounting.isBalanced) + XCTAssertEqual(accounting.notCopied, 0) + } + + func testRunArtifactPathsDecodesWithoutReceiptPath() throws { + let older = """ + {"destinationRoot":"/Volumes/Archive","reportPath":"/r.csv","logsDirectoryPath":"/Volumes/Archive/.organize_logs"} + """ + + let decoded = try JSONDecoder().decode(RunArtifactPaths.self, from: Data(older.utf8)) + + XCTAssertEqual(decoded.destinationRoot, "/Volumes/Archive") + XCTAssertNil(decoded.receiptPath) + + let withReceipt = RunArtifactPaths(destinationRoot: "/d", receiptPath: "/d/.organize_logs/audit_receipt_x.json") + let roundTripped = try JSONDecoder().decode( + RunArtifactPaths.self, + from: JSONEncoder().encode(withReceipt) + ) + XCTAssertEqual(roundTripped, withReceipt) + } + + func testRunMetricsDecodesWithoutNewFilesByMonth() throws { + let older = #"{"discoveredCount":4,"plannedCount":3}"# + + let decoded = try JSONDecoder().decode(RunMetrics.self, from: Data(older.utf8)) + + XCTAssertEqual(decoded.discoveredCount, 4) + XCTAssertEqual(decoded.newFilesByMonth, [:]) + + var metrics = RunMetrics() + metrics.newFilesByMonth = ["2026-10": 12] + let roundTripped = try JSONDecoder().decode(RunMetrics.self, from: JSONEncoder().encode(metrics)) + XCTAssertEqual(roundTripped.newFilesByMonth, ["2026-10": 12]) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/FreeTestBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/FreeTestBatchPlannerTests.swift index c08dc6ca..8cac987b 100644 --- a/ui/Tests/ChronoframeAppCoreTests/FreeTestBatchPlannerTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/FreeTestBatchPlannerTests.swift @@ -192,6 +192,73 @@ final class FreeTestBatchPlannerTests: XCTestCase { XCTAssertEqual(applied.map(\.sourcePath), batch.included.map(\.sourcePath)) } + + // MARK: - Month requests (FRX C-05) + + /// A request confirms nothing, so if the engine branch for it were ever + /// missed the outcome is "nothing copied", never "everything copied". + func testMonthRequestSelectionAppliesToNothing() { + let request = FreeMonthRequest(key: "2026-03", limit: 100) + let selection = FreeTestBatchSelection(requestingMonth: request) + + XCTAssertEqual(selection.monthRequest, request) + XCTAssertEqual(request.key, "2026-03") + XCTAssertEqual(request.limit, 100) + XCTAssertTrue(selection.confirmedIdentities.isEmpty) + XCTAssertTrue(selection.isEmpty) + XCTAssertEqual(selection.count, 0) + XCTAssertTrue(selection.apply(to: plan()).isEmpty) + } + + func testReducedToMonthRequestKeepsNothing() { + let transfers = plan() + let result = DryRunPlanningResult( + discoveredSourceCount: 4, + destinationIndexedCount: 0, + sourceHashedCount: 4, + copyPlan: CopyPlanResult( + transfers: transfers, + counts: CopyPlanCounts(newCount: 4), + warningMessages: [], + sequenceState: SequenceCounterState() + ) + ) + + let reduced = result.reduced( + to: FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: "2026-03", limit: 100)) + ) + + XCTAssertEqual(reduced.transferCount, 0) + XCTAssertEqual(reduced.counts.newCount, 0) + } + + func testBatchDefaultsHaveNoMonthAndAreNotRequested() { + let batch = FreeTestBatch(included: plan(), deferredCount: 0) + + XCTAssertNil(batch.monthKey) + XCTAssertFalse(batch.wasRequested) + XCTAssertNil(batch.selection.monthRequest) + + let month = FreeTestBatch(included: plan(), deferredCount: 2, monthKey: "2026-03", wasRequested: true) + XCTAssertEqual(month.monthKey, "2026-03") + XCTAssertTrue(month.wasRequested) + } + + /// The identity selection is what actually runs a confirmed batch, and it + /// behaves exactly as before the month fields existed. + func testIdentitySelectionBehaviourUnchanged() { + let batch = FreeTestBatchPlanner.batch(from: plan(), limit: 2) + let selection = batch.selection + + XCTAssertNil(selection.monthRequest) + XCTAssertEqual(selection.count, 2) + XCTAssertEqual(selection.apply(to: plan()), batch.included) + XCTAssertEqual(selection, FreeTestBatchSelection(confirmedIdentities: selection.confirmedIdentities)) + XCTAssertNotEqual( + selection, + FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: "2026-01", limit: 2)) + ) + } } /// Covers reducing a whole planning result to a confirmed batch (T15). From c1dee6fb89f6fc622d354e0cc75f7a5789c0da04 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:05:02 -0800 Subject: [PATCH 06/30] FRX WP-03: AppCore: engine, offer, unlock presentation Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 2 + docs/plan/first-run-experience/PROGRESS.md | 8 +- .../Services/SwiftOrganizerEngine.swift | 53 +++- .../Services/TrialAuthorizer.swift | 81 +++++ .../Services/TrialRemaining.swift | 30 ++ .../Services/UnlockPresentation.swift | 109 ++++++- .../FreeMonthBatchOfferTests.swift | 229 ++++++++++++++ ...SwiftOrganizerEngineIntegrationTests.swift | 295 ++++++++++++++++++ .../TrialRemainingTests.swift | 81 +++++ .../UnlockPresentationTests.swift | 150 +++++++++ .../UnlockSheetBatchOfferTests.swift | 30 ++ 11 files changed, 1039 insertions(+), 29 deletions(-) create mode 100644 ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/FreeMonthBatchOfferTests.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 36b31f53..834fa1ec 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -48,3 +48,5 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh ## Runtime decisions - **D-FRX-101 Sheet render size and fixture numbers (WP-01).** C-00 gives no size for the unlock-sheet renders and no refusal numbers. The sheet tests render at 460×560 (the sheet is 420 wide in `UnlockSheetLayoutTests`) with refusals `.allowanceSpent` organize 250/0 and dedupe 25/0. Evidence-only values; nothing in production reads them. - **D-FRX-102 Free-month planner details (WP-02).** (a) `monthKey(forDateBucket:)` is strict: exactly `yyyy-MM-dd` in ASCII digits with month 01–12 and day 01–31, otherwise nil. (b) A companion counts toward, and travels with, its owner's month whatever its own `dateBucket`; a companion whose owner is an exact copy or is not in the plan is not counted. (c) When a month is too large, `select` stops at the first day that does not fit (it never skips ahead to a smaller later day); within a too-large first day it stops at the first owner unit that does not fit. (d) `options` leaves out a month whose count is 0. All four are the narrowest reading of C-05; none widens what a free copy can contain. +- **D-FRX-103 Month-request branch placement and guard (WP-03).** C-06 says the branch goes "directly after planning and the zero-transfer branches, before `plan.reduced(to:)`", but in the code the zero-transfer branches come after `reduced`. The branch sits after `planAsync` and the cancellation check, immediately before `plan.reduced(to:)`, and is guarded with `plan.transferCount > 0`. An empty plan falls through: the request confirms no file, reduces to nothing and takes the existing "Nothing left to copy" return, which is ahead of `authorizeTransfer`. The literal one-liner would have raised an unlock sheet for 0 files. Known wart: that existing warning ("None of the files in that batch are still where they were…") is slightly off for a request; left alone (fewest changed lines). +- **D-FRX-104 Free-month sheet details (WP-03).** (a) `proposingFreeMonth` sets `wasRequested: true` on the suggested-month fallback too; the title names the month actually offered. (b) It does not apply the covers-whole-plan check (C-06 gives that rule only to `offeringFreeMonthBatch`); the sheet's existing `offerableBatch` still drops such a batch. (c) With a failed price load a requested-month sheet keeps the requested message. (d) Singular forms added per the copy rule: `Organize all %@ file`, `Remove all %@ duplicate`, `This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.` (e) `TrialRemaining.value` is also nil while the entitlement is resolving. (f) The two builders are internal, not public. (g) `TrialAuthorizer.swift` gained one private helper `monthBatch` shared by the two builders. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 4bb07d32..6af9b865 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -14,9 +14,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled |---|---|---|---|---|---|---|---| | WP-00 | Branch, plan folder, baseline | done | build exit 0 | suite exit 0 (2513 passed) | n/a | a09eca6, aa56f84 | INV-31 on main: 1 | | WP-01 | Render evidence harness | done | build exit 0 | `test ScreenRenderEvidenceTests` exit 0 (3 skipped without marker; 3 run, 3 PNGs with marker) | approve (round 1) | fb09f36 | rendered: harness produces non-blank PNGs; D-FRX-101 | -| WP-02 | Core: accounting, free month, model fields | done | build exit 0 | RunAccounting 8, FreeMonthBatchPlanner 14, FreeTestBatchPlanner 19 tests, all exit 0 | approve (round 1) | (WP-02 commit) | orchestrator read the FreeTestBatchPlanner.swift and RunModels.swift diffs: additions only; D-FRX-102 | -| WP-03 | AppCore: engine, offer, unlock presentation | in-progress | | | | | D-FRX-04 files only | -| WP-04 | App: preview free limit and free month | todo | | | | | | +| WP-02 | Core: accounting, free month, model fields | done | build exit 0 | RunAccounting 8, FreeMonthBatchPlanner 14, FreeTestBatchPlanner 19 tests, all exit 0 | approve (round 1) | 682f714 | orchestrator read the FreeTestBatchPlanner.swift and RunModels.swift diffs: additions only; D-FRX-102 | +| WP-03 | AppCore: engine, offer, unlock presentation | done | build exit 0 | TrialRemaining 4, FreeMonthBatchOffer 11, UnlockPresentation 19, UnlockSheetBatchOffer 14, FreeTestBatchOffer 9, FreeTestBatchRun 4, SwiftOrganizerEngineIntegration 43 tests, all exit 0 | approve (round 1) | (WP-03 commit) | orchestrator read the full SwiftOrganizerEngine.swift and TrialAuthorizer.swift diffs: every changed line traces to C-03/C-06; the month-request branch throws before `plan.reduced(to:)`, so it reaches neither `authorizeTransfer` nor the job queue; D-FRX-103, D-FRX-104 | +| WP-04 | App: preview free limit and free month | in-progress | | | | | | | WP-05 | App: accounted-for line, Undo, add folder | todo | | | | | INV-8 tag on the undo test | | WP-06 | Docs and strings, M1 | todo | | | | | | | G1 | Gate, M1 | todo | | | n/a | | | @@ -44,3 +44,5 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled ## Log - 2026-11-28 WP-01 Done-when (orchestrator): `cf_swift.sh test ScreenRenderEvidenceTests` exit 0 without marker (3 skipped); with `.tmp/frx-evidence/.enabled` exit 0, 3 PNGs (`m1-copy-complete`, `m1-unlock-organize`, `m1-unlock-dedupe`); `cf_swift.sh build` exit 0; `git diff --check` exit 0. Marker removed afterwards. - 2026-11-28 WP-02 Done-when (orchestrator): `cf_swift.sh test ChronoframeCoreRunAccountingTests` exit 0 (8 tests); `cf_swift.sh test ChronoframeCoreFreeMonthBatchPlannerTests` exit 0 (14); `cf_swift.sh test FreeTestBatchPlannerTests` exit 0 (19); `cf_swift.sh build` exit 0; `git diff --check` exit 0. No user-facing strings, no existing assertions changed. +- 2026-11-28 WP-03 Done-when (orchestrator): `cf_swift.sh test` exit 0 for TrialRemainingTests (4), FreeMonthBatchOfferTests (11), UnlockPresentationTests (19), UnlockSheetBatchOfferTests (14), FreeTestBatchOfferTests (9), FreeTestBatchRunTests (4), SwiftOrganizerEngineIntegrationTests (43); `cf_swift.sh build` exit 0; `script/check_authorizer_has_no_default.sh` exit 0; `script/check_storekit_config_matches_policy.sh` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0. No existing assertions changed. +- WP-03 strings for WP-06 (all Core, `UnlockPresentation.swift`, via `CoreL10n.text`): `Organize all %@ files`; `Organize all %@ file`; `Remove all %@ duplicates`; `Remove all %@ duplicate`; `One-time purchase with Family Sharing. No subscription.`; `Copies %@ now, %@, and leaves %@ for later.`; `Copy %@ free`; `These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.`; `This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.` diff --git a/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift b/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift index fac69d40..1981fec2 100644 --- a/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift +++ b/ui/Sources/ChronoframeAppCore/Services/SwiftOrganizerEngine.swift @@ -540,7 +540,8 @@ public final class SwiftOrganizerEngine: OrganizerEngine { hashErrorCount: result.counts.hashErrorCount, dateHistogram: result.dateHistogram, plannedCompanionCount: result.companionOwners.count, - unresolvedCompanionCount: result.copyPlan.unresolvedCompanions.count + unresolvedCompanionCount: result.copyPlan.unresolvedCompanions.count, + newFilesByMonth: FreeMonthBatchPlanner.newFilesByMonth(for: result) ) Self.emitPostPlanningEvents(for: result, into: continuation) @@ -746,6 +747,15 @@ public final class SwiftOrganizerEngine: OrganizerEngine { return } + // A request to see one free month is a question, not a run (FRX C-06). + // Answer it with the proposal and stop: nothing below this point is + // reached, so nothing is reserved, queued, copied or receipted. A plan + // with nothing in it falls through, where the request (which confirms + // no file) reduces to nothing and takes the no-copy branch below. + if let request = batch?.monthRequest, plan.transferCount > 0 { + throw TrialAuthorizationError.proposingFreeMonth(request, result: plan) + } + // A confirmed free test batch narrows the plan before anything else // sees it (T15), so the events, the log line, the gate, and the queue // all describe the run that is actually about to happen. Reducing after @@ -896,9 +906,9 @@ public final class SwiftOrganizerEngine: OrganizerEngine { // A refusal that leaves allowance on the table carries the smaller // run that would fit, so the UI can offer it instead of sending // someone to Finder to build a smaller folder by hand (T15). - throw TrialAuthorizationError.offeringFreeTestBatch( + throw TrialAuthorizationError.offeringFreeMonthBatch( error, - plannedTransfers: result.transfers + result: result ) } @@ -995,6 +1005,11 @@ public final class SwiftOrganizerEngine: OrganizerEngine { completedStatus = .finished completedTitle = CoreL10n.text("Done") } + var summaryArtifacts = executionResult.artifacts + summaryArtifacts.receiptPath = receiptURL( + runID: runID, + logsDirectoryPath: summaryArtifacts.logsDirectoryPath + )?.path continuation.yield( .complete( RunSummary( @@ -1022,7 +1037,7 @@ public final class SwiftOrganizerEngine: OrganizerEngine { ), unresolvedCompanionCount: result.copyPlan.unresolvedCompanions.count ), - artifacts: executionResult.artifacts, + artifacts: summaryArtifacts, failureMessage: completedStatus == .failed ? CoreL10n.text("The transfer did not finish: \(executionResult.failedCount) failed and \(executionResult.skippedCount) were skipped. Originals were left untouched.") : nil, @@ -1354,16 +1369,12 @@ public final class SwiftOrganizerEngine: OrganizerEngine { ) -> Int { guard plannedCompanionCount > 0 else { return 0 } - if let logsPath = executionResult.artifacts.logsDirectoryPath { - let logsURL = URL(fileURLWithPath: logsPath, isDirectory: true) - let prefix = EngineArtifactLayout.chronoframeDefault.auditReceiptPrefix - let names = (try? FileManager.default.contentsOfDirectory(atPath: logsURL.path)) ?? [] - if let name = names.sorted().last(where: { - $0.hasPrefix(prefix) && $0.hasSuffix(".json") && $0.contains(runID.uuidString) - }), - let receipt = try? RevertExecutor().loadReceipt(at: logsURL.appendingPathComponent(name)) { - return receipt.transfers.filter { MediaLibraryRules.isCompanionFile(path: $0.dest) }.count - } + if let url = receiptURL( + runID: runID, + logsDirectoryPath: executionResult.artifacts.logsDirectoryPath + ), + let receipt = try? RevertExecutor().loadReceipt(at: url) { + return receipt.transfers.filter { MediaLibraryRules.isCompanionFile(path: $0.dest) }.count } return executionResult.failedCount == 0 @@ -1371,6 +1382,20 @@ public final class SwiftOrganizerEngine: OrganizerEngine { && executionResult.copiedCount == plannedTransferCount ? plannedCompanionCount : 0 } + /// The run's audit receipt in `logsDirectoryPath`: a name with the + /// audit-receipt prefix, ending `.json`, containing the run ID; the last + /// when sorted (FRX C-03). + nonisolated static func receiptURL(runID: UUID, logsDirectoryPath: String?) -> URL? { + guard let logsPath = logsDirectoryPath else { return nil } + let logsURL = URL(fileURLWithPath: logsPath, isDirectory: true) + let prefix = EngineArtifactLayout.chronoframeDefault.auditReceiptPrefix + let names = (try? FileManager.default.contentsOfDirectory(atPath: logsURL.path)) ?? [] + guard let name = names.sorted().last(where: { + $0.hasPrefix(prefix) && $0.hasSuffix(".json") && $0.contains(runID.uuidString) + }) else { return nil } + return logsURL.appendingPathComponent(name) + } + nonisolated private static func writeDryRunArtifacts( result: DryRunPlanningResult, destinationRoot: String diff --git a/ui/Sources/ChronoframeAppCore/Services/TrialAuthorizer.swift b/ui/Sources/ChronoframeAppCore/Services/TrialAuthorizer.swift index 9fe9ae55..9b00b056 100644 --- a/ui/Sources/ChronoframeAppCore/Services/TrialAuthorizer.swift +++ b/ui/Sources/ChronoframeAppCore/Services/TrialAuthorizer.swift @@ -95,6 +95,87 @@ public struct TrialAuthorizationError: LocalizedError, Sendable, Equatable { return TrialAuthorizationError(refusal: error.refusal, offeredBatch: batch) } + /// Refusal path. Same conditions as `offeringFreeTestBatch`; the batch is + /// the suggested month (FRX C-06). + static func offeringFreeMonthBatch( + _ error: TrialAuthorizationError, + result: DryRunPlanningResult + ) -> TrialAuthorizationError { + guard case let .allowanceSpent(details) = error.refusal, + details.meter == .organize, + details.remaining > 0 else { return error } + + let options = FreeMonthBatchPlanner.options( + newFilesByMonth: FreeMonthBatchPlanner.newFilesByMonth(for: result), + remaining: details.remaining + ) + guard let month = FreeMonthBatchPlanner.suggestedOption(options) else { return error } + + let batch = monthBatch( + from: result, + monthKey: month.key, + limit: details.remaining, + wasRequested: false + ) + guard !batch.included.isEmpty, !batch.coversWholePlan else { return error } + + return TrialAuthorizationError(refusal: error.refusal, offeredBatch: batch) + } + + /// Request path. The person asked to see a free copy of one month. Nothing + /// has been authorized or copied (FRX C-06). + /// + /// The batch is only a proposal for the sheet to list; what runs is what + /// the person confirms, through `FreeTestBatchSelection`. + static func proposingFreeMonth( + _ request: FreeMonthRequest, + result: DryRunPlanningResult + ) -> TrialAuthorizationError { + let refusal = TrialAuthorizationRefusal.allowanceSpent( + TrialRefusal(meter: .organize, requested: result.transferCount, remaining: request.limit) + ) + + var batch = monthBatch( + from: result, + monthKey: request.key, + limit: request.limit, + wasRequested: true + ) + if batch.included.isEmpty { + let options = FreeMonthBatchPlanner.options( + newFilesByMonth: FreeMonthBatchPlanner.newFilesByMonth(for: result), + remaining: request.limit + ) + guard let month = FreeMonthBatchPlanner.suggestedOption(options) else { + return TrialAuthorizationError(refusal: refusal) + } + batch = monthBatch( + from: result, + monthKey: month.key, + limit: request.limit, + wasRequested: true + ) + } + guard !batch.included.isEmpty else { return TrialAuthorizationError(refusal: refusal) } + + return TrialAuthorizationError(refusal: refusal, offeredBatch: batch) + } + + private static func monthBatch( + from result: DryRunPlanningResult, + monthKey: String, + limit: Int, + wasRequested: Bool + ) -> FreeTestBatch { + let included = FreeMonthBatchPlanner.select(from: result, monthKey: monthKey, limit: limit) + return FreeTestBatch( + included: included, + deferredCount: result.transferCount - included.count, + monthKey: monthKey, + wasRequested: wasRequested + ) + } + public var errorDescription: String? { switch refusal { case let .allowanceSpent(details): diff --git a/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift b/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift new file mode 100644 index 00000000..82411908 --- /dev/null +++ b/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift @@ -0,0 +1,30 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// How much of the free allowance is left on a meter, for the screens that +/// quote it (FRX C-06). +/// +/// One definition, shared with the indicator's rules: a number is only returned +/// when it is a real, readable balance for someone the allowance applies to. +public enum TrialRemaining { + /// Nil when not the App Store channel, unlocked, loading, unknown or + /// unavailable. + /// + /// - Not the App Store channel: that build is unrestricted and meters + /// nothing, so a count would describe a limit that does not exist. + /// - Unlocked: there is no limit. + /// - Loading, unknown or unavailable: nothing is known. An unreadable + /// ledger reports zero to the gate so it fails closed, and that zero must + /// never be quoted as the customer's own balance. + public static func value( + status: TrialStatus, + meter: TrialMeter, + isAppStoreChannel: Bool + ) -> Int? { + guard isAppStoreChannel else { return nil } + guard !status.isUnlocked, !status.entitlement.isResolving else { return nil } + return status.remaining(for: meter) + } +} diff --git a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift index 3b650c05..216e6421 100644 --- a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift +++ b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift @@ -50,6 +50,12 @@ public struct UnlockSheetModel: Equatable, Sendable { /// Only an in-flight purchase or restore blocks it, because starting a run /// underneath either of those is a race. public let isBatchEnabled: Bool + /// The terms of the purchase in one line, shown under the message when the + /// sheet asks someone to buy (FRX C-06). + /// + /// Nil where it would be wrong or redundant: `purchaseUnconfirmed` may + /// already own the unlock, and the voluntary sheet's message says it. + public let purchaseTermsLine: String? public init( title: String, @@ -57,7 +63,8 @@ public struct UnlockSheetModel: Equatable, Sendable { actions: [UnlockSheetAction], isBusy: Bool, batchDetail: String? = nil, - isBatchEnabled: Bool = true + isBatchEnabled: Bool = true, + purchaseTermsLine: String? = nil ) { self.title = title self.message = message @@ -65,6 +72,7 @@ public struct UnlockSheetModel: Equatable, Sendable { self.isBusy = isBusy self.batchDetail = batchDetail self.isBatchEnabled = isBatchEnabled + self.purchaseTermsLine = purchaseTermsLine } /// Build the sheet's contents. @@ -88,13 +96,24 @@ public struct UnlockSheetModel: Equatable, Sendable { offeredBatch: FreeTestBatch? = nil ) -> UnlockSheetModel { let busy = isPurchasing || isRestoring - let title = Self.title(for: refusal) - let message = Self.message(for: refusal) let batch = Self.offerableBatch(offeredBatch, refusal: refusal) + // The person pressed "copy this month free": the sheet is about that + // copy, so it says so and offers it first (FRX C-06). + let requestedMonth: (batch: FreeTestBatch, key: String)? = batch.flatMap { batch in + guard batch.wasRequested, let key = batch.monthKey else { return nil } + return (batch, key) + } + let title = requestedMonth.map { Self.requestedMonthTitle(monthKey: $0.key) } + ?? Self.title(for: refusal) + let message = requestedMonth.map { Self.requestedMonthMessage(includedCount: $0.batch.includedCount) } + ?? Self.message(for: refusal) let batchAction: [UnlockSheetAction] = batch.map { [.runFreeTestBatch(fileCount: $0.includedCount, deferredCount: $0.deferredCount)] } ?? [] + let leadingBatchAction = requestedMonth == nil ? [] : batchAction + let trailingBatchAction = requestedMonth == nil ? batchAction : [] let batchDetail = batch.flatMap(Self.batchDetail) + let purchaseTermsLine = Self.purchaseTermsLine(for: refusal) // Never offer a purchase this customer may not need. `purchaseUnconfirmed` // means Chronoframe could not verify an entitlement that may well exist, @@ -112,13 +131,14 @@ public struct UnlockSheetModel: Equatable, Sendable { return UnlockSheetModel( title: title, message: message, - actions: [ + actions: leadingBatchAction + [ .buy(displayName: product.displayName, displayPrice: product.displayPrice), .restore, - ] + batchAction + [.dismiss], + ] + trailingBatchAction + [.dismiss], isBusy: busy, batchDetail: batchDetail, - isBatchEnabled: !busy + isBatchEnabled: !busy, + purchaseTermsLine: purchaseTermsLine ) } @@ -136,7 +156,8 @@ public struct UnlockSheetModel: Equatable, Sendable { batchDetail: batchDetail, // Not `!isBusy`: the spinner is for the price lookup, and the // batch does not need a price. - isBatchEnabled: !busy + isBatchEnabled: !busy, + purchaseTermsLine: purchaseTermsLine ) } @@ -144,11 +165,14 @@ public struct UnlockSheetModel: Equatable, Sendable { // who already owns it and does not need the product at all. return UnlockSheetModel( title: title, - message: CoreL10n.text("Chronoframe could not reach the App Store to check the price. Check your internet connection and try again."), - actions: [.retryProductLoad, .restore] + batchAction + [.dismiss], + message: requestedMonth != nil + ? message + : CoreL10n.text("Chronoframe could not reach the App Store to check the price. Check your internet connection and try again."), + actions: leadingBatchAction + [.retryProductLoad, .restore] + trailingBatchAction + [.dismiss], isBusy: busy, batchDetail: batchDetail, - isBatchEnabled: !busy + isBatchEnabled: !busy, + purchaseTermsLine: purchaseTermsLine ) } @@ -172,6 +196,10 @@ public struct UnlockSheetModel: Equatable, Sendable { private static func batchDetail(_ batch: FreeTestBatch) -> String { let files = CoreL10n.files(batch.includedCount) + if let monthKey = batch.monthKey { + let month = Self.monthYearName(forKey: monthKey) + return CoreL10n.text("Copies \(month) now, \(files), and leaves \(batch.deferredCount.formatted()) for later.") + } guard let range = batch.dateBucketRange else { return CoreL10n.text("Copies \(files) now and leaves \(batch.deferredCount) for later.") } @@ -185,8 +213,8 @@ public struct UnlockSheetModel: Equatable, Sendable { switch refusal { case nil: return CoreL10n.text("Unlock Chronoframe") - case .allowanceSpent: - return CoreL10n.text("Unlock Chronoframe") + case let .allowanceSpent(details): + return Self.allowanceSpentTitle(details) case .purchaseUnconfirmed: return CoreL10n.text("Purchase Not Confirmed") case .requiresUnlock: @@ -194,6 +222,63 @@ public struct UnlockSheetModel: Equatable, Sendable { } } + /// Names the outcome the purchase buys, so the sheet's title says what + /// pressing Buy gets (FRX C-06). Plural follows `CoreL10n.files` and + /// `CoreL10n.duplicates`. + private static func allowanceSpentTitle(_ refusal: TrialRefusal) -> String { + let count = refusal.requested.formatted() + switch refusal.meter { + case .organize: + return refusal.requested == 1 + ? CoreL10n.text("Organize all \(count) file") + : CoreL10n.text("Organize all \(count) files") + case .dedupe: + return refusal.requested == 1 + ? CoreL10n.text("Remove all \(count) duplicate") + : CoreL10n.text("Remove all \(count) duplicates") + } + } + + private static func purchaseTermsLine(for refusal: TrialAuthorizationRefusal?) -> String? { + switch refusal { + case .allowanceSpent, .requiresUnlock: + return CoreL10n.text("One-time purchase with Family Sharing. No subscription.") + case .purchaseUnconfirmed, nil: + return nil + } + } + + private static func requestedMonthTitle(monthKey: String) -> String { + let month = Self.monthYearName(forKey: monthKey) + return CoreL10n.text("Copy \(month) free") + } + + private static func requestedMonthMessage(includedCount: Int) -> String { + let count = includedCount.formatted() + return includedCount == 1 + ? CoreL10n.text("This \(count) new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.") + : CoreL10n.text("These \(count) new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.") + } + + /// `"2026-10"` as "October 2026" in the current locale. A key that is not + /// `yyyy-MM` is shown as it is rather than guessed at. + private static func monthYearName(forKey key: String) -> String { + let parts = key.split(separator: "-") + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC") ?? calendar.timeZone + guard parts.count == 2, + let year = Int(parts[0]), let month = Int(parts[1]), + let date = calendar.date(from: DateComponents(year: year, month: month, day: 1)) + else { return key } + + let formatter = DateFormatter() + formatter.locale = .current + formatter.calendar = calendar + formatter.timeZone = calendar.timeZone + formatter.setLocalizedDateFormatFromTemplate("MMMMyyyy") + return formatter.string(from: date) + } + private static func message(for refusal: TrialAuthorizationRefusal?) -> String { switch refusal { case nil: diff --git a/ui/Tests/ChronoframeAppCoreTests/FreeMonthBatchOfferTests.swift b/ui/Tests/ChronoframeAppCoreTests/FreeMonthBatchOfferTests.swift new file mode 100644 index 00000000..8e6a22b4 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/FreeMonthBatchOfferTests.swift @@ -0,0 +1,229 @@ +import Foundation +import XCTest +@testable import ChronoframeAppCore +@testable import ChronoframeCore + +/// The free whole month, as a refusal or a request carries it (FRX C-06). +/// +/// A month is only ever proposed here. Nothing in these builders copies, +/// reserves or authorizes anything; they only decide which files the sheet +/// will list for confirmation. +final class FreeMonthBatchOfferTests: XCTestCase { + private func transfer( + _ name: String, + bucket: String, + isDuplicate: Bool = false + ) -> PlannedTransfer { + PlannedTransfer( + sourcePath: "/Volumes/Card/\(name)", + destinationPath: "/Volumes/Archive/\(bucket)/\(name)", + identity: FileIdentity(size: Int64(name.count), digest: "digest-\(name)"), + dateBucket: bucket, + isDuplicate: isDuplicate + ) + } + + private func result(_ transfers: [PlannedTransfer]) -> DryRunPlanningResult { + DryRunPlanningResult( + discoveredSourceCount: transfers.count, + destinationIndexedCount: 0, + sourceHashedCount: transfers.count, + copyPlan: CopyPlanResult( + transfers: transfers, + counts: CopyPlanCounts(newCount: transfers.filter { !$0.isDuplicate }.count), + warningMessages: [], + sequenceState: SequenceCounterState() + ), + companionOwners: [:] + ) + } + + private func photos(_ prefix: String, day: String, count: Int) -> [PlannedTransfer] { + (0..<count).map { transfer("\(prefix)-\($0).jpg", bucket: day) } + } + + /// October 6, September 3, August 2: eleven new files in all. + private var threeMonths: DryRunPlanningResult { + result( + photos("oct", day: "2026-10-05", count: 6) + + photos("sep", day: "2026-09-12", count: 3) + + photos("aug", day: "2026-08-20", count: 2) + ) + } + + private func refusal(requested: Int, remaining: Int) -> TrialAuthorizationError { + TrialAuthorizationError( + refusal: .allowanceSpent(TrialRefusal(meter: .organize, requested: requested, remaining: remaining)) + ) + } + + // MARK: - Refusal path + + func testRefusalOffersNewestMonthThatFits() { + let plan = threeMonths + let offered = TrialAuthorizationError.offeringFreeMonthBatch( + refusal(requested: 11, remaining: 4), + result: plan + ).offeredBatch + + XCTAssertEqual(offered?.monthKey, "2026-09", "October (6) does not fit 4; September (3) is the newest that does") + XCTAssertEqual(offered?.includedCount, 3) + XCTAssertEqual(offered?.deferredCount, 8) + XCTAssertEqual(offered?.wasRequested, false) + } + + func testOfferNeverContainsExactCopies() { + let plan = result( + photos("new", day: "2026-10-05", count: 2) + + [ + transfer("copy-a.jpg", bucket: "2026-10-05", isDuplicate: true), + transfer("copy-b.jpg", bucket: "2026-10-06", isDuplicate: true), + ] + + photos("older", day: "2026-09-01", count: 5) + ) + let offered = TrialAuthorizationError.offeringFreeMonthBatch( + refusal(requested: 9, remaining: 3), + result: plan + ).offeredBatch + + XCTAssertNotNil(offered) + XCTAssertTrue(offered?.included.allSatisfy { !$0.isDuplicate } ?? false) + XCTAssertEqual(offered?.monthKey, "2026-10") + XCTAssertEqual(offered?.includedCount, 2) + } + + func testNoOfferWhenNothingDatedAndNew() { + let plan = result( + photos("undated", day: "Unknown_Date", count: 4) + + [transfer("copy.jpg", bucket: "2026-10-05", isDuplicate: true)] + ) + let error = refusal(requested: 5, remaining: 2) + + let enriched = TrialAuthorizationError.offeringFreeMonthBatch(error, result: plan) + + XCTAssertNil(enriched.offeredBatch) + XCTAssertEqual(enriched, error, "Without an offer the refusal is returned untouched") + } + + func testNoOfferWhenNothingRemains() { + XCTAssertNil( + TrialAuthorizationError.offeringFreeMonthBatch( + refusal(requested: 11, remaining: 0), + result: threeMonths + ).offeredBatch + ) + } + + /// The same three conditions as the earliest-first offer: only a spent + /// organize allowance, and never one that would cover the whole plan. + func testNoOfferForOtherRefusalsOrWhenTheBatchCoversThePlan() { + let plan = threeMonths + for other: TrialAuthorizationRefusal in [ + .purchaseUnconfirmed(TrialRefusal(meter: .organize, requested: 11, remaining: 4)), + .requiresUnlock, + .allowanceSpent(TrialRefusal(meter: .dedupe, requested: 11, remaining: 4)), + ] { + XCTAssertNil( + TrialAuthorizationError.offeringFreeMonthBatch( + TrialAuthorizationError(refusal: other), + result: plan + ).offeredBatch, + "\(other)" + ) + } + + let oneMonth = result(photos("oct", day: "2026-10-05", count: 3)) + XCTAssertNil( + TrialAuthorizationError.offeringFreeMonthBatch( + refusal(requested: 3, remaining: 10), + result: oneMonth + ).offeredBatch, + "A batch that covers the whole plan means size is not why this was refused" + ) + } + + func testOfferedBatchCarriesMonthKey() { + let offered = TrialAuthorizationError.offeringFreeMonthBatch( + refusal(requested: 11, remaining: 2), + result: threeMonths + ).offeredBatch + + XCTAssertEqual(offered?.monthKey, "2026-08") + XCTAssertEqual(offered?.dateBucketRange?.earliest, "2026-08-20") + XCTAssertEqual( + offered?.selection.confirmedIdentities.count, + 2, + "The batch's selection names exactly the listed files, so what runs is what was shown" + ) + } + + func testRefusalDoesNotChangeTheRefusalOrItsMessage() { + let original = refusal(requested: 11, remaining: 4) + + let enriched = TrialAuthorizationError.offeringFreeMonthBatch(original, result: threeMonths) + + XCTAssertEqual(enriched.refusal, original.refusal) + XCTAssertEqual(enriched.errorDescription, original.errorDescription) + } + + // MARK: - Request path + + func testRequestedMonthIsProposedAsRequested() { + let plan = threeMonths + let proposed = TrialAuthorizationError.proposingFreeMonth( + FreeMonthRequest(key: "2026-08", limit: 4), + result: plan + ) + + XCTAssertEqual(proposed.offeredBatch?.monthKey, "2026-08") + XCTAssertEqual(proposed.offeredBatch?.wasRequested, true) + XCTAssertEqual(proposed.offeredBatch?.includedCount, 2) + XCTAssertEqual(proposed.offeredBatch?.deferredCount, 9) + XCTAssertEqual( + proposed.refusal, + .allowanceSpent(TrialRefusal(meter: .organize, requested: 11, remaining: 4)), + "Nothing was authorized; the refusal only carries what the screen showed" + ) + } + + func testRequestedMonthFallsBackToSuggestedWhenEmpty() { + let proposed = TrialAuthorizationError.proposingFreeMonth( + FreeMonthRequest(key: "2025-01", limit: 4), + result: threeMonths + ) + + XCTAssertEqual(proposed.offeredBatch?.monthKey, "2026-09", "The suggested month: newest that fits 4") + XCTAssertEqual(proposed.offeredBatch?.includedCount, 3) + } + + func testRequestedMonthWithNothingToOfferCarriesNoBatch() { + let undated = result(photos("undated", day: "Unknown_Date", count: 4)) + + let proposed = TrialAuthorizationError.proposingFreeMonth( + FreeMonthRequest(key: "2026-10", limit: 4), + result: undated + ) + + XCTAssertNil(proposed.offeredBatch) + XCTAssertEqual( + proposed.refusal, + .allowanceSpent(TrialRefusal(meter: .organize, requested: 4, remaining: 4)) + ) + } + + /// A partial month: when the month is larger than the limit the batch is + /// whole days that fit, never more than the limit. + func testRequestedMonthNeverExceedsTheLimit() { + let plan = result( + photos("a", day: "2026-10-01", count: 3) + + photos("b", day: "2026-10-02", count: 3) + ) + let proposed = TrialAuthorizationError.proposingFreeMonth( + FreeMonthRequest(key: "2026-10", limit: 4), + result: plan + ) + + XCTAssertEqual(proposed.offeredBatch?.includedCount, 3) + XCTAssertEqual(proposed.offeredBatch?.deferredCount, 3) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/SwiftOrganizerEngineIntegrationTests.swift b/ui/Tests/ChronoframeAppCoreTests/SwiftOrganizerEngineIntegrationTests.swift index 08631eed..d967d8b8 100644 --- a/ui/Tests/ChronoframeAppCoreTests/SwiftOrganizerEngineIntegrationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/SwiftOrganizerEngineIntegrationTests.swift @@ -1312,6 +1312,265 @@ final class SwiftOrganizerEngineIntegrationTests: XCTestCase { XCTAssertEqual(summary.metrics.copiedCount, 3) } + // MARK: - Free whole month and the receipt path (FRX C-03, C-06) + + /// Two new files in March 2024 and one in February 2024. + private func makeMonthSource() throws -> (source: URL, destination: URL) { + let sourceURL = temporaryDirectoryURL.appendingPathComponent("source", isDirectory: true) + let destinationURL = temporaryDirectoryURL.appendingPathComponent("dest", isDirectory: true) + try FileManager.default.createDirectory(at: sourceURL, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: destinationURL, withIntermediateDirectories: true) + + for day in ["20240302", "20240303", "20240210"] { + let fileURL = sourceURL.appendingPathComponent("camera/IMG_\(day)_101010.jpg") + try FileManager.default.createDirectory( + at: fileURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Data("month-payload-\(day)".utf8).write(to: fileURL) + } + return (sourceURL, destinationURL) + } + + private func receiptURLs(in destinationURL: URL) -> [URL] { + let logs = destinationURL.appendingPathComponent(".organize_logs", isDirectory: true) + let contents = (try? FileManager.default.contentsOfDirectory(at: logs, includingPropertiesForKeys: nil)) ?? [] + return contents.filter { $0.lastPathComponent.hasPrefix("audit_receipt_") } + } + + @MainActor + func testPreviewMetricsCarryNewFilesByMonth() async throws { + let (sourceURL, destinationURL) = try makeMonthSource() + let engine = SwiftOrganizerEngine( + authorizer: UnrestrictedTrialAuthorizer(), + profilesRepository: TestProfilesRepository( + profiles: [], + profilesFileURL: temporaryDirectoryURL.appendingPathComponent("profiles.yaml") + ) + ) + + let events = try await Self.collect( + try engine.start( + RunConfiguration(mode: .preview, sourcePath: sourceURL.path, destinationPath: destinationURL.path) + ) + ) + + guard case let .complete(summary)? = events.last else { + return XCTFail("Expected complete event") + } + XCTAssertEqual(summary.status, .dryRunFinished) + XCTAssertEqual(summary.metrics.newFilesByMonth, ["2024-03": 2, "2024-02": 1]) + } + + @MainActor + func testTransferSummaryCarriesReceiptPath() async throws { + let (sourceURL, destinationURL) = try makeMonthSource() + let engine = SwiftOrganizerEngine( + authorizer: UnrestrictedTrialAuthorizer(), + profilesRepository: TestProfilesRepository( + profiles: [], + profilesFileURL: temporaryDirectoryURL.appendingPathComponent("profiles.yaml") + ) + ) + + let events = try await Self.collect( + try engine.start( + RunConfiguration(mode: .transfer, sourcePath: sourceURL.path, destinationPath: destinationURL.path) + ) + ) + + guard case let .complete(summary)? = events.last else { + return XCTFail("Expected completion summary") + } + XCTAssertEqual(summary.status, .finished) + + let receiptPath = try XCTUnwrap(summary.artifacts.receiptPath, "A finished copy publishes its receipt") + XCTAssertTrue(FileManager.default.fileExists(atPath: receiptPath)) + let name = URL(fileURLWithPath: receiptPath).lastPathComponent + XCTAssertTrue(name.hasPrefix("audit_receipt_") && name.hasSuffix(".json"), name) + XCTAssertEqual( + URL(fileURLWithPath: receiptPath).deletingLastPathComponent().path, + summary.artifacts.logsDirectoryPath + ) + XCTAssertEqual(receiptURLs(in: destinationURL).map(\.lastPathComponent), [name]) + // The rest of the artifacts are exactly what the executor reported. + XCTAssertEqual(summary.artifacts.destinationRoot, destinationURL.path) + XCTAssertNotNil(summary.artifacts.logFilePath) + } + + func testReceiptURLPicksTheLastReceiptNamingTheRun() throws { + let logs = temporaryDirectoryURL.appendingPathComponent("logs", isDirectory: true) + try FileManager.default.createDirectory(at: logs, withIntermediateDirectories: true) + let runID = UUID() + let otherRunID = UUID() + for name in [ + "audit_receipt_20260101_000000_\(runID.uuidString).json", + "audit_receipt_20260102_000000_\(runID.uuidString).json", + "audit_receipt_20260103_000000_\(otherRunID.uuidString).json", + "audit_receipt_20260104_000000_\(runID.uuidString).json.spool", + "dedupe_audit_receipt_20260105_000000_\(runID.uuidString).json", + ] { + try Data("{}".utf8).write(to: logs.appendingPathComponent(name)) + } + + XCTAssertEqual( + SwiftOrganizerEngine.receiptURL(runID: runID, logsDirectoryPath: logs.path)?.lastPathComponent, + "audit_receipt_20260102_000000_\(runID.uuidString).json" + ) + XCTAssertNil(SwiftOrganizerEngine.receiptURL(runID: UUID(), logsDirectoryPath: logs.path)) + XCTAssertNil(SwiftOrganizerEngine.receiptURL(runID: runID, logsDirectoryPath: nil)) + } + + /// A month request is a question, not a run. It must answer with the month + /// batch and leave the destination exactly as a preview would. + @MainActor + func testMonthRequestCopiesNothingAndReservesNothing() async throws { + let (sourceURL, destinationURL) = try makeMonthSource() + let sourceDigests = try Self.mediaDigests(under: sourceURL) + let authorizer = RecordingAuthorizer() + let engine = SwiftOrganizerEngine( + authorizer: authorizer, + profilesRepository: TestProfilesRepository( + profiles: [], + profilesFileURL: temporaryDirectoryURL.appendingPathComponent("profiles.yaml") + ) + ) + + let stream = try engine.start( + RunConfiguration(mode: .transfer, sourcePath: sourceURL.path, destinationPath: destinationURL.path), + batch: FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: "2024-03", limit: 2)) + ) + + do { + _ = try await Self.collect(stream) + return XCTFail("A month request must answer with a proposal, never run to completion") + } catch let error as TrialAuthorizationError { + guard case let .allowanceSpent(refusal) = error.refusal else { + return XCTFail("Expected the proposal's refusal, got \(error.refusal)") + } + XCTAssertEqual(refusal.meter, .organize) + XCTAssertEqual(refusal.requested, 3) + XCTAssertEqual(refusal.remaining, 2) + XCTAssertEqual(error.offeredBatch?.monthKey, "2024-03") + XCTAssertEqual(error.offeredBatch?.wasRequested, true) + XCTAssertEqual(error.offeredBatch?.includedCount, 2) + XCTAssertEqual(error.offeredBatch?.deferredCount, 1) + } + + XCTAssertTrue(Self.mediaURLs(under: destinationURL).isEmpty, "A request copies no media") + XCTAssertTrue(receiptURLs(in: destinationURL).isEmpty, "A request writes no receipt") + let queuedJobs = try Self.withDatabaseWhenReady( + at: destinationURL.appendingPathComponent(".organize_cache.db") + ) { try $0.loadQueuedJobs() } + XCTAssertTrue(queuedJobs.isEmpty, "A request enqueues nothing, got \(queuedJobs)") + XCTAssertEqual(authorizer.authorizeCallCount, 0, "A request never reaches the trial gate") + XCTAssertEqual(authorizer.finalizeCallCount + authorizer.releaseCallCount, 0) + XCTAssertEqual(try Self.mediaDigests(under: sourceURL), sourceDigests) + } + + // AGENTS-INVARIANT: 1 + @MainActor + func testConfirmedMonthBatchCopiesOnlyTheListedFiles() async throws { + let (sourceURL, destinationURL) = try makeMonthSource() + let sourceDigests = try Self.mediaDigests(under: sourceURL) + let ledger = InMemoryTrialLedger(caps: TrialAllowanceCaps(organizeFiles: 2, dedupeFiles: 1)) + let engine = meteredEngine(ledger: ledger) + let configuration = RunConfiguration( + mode: .transfer, sourcePath: sourceURL.path, destinationPath: destinationURL.path + ) + + // The person asks for March; the engine answers with the files to list. + var proposed: FreeTestBatch? + do { + _ = try await Self.collect( + try engine.start( + configuration, + batch: FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: "2024-03", limit: 2)) + ) + ) + return XCTFail("A request must answer with a proposal") + } catch let error as TrialAuthorizationError { + proposed = error.offeredBatch + } + let batch = try XCTUnwrap(proposed) + XCTAssertEqual(batch.includedCount, 2) + XCTAssertEqual(try ledger.balance(accountKey: Self.testAccountKey).usage.organizeUsed, 0) + + // The confirmation runs exactly the listed files and nothing else. + let events = try await Self.collect(try engine.start(configuration, batch: batch.selection)) + + guard case let .complete(summary)? = events.last else { + return XCTFail("Expected completion summary") + } + XCTAssertEqual(summary.status, .finished) + XCTAssertEqual(summary.metrics.copiedCount, 2) + XCTAssertEqual(summary.copiedBatchSourcePaths, Set(batch.included.map(\.sourcePath))) + + XCTAssertEqual(Self.mediaURLs(under: destinationURL).count, 2) + XCTAssertTrue(FileManager.default.fileExists( + atPath: destinationURL.appendingPathComponent("2024/03/02/2024-03-02_001.jpg").path + )) + XCTAssertTrue(FileManager.default.fileExists( + atPath: destinationURL.appendingPathComponent("2024/03/03/2024-03-03_001.jpg").path + )) + XCTAssertFalse( + FileManager.default.fileExists(atPath: destinationURL.appendingPathComponent("2024/02").path), + "February was not in the confirmed batch" + ) + XCTAssertEqual(try Self.mediaDigests(under: sourceURL), sourceDigests, "Every source file is byte-for-byte unchanged") + XCTAssertEqual(try ledger.balance(accountKey: Self.testAccountKey).usage.organizeUsed, 2) + XCTAssertTrue(try ledger.openReservations().isEmpty) + } + + /// Confirming a batch does not bypass the gate: the real authorization runs + /// on the confirmed count, and a smaller allowance still refuses it. + @MainActor + func testConfirmedMonthBatchStillRefusedWhenAllowanceTooSmall() async throws { + let (sourceURL, destinationURL) = try makeMonthSource() + let sourceDigests = try Self.mediaDigests(under: sourceURL) + let ledger = InMemoryTrialLedger(caps: TrialAllowanceCaps(organizeFiles: 1, dedupeFiles: 1)) + let engine = meteredEngine(ledger: ledger) + let configuration = RunConfiguration( + mode: .transfer, sourcePath: sourceURL.path, destinationPath: destinationURL.path + ) + + // A batch of two, as a screen that showed a limit of two would have proposed it. + var proposed: FreeTestBatch? + do { + _ = try await Self.collect( + try engine.start( + configuration, + batch: FreeTestBatchSelection(requestingMonth: FreeMonthRequest(key: "2024-03", limit: 2)) + ) + ) + return XCTFail("A request must answer with a proposal") + } catch let error as TrialAuthorizationError { + proposed = error.offeredBatch + } + let batch = try XCTUnwrap(proposed) + XCTAssertEqual(batch.includedCount, 2) + + do { + _ = try await Self.collect(try engine.start(configuration, batch: batch.selection)) + XCTFail("Two files against one remaining must be refused") + } catch let error as TrialAuthorizationError { + guard case let .allowanceSpent(refusal) = error.refusal else { + return XCTFail("Expected a spent allowance, got \(error.refusal)") + } + XCTAssertEqual(refusal.requested, 2) + XCTAssertEqual(refusal.remaining, 1) + // The refusal still offers a month batch that does fit: never more than what is left. + XCTAssertLessThanOrEqual(error.offeredBatch?.includedCount ?? 0, 1) + XCTAssertEqual(error.offeredBatch?.wasRequested, false) + } + + XCTAssertTrue(Self.mediaURLs(under: destinationURL).isEmpty, "A refused batch copies nothing") + XCTAssertTrue(receiptURLs(in: destinationURL).isEmpty, "A refused batch writes no receipt") + XCTAssertEqual(try Self.mediaDigests(under: sourceURL), sourceDigests) + XCTAssertEqual(try ledger.balance(accountKey: Self.testAccountKey).usage.organizeUsed, 0) + XCTAssertTrue(try ledger.openReservations().isEmpty) + } + private static func mediaURLs(under root: URL) -> [URL] { FileManager.default .enumerator(at: root, includingPropertiesForKeys: nil)? @@ -1825,6 +2084,42 @@ private final class SlowAuthorizer: TrialAuthorizing, @unchecked Sendable { func authorizeUnlockOnlyWork() async -> TrialAuthorization { .permitted } } +/// Permits everything and counts every call, so a test can prove the gate was +/// never reached. +private final class RecordingAuthorizer: TrialAuthorizing, @unchecked Sendable { + private let lock = NSLock() + private var authorized = 0 + private var finalized = 0 + private var released = 0 + + var authorizeCallCount: Int { lock.withLock { authorized } } + var finalizeCallCount: Int { lock.withLock { finalized } } + var releaseCallCount: Int { lock.withLock { released } } + + func authorizeMeteredWork( + runID: UUID, + meter: TrialMeter, + count: Int, + destinationRoot: String? + ) async -> TrialAuthorization { + lock.withLock { authorized += 1 } + return .permitted + } + + func finalizeMeteredWork(runID: UUID, actualCount: Int) async { + lock.withLock { finalized += 1 } + } + + func releaseMeteredWork(runID: UUID) async { + lock.withLock { released += 1 } + } + + func authorizeUnlockOnlyWork() async -> TrialAuthorization { + lock.withLock { authorized += 1 } + return .permitted + } +} + private final class TestProfilesRepository: ProfilesRepositorying { private var profiles: [Profile] private let storedProfilesFileURL: URL diff --git a/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift b/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift new file mode 100644 index 00000000..6f93c390 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift @@ -0,0 +1,81 @@ +import Foundation +import XCTest +@testable import ChronoframeAppCore +@testable import ChronoframeCore + +/// The one number the preview and the sheet quote for "what is left" (FRX C-06). +/// +/// Absent for anyone who paid or whose allowance is not known, because a number +/// the app does not actually have must never be shown. +final class TrialRemainingTests: XCTestCase { + private let caps = TrialAllowanceCaps(organizeFiles: 500, dedupeFiles: 100) + + private func status( + _ entitlement: EntitlementState, + organizeUsed: Int = 0, + dedupeUsed: Int = 0 + ) -> TrialStatus { + TrialStatus( + entitlement: entitlement, + allowance: .remaining( + TrialBalance( + caps: caps, + usage: TrialUsage(organizeUsed: organizeUsed, dedupeUsed: dedupeUsed) + ) + ) + ) + } + + func testNilWhenNotAppStoreChannel() { + XCTAssertNil( + TrialRemaining.value(status: status(.locked), meter: .organize, isAppStoreChannel: false), + "The Developer ID build is unrestricted; a remaining count would describe a limit that does not exist" + ) + } + + func testNilWhenUnlocked() { + XCTAssertNil( + TrialRemaining.value( + status: status(.unlocked(reason: .inAppPurchase)), + meter: .organize, + isAppStoreChannel: true + ) + ) + XCTAssertNil( + TrialRemaining.value( + status: TrialStatus(entitlement: .unlocked(reason: .legacyPurchase), allowance: .unlimited), + meter: .dedupe, + isAppStoreChannel: true + ) + ) + } + + func testNilWhenUnknownOrLoading() { + XCTAssertNil(TrialRemaining.value(status: .loading, meter: .organize, isAppStoreChannel: true)) + XCTAssertNil( + TrialRemaining.value( + status: TrialStatus(entitlement: .locked, allowance: .unknown), + meter: .organize, + isAppStoreChannel: true + ) + ) + XCTAssertNil( + TrialRemaining.value( + status: TrialStatus(entitlement: .locked, allowance: .unavailable), + meter: .organize, + isAppStoreChannel: true + ), + "An unreadable ledger reports zero to the gate, but must not be quoted as a number" + ) + } + + func testRemainingForEachMeter() { + let locked = status(.locked, organizeUsed: 120, dedupeUsed: 4) + + XCTAssertEqual(TrialRemaining.value(status: locked, meter: .organize, isAppStoreChannel: true), 380) + XCTAssertEqual(TrialRemaining.value(status: locked, meter: .dedupe, isAppStoreChannel: true), 96) + + let spent = status(.locked, organizeUsed: 500) + XCTAssertEqual(TrialRemaining.value(status: spent, meter: .organize, isAppStoreChannel: true), 0) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift index df10e2df..87269d3c 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift @@ -166,6 +166,156 @@ final class UnlockPresentationTests: XCTestCase { XCTAssertFalse(message.localizedCaseInsensitiveContains("copied"), message) } + // MARK: - The title names the outcome (FRX C-06) + + func testAllowanceSpentOrganizeTitleNamesFileCount() { + XCTAssertEqual(model(refusal: spent(remaining: 0, requested: 40), product: product).title, "Organize all 40 files") + XCTAssertEqual(model(refusal: spent(remaining: 12, requested: 1), product: product).title, "Organize all 1 file") + XCTAssertEqual( + model(refusal: spent(remaining: 0, requested: 12_345), product: product).title, + "Organize all \(12_345.formatted()) files", + "Numbers are formatted for the reader" + ) + // The other titles are unchanged. + XCTAssertEqual(model(refusal: .requiresUnlock, product: product).title, "Unlock Chronoframe") + XCTAssertEqual( + model(refusal: .purchaseUnconfirmed(TrialRefusal(meter: .organize, requested: 5, remaining: 0)), product: product).title, + "Purchase Not Confirmed" + ) + } + + func testAllowanceSpentDedupeTitleNamesDuplicateCount() { + let dedupe = { (requested: Int) in + self.model( + refusal: .allowanceSpent(TrialRefusal(meter: .dedupe, requested: requested, remaining: 0)), + product: self.product + ).title + } + + XCTAssertEqual(dedupe(25), "Remove all 25 duplicates") + XCTAssertEqual(dedupe(1), "Remove all 1 duplicate") + } + + func testPurchaseTermsLineForAllowanceSpentAndRequiresUnlock() { + let line = "One-time purchase with Family Sharing. No subscription." + + XCTAssertEqual(model(refusal: spent(), product: product).purchaseTermsLine, line) + XCTAssertEqual(model(refusal: spent(), product: nil, isLoadingProduct: true).purchaseTermsLine, line) + XCTAssertEqual(model(refusal: spent(), product: nil).purchaseTermsLine, line) + XCTAssertEqual(model(refusal: .requiresUnlock, product: product).purchaseTermsLine, line) + } + + /// Someone whose purchase could not be confirmed may already own it, so the + /// sheet does not describe a purchase to them. The voluntary sheet's message + /// already says it. + func testNoPurchaseTermsLineForUnconfirmedPurchaseOrVoluntaryUnlock() { + let unconfirmed = model( + refusal: .purchaseUnconfirmed(TrialRefusal(meter: .organize, requested: 5, remaining: 0)), + product: product + ) + XCTAssertNil(unconfirmed.purchaseTermsLine) + + let voluntary = UnlockSheetModel.make( + product: product, isLoadingProduct: false, isPurchasing: false, isRestoring: false + ) + XCTAssertNil(voluntary.purchaseTermsLine) + } + + // MARK: - The person asked for the free month (FRX C-06) + + private func requestedMonthBatch(included: Int = 3, deferred: Int = 897) -> FreeTestBatch { + let transfers = (0..<included).map { + PlannedTransfer( + sourcePath: "/Volumes/Card/file-\($0).jpg", + destinationPath: "/Volumes/Archive/2026-10-05/file-\($0).jpg", + identity: FileIdentity(size: Int64($0 + 1), digest: "digest-\($0)"), + dateBucket: "2026-10-05", + isDuplicate: false + ) + } + return FreeTestBatch(included: transfers, deferredCount: deferred, monthKey: "2026-10", wasRequested: true) + } + + private func requestedModel( + product: StoreProductInfo? = nil, + isLoadingProduct: Bool = false, + batch: FreeTestBatch? = nil + ) -> UnlockSheetModel { + UnlockSheetModel.make( + refusal: spent(remaining: 4, requested: 900), + product: product, + isLoadingProduct: isLoadingProduct, + isPurchasing: false, + isRestoring: false, + offeredBatch: batch ?? requestedMonthBatch() + ) + } + + func testRequestedMonthTitleAndMessage() { + let requested = requestedModel(product: product) + + XCTAssertEqual(requested.title, "Copy October 2026 free") + XCTAssertEqual( + requested.message, + "These 3 new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed." + ) + XCTAssertEqual(requested.purchaseTermsLine, "One-time purchase with Family Sharing. No subscription.") + + // A suggested month (not requested) keeps the refusal's own title and message. + var suggestedBatch = requestedMonthBatch() + suggestedBatch = FreeTestBatch( + included: suggestedBatch.included, + deferredCount: suggestedBatch.deferredCount, + monthKey: "2026-10", + wasRequested: false + ) + let suggested = requestedModel(product: product, batch: suggestedBatch) + XCTAssertEqual(suggested.title, "Organize all 900 files") + XCTAssertTrue(suggested.message.contains("4 files left"), suggested.message) + + // A single file reads as one. + let one = requestedModel(product: product, batch: requestedMonthBatch(included: 1, deferred: 5)) + XCTAssertFalse(one.message.contains("1 new photos"), one.message) + XCTAssertTrue(one.message.contains("1 new photo or video"), one.message) + } + + func testRequestedMonthPutsFreeCopyFirst() { + let requested = requestedModel(product: product) + XCTAssertEqual( + requested.actions, + [ + .runFreeTestBatch(fileCount: 3, deferredCount: 897), + .buy(displayName: product.displayName, displayPrice: "£14.99"), + .restore, + .dismiss, + ] + ) + + let loading = requestedModel(product: nil, isLoadingProduct: true) + XCTAssertEqual(loading.actions, [.runFreeTestBatch(fileCount: 3, deferredCount: 897), .dismiss]) + + let failed = requestedModel(product: nil) + XCTAssertEqual( + failed.actions, + [.runFreeTestBatch(fileCount: 3, deferredCount: 897), .retryProductLoad, .restore, .dismiss] + ) + + // Not requested: the order shipped in T15 is unchanged. + let notRequested = requestedModel( + product: product, + batch: FreeTestBatch(included: requestedMonthBatch().included, deferredCount: 897, monthKey: "2026-10") + ) + XCTAssertEqual( + notRequested.actions, + [ + .buy(displayName: product.displayName, displayPrice: "£14.99"), + .restore, + .runFreeTestBatch(fileCount: 3, deferredCount: 897), + .dismiss, + ] + ) + } + // 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 5d4f19dd..b3dee0b5 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockSheetBatchOfferTests.swift @@ -98,6 +98,36 @@ final class UnlockSheetBatchOfferTests: XCTestCase { XCTAssertTrue(detail.contains("to"), "A multi-day batch names its span: \(detail)") } + /// A month batch names the month, not the earliest files (FRX C-06). + func testMonthBatchDetailNamesMonth() { + let monthBatch = FreeTestBatch( + included: batch(included: 3, deferred: 0, singleDate: true).included, + deferredCount: 897, + monthKey: "2026-10" + ) + + let detail = model(offeredBatch: monthBatch).batchDetail ?? "" + + XCTAssertEqual(detail, "Copies October 2026 now, 3 files, and leaves 897 for later.") + XCTAssertFalse(detail.contains("earliest"), detail) + + let one = FreeTestBatch( + included: Array(monthBatch.included.prefix(1)), + deferredCount: 1_200, + monthKey: "2026-02" + ) + XCTAssertEqual( + model(offeredBatch: one).batchDetail, + "Copies February 2026 now, 1 file, and leaves \(1_200.formatted()) for later." + ) + + // A batch without a month keeps the earliest-first sentences. + XCTAssertTrue( + (model(offeredBatch: batch(included: 3, deferred: 897)).batchDetail ?? "").contains("the earliest"), + "Batches without a month are described as before" + ) + } + func testASingleDayBatchDoesNotNameARange() { let detail = model(offeredBatch: batch(included: 2, deferred: 5, singleDate: true)).batchDetail ?? "" From 5a0dc9d6b5cca1315697f1db25f0533a11e80d32 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:14:39 -0800 Subject: [PATCH 07/30] FRX WP-04: App: preview shows the free limit and the free month Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 10 +- .../App/AccessibilityIdentifiers.swift | 6 +- ui/Sources/ChronoframeApp/App/AppState.swift | 45 ++++- .../App/UITesting/UITestAppStateFactory.swift | 90 ++++++++- .../App/UITesting/UITestScenario.swift | 7 +- .../Views/Purchase/UnlockSheet.swift | 11 + .../ChronoframeApp/Views/RootSplitView.swift | 2 +- .../Views/Run/CurrentRunView.swift | 10 +- .../Views/Run/RunSectionViews.swift | 67 +++++++ .../Views/Run/RunWorkspaceModel.swift | 144 ++++++++++++- .../ChronoframeAppTests/AppStateTests.swift | 189 ++++++++++++++++++ .../RunWorkspaceModelTests.swift | 189 ++++++++++++++++++ .../ScreenRenderEvidenceTests.swift | 7 + .../UITestWindowFitTests.swift | 16 ++ .../UnlockSheetLayoutTests.swift | 35 ++++ 16 files changed, 806 insertions(+), 23 deletions(-) diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 834fa1ec..9cebaa3c 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -50,3 +50,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-102 Free-month planner details (WP-02).** (a) `monthKey(forDateBucket:)` is strict: exactly `yyyy-MM-dd` in ASCII digits with month 01–12 and day 01–31, otherwise nil. (b) A companion counts toward, and travels with, its owner's month whatever its own `dateBucket`; a companion whose owner is an exact copy or is not in the plan is not counted. (c) When a month is too large, `select` stops at the first day that does not fit (it never skips ahead to a smaller later day); within a too-large first day it stops at the first owner unit that does not fit. (d) `options` leaves out a month whose count is 0. All four are the narrowest reading of C-05; none widens what a free copy can contain. - **D-FRX-103 Month-request branch placement and guard (WP-03).** C-06 says the branch goes "directly after planning and the zero-transfer branches, before `plan.reduced(to:)`", but in the code the zero-transfer branches come after `reduced`. The branch sits after `planAsync` and the cancellation check, immediately before `plan.reduced(to:)`, and is guarded with `plan.transferCount > 0`. An empty plan falls through: the request confirms no file, reduces to nothing and takes the existing "Nothing left to copy" return, which is ahead of `authorizeTransfer`. The literal one-liner would have raised an unlock sheet for 0 files. Known wart: that existing warning ("None of the files in that batch are still where they were…") is slightly off for a request; left alone (fewest changed lines). - **D-FRX-104 Free-month sheet details (WP-03).** (a) `proposingFreeMonth` sets `wasRequested: true` on the suggested-month fallback too; the title names the month actually offered. (b) It does not apply the covers-whole-plan check (C-06 gives that rule only to `offeringFreeMonthBatch`); the sheet's existing `offerableBatch` still drops such a batch. (c) With a failed price load a requested-month sheet keeps the requested message. (d) Singular forms added per the copy rule: `Organize all %@ file`, `Remove all %@ duplicate`, `This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.` (e) `TrialRemaining.value` is also nil while the entitlement is resolving. (f) The two builders are internal, not public. (g) `TrialAuthorizer.swift` gained one private helper `monthBatch` shared by the two builders. +- **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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 6af9b865..b25b5736 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -15,9 +15,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-00 | Branch, plan folder, baseline | done | build exit 0 | suite exit 0 (2513 passed) | n/a | a09eca6, aa56f84 | INV-31 on main: 1 | | WP-01 | Render evidence harness | done | build exit 0 | `test ScreenRenderEvidenceTests` exit 0 (3 skipped without marker; 3 run, 3 PNGs with marker) | approve (round 1) | fb09f36 | rendered: harness produces non-blank PNGs; D-FRX-101 | | WP-02 | Core: accounting, free month, model fields | done | build exit 0 | RunAccounting 8, FreeMonthBatchPlanner 14, FreeTestBatchPlanner 19 tests, all exit 0 | approve (round 1) | 682f714 | orchestrator read the FreeTestBatchPlanner.swift and RunModels.swift diffs: additions only; D-FRX-102 | -| WP-03 | AppCore: engine, offer, unlock presentation | done | build exit 0 | TrialRemaining 4, FreeMonthBatchOffer 11, UnlockPresentation 19, UnlockSheetBatchOffer 14, FreeTestBatchOffer 9, FreeTestBatchRun 4, SwiftOrganizerEngineIntegration 43 tests, all exit 0 | approve (round 1) | (WP-03 commit) | orchestrator read the full SwiftOrganizerEngine.swift and TrialAuthorizer.swift diffs: every changed line traces to C-03/C-06; the month-request branch throws before `plan.reduced(to:)`, so it reaches neither `authorizeTransfer` nor the job queue; D-FRX-103, D-FRX-104 | -| WP-04 | App: preview free limit and free month | in-progress | | | | | | -| WP-05 | App: accounted-for line, Undo, add folder | todo | | | | | INV-8 tag on the undo test | +| WP-03 | AppCore: engine, offer, unlock presentation | done | build exit 0 | TrialRemaining 4, FreeMonthBatchOffer 11, UnlockPresentation 19, UnlockSheetBatchOffer 14, FreeTestBatchOffer 9, FreeTestBatchRun 4, SwiftOrganizerEngineIntegration 43 tests, all exit 0 | approve (round 1) | c1dee6f | orchestrator read the full SwiftOrganizerEngine.swift and TrialAuthorizer.swift diffs: every changed line traces to C-03/C-06; the month-request branch throws before `plan.reduced(to:)`, so it reaches neither `authorizeTransfer` nor the job queue; D-FRX-103, D-FRX-104 | +| 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) | (WP-04 commit) | 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 | in-progress | | | | | INV-8 tag on the undo test | | WP-06 | Docs and strings, M1 | todo | | | | | | | G1 | Gate, M1 | todo | | | n/a | | | | WP-10 | Branch and baseline, M2 | todo | | | n/a | | | @@ -46,3 +46,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 2026-11-28 WP-02 Done-when (orchestrator): `cf_swift.sh test ChronoframeCoreRunAccountingTests` exit 0 (8 tests); `cf_swift.sh test ChronoframeCoreFreeMonthBatchPlannerTests` exit 0 (14); `cf_swift.sh test FreeTestBatchPlannerTests` exit 0 (19); `cf_swift.sh build` exit 0; `git diff --check` exit 0. No user-facing strings, no existing assertions changed. - 2026-11-28 WP-03 Done-when (orchestrator): `cf_swift.sh test` exit 0 for TrialRemainingTests (4), FreeMonthBatchOfferTests (11), UnlockPresentationTests (19), UnlockSheetBatchOfferTests (14), FreeTestBatchOfferTests (9), FreeTestBatchRunTests (4), SwiftOrganizerEngineIntegrationTests (43); `cf_swift.sh build` exit 0; `script/check_authorizer_has_no_default.sh` exit 0; `script/check_storekit_config_matches_policy.sh` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0. No existing assertions changed. - WP-03 strings for WP-06 (all Core, `UnlockPresentation.swift`, via `CoreL10n.text`): `Organize all %@ files`; `Organize all %@ file`; `Remove all %@ duplicates`; `Remove all %@ duplicate`; `One-time purchase with Family Sharing. No subscription.`; `Copies %@ now, %@, and leaves %@ for later.`; `Copy %@ free`; `These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.`; `This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.` +- 2026-11-28 WP-04 Done-when (orchestrator): `cf_swift.sh test` exit 0 for RunWorkspaceModelTests (26), AppStateTests (44), UnlockSheetLayoutTests (2), UITestWindowFitTests (8), ScreenRenderEvidenceTests (4 skipped without marker; 4 run and 4 PNGs with it); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `script/check_detail_views_set_navigation_title.sh` exit 0; `git diff --check` exit 0. No existing assertions changed. +- WP-04 strings for WP-06 (App catalog). Templates in `RunWorkspaceModel.swift` looked up via AppLocalization: `You can copy %1$@ free. This plan has %2$@.`; `The newest month that fits is %1$@: %2$@.`; `%@ is larger than that, so the free copy takes its first days.`; `Your free copies are used up. This plan has %@.`; `Copy %@ Free…`. SwiftUI literals in `RunSectionViews.swift`: `Choose Another Month`; `Unlock to Copy Everything`; `Shows the files first. Nothing is copied until you confirm`. +- For G1 step 4: `ui/Xcode/UITests/ChronoframeUITests.swift:545` and `:547` assert `discovered: 84` for `runPreviewReview` (WP-05 changes it to 72); the UI-test `Scenario` enum has no `runPreviewOverAllowance` case (none is needed unless a UI test uses it). +- Noticed, not fixed: in the `runPreviewOverAllowance` fixture the Timeline header reads "21,140 planned files" while the plan has 18,412 (the fixture histogram does not sum to the plan). Fixture-only. diff --git a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift index 26c6d850..14353ad8 100644 --- a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift +++ b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift @@ -38,6 +38,9 @@ enum AccessibilityIdentifiers { static let openReportButton = "openReportButton" static let openLogsButton = "openLogsButton" static let startTransferFromPreviewButton = "startTransferFromPreviewButton" + static let runFreeMonthCopy = "runFreeMonthCopy" + static let runFreeMonthMenu = "runFreeMonthMenu" + static let runUnlockEverything = "runUnlockEverything" static let runWorkspaceTabs = "runWorkspaceTabs" static let runIdleOnboardingCard = "runIdleOnboardingCard" static let runOutcomeSummaryCard = "runOutcomeSummaryCard" @@ -178,7 +181,8 @@ enum AccessibilityIdentifiers { profilePicker, previewButton, transferButton, setupPreflightChecklist, setupSafetyDetailsDisclosure, setupHeroTitle, setupSourceItems, consoleScrollView, openDestinationButton, openReportButton, openLogsButton, - startTransferFromPreviewButton, runWorkspaceTabs, runIdleOnboardingCard, + startTransferFromPreviewButton, runFreeMonthCopy, runFreeMonthMenu, runUnlockEverything, + runWorkspaceTabs, runIdleOnboardingCard, runOutcomeSummaryCard, runPreviewSummary, previewReviewFilter, refreshLibraryHealthButton, reorganizeDestinationButton, dedupeAcceptAllSuggestionsButton, dedupeAcceptClusterSuggestionButton, diff --git a/ui/Sources/ChronoframeApp/App/AppState.swift b/ui/Sources/ChronoframeApp/App/AppState.swift index db6c17a6..f32c58cf 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -3,6 +3,9 @@ import Combine #if canImport(ChronoframeAppCore) import ChronoframeAppCore #endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif import Foundation @MainActor @@ -510,7 +513,42 @@ final class AppState: ObservableObject { /// status. Checking only the first would leave a customer who exhausted /// the dedupe allowance looking at an error with no way to unlock. var unlockRefusal: TrialAuthorizationRefusal? { - runSessionStore.lastRefusal ?? deduplicateSessionStore.lastRefusal + runSessionStore.lastRefusal ?? deduplicateSessionStore.lastRefusal ?? requestedUnlockRefusal + } + + /// An unlock the person asked for from the preview (Unlock to Copy + /// Everything), as opposed to one an operation was refused for. Nothing was + /// refused, so no store holds it; it lives here until the sheet closes. + @Published private(set) var requestedUnlockRefusal: TrialAuthorizationRefusal? + + /// Free organize copies left, for the preview and the actions it offers; nil + /// when the allowance does not apply or is not known (FRX C-07). + var organizeAllowanceRemaining: Int? { + TrialRemaining.value( + status: trialStatusStore.status, + meter: .organize, + isAppStoreChannel: isAppStoreChannel + ) + } + + /// Ask the engine to propose a free copy of that month. Copies nothing: the + /// sheet that follows lists the files, and only its button copies them (C-06). + func startFreeMonthCopy(_ option: FreeMonthOption) async { + guard let remaining = organizeAllowanceRemaining, remaining > 0 else { return } + let request = FreeMonthRequest(key: option.key, limit: remaining) + await runCoordinator.startTransfer(batch: FreeTestBatchSelection(requestingMonth: request)) + } + + /// Open the unlock sheet for the plan on screen, without starting anything. + func requestUnlockForPlan(requested: Int? = nil) { + guard let remaining = organizeAllowanceRemaining else { return } + requestedUnlockRefusal = .allowanceSpent( + TrialRefusal( + meter: .organize, + requested: requested ?? runSessionStore.metrics.plannedCount, + remaining: remaining + ) + ) } /// A smaller run the remaining allowance covers, when one was offered @@ -542,6 +580,7 @@ final class AppState: ObservableObject { func dismissUnlockSheet() { runSessionStore.dismissRefusal() deduplicateSessionStore.dismissRefusal() + requestedUnlockRefusal = nil } /// Start over after an unlock, from preflight. @@ -562,6 +601,10 @@ final class AppState: ObservableObject { // and must not by itself authorize starting another operation. guard unlockRefusal != nil else { return } + // A requested unlock started no operation, so there is nothing to + // retry: the person presses Start Copying, now shown again. + requestedUnlockRefusal = nil + // The sheet shows the Organize refusal ahead of the Deduplicate one // (see `unlockRefusal`), so that is the one the customer just unlocked. // Act on it first. diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index ae150b2a..5ed75f39 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -94,6 +94,19 @@ enum UITestAppStateFactory { engine = previewReviewEngine(sourcePath: setupStore.sourcePath, destinationPath: setupStore.destinationPath) route = .organize(.run) + case .runPreviewOverAllowance: + // A large plan against an untouched free allowance, so the preview + // offers a free month and the unlock instead of "Start Copying". + setupStore.sourcePath = "/Volumes/Card/April Session" + setupStore.destinationPath = "/Volumes/Archive/Chronoframe Library" + historyStore = HistoryStore(destinationRoot: setupStore.destinationPath) + engine = previewReviewEngine( + sourcePath: setupStore.sourcePath, + destinationPath: setupStore.destinationPath, + overAllowance: true + ) + route = .organize(.run) + case .runCopyComplete: // The destination is a scenario-owned temp folder because a finished // run records its source in the destination's transferred-sources log. @@ -251,7 +264,7 @@ enum UITestAppStateFactory { break } - if scenario == .runPreviewReview || scenario == .runCopyComplete || scenario == .previewDateConflict { + if scenario == .runPreviewReview || scenario == .runPreviewOverAllowance || scenario == .runCopyComplete || scenario == .previewDateConflict { Task { @MainActor in await appState.startPreview() } @@ -279,13 +292,16 @@ enum UITestAppStateFactory { let accountKey = "chronoframe-ui-test-account" let ledger = InMemoryTrialLedger() - seedCharge( - 120, - meter: .organize, - runID: "00000000-0000-0000-0000-000000000501", - ledger: ledger, - accountKey: accountKey - ) + // The over-allowance preview starts from an untouched organize allowance. + if scenario != .runPreviewOverAllowance { + seedCharge( + 120, + meter: .organize, + runID: "00000000-0000-0000-0000-000000000501", + ledger: ledger, + accountKey: accountKey + ) + } seedCharge( ProcessInfo.processInfo.environment["CHRONOFRAME_UI_TEST_DEDUPE_REFUSAL"] == "1" ? 100 : 4, meter: .dedupe, @@ -385,10 +401,62 @@ enum UITestAppStateFactory { ) } + /// The over-allowance preview: 18,475 found = 18,412 to copy + 63 already + /// there, a 14-month histogram ending 2026-10, and three months of new + /// files to offer for free (FRX C-08). + private static func overAllowanceEngine(preflight: RunPreflight, destinationPath: String) -> MockOrganizerEngine { + let months = [ + "2025-09", "2025-10", "2025-11", "2025-12", "2026-01", "2026-02", "2026-03", + "2026-04", "2026-05", "2026-06", "2026-07", "2026-08", "2026-09", "2026-10", + ] + let histogram = months.enumerated().map { index, key in + DateHistogramBucket( + key: key, + plannedCount: 600 + index * 140, + samplePaths: ["/Volumes/Card/April Session/\(key)/IMG_0001.jpg"] + ) + } + let metrics = RunMetrics( + discoveredCount: 18_475, + plannedCount: 18_412, + alreadyInDestinationCount: 63, + duplicateCount: 1_204, + dateHistogram: histogram, + newFilesByMonth: ["2026-10": 212, "2026-09": 148, "2026-08": 734] + ) + let summary = RunSummary( + status: .dryRunFinished, + title: "Preview complete", + metrics: metrics, + artifacts: RunArtifactPaths( + destinationRoot: destinationPath, + reportPath: "\(destinationPath)/.organize_logs/dry_run_report.csv", + logFilePath: "\(destinationPath)/.organize_log.txt", + logsDirectoryPath: "\(destinationPath)/.organize_logs" + ) + ) + return MockOrganizerEngine( + preflightResult: .success(preflight), + startMode: .events([ + .startup, + .dateHistogram(buckets: histogram), + .phaseStarted(phase: .discovery, total: 18_475), + .phaseCompleted(phase: .sourceHashing, result: RunPhaseResult(found: 18_475)), + .phaseCompleted( + phase: .classification, + result: RunPhaseResult(newCount: 17_208, alreadyInDestinationCount: 63, duplicateCount: 1_204) + ), + .copyPlanReady(count: 18_412), + .complete(summary), + ]) + ) + } + private static func previewReviewEngine( sourcePath: String, destinationPath: String, - includeDateConflict: Bool = false + includeDateConflict: Bool = false, + overAllowance: Bool = false ) -> MockOrganizerEngine { let preflight = RunPreflight( configuration: RunConfiguration(mode: .preview, sourcePath: sourcePath, destinationPath: destinationPath), @@ -396,6 +464,10 @@ enum UITestAppStateFactory { resolvedDestinationPath: destinationPath ) + if overAllowance { + return overAllowanceEngine(preflight: preflight, destinationPath: destinationPath) + } + let sampleHistogram = [ DateHistogramBucket(key: "2026-04", plannedCount: 42, samplePaths: ["/Volumes/Card/April Session/pic1.jpg"]) ] diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift index f43559ca..6120ab71 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift @@ -6,6 +6,7 @@ enum UITestScenario: String, CaseIterable { case setupReady case setupMultiFolder case runPreviewReview + case runPreviewOverAllowance case runCopyComplete case previewDateConflict case healthDashboard @@ -60,18 +61,18 @@ enum UITestScenario: String, CaseIterable { /// the audit never depends on StoreKit, signing, or a test account. var usesMeteredTrialUI: Bool { switch self { - case .runPreviewReview, .settingsLicense, .deduplicateReviewWide, .deduplicateReviewCompact: + case .runPreviewReview, .runPreviewOverAllowance, .settingsLicense, .deduplicateReviewWide, .deduplicateReviewCompact: return true default: return false } } - private var preferredMainWindowSize: NSSize { + var preferredMainWindowSize: NSSize { switch self { case .historyPopulated: return NSSize(width: 1360, height: 1200) - case .setupIncompleteRun, .setupReady, .setupMultiFolder, .runPreviewReview, .runCopyComplete, .previewDateConflict, .healthDashboard, .watchedSources, .photosImport, .profilesPopulated: + case .setupIncompleteRun, .setupReady, .setupMultiFolder, .runPreviewReview, .runPreviewOverAllowance, .runCopyComplete, .previewDateConflict, .healthDashboard, .watchedSources, .photosImport, .profilesPopulated: return NSSize(width: 1360, height: 920) case .settingsSections, .settingsLayout, .settingsPerformance, .settingsDeduplicate, .settingsLicense, .settingsDiagnostics: return NSSize(width: 1360, height: 920) diff --git a/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift b/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift index 15545aa0..c17de2cf 100644 --- a/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift +++ b/ui/Sources/ChronoframeApp/Views/Purchase/UnlockSheet.swift @@ -59,6 +59,9 @@ struct UnlockSheet: View { model.actions.filter { if case .runFreeTestBatch = $0 { return false } else { return true } } } + /// The one-line purchase terms the model chose for this refusal, if any. + var termsLine: String? { model.purchaseTermsLine } + var body: some View { VStack(alignment: .leading, spacing: 14) { Text(model.title) @@ -67,6 +70,14 @@ struct UnlockSheet: View { Text(model.message) .fixedSize(horizontal: false, vertical: true) + if let termsLine { + Text(termsLine) + .font(.callout) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("unlockSheet.termsLine") + } + if let statusMessage = entitlementStore.statusMessage { Text(statusMessage) .font(.callout) diff --git a/ui/Sources/ChronoframeApp/Views/RootSplitView.swift b/ui/Sources/ChronoframeApp/Views/RootSplitView.swift index c89ea1eb..0c3f51db 100644 --- a/ui/Sources/ChronoframeApp/Views/RootSplitView.swift +++ b/ui/Sources/ChronoframeApp/Views/RootSplitView.swift @@ -20,7 +20,7 @@ struct RootSplitView: View { // presenting view must observe both, including a dedupe commit that is // refused after its confirmation dialog has closed. private var unlockRefusal: TrialAuthorizationRefusal? { - runSessionStore.lastRefusal ?? deduplicateSessionStore.lastRefusal + runSessionStore.lastRefusal ?? deduplicateSessionStore.lastRefusal ?? appState.requestedUnlockRefusal } var body: some View { diff --git a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift index 1dc4ef7c..7ce936e4 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift @@ -10,6 +10,8 @@ struct CurrentRunView: View { @ObservedObject private var runLogStore: RunLogStore @ObservedObject private var historyStore: HistoryStore @ObservedObject private var previewReviewStore: PreviewReviewStore + /// Observed so the free-limit lines follow the allowance as it is read and spent. + @ObservedObject private var trialStatusStore: TrialStatusStore @State private var workspaceTab: RunWorkspaceTab = .overview @Environment(\.undoManager) private var undoManager @@ -19,6 +21,7 @@ struct CurrentRunView: View { self._runLogStore = ObservedObject(wrappedValue: appState.runLogStore) self._historyStore = ObservedObject(wrappedValue: appState.historyStore) self._previewReviewStore = ObservedObject(wrappedValue: appState.previewReviewStore) + self._trialStatusStore = ObservedObject(wrappedValue: appState.trialStatusStore) } private var model: RunWorkspaceModel { @@ -28,7 +31,12 @@ struct CurrentRunView: View { historyStore: historyStore, canStartRun: appState.canStartRun, previewReviewStore: previewReviewStore, - photosEditedVersionCounts: appState.photosImportEditedVersionCounts + photosEditedVersionCounts: appState.photosImportEditedVersionCounts, + organizeAllowanceRemaining: TrialRemaining.value( + status: trialStatusStore.status, + meter: .organize, + isAppStoreChannel: appState.isAppStoreChannel + ) ) } diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index 88a9af5d..63abc95f 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -5,6 +5,9 @@ import AppKit #if canImport(ChronoframeAppCore) import ChronoframeAppCore #endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif #if canImport(AppKit) private extension RunAnnouncementPlanner.Priority { @@ -70,6 +73,13 @@ struct RunHeroSection: View { systemImage: model.heroState.heroSymbol ) { VStack(alignment: .leading, spacing: 12) { + if let freeCopyLine = model.freeCopyLine { + Text(verbatim: freeCopyLine) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .fixedSize(horizontal: false, vertical: true) + } + if model.showsProgressSurface { RunProgressSurface(model: model) } @@ -118,6 +128,57 @@ struct RunHeroSection: View { } } + /// Over the free limit: the newest month that fits as the primary action, the + /// other months in a menu, and the unlock beside them. "Start Copying" is + /// not offered here (FRX C-07, D-FRX-14). + @ViewBuilder + private var freeMonthButtons: some View { + if case let .overAllowance(_, _, options, suggested) = model.freeCopyState, let suggested { + VStack(alignment: .leading, spacing: 8) { + Button { + Task { await appState.startFreeMonthCopy(suggested) } + } label: { + Label(RunFreeCopyText.copyButtonTitle(for: suggested), systemImage: "calendar.badge.checkmark") + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .disabled(!model.context.canStartRun) + .accessibilityIdentifier(AccessibilityIdentifiers.runFreeMonthCopy) + .accessibilityHint("Shows the files first. Nothing is copied until you confirm") + + Menu { + ForEach(options) { option in + Button(RunFreeCopyText.menuTitle(for: option)) { + Task { await appState.startFreeMonthCopy(option) } + } + .disabled(!RunFreeCopyText.isMenuOptionEnabled(option, suggested: suggested)) + } + } label: { + Label("Choose Another Month", systemImage: "calendar") + .frame(maxWidth: .infinity) + } + .menuStyle(.borderedButton) + .disabled(!model.context.canStartRun) + .accessibilityIdentifier(AccessibilityIdentifiers.runFreeMonthMenu) + + unlockEverythingButton + } + } else { + unlockEverythingButton + } + } + + private var unlockEverythingButton: some View { + Button { + appState.requestUnlockForPlan() + } label: { + Label("Unlock to Copy Everything", systemImage: "lock.open") + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .accessibilityIdentifier(AccessibilityIdentifiers.runUnlockEverything) + } + @ViewBuilder private func heroPrimaryButton(for action: RunHeroPrimaryAction) -> some View { switch action { @@ -155,6 +216,12 @@ struct RunHeroSection: View { .accessibilityIdentifier(AccessibilityIdentifiers.startTransferFromPreviewButton) .accessibilityHint(model.canStartTransferFromPreview ? "Copies the planned files after you confirm" : "Preview first") + case .freeMonthCopy: + freeMonthButtons + + case .unlockEverything: + unlockEverythingButton + case .cancel: Button(role: .destructive) { appState.cancelRun() diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift index 29443493..626d2dbf 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift @@ -3,6 +3,9 @@ import SwiftUI #if canImport(ChronoframeAppCore) import ChronoframeAppCore #endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif enum RunWorkspaceTab: String, CaseIterable, Identifiable { case overview @@ -49,6 +52,11 @@ enum RunHeroPrimaryAction: Equatable { case setup case preview case transfer + /// Over the free allowance with a month to offer: copy that month free, + /// choose another, or unlock (FRX C-07). + case freeMonthCopy + /// The free copies are spent, or nothing dated can be offered: unlock only. + case unlockEverything case cancel case openDestination case showIssues @@ -123,6 +131,9 @@ struct RunWorkspaceContext { /// Edited-version counts when this run belongs to a Photos import that ran /// with "Include edited versions"; nil for every other run. var photosEditedVersionCounts: PhotosImportEditedVersionCounts? + /// Free organize copies left on this device's allowance; nil when the + /// allowance does not apply or is not known (FRX C-07). + var organizeAllowanceRemaining: Int? init( status: RunStatus, @@ -145,7 +156,8 @@ struct RunWorkspaceContext { previewReviewPath: String? = nil, currentFileURL: URL? = nil, isCancelling: Bool = false, - photosEditedVersionCounts: PhotosImportEditedVersionCounts? = nil + photosEditedVersionCounts: PhotosImportEditedVersionCounts? = nil, + organizeAllowanceRemaining: Int? = nil ) { self.status = status self.currentMode = currentMode @@ -168,9 +180,18 @@ struct RunWorkspaceContext { self.currentFileURL = currentFileURL self.isCancelling = isCancelling self.photosEditedVersionCounts = photosEditedVersionCounts + self.organizeAllowanceRemaining = organizeAllowanceRemaining } } +/// What the preview says about the free limit (FRX C-07). +enum RunFreeCopyState: Equatable { + case notMetered + case fits(remaining: Int) + case overAllowance(remaining: Int, planned: Int, options: [FreeMonthOption], suggested: FreeMonthOption?) + case spent(planned: Int) +} + enum RunNextStep: Equatable { case findDuplicates(setAsideCount: Int) } @@ -185,7 +206,8 @@ struct RunWorkspaceModel { historyStore: HistoryStore, canStartRun: Bool, previewReviewStore: PreviewReviewStore? = nil, - photosEditedVersionCounts: PhotosImportEditedVersionCounts? = nil + photosEditedVersionCounts: PhotosImportEditedVersionCounts? = nil, + organizeAllowanceRemaining: Int? = nil ) { self.init( context: RunWorkspaceContext( @@ -213,7 +235,8 @@ struct RunWorkspaceModel { previewReviewPath: runSessionStore.summary?.artifacts.previewReviewPath, currentFileURL: runSessionStore.currentFileURL, isCancelling: runSessionStore.isCancelling, - photosEditedVersionCounts: photosEditedVersionCounts + photosEditedVersionCounts: photosEditedVersionCounts, + organizeAllowanceRemaining: organizeAllowanceRemaining ) ) } @@ -253,6 +276,48 @@ struct RunWorkspaceModel { || outcomeMetrics.hashErrorCount > 0 || context.issueCount > 0 } + /// Evaluated only for a ready, current preview with something to copy; every + /// other situation is `.notMetered` so the hero stays as it was. + var freeCopyState: RunFreeCopyState { + guard context.status == .dryRunFinished, + context.metrics.plannedCount > 0, + !context.previewReviewIsStale, + let remaining = context.organizeAllowanceRemaining + else { return .notMetered } + + let planned = context.metrics.plannedCount + if remaining <= 0 { return .spent(planned: planned) } + if planned <= remaining { return .fits(remaining: remaining) } + + let options = FreeMonthBatchPlanner.options( + newFilesByMonth: context.metrics.newFilesByMonth, + remaining: remaining + ) + return .overAllowance( + remaining: remaining, + planned: planned, + options: options, + suggested: FreeMonthBatchPlanner.suggestedOption(options) + ) + } + + /// The extra line under the preview headline when the plan is over the free + /// limit; nil when the limit is not in play. + var freeCopyLine: String? { + RunFreeCopyText.line(for: freeCopyState) + } + + private var previewPrimaryAction: RunHeroPrimaryAction { + switch freeCopyState { + case .notMetered, .fits: + return .transfer + case let .overAllowance(_, _, _, suggested): + return suggested == nil ? .unlockEverything : .freeMonthCopy + case .spent: + return .unlockEverything + } + } + var heroState: RunHeroState { switch context.status { case .idle: @@ -312,7 +377,7 @@ struct RunWorkspaceModel { badgeSymbol: "checkmark.circle.fill", heroSymbol: "doc.text.magnifyingglass", tone: .ready, - primaryAction: .transfer + primaryAction: previewPrimaryAction ) case .finished where hasOutcomeIssues: @@ -875,3 +940,74 @@ struct RunWorkspaceModel { ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) } } + +/// The words of the free-limit line and buttons, as pure functions so they can +/// be tested without a view (FRX C-07). +/// +/// Every sentence is a `%@` template looked up whole and filled in afterwards, +/// never an interpolated sentence looked up. +enum RunFreeCopyText { + static func line(for state: RunFreeCopyState) -> String? { + switch state { + case .notMetered, .fits: + return nil + + case let .overAllowance(remaining, planned, _, suggested): + let counts = String( + format: AppLocalization.string("You can copy %1$@ free. This plan has %2$@."), + PluralPhrases.files(remaining), + planned.formatted() + ) + guard let suggested else { return counts } + let month = monthYearName(forKey: suggested.key) + let advice = suggested.fits + ? String( + format: AppLocalization.string("The newest month that fits is %1$@: %2$@."), + month, + PluralPhrases.files(suggested.fileCount) + ) + : AppLocalization.format("%@ is larger than that, so the free copy takes its first days.", month) + return counts + " " + advice + + case let .spent(planned): + return AppLocalization.format( + "Your free copies are used up. This plan has %@.", + PluralPhrases.files(planned) + ) + } + } + + /// `Copy {Month Year} Free…` + static func copyButtonTitle(for option: FreeMonthOption) -> String { + AppLocalization.format("Copy %@ Free…", monthYearName(forKey: option.key)) + } + + /// `{Month Year} · {fileCount} files` + static func menuTitle(for option: FreeMonthOption) -> String { + "\(monthYearName(forKey: option.key)) · \(PluralPhrases.files(option.fileCount))" + } + + /// A month that does not fit is disabled unless it is the suggested one. + static func isMenuOptionEnabled(_ option: FreeMonthOption, suggested: FreeMonthOption?) -> Bool { + option.fits || option.key == suggested?.key + } + + /// `"2026-10"` as "October 2026" in the current locale; a key that is not + /// `yyyy-MM` is shown as it is. + static func monthYearName(forKey key: String) -> String { + let parts = key.split(separator: "-") + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC") ?? calendar.timeZone + guard parts.count == 2, + let year = Int(parts[0]), let month = Int(parts[1]), + let date = calendar.date(from: DateComponents(year: year, month: month, day: 1)) + else { return key } + + let formatter = DateFormatter() + formatter.locale = .current + formatter.calendar = calendar + formatter.timeZone = calendar.timeZone + formatter.setLocalizedDateFormatFromTemplate("MMMMyyyy") + return formatter.string(from: date) + } +} diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index 6bcca923..2216ac4f 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -1,6 +1,9 @@ #if canImport(ChronoframeAppCore) import ChronoframeAppCore #endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif import Combine import Foundation import XCTest @@ -1102,6 +1105,192 @@ final class AppStateTests: XCTestCase { await appState.removeSourceItem(listed) XCTAssertFalse(appState.hasActiveWatchedImport, "Removing a folder drops the pending import") } + + // MARK: - Free limit on the preview (FRX C-07) + + /// An App Store-channel state with nothing used from the organize allowance, + /// built on the harness's stores so its mock engine records what is asked. + @MainActor + private func makeMeteredState( + harness: AppStateHarness, + organizeUsed: Int = 0 + ) -> AppState { + let accountKey = "frx-wp04-account" + let ledger = InMemoryTrialLedger() + if organizeUsed > 0 { + _ = try? ledger.reserve( + runID: UUID(), accountKey: accountKey, meter: .organize, + count: organizeUsed, destinationRoot: "/tmp/destination" + ) + } + let trialStore = TrialStatusStore(ledger: ledger) + trialStore.refresh(entitlement: .locked, accountKey: accountKey) + harness.setupStore.sourcePath = "/tmp/source" + harness.setupStore.destinationPath = "/tmp/destination" + return AppState( + preferencesStore: harness.preferencesStore, + setupStore: harness.setupStore, + runLogStore: harness.runLogStore, + historyStore: harness.historyStore, + runSessionStore: harness.runSessionStore, + deduplicateSessionStore: harness.deduplicateSessionStore, + photosImportStore: PhotosImportStore( + access: AppStatePhotosAccessStub(), + catalog: AppStatePhotosCatalogStub(), + exporter: AppStatePhotosExporterStub(), + stagingParentURL: harness.photosStagingParent + ), + folderAccessService: harness.folderAccessService, + finderService: harness.finderService, + profilesRepository: harness.repository, + performInitialBootstrap: false, + restoreBookmarksDuringBootstrap: false, + trialStatusStore: trialStore, + isAppStoreChannel: true, + volumeClassifier: AppStateHarness.localClassifier + ) + } + + @MainActor + func testStartFreeMonthCopyRequestsAProposalForThatMonth() async throws { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness, organizeUsed: 120) + let options = FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 212, "2026-09": 148], remaining: 380) + let september = try XCTUnwrap(options.first { $0.key == "2026-09" }) + + await state.startFreeMonthCopy(september) + let started = await waitForCondition { harness.engine.startBatches.count == 1 } + + XCTAssertTrue(started) + XCTAssertEqual(harness.engine.startBatches.count, 1) + let batch = try XCTUnwrap(harness.engine.startBatches.first) + XCTAssertEqual(batch.monthRequest, FreeMonthRequest(key: "2026-09", limit: 380)) + XCTAssertTrue(batch.isEmpty, "A request confirms no file; the sheet that follows lists them") + XCTAssertEqual(harness.engine.startConfigurations.count, 1) + } + + @MainActor + func testOverAllowanceScenarioPreviewMatchesTheFixtureContract() async throws { + let appState = UITestAppStateFactory.make(scenario: .runPreviewOverAllowance) + let finished = await waitForCondition(timeoutNanoseconds: 2_000_000_000) { + appState.runSessionStore.summary?.status == .dryRunFinished + } + XCTAssertTrue(finished) + let metrics = try XCTUnwrap(appState.runSessionStore.summary?.metrics) + XCTAssertEqual(metrics.discoveredCount, 18_475) + XCTAssertEqual(metrics.plannedCount, 18_412) + XCTAssertEqual(metrics.alreadyInDestinationCount, 63) + XCTAssertEqual(metrics.duplicateCount, 1_204) + XCTAssertEqual(metrics.newFilesByMonth, ["2026-10": 212, "2026-09": 148, "2026-08": 734]) + XCTAssertGreaterThanOrEqual(metrics.dateHistogram.count, 14) + XCTAssertEqual(metrics.dateHistogram.last?.key, "2026-10") + XCTAssertTrue(appState.isAppStoreChannel) + await appState.refreshTrialStatus() + XCTAssertEqual(appState.organizeAllowanceRemaining, 500) + } + + @MainActor + func testStartFreeMonthCopyDoesNothingWithoutAKnownAllowance() async throws { + let harness = AppStateHarness() + harness.setupStore.sourcePath = "/tmp/source" + harness.setupStore.destinationPath = "/tmp/destination" + // The default test channel is not the App Store build: nothing is metered. + let state = harness.makeAppState(performInitialBootstrap: false) + let option = try XCTUnwrap( + FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 10], remaining: 500).first + ) + + await state.startFreeMonthCopy(option) + + XCTAssertTrue(harness.engine.startBatches.isEmpty) + XCTAssertTrue(harness.engine.startConfigurations.isEmpty) + state.requestUnlockForPlan(requested: 600) + XCTAssertNil(state.requestedUnlockRefusal) + XCTAssertNil(state.unlockRefusal) + } + + @MainActor + func testRequestUnlockForPlanPresentsOrganizeRefusal() async { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness, organizeUsed: 120) + harness.engine.startMode = .events([ + .complete(RunSummary( + status: .dryRunFinished, + title: "Preview complete", + metrics: RunMetrics(plannedCount: 18_412), + artifacts: RunArtifactPaths(destinationRoot: "/tmp/destination") + )) + ]) + await state.startPreview() + let previewed = await waitForCondition { harness.runSessionStore.summary?.status == .dryRunFinished } + XCTAssertTrue(previewed) + XCTAssertNil(state.unlockRefusal) + + state.requestUnlockForPlan() + + let expected = TrialAuthorizationRefusal.allowanceSpent( + TrialRefusal(meter: .organize, requested: 18_412, remaining: 380) + ) + XCTAssertEqual(state.requestedUnlockRefusal, expected) + XCTAssertEqual(state.unlockRefusal, expected) + + state.requestUnlockForPlan(requested: 77) + XCTAssertEqual( + state.unlockRefusal, + .allowanceSpent(TrialRefusal(meter: .organize, requested: 77, remaining: 380)) + ) + } + + @MainActor + func testDismissUnlockSheetClearsRequestedRefusal() { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness) + state.requestUnlockForPlan(requested: 600) + XCTAssertNotNil(state.unlockRefusal) + + state.dismissUnlockSheet() + + XCTAssertNil(state.requestedUnlockRefusal) + XCTAssertNil(state.unlockRefusal) + } + + @MainActor + func testRetryAfterUnlockWithRequestedRefusalStartsNothing() async { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness) + state.requestUnlockForPlan(requested: 600) + XCTAssertNotNil(state.unlockRefusal) + + await state.retryAfterUnlock() + + XCTAssertNil(state.requestedUnlockRefusal) + XCTAssertNil(state.unlockRefusal, "The sheet must not reopen for an unlocked customer") + XCTAssertTrue(harness.engine.preflightConfigurations.isEmpty) + XCTAssertTrue(harness.engine.startConfigurations.isEmpty) + XCTAssertTrue(harness.engine.startBatches.isEmpty) + XCTAssertNil(harness.runSessionStore.prompt) + XCTAssertNil(harness.runSessionStore.summary) + XCTAssertFalse(harness.deduplicateSessionStore.isWorking) + } + + @MainActor + func testRetryAfterUnlockClearsAStaleRequestedRefusalBehindARunRefusal() async { + let harness = AppStateHarness() + let state = makeMeteredState(harness: harness) + state.requestUnlockForPlan(requested: 600) + harness.engine.startMode = .fails(TrialAuthorizationError(refusal: .allowanceSpent( + TrialRefusal(meter: .organize, requested: 600, remaining: 0) + ))) + await state.startPreview() + let refused = await waitForCondition { harness.runSessionStore.lastRefusal != nil } + XCTAssertTrue(refused) + harness.engine.startMode = .events([]) + + await state.retryAfterUnlock() + + XCTAssertNil(state.requestedUnlockRefusal) + XCTAssertNil(state.unlockRefusal) + } } private final class RecordingDedupeSnapshotStore: DeduplicateReviewSnapshotStoring, @unchecked Sendable { diff --git a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift index 9ab07054..adbd7dc9 100644 --- a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift @@ -1,6 +1,9 @@ #if canImport(ChronoframeAppCore) import ChronoframeAppCore #endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif import XCTest @testable import ChronoframeApp @@ -496,6 +499,192 @@ final class RunWorkspaceModelTests: XCTestCase { ) } + // MARK: - Free limit on the preview (FRX C-07) + + private func freeCopyModel( + status: RunStatus = .dryRunFinished, + planned: Int, + remaining: Int?, + newFilesByMonth: [String: Int] = [:], + stale: Bool = false + ) -> RunWorkspaceModel { + RunWorkspaceModel( + context: RunWorkspaceContext( + status: status, + currentMode: .preview, + currentTaskTitle: "", + currentPhase: nil, + progress: 1, + metrics: RunMetrics(plannedCount: planned, newFilesByMonth: newFilesByMonth), + summary: nil, + lastErrorMessage: nil, + warningCount: 0, + errorCount: 0, + issueCount: 0, + logEntries: [], + historyDestinationRoot: "/Volumes/Archive", + currentSourceRoot: "/Volumes/Ingest", + canStartRun: true, + previewReviewIsStale: stale, + organizeAllowanceRemaining: remaining + ) + ) + } + + private func monthYear(_ key: String) -> String { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "UTC") ?? calendar.timeZone + let parts = key.split(separator: "-").compactMap { Int($0) } + let date = calendar.date(from: DateComponents(year: parts[0], month: parts[1], day: 1)) ?? Date() + let formatter = DateFormatter() + formatter.locale = .current + formatter.calendar = calendar + formatter.timeZone = calendar.timeZone + formatter.setLocalizedDateFormatFromTemplate("MMMMyyyy") + return formatter.string(from: date) + } + + func testFreeCopyStateNotMeteredWithoutAllowance() { + XCTAssertEqual(freeCopyModel(planned: 18_412, remaining: nil).freeCopyState, .notMetered) + XCTAssertNil(freeCopyModel(planned: 18_412, remaining: nil).freeCopyLine) + XCTAssertEqual(freeCopyModel(planned: 18_412, remaining: nil).heroState.primaryAction, .transfer) + // Not a ready preview: nothing to evaluate even with a balance. + XCTAssertEqual(freeCopyModel(status: .running, planned: 18_412, remaining: 500).freeCopyState, .notMetered) + XCTAssertEqual(freeCopyModel(status: .finished, planned: 18_412, remaining: 500).freeCopyState, .notMetered) + XCTAssertEqual(freeCopyModel(planned: 0, remaining: 500).freeCopyState, .notMetered) + } + + func testFreeCopyStateFitsWhenPlanWithinAllowance() { + XCTAssertEqual(freeCopyModel(planned: 40, remaining: 500).freeCopyState, .fits(remaining: 500)) + XCTAssertEqual(freeCopyModel(planned: 500, remaining: 500).freeCopyState, .fits(remaining: 500)) + let model = freeCopyModel(planned: 40, remaining: 500) + XCTAssertEqual(model.heroState.primaryAction, .transfer) + XCTAssertNil(model.freeCopyLine) + } + + func testFreeCopyStateOverAllowanceSuggestsNewestFittingMonth() { + // 2026-10 is the newest month but does not fit; 2026-09 is the newest that does. + let byMonth = ["2026-10": 900, "2026-09": 148, "2026-08": 40] + let state = freeCopyModel(planned: 18_412, remaining: 500, newFilesByMonth: byMonth).freeCopyState + let options = FreeMonthBatchPlanner.options(newFilesByMonth: byMonth, remaining: 500) + XCTAssertEqual( + state, + .overAllowance( + remaining: 500, planned: 18_412, options: options, + suggested: FreeMonthBatchPlanner.suggestedOption(options) + ) + ) + guard case let .overAllowance(_, _, listed, suggested) = state else { + return XCTFail("Expected overAllowance, got \(state)") + } + XCTAssertEqual(listed.map(\.key), ["2026-10", "2026-09", "2026-08"]) + XCTAssertEqual(suggested?.key, "2026-09") + XCTAssertEqual(suggested?.fileCount, 148) + + // Nothing dated and new: still over, but nothing to offer. + guard case let .overAllowance(_, _, noOptions, noSuggestion) = freeCopyModel(planned: 90, remaining: 50).freeCopyState else { + return XCTFail("Expected overAllowance without options") + } + XCTAssertTrue(noOptions.isEmpty) + XCTAssertNil(noSuggestion) + } + + func testFreeCopyStateSpentWhenNothingRemains() { + XCTAssertEqual(freeCopyModel(planned: 300, remaining: 0).freeCopyState, .spent(planned: 300)) + XCTAssertEqual(freeCopyModel(planned: 300, remaining: -3).freeCopyState, .spent(planned: 300)) + let model = freeCopyModel(planned: 300, remaining: 0, newFilesByMonth: ["2026-10": 10]) + XCTAssertEqual(model.heroState.primaryAction, .unlockEverything) + XCTAssertEqual( + model.freeCopyLine, + "Your free copies are used up. This plan has \(300.formatted()) files." + ) + XCTAssertEqual( + freeCopyModel(planned: 1, remaining: 0).freeCopyLine, + "Your free copies are used up. This plan has 1 file." + ) + } + + func testFreeCopyStateNotOfferedForStalePreview() { + let byMonth = ["2026-10": 212] + XCTAssertEqual( + freeCopyModel(planned: 18_412, remaining: 500, newFilesByMonth: byMonth, stale: true).freeCopyState, + .notMetered + ) + XCTAssertEqual( + freeCopyModel(planned: 18_412, remaining: 0, newFilesByMonth: byMonth, stale: true).freeCopyState, + .notMetered + ) + // Stale previews keep the existing disabled Start Copying. + XCTAssertEqual( + freeCopyModel(planned: 18_412, remaining: 500, newFilesByMonth: byMonth, stale: true).heroState.primaryAction, + .transfer + ) + } + + func testOverAllowanceHeroHidesStartCopying() { + let withMonths = freeCopyModel(planned: 18_412, remaining: 500, newFilesByMonth: ["2026-10": 212]) + XCTAssertEqual(withMonths.heroState.primaryAction, .freeMonthCopy) + XCTAssertNotEqual(withMonths.heroState.primaryAction, .transfer) + + // No dated new files: only "Unlock to Copy Everything" is offered. + let noMonths = freeCopyModel(planned: 18_412, remaining: 500) + XCTAssertEqual(noMonths.heroState.primaryAction, .unlockEverything) + XCTAssertNotEqual(noMonths.heroState.primaryAction, .transfer) + + // The rest of the hero is untouched. + XCTAssertEqual(withMonths.heroState.title, "Preview ready") + XCTAssertEqual(withMonths.heroState.badgeTitle, "Preview ready") + } + + func testOverAllowanceLineNamesBothNumbersAndTheSuggestedMonth() { + let fitting = freeCopyModel( + planned: 18_412, remaining: 500, + newFilesByMonth: ["2026-10": 212, "2026-09": 148, "2026-08": 734] + ) + XCTAssertEqual( + fitting.freeCopyLine, + "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()). " + + "The newest month that fits is \(monthYear("2026-10")): \(212.formatted()) files." + ) + + // A single file in the suggested month takes the file's singular form. + XCTAssertEqual( + freeCopyModel(planned: 900, remaining: 500, newFilesByMonth: ["2026-10": 1]).freeCopyLine, + "You can copy \(500.formatted()) files free. This plan has \(900.formatted()). " + + "The newest month that fits is \(monthYear("2026-10")): 1 file." + ) + + // Every month is bigger than what is left: the free copy takes its first days. + XCTAssertEqual( + freeCopyModel(planned: 18_412, remaining: 500, newFilesByMonth: ["2026-10": 900, "2026-09": 700]).freeCopyLine, + "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted()). " + + "\(monthYear("2026-10")) is larger than that, so the free copy takes its first days." + ) + + // No options: the numbers alone. + XCTAssertEqual( + freeCopyModel(planned: 18_412, remaining: 500).freeCopyLine, + "You can copy \(500.formatted()) files free. This plan has \(18_412.formatted())." + ) + XCTAssertEqual( + freeCopyModel(planned: 18_412, remaining: 1).freeCopyLine, + "You can copy 1 file free. This plan has \(18_412.formatted())." + ) + } + + func testFreeMonthButtonAndMenuTitles() { + let options = FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 212, "2026-08": 734], remaining: 500) + XCTAssertEqual(RunFreeCopyText.copyButtonTitle(for: options[0]), "Copy \(monthYear("2026-10")) Free…") + XCTAssertEqual(RunFreeCopyText.menuTitle(for: options[0]), "\(monthYear("2026-10")) · \(212.formatted()) files") + XCTAssertEqual(RunFreeCopyText.menuTitle(for: options[1]), "\(monthYear("2026-08")) · \(734.formatted()) files") + let suggested = FreeMonthBatchPlanner.suggestedOption(options) + // The suggested month is always enabled; one that does not fit is not. + XCTAssertTrue(RunFreeCopyText.isMenuOptionEnabled(options[0], suggested: suggested)) + XCTAssertFalse(RunFreeCopyText.isMenuOptionEnabled(options[1], suggested: suggested)) + let partial = FreeMonthBatchPlanner.options(newFilesByMonth: ["2026-10": 900], remaining: 500) + XCTAssertTrue(RunFreeCopyText.isMenuOptionEnabled(partial[0], suggested: FreeMonthBatchPlanner.suggestedOption(partial))) + } + // MARK: - Helpers private func makeModel(status: RunStatus, discoveredCount: Int = 0) -> RunWorkspaceModel { diff --git a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift index 478db396..46d0919b 100644 --- a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift +++ b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift @@ -50,6 +50,13 @@ final class ScreenRenderEvidenceTests: XCTestCase { XCTAssertTrue(FileManager.default.fileExists(atPath: path), "Expected \(path) to be written", file: file, line: line) } + func testRenderPreviewOverAllowance() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .runPreviewOverAllowance) + try await render(RootSplitView(appState: appState), name: "m1-preview-over-allowance") + assertWritten("m1-preview-over-allowance") + } + func testRenderCopyComplete() async throws { try requireEvidenceMarker() let appState = UITestAppStateFactory.make(scenario: .runCopyComplete) diff --git a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift index 7ee7f715..87680168 100644 --- a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift +++ b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift @@ -51,6 +51,22 @@ final class UITestWindowFitTests: XCTestCase { XCTAssertEqual(pinned.maxY, visible.maxY) } + func testOverAllowancePreviewScenarioIsMeteredAndSizedLikeThePreviewScenario() { + let scenario = UITestScenario.runPreviewOverAllowance + XCTAssertEqual(UITestScenario(rawValue: "runPreviewOverAllowance"), scenario) + XCTAssertTrue(scenario.usesMeteredTrialUI) + XCTAssertFalse(scenario.opensSettingsOnLaunch) + XCTAssertEqual(scenario.preferredMainWindowSize, UITestScenario.runPreviewReview.preferredMainWindowSize) + XCTAssertEqual(scenario.preferredMainWindowSize, NSSize(width: 1360, height: 920)) + + // 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 + ) + XCTAssertEqual(size, NSSize(width: 1024, height: 638)) + } + func testVisibleSizeOverrideParsesWidthByHeightOnly() { let key = UITestScenario.visibleSizeOverrideKey XCTAssertEqual(UITestScenario.visibleSizeOverride(environment: [key: "1024x720"]), NSSize(width: 1024, height: 720)) diff --git a/ui/Tests/ChronoframeAppTests/UnlockSheetLayoutTests.swift b/ui/Tests/ChronoframeAppTests/UnlockSheetLayoutTests.swift index dd9eb03f..b8d388ca 100644 --- a/ui/Tests/ChronoframeAppTests/UnlockSheetLayoutTests.swift +++ b/ui/Tests/ChronoframeAppTests/UnlockSheetLayoutTests.swift @@ -103,6 +103,41 @@ final class UnlockSheetLayoutTests: XCTestCase { } } } + + /// The terms line is the sheet's own wiring of `UnlockSheetModel.purchaseTermsLine` + /// (FRX C-06), so this reads what the sheet will draw rather than pixels. + func testPurchaseTermsLineIsShown() async { + let store = EntitlementStore( + storeKit: LayoutStore(displayName: "Chronoframe Unlock", displayPrice: "$14.99"), + appTransactionClient: LayoutTransaction(), + defaults: .standard + ) + await store.loadProduct() + let terms = "One-time purchase with Family Sharing. No subscription." + + let spent = UnlockSheet( + refusal: .allowanceSpent(TrialRefusal(meter: .organize, requested: 18_412, remaining: 0)), + entitlementStore: store, onUnlocked: {}, onDismiss: {} + ) + XCTAssertEqual(spent.termsLine, terms) + + let requiresUnlock = UnlockSheet( + refusal: .requiresUnlock, + entitlementStore: store, onUnlocked: {}, onDismiss: {} + ) + XCTAssertEqual(requiresUnlock.termsLine, terms) + + // Could not confirm a purchase that may already exist: no sales line. + let unconfirmed = UnlockSheet( + refusal: .purchaseUnconfirmed(TrialRefusal(meter: .organize, requested: 5, remaining: 0)), + entitlementStore: store, onUnlocked: {}, onDismiss: {} + ) + XCTAssertNil(unconfirmed.termsLine) + + // The voluntary sheet's message already says it. + let voluntary = UnlockSheet(refusal: nil, entitlementStore: store, onUnlocked: {}, onDismiss: {}) + XCTAssertNil(voluntary.termsLine) + } } private struct LayoutStore: StoreKitClient { From 44ce018942f179591f9109c842b01bdb66688caa Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:26:16 -0800 Subject: [PATCH 08/30] FRX WP-05: App: accounted-for line, Undo, add another folder Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 10 +- .../App/AccessibilityIdentifiers.swift | 6 +- ui/Sources/ChronoframeApp/App/AppState.swift | 31 ++ .../App/UITesting/UITestAppStateFactory.swift | 66 +++- .../Views/Run/CurrentRunView.swift | 83 ++++- .../Views/Run/RunAccountingText.swift | 150 +++++++++ .../Views/Run/RunSectionViews.swift | 8 + .../ChronoframeAppTests/AppStateTests.swift | 290 ++++++++++++++++++ .../RunAccountingTextTests.swift | 228 ++++++++++++++ .../RunWorkspaceModelTests.swift | 121 ++++++++ 11 files changed, 981 insertions(+), 13 deletions(-) create mode 100644 ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift create mode 100644 ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 9cebaa3c..aa936297 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -51,3 +51,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-103 Month-request branch placement and guard (WP-03).** C-06 says the branch goes "directly after planning and the zero-transfer branches, before `plan.reduced(to:)`", but in the code the zero-transfer branches come after `reduced`. The branch sits after `planAsync` and the cancellation check, immediately before `plan.reduced(to:)`, and is guarded with `plan.transferCount > 0`. An empty plan falls through: the request confirms no file, reduces to nothing and takes the existing "Nothing left to copy" return, which is ahead of `authorizeTransfer`. The literal one-liner would have raised an unlock sheet for 0 files. Known wart: that existing warning ("None of the files in that batch are still where they were…") is slightly off for a request; left alone (fewest changed lines). - **D-FRX-104 Free-month sheet details (WP-03).** (a) `proposingFreeMonth` sets `wasRequested: true` on the suggested-month fallback too; the title names the month actually offered. (b) It does not apply the covers-whole-plan check (C-06 gives that rule only to `offeringFreeMonthBatch`); the sheet's existing `offerableBatch` still drops such a batch. (c) With a failed price load a requested-month sheet keeps the requested message. (d) Singular forms added per the copy rule: `Organize all %@ file`, `Remove all %@ duplicate`, `This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.` (e) `TrialRemaining.value` is also nil while the entitlement is resolving. (f) The two builders are internal, not public. (g) `TrialAuthorizer.swift` gained one private helper `monthBatch` shared by the two builders. - **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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index b25b5736..ec366881 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -16,9 +16,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-01 | Render evidence harness | done | build exit 0 | `test ScreenRenderEvidenceTests` exit 0 (3 skipped without marker; 3 run, 3 PNGs with marker) | approve (round 1) | fb09f36 | rendered: harness produces non-blank PNGs; D-FRX-101 | | WP-02 | Core: accounting, free month, model fields | done | build exit 0 | RunAccounting 8, FreeMonthBatchPlanner 14, FreeTestBatchPlanner 19 tests, all exit 0 | approve (round 1) | 682f714 | orchestrator read the FreeTestBatchPlanner.swift and RunModels.swift diffs: additions only; D-FRX-102 | | WP-03 | AppCore: engine, offer, unlock presentation | done | build exit 0 | TrialRemaining 4, FreeMonthBatchOffer 11, UnlockPresentation 19, UnlockSheetBatchOffer 14, FreeTestBatchOffer 9, FreeTestBatchRun 4, SwiftOrganizerEngineIntegration 43 tests, all exit 0 | approve (round 1) | c1dee6f | orchestrator read the full SwiftOrganizerEngine.swift and TrialAuthorizer.swift diffs: every changed line traces to C-03/C-06; the month-request branch throws before `plan.reduced(to:)`, so it reaches neither `authorizeTransfer` nor the job queue; D-FRX-103, D-FRX-104 | -| 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) | (WP-04 commit) | 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 | in-progress | | | | | INV-8 tag on the undo test | -| WP-06 | Docs and strings, M1 | todo | | | | | | +| 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) | (WP-05 commit) | 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 | in-progress | | | | | | | G1 | Gate, M1 | todo | | | n/a | | | | WP-10 | Branch and baseline, M2 | todo | | | n/a | | | | WP-11 | Core: review lane, free removal batch | todo | | | | | safety-critical; extra opus review | @@ -36,6 +36,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled ## Existing assertions changed (D-FRX-20) | WP | Test file:line | Old expectation | New expectation | Contract | |---|---|---|---|---| +| 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 | ## Renders checked | Gate | File | Checked against | Result | @@ -50,3 +52,5 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - WP-04 strings for WP-06 (App catalog). Templates in `RunWorkspaceModel.swift` looked up via AppLocalization: `You can copy %1$@ free. This plan has %2$@.`; `The newest month that fits is %1$@: %2$@.`; `%@ is larger than that, so the free copy takes its first days.`; `Your free copies are used up. This plan has %@.`; `Copy %@ Free…`. SwiftUI literals in `RunSectionViews.swift`: `Choose Another Month`; `Unlock to Copy Everything`; `Shows the files first. Nothing is copied until you confirm`. - For G1 step 4: `ui/Xcode/UITests/ChronoframeUITests.swift:545` and `:547` assert `discovered: 84` for `runPreviewReview` (WP-05 changes it to 72); the UI-test `Scenario` enum has no `runPreviewOverAllowance` case (none is needed unless a UI test uses it). - Noticed, not fixed: in the `runPreviewOverAllowance` fixture the Timeline header reads "21,140 planned files" while the plan has 18,412 (the fixture histogram does not sum to the plan). Fixture-only. +- 2026-11-28 WP-05 Done-when (orchestrator): `cf_swift.sh test` exit 0 for RunAccountingTextTests (9), RunWorkspaceModelTests (29), AppStateTests (49), RunOutcomeAccuracyTests (14), AccessibilityTests (8), ScreenRenderEvidenceTests (4 run with marker, 4 PNGs); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `script/check_no_raw_animations.sh` exit 0; `git diff --check` exit 0. No test assertion changed; two fixture values changed (table above). +- For G1 step 4: `ui/Xcode/UITests/A11yBaseline.json:48,50` hold "84, FOUND" for `runPreviewReview` and `:343` is the `runCopyComplete` baseline (gains the accounting line, Undo and Add Another Folder elements). diff --git a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift index 14353ad8..e6c061a9 100644 --- a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift +++ b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift @@ -44,6 +44,9 @@ enum AccessibilityIdentifiers { static let runWorkspaceTabs = "runWorkspaceTabs" static let runIdleOnboardingCard = "runIdleOnboardingCard" static let runOutcomeSummaryCard = "runOutcomeSummaryCard" + static let runOutcomeUndoCopy = "runOutcomeUndoCopy" + static let runOutcomeAddFolder = "runOutcomeAddFolder" + static let runOutcomeUnlockRest = "runOutcomeUnlockRest" static let runPreviewSummary = "run.preview.summary" static let runNextStepCard = "run.nextStep.card" static let runNextStepFindDuplicates = "run.nextStep.findDuplicates" @@ -183,7 +186,8 @@ enum AccessibilityIdentifiers { consoleScrollView, openDestinationButton, openReportButton, openLogsButton, startTransferFromPreviewButton, runFreeMonthCopy, runFreeMonthMenu, runUnlockEverything, runWorkspaceTabs, runIdleOnboardingCard, - runOutcomeSummaryCard, runPreviewSummary, previewReviewFilter, + runOutcomeSummaryCard, runOutcomeUndoCopy, runOutcomeAddFolder, runOutcomeUnlockRest, + runPreviewSummary, previewReviewFilter, refreshLibraryHealthButton, reorganizeDestinationButton, dedupeAcceptAllSuggestionsButton, dedupeAcceptClusterSuggestionButton, dedupeAcceptHighConfidenceButton, dedupeCancelCommitButton, dedupeChangeFolderButton, diff --git a/ui/Sources/ChronoframeApp/App/AppState.swift b/ui/Sources/ChronoframeApp/App/AppState.swift index f32c58cf..c4fe278a 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -977,6 +977,37 @@ final class AppState: ObservableObject { historyCoordinator.revertHistoryEntry(entry) } + /// The organize receipt of the copy that just finished, when History has + /// indexed it: a finished transfer whose summary names a receipt that is in + /// History's list (FRX C-04). Nil for a preview, an undo, a failed run or a + /// copy whose receipt is not in History. + var lastCopyUndoEntry: RunHistoryEntry? { + guard runSessionStore.status == .finished, + runSessionStore.currentMode == .transfer, + let receiptPath = runSessionStore.summary?.artifacts.receiptPath + else { return nil } + // History lists a folder through its real location, so the same receipt + // can be spelled differently (/var and /private/var, a symlinked + // Pictures folder). Match the file name first, then compare locations. + let receiptURL = URL(fileURLWithPath: receiptPath) + let receiptName = receiptURL.lastPathComponent + let resolvedReceiptPath = receiptURL.resolvingSymlinksInPath().path + return historyStore.entries.first { entry in + guard entry.kind == .auditReceipt, + URL(fileURLWithPath: entry.path).lastPathComponent == receiptName + else { return false } + return entry.path == receiptPath + || URL(fileURLWithPath: entry.path).resolvingSymlinksInPath().path == resolvedReceiptPath + } + } + + /// Undo the copy that just finished. This is `revertHistoryEntry` on that + /// receipt and nothing more: the same hash-checked revert History uses. + func undoLastCopy() { + guard let entry = lastCopyUndoEntry else { return } + revertHistoryEntry(entry) + } + /// Reorganize the current destination so its folder layout matches the /// preferred `FolderStructure`. Streams progress through the Run workspace. func reorganizeDestination(targetStructure: FolderStructure) { diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index 5ed75f39..62e0d914 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -113,8 +113,20 @@ enum UITestAppStateFactory { let fixture = multiFolderFixture() setupStore.sourcePath = "/Volumes/Card/April Session" setupStore.destinationPath = fixture.destination.path - historyStore = HistoryStore(destinationRoot: setupStore.destinationPath) - engine = copyCompleteEngine(sourcePath: setupStore.sourcePath, destinationPath: setupStore.destinationPath) + // The receipt is a real file in the scenario-owned destination: a + // finished run re-reads History from disk, so a receipt that only + // existed in memory would vanish and Undo would never render. + let receiptPath = copyCompleteReceiptPath(destinationPath: setupStore.destinationPath) + historyStore = HistoryStore( + entries: [copyCompleteReceiptEntry(receiptPath: receiptPath)], + destinationRoot: setupStore.destinationPath + ) + seedCopyCompleteReceiptFile(atPath: receiptPath) + engine = copyCompleteEngine( + sourcePath: setupStore.sourcePath, + destinationPath: setupStore.destinationPath, + receiptPath: receiptPath + ) route = .organize(.run) case .previewDateConflict: @@ -371,10 +383,47 @@ enum UITestAppStateFactory { } } - /// A finished copy: 4,200 files copied, 37 exact copies set aside. - private static func copyCompleteEngine(sourcePath: String, destinationPath: String) -> MockOrganizerEngine { + /// Where the finished copy's receipt lives, named as the engine names it. + private static func copyCompleteReceiptPath(destinationPath: String) -> String { + "\(destinationPath)/.organize_logs/audit_receipt_20261128_101500_00000000-0000-0000-0000-000000000601.json" + } + + private static func copyCompleteReceiptEntry(receiptPath: String) -> RunHistoryEntry { + RunHistoryEntry( + kind: .auditReceipt, + title: "Transfer Receipt", + path: receiptPath, + relativePath: ".organize_logs/" + URL(fileURLWithPath: receiptPath).lastPathComponent, + fileSizeBytes: 2, + createdAt: Date(timeIntervalSinceReferenceDate: 786_000_000) + ) + } + + /// Writes a placeholder receipt into the scenario-owned destination. Undo is + /// only offered, never run, by the evidence renders and the UI tests. + private static func seedCopyCompleteReceiptFile(atPath receiptPath: String) { + let url = URL(fileURLWithPath: receiptPath) + do { + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + try Data("{}".utf8).write(to: url) + } catch { + preconditionFailure("Could not create the copy-complete UI fixture receipt: \(error)") + } + } + + /// A finished copy: 4,263 found = 4,163 new + 37 exact copies + 63 already + /// there; 4,200 copied (FRX C-08). + private static func copyCompleteEngine( + sourcePath: String, + destinationPath: String, + receiptPath: String + ) -> MockOrganizerEngine { + // A finished copy is a transfer run, which is what offers Undo. let preflight = RunPreflight( - configuration: RunConfiguration(mode: .preview, sourcePath: sourcePath, destinationPath: destinationPath), + configuration: RunConfiguration(mode: .transfer, sourcePath: sourcePath, destinationPath: destinationPath), resolvedSourcePath: sourcePath, resolvedDestinationPath: destinationPath ) @@ -382,7 +431,7 @@ enum UITestAppStateFactory { status: .finished, title: "Copy complete", metrics: RunMetrics( - discoveredCount: 4_300, + discoveredCount: 4_263, plannedCount: 4_200, alreadyInDestinationCount: 63, duplicateCount: 37, @@ -392,7 +441,8 @@ enum UITestAppStateFactory { destinationRoot: destinationPath, reportPath: "\(destinationPath)/.organize_logs/dry_run_report.csv", logFilePath: "\(destinationPath)/.organize_log.txt", - logsDirectoryPath: "\(destinationPath)/.organize_logs" + logsDirectoryPath: "\(destinationPath)/.organize_logs", + receiptPath: receiptPath ) ) return MockOrganizerEngine( @@ -506,7 +556,7 @@ enum UITestAppStateFactory { status: .dryRunFinished, title: "Preview complete", metrics: RunMetrics( - discoveredCount: 84, + discoveredCount: 72, plannedCount: 42, alreadyInDestinationCount: 29, duplicateCount: 7, diff --git a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift index 7ce936e4..936a829d 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift @@ -54,7 +54,7 @@ struct CurrentRunView: View { TrialIndicatorLabel(appState: appState, meter: .organize) if model.showsOutcomeSummary { - RunOutcomeSummaryCard(model: model, appState: appState) + RunOutcomeSummaryCard(model: model, appState: appState, undoEntry: appState.lastCopyUndoEntry) } if model.showsPreviewReview { @@ -131,6 +131,10 @@ struct CurrentRunView: View { private struct RunOutcomeSummaryCard: View { let model: RunWorkspaceModel let appState: AppState + /// Passed in, not read from `appState` here, so the card redraws when + /// History picks the receipt up. + let undoEntry: RunHistoryEntry? + @State private var pendingUndoEntry: RunHistoryEntry? var body: some View { MeridianSurfaceCard(tint: model.heroState.tone.color) { @@ -139,6 +143,14 @@ private struct RunOutcomeSummaryCard: View { Text("Summary") .scaledFont(.cardTitle) Spacer() + if let undoEntry { + Button("Undo This Copy…") { + pendingUndoEntry = undoEntry + } + .buttonStyle(.bordered) + .controlSize(.small) + .accessibilityIdentifier(AccessibilityIdentifiers.runOutcomeUndoCopy) + } Button("Open History") { appState.navigate(to: .organize(.history)) } @@ -146,6 +158,23 @@ private struct RunOutcomeSummaryCard: View { .controlSize(.small) } + if let accountingLine = model.accountingLine { + Text(verbatim: accountingLine) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } + + if showsUnlockRest { + Button("Unlock to Copy the Rest") { + appState.requestUnlockForPlan(requested: accounting.remainder) + } + .buttonStyle(.bordered) + .controlSize(.small) + .accessibilityIdentifier(AccessibilityIdentifiers.runOutcomeUnlockRest) + } + LazyVGrid(columns: [GridItem(.adaptive(minimum: 150), spacing: 10)], spacing: 10) { summaryMetric("Copied", value: model.outcomeMetrics.copiedCount.formatted(), tint: DesignTokens.ColorSystem.statusSuccess) summaryMetric("To Copy", value: model.outcomeMetrics.plannedCount.formatted(), tint: DesignTokens.ColorSystem.accentAction) @@ -165,6 +194,10 @@ private struct RunOutcomeSummaryCard: View { Text(model.outcomeSummaryMessage) .font(.caption) .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + + if model.context.status == .finished { + addAnotherFolder + } } } // A bare identifier makes an unnamed group, which the accessibility @@ -172,6 +205,54 @@ private struct RunOutcomeSummaryCard: View { .accessibilityElement(children: .contain) .accessibilityLabel("Summary") .accessibilityIdentifier(AccessibilityIdentifiers.runOutcomeSummaryCard) + .confirmationDialog( + RunHistoryView.confirmationTitle(for: pendingUndoEntry), + isPresented: Binding( + get: { pendingUndoEntry != nil }, + set: { if !$0 { pendingUndoEntry = nil } } + ), + presenting: pendingUndoEntry + ) { entry in + Button(RunHistoryView.confirmationActionLabel(for: entry), role: RunHistoryView.confirmationActionRole(for: entry)) { + appState.undoLastCopy() + pendingUndoEntry = nil + } + Button("Cancel", role: .cancel) { + pendingUndoEntry = nil + } + } message: { entry in + Text(RunHistoryView.confirmationMessage(for: entry)) + } + } + + private var accounting: RunAccounting { + RunAccounting.finished(model.outcomeMetrics) + } + + /// After a free copy that left photos waiting, while the free allowance is + /// in play (FRX C-07). + private var showsUnlockRest: Bool { + model.context.status == .finished + && RunAccountingText.showsUnlockRest( + accounting, + isFreeBatch: model.isFreeBatchCopy, + allowanceRemaining: model.context.organizeAllowanceRemaining + ) + } + + private var addAnotherFolder: some View { + VStack(alignment: .leading, spacing: 8) { + Text("Have more photos somewhere else? Add that folder next. Photos already in your library are skipped.") + .font(.caption) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + Button("Add Another Folder") { + appState.navigate(to: .organize(.setup)) + } + .buttonStyle(.bordered) + .controlSize(.small) + .accessibilityIdentifier(AccessibilityIdentifiers.runOutcomeAddFolder) + } } private func summaryMetric(_ title: String, value: String, tint: Color) -> some View { diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift b/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift new file mode 100644 index 00000000..41e72635 --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Run/RunAccountingText.swift @@ -0,0 +1,150 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// The "every photo is accounted for" sentences (FRX C-02, D-FRX-09). +/// +/// Evidence-bound: the balanced wording is used only when the categories add up +/// to the files found, and any disagreement reads as unbalanced. Nothing here +/// says or implies that anything may be removed from the source. +/// +/// Every sentence is a template looked up whole and filled in afterwards, never +/// an interpolated sentence looked up. A count that needs its own verb +/// ("1 is waiting", "10 are waiting") is a phrase of its own, composed into the +/// sentence, so each count agrees on its own. +enum RunAccountingText { + /// First line of the preview summary; nil when nothing was found. + static func previewLine(_ accounting: RunAccounting) -> String? { + guard accounting.found > 0 else { return nil } + + if accounting.isBalanced { + return accounting.found == 1 + ? AppLocalization.string("The 1 photo or video Chronoframe found is listed below.") + : AppLocalization.format( + "Every one of the %@ photos and videos Chronoframe found is listed below.", + accounting.found.formatted() + ) + } + + return String( + format: AppLocalization.string("Chronoframe found %1$@, and %2$@. Rebuild the preview before copying."), + PluralPhrases.photosAndVideos(accounting.found), + notInPlanPhrase(abs(accounting.remainder)) + ) + } + + /// First line of the completion summary; nil when nothing was found. + static func finishedLine(_ accounting: RunAccounting, isFreeBatch: Bool) -> String? { + guard accounting.found > 0 else { return nil } + + if accounting.isBalanced, accounting.notCopied == 0 { + let parts = balancedParts(accounting) + if !parts.isEmpty { + let joined = parts.joined(separator: ", ") + return accounting.found == 1 + ? AppLocalization.format("The 1 photo or video Chronoframe found is accounted for: %@.", joined) + : String( + format: AppLocalization.string("All %1$@ photos and videos Chronoframe found are accounted for: %2$@."), + accounting.found.formatted(), + joined + ) + } + } + + if accounting.notCopied > 0 { + return accounting.notCopied == 1 + ? AppLocalization.string("1 planned photo or video was not copied. Your originals were not changed. See Problems.") + : AppLocalization.format( + "%@ planned photos and videos were not copied. Your originals were not changed. See Problems.", + accounting.notCopied.formatted() + ) + } + + if isFreeBatch, accounting.remainder > 0 { + return String( + format: AppLocalization.string("Chronoframe found %1$@. This free copy handled %2$@; %3$@."), + PluralPhrases.photosAndVideos(accounting.found), + (accounting.found - accounting.remainder).formatted(), + waitingPhrase(accounting.remainder) + ) + } + + return String( + format: AppLocalization.string("Chronoframe found %1$@, and %2$@. Open History for the full record."), + PluralPhrases.photosAndVideos(accounting.found), + notAccountedForPhrase(abs(accounting.remainder)) + ) + } + + /// `Unlock to Copy the Rest` is offered after a free copy that left photos + /// waiting, and only when the free allowance is in play (FRX C-07). + static func showsUnlockRest(_ accounting: RunAccounting, isFreeBatch: Bool, allowanceRemaining: Int?) -> Bool { + isFreeBatch + && accounting.remainder > 0 + && accounting.notCopied == 0 + && allowanceRemaining != nil + } + + // MARK: Parts + + /// Copied, already in the library, could not be read; a part is left out + /// when its number is 0. + private static func balancedParts(_ accounting: RunAccounting) -> [String] { + var parts: [String] = [] + if accounting.copiedMedia > 0 { + parts.append(AppLocalization.format("%@ copied", accounting.copiedMedia.formatted())) + } + if accounting.alreadyThere > 0 { + parts.append(AppLocalization.format("%@ already in your library", accounting.alreadyThere.formatted())) + } + if accounting.unreadable > 0 { + parts.append(AppLocalization.format("%@ could not be read", accounting.unreadable.formatted())) + } + return parts + } + + private static func notInPlanPhrase(_ count: Int) -> String { + count == 1 + ? AppLocalization.string("1 is not in this plan yet") + : AppLocalization.format("%@ are not in this plan yet", count.formatted()) + } + + private static func notAccountedForPhrase(_ count: Int) -> String { + count == 1 + ? AppLocalization.string("1 is not accounted for in this copy") + : AppLocalization.format("%@ are not accounted for in this copy", count.formatted()) + } + + private static func waitingPhrase(_ count: Int) -> String { + count == 1 + ? AppLocalization.string("1 is waiting for the next copy") + : AppLocalization.format("%@ are waiting for the next copy", count.formatted()) + } +} + +extension RunWorkspaceModel { + /// `previewLine` for `.dryRunFinished` with a current preview, `finishedLine` + /// for `.finished`, nil for every other status (nothing to copy, reverted, + /// reorganized, failed, running). + var accountingLine: String? { + switch context.status { + case .dryRunFinished: + guard !context.previewReviewIsStale else { return nil } + return RunAccountingText.previewLine(RunAccounting.preview(context.metrics)) + case .finished: + return RunAccountingText.finishedLine( + RunAccounting.finished(outcomeMetrics), + isFreeBatch: isFreeBatchCopy + ) + default: + return nil + } + } + + /// The finished run was a free batch: the engine reports which source paths + /// it retained only for a batch. + var isFreeBatchCopy: Bool { + context.summary?.copiedBatchSourcePaths != nil + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index 63abc95f..07a9b4e5 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -335,6 +335,14 @@ struct RunPreviewSummarySection: View { .scaledFont(.cardTitle) .foregroundStyle(DesignTokens.Color.inkPrimary) + if let accountingLine = model.accountingLine { + Text(verbatim: accountingLine) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .frame(maxWidth: .infinity, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + } + if let editedLine = model.photosEditedPreviewLine { Label(editedLine, systemImage: "photo.badge.plus") .scaledFont(.body) diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index 2216ac4f..95e85e86 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -1291,6 +1291,296 @@ final class AppStateTests: XCTestCase { XCTAssertNil(state.requestedUnlockRefusal) XCTAssertNil(state.unlockRefusal) } + + // MARK: - Undo this copy (FRX C-04) + + /// A destination folder owned by the test, holding two organize receipts and + /// one copied photo, so a revert request can be checked against exactly one + /// receipt and nothing else can go missing. + private struct UndoFixture { + let destination: URL + let receipt: URL + let otherReceipt: URL + let photo: URL + } + + private func resolved(_ path: String) -> String { + URL(fileURLWithPath: path).resolvingSymlinksInPath().path + } + + private func makeUndoFixture() throws -> UndoFixture { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("frx-undo-\(UUID().uuidString)", isDirectory: true) + let logs = root.appendingPathComponent(".organize_logs", isDirectory: true) + let month = root.appendingPathComponent("2026/10", isDirectory: true) + try FileManager.default.createDirectory(at: logs, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: month, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + + let receipt = logs.appendingPathComponent("audit_receipt_20261128_101500_\(UUID().uuidString).json") + let otherReceipt = logs.appendingPathComponent("audit_receipt_20261101_090000_\(UUID().uuidString).json") + let photo = month.appendingPathComponent("IMG_0001.jpg") + try Data("{}".utf8).write(to: receipt) + try Data("{}".utf8).write(to: otherReceipt) + try Data([0xFF, 0xD8]).write(to: photo) + return UndoFixture(destination: root, receipt: receipt, otherReceipt: otherReceipt, photo: photo) + } + + /// An app state whose run session talks to a recording engine, because the + /// shared mock engine refuses to revert and so records nothing. + @MainActor + private func makeUndoState( + harness: AppStateHarness, + engine: UndoRecordingEngine + ) -> AppState { + let runSessionStore = RunSessionStore( + engine: engine, + logStore: harness.runLogStore, + historyStore: harness.historyStore + ) + return AppState( + preferencesStore: harness.preferencesStore, + setupStore: harness.setupStore, + runLogStore: harness.runLogStore, + historyStore: harness.historyStore, + runSessionStore: runSessionStore, + deduplicateSessionStore: harness.deduplicateSessionStore, + photosImportStore: PhotosImportStore( + access: AppStatePhotosAccessStub(), + catalog: AppStatePhotosCatalogStub(), + exporter: AppStatePhotosExporterStub(), + stagingParentURL: harness.photosStagingParent + ), + folderAccessService: harness.folderAccessService, + finderService: harness.finderService, + profilesRepository: harness.repository, + performInitialBootstrap: false, + restoreBookmarksDuringBootstrap: false, + volumeClassifier: AppStateHarness.localClassifier + ) + } + + /// Runs one organize session to its end and waits for History to read the + /// destination, as the app does when a run finishes. + @MainActor + private func finishRun( + appState: AppState, + engine: UndoRecordingEngine, + fixture: UndoFixture, + mode: RunMode, + status: RunStatus, + receiptPath: String? + ) async { + let configuration = RunConfiguration( + mode: mode, + sourcePath: "/tmp/source", + destinationPath: fixture.destination.path + ) + engine.preflightResult = RunPreflight( + configuration: configuration, + resolvedSourcePath: "/tmp/source", + resolvedDestinationPath: fixture.destination.path + ) + let summary = RunSummary( + status: status, + title: "Done", + metrics: RunMetrics(discoveredCount: 3, plannedCount: 3, copiedCount: 3), + artifacts: RunArtifactPaths( + destinationRoot: fixture.destination.path, + logsDirectoryPath: fixture.destination.appendingPathComponent(".organize_logs").path, + receiptPath: receiptPath + ) + ) + engine.startEvents = [.complete(summary)] + engine.revertEvents = [.complete(summary)] + + let store = appState.runSessionStore + if mode == .revert { + store.requestRevert(receiptURL: fixture.receipt, destinationRoot: fixture.destination.path) + } else { + await store.requestRun(mode: mode, configuration: configuration) + if mode == .transfer { + store.confirmPrompt() + } + } + _ = await waitForCondition(timeoutNanoseconds: 3_000_000_000) { + store.summary?.status == status + } + _ = await waitForCondition(timeoutNanoseconds: 3_000_000_000) { + appState.historyStore.entries.contains { $0.kind == .auditReceipt } + } + } + + @MainActor + func testLastCopyUndoEntryMatchesReceiptPath() async throws { + let harness = AppStateHarness() + let fixture = try makeUndoFixture() + let engine = UndoRecordingEngine() + let appState = makeUndoState(harness: harness, engine: engine) + + await finishRun( + appState: appState, engine: engine, fixture: fixture, mode: .transfer, status: .finished, + receiptPath: fixture.receipt.path + ) + + let entry = try XCTUnwrap(appState.lastCopyUndoEntry) + XCTAssertEqual(entry.kind, .auditReceipt) + // History lists the folder through its real location (/private/var for + // a temp folder), so the same file can carry a different spelling. + XCTAssertEqual(resolved(entry.path), resolved(fixture.receipt.path)) + XCTAssertNotEqual(resolved(entry.path), resolved(fixture.otherReceipt.path)) + } + + @MainActor + func testNoUndoEntryWithoutReceiptPath() async throws { + let harness = AppStateHarness() + let fixture = try makeUndoFixture() + let engine = UndoRecordingEngine() + let appState = makeUndoState(harness: harness, engine: engine) + + await finishRun( + appState: appState, engine: engine, fixture: fixture, mode: .transfer, status: .finished, + receiptPath: nil + ) + XCTAssertFalse(appState.historyStore.entries.isEmpty, "History has the receipts, the summary just does not name one") + XCTAssertNil(appState.lastCopyUndoEntry) + + // A receipt path History has not indexed is not an Undo target either. + let unindexed = fixture.destination + .appendingPathComponent(".organize_logs/audit_receipt_19990101_000000_\(UUID().uuidString).json").path + await finishRun( + appState: appState, engine: engine, fixture: fixture, mode: .transfer, status: .finished, + receiptPath: unindexed + ) + XCTAssertNil(appState.lastCopyUndoEntry) + } + + @MainActor + func testNoUndoEntryForPreviewOrRevertRuns() async throws { + let harness = AppStateHarness() + let fixture = try makeUndoFixture() + let engine = UndoRecordingEngine() + let appState = makeUndoState(harness: harness, engine: engine) + + // Nothing has run yet. + XCTAssertNil(appState.lastCopyUndoEntry) + + await finishRun( + appState: appState, engine: engine, fixture: fixture, mode: .preview, status: .dryRunFinished, + receiptPath: fixture.receipt.path + ) + XCTAssertEqual(appState.runSessionStore.summary?.status, .dryRunFinished) + XCTAssertNil(appState.lastCopyUndoEntry, "A preview copied nothing, so there is nothing to undo") + + await finishRun( + appState: appState, engine: engine, fixture: fixture, mode: .revert, status: .reverted, + receiptPath: fixture.receipt.path + ) + XCTAssertEqual(appState.runSessionStore.summary?.status, .reverted) + XCTAssertNil(appState.lastCopyUndoEntry, "An undo is not itself offered for undoing") + } + + @MainActor + func testCopyCompleteFixtureOffersUndo() async throws { + let appState = UITestAppStateFactory.make(scenario: .runCopyComplete) + let finished = await waitForCondition(timeoutNanoseconds: 3_000_000_000) { + appState.runSessionStore.summary?.status == .finished + } + XCTAssertTrue(finished) + let receiptPath = try XCTUnwrap(appState.runSessionStore.summary?.artifacts.receiptPath) + let offered = await waitForCondition(timeoutNanoseconds: 3_000_000_000) { + appState.lastCopyUndoEntry != nil + } + + XCTAssertTrue(offered, "Undo must still be offered once the finished run has re-read History") + XCTAssertEqual(appState.lastCopyUndoEntry?.kind, .auditReceipt) + XCTAssertEqual( + appState.lastCopyUndoEntry.map { resolved($0.path) }, + resolved(receiptPath) + ) + } + + // AGENTS-INVARIANT: 8 + @MainActor + func testUndoLastCopyRevertsThatReceiptOnly() async throws { + let harness = AppStateHarness() + let fixture = try makeUndoFixture() + let engine = UndoRecordingEngine() + let appState = makeUndoState(harness: harness, engine: engine) + + // Nothing to undo yet: the request is a no-op. + appState.undoLastCopy() + XCTAssertTrue(engine.revertRequests.isEmpty) + + await finishRun( + appState: appState, engine: engine, fixture: fixture, mode: .transfer, status: .finished, + receiptPath: fixture.receipt.path + ) + XCTAssertNotNil(appState.lastCopyUndoEntry) + + appState.undoLastCopy() + let requested = await waitForCondition { engine.revertRequests.count == 1 } + + XCTAssertTrue(requested) + XCTAssertEqual(engine.revertRequests.count, 1, "Exactly one revert is requested") + XCTAssertEqual(engine.revertRequests.first.map { resolved($0.receiptURL.path) }, resolved(fixture.receipt.path)) + XCTAssertEqual(engine.revertRequests.first.map { resolved($0.destinationRoot) }, resolved(fixture.destination.path)) + // The revert goes through the engine only: Undo itself removes nothing. + XCTAssertTrue(FileManager.default.fileExists(atPath: fixture.receipt.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: fixture.otherReceipt.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: fixture.photo.path)) + XCTAssertEqual(appState.organizeSubSelection, .run) + } +} + +/// Plays one canned run and records every revert it is asked for. +@MainActor +private final class UndoRecordingEngine: OrganizerEngine { + var preflightResult = RunPreflight( + configuration: RunConfiguration(mode: .transfer, sourcePath: "/tmp/source", destinationPath: "/tmp/destination"), + resolvedSourcePath: "/tmp/source", + resolvedDestinationPath: "/tmp/destination" + ) + var startEvents: [RunEvent] = [] + var revertEvents: [RunEvent] = [] + private(set) var revertRequests: [(receiptURL: URL, destinationRoot: String)] = [] + private let lockRoot = FileManager.default.temporaryDirectory + .appendingPathComponent("UndoRecordingEngine-\(UUID().uuidString)", isDirectory: true) + + func preflight(_ configuration: RunConfiguration) async throws -> RunPreflight { preflightResult } + + func prepare(_ configuration: RunConfiguration) async throws -> PreparedRun { + let lease = try DestinationOperationLock.acquire( + destinationRoot: lockRoot, + surface: "test", + operation: configuration.mode.rawValue + ) + return PreparedRun(preflight: preflightResult, lease: lease) + } + + func start(_ configuration: RunConfiguration) throws -> AsyncThrowingStream<RunEvent, Error> { + stream(startEvents) + } + + func resume(_ configuration: RunConfiguration) throws -> AsyncThrowingStream<RunEvent, Error> { + stream(startEvents) + } + + func cancelCurrentRun() {} + + func revert(receiptURL: URL, destinationRoot: String) throws -> AsyncThrowingStream<RunEvent, Error> { + revertRequests.append((receiptURL: receiptURL, destinationRoot: destinationRoot)) + return stream(revertEvents) + } + + private func stream(_ events: [RunEvent]) -> AsyncThrowingStream<RunEvent, Error> { + AsyncThrowingStream { continuation in + Task { @MainActor in + for event in events { continuation.yield(event) } + continuation.finish() + } + } + } } private final class RecordingDedupeSnapshotStore: DeduplicateReviewSnapshotStoring, @unchecked Sendable { diff --git a/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift b/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift new file mode 100644 index 00000000..bb065ee0 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/RunAccountingTextTests.swift @@ -0,0 +1,228 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import XCTest +@testable import ChronoframeApp + +/// The accounted-for sentences (FRX C-02, D-FRX-09): evidence-bound, and never a +/// statement about what may be removed from the source. +@MainActor +final class RunAccountingTextTests: XCTestCase { + // MARK: Fixtures + + /// 4,263 found = 4,163 new + 37 exact copies + 63 already there. + private func balancedFinishedMetrics() -> RunMetrics { + RunMetrics( + discoveredCount: 4_263, + plannedCount: 4_200, + alreadyInDestinationCount: 63, + duplicateCount: 37, + copiedCount: 4_200 + ) + } + + private func finished(_ metrics: RunMetrics) -> RunAccounting { RunAccounting.finished(metrics) } + private func preview(_ metrics: RunMetrics) -> RunAccounting { RunAccounting.preview(metrics) } + + // MARK: Preview + + func testPreviewBalancedLine() { + let accounting = preview(balancedFinishedMetrics()) + XCTAssertTrue(accounting.isBalanced) + XCTAssertEqual( + RunAccountingText.previewLine(accounting), + "Every one of the \(4_263.formatted()) photos and videos Chronoframe found is listed below." + ) + } + + func testPreviewUnbalancedLineNamesTheGap() { + // 100 found, 90 listed: 10 are missing. + let short = preview(RunMetrics(discoveredCount: 100, plannedCount: 50, alreadyInDestinationCount: 40)) + XCTAssertEqual(short.remainder, 10) + XCTAssertEqual( + RunAccountingText.previewLine(short), + "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not in this plan yet. Rebuild the preview before copying." + ) + + // A negative remainder names the gap by its absolute value. + let over = preview(RunMetrics(discoveredCount: 100, plannedCount: 70, alreadyInDestinationCount: 40)) + XCTAssertEqual(over.remainder, -10) + XCTAssertEqual( + RunAccountingText.previewLine(over), + "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not in this plan yet. Rebuild the preview before copying." + ) + + // Singular forms agree on their own count. + let one = preview(RunMetrics(discoveredCount: 1)) + XCTAssertEqual(one.remainder, 1) + XCTAssertEqual( + RunAccountingText.previewLine(one), + "Chronoframe found 1 photo or video, and 1 is not in this plan yet. Rebuild the preview before copying." + ) + } + + func testPreviewNilWhenNothingFound() { + XCTAssertNil(RunAccountingText.previewLine(preview(RunMetrics()))) + XCTAssertNil(RunAccountingText.finishedLine(finished(RunMetrics()), isFreeBatch: false)) + XCTAssertNil(RunAccountingText.finishedLine(finished(RunMetrics()), isFreeBatch: true)) + } + + // MARK: Finished + + func testFinishedBalancedLineOmitsZeroParts() { + XCTAssertEqual( + RunAccountingText.finishedLine(finished(balancedFinishedMetrics()), isFreeBatch: false), + "All \(4_263.formatted()) photos and videos Chronoframe found are accounted for: \(4_200.formatted()) copied, \(63.formatted()) already in your library." + ) + + // Nothing unreadable, nothing already there: only the copied part remains. + let allCopied = finished(RunMetrics(discoveredCount: 20, plannedCount: 20, copiedCount: 20)) + XCTAssertEqual( + RunAccountingText.finishedLine(allCopied, isFreeBatch: false), + "All \(20.formatted()) photos and videos Chronoframe found are accounted for: \(20.formatted()) copied." + ) + + // Every part present, in the order copied, already there, unreadable. + let everything = finished(RunMetrics( + discoveredCount: 72, + plannedCount: 42, + alreadyInDestinationCount: 29, + duplicateCount: 7, + hashErrorCount: 1, + copiedCount: 42 + )) + XCTAssertEqual( + RunAccountingText.finishedLine(everything, isFreeBatch: false), + "All \(72.formatted()) photos and videos Chronoframe found are accounted for: \(42.formatted()) copied, \(29.formatted()) already in your library, 1 could not be read." + ) + + // One file found: the singular phrase and verb. + let one = finished(RunMetrics(discoveredCount: 1, plannedCount: 1, copiedCount: 1)) + XCTAssertEqual( + RunAccountingText.finishedLine(one, isFreeBatch: false), + "The 1 photo or video Chronoframe found is accounted for: 1 copied." + ) + } + + func testFinishedFreeBatchLine() { + // 4,263 found; a free copy handled 500 of them (480 new + 20 exact copies) + // and 3,763 are waiting. + let metrics = RunMetrics( + discoveredCount: 4_263, + plannedCount: 500, + alreadyInDestinationCount: 0, + duplicateCount: 20, + copiedCount: 500 + ) + let accounting = finished(metrics) + XCTAssertEqual(accounting.remainder, 3_763) + XCTAssertEqual(accounting.notCopied, 0) + XCTAssertEqual( + RunAccountingText.finishedLine(accounting, isFreeBatch: true), + "Chronoframe found \(4_263.formatted()) photos and videos. This free copy handled \(500.formatted()); \(3_763.formatted()) are waiting for the next copy." + ) + + // The same numbers without a free batch are an unbalanced copy. + XCTAssertEqual( + RunAccountingText.finishedLine(accounting, isFreeBatch: false), + "Chronoframe found \(4_263.formatted()) photos and videos, and \(3_763.formatted()) are not accounted for in this copy. Open History for the full record." + ) + + // One left over reads as one. + let last = finished(RunMetrics(discoveredCount: 11, plannedCount: 10, copiedCount: 10)) + XCTAssertEqual( + RunAccountingText.finishedLine(last, isFreeBatch: true), + "Chronoframe found \(11.formatted()) photos and videos. This free copy handled \(10.formatted()); 1 is waiting for the next copy." + ) + } + + func testFinishedNotCopiedLine() { + // 4,263 found and fully listed, but 12 planned files were not copied. + let metrics = RunMetrics( + discoveredCount: 4_263, + plannedCount: 4_200, + alreadyInDestinationCount: 63, + duplicateCount: 37, + copiedCount: 4_188, + failedCount: 12 + ) + let accounting = finished(metrics) + XCTAssertTrue(accounting.isBalanced) + XCTAssertEqual(accounting.notCopied, 12) + let expected = "\(12.formatted()) planned photos and videos were not copied. Your originals were not changed. See Problems." + XCTAssertEqual(RunAccountingText.finishedLine(accounting, isFreeBatch: false), expected) + // Not copied outranks the free-batch wording. + XCTAssertEqual(RunAccountingText.finishedLine(accounting, isFreeBatch: true), expected) + + let single = finished(RunMetrics(discoveredCount: 5, plannedCount: 5, copiedCount: 4, failedCount: 1)) + XCTAssertEqual( + RunAccountingText.finishedLine(single, isFreeBatch: false), + "1 planned photo or video was not copied. Your originals were not changed. See Problems." + ) + } + + func testFinishedUnbalancedLine() { + // 100 found but only 90 listed, and everything planned was copied. + let metrics = RunMetrics(discoveredCount: 100, plannedCount: 50, alreadyInDestinationCount: 40, copiedCount: 50) + let accounting = finished(metrics) + XCTAssertEqual(accounting.remainder, 10) + XCTAssertEqual(accounting.notCopied, 0) + XCTAssertEqual( + RunAccountingText.finishedLine(accounting, isFreeBatch: false), + "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not accounted for in this copy. Open History for the full record." + ) + + // Negative remainder: listed more than found. + let over = finished(RunMetrics(discoveredCount: 100, plannedCount: 70, alreadyInDestinationCount: 40, copiedCount: 70)) + XCTAssertEqual(over.remainder, -10) + XCTAssertEqual( + RunAccountingText.finishedLine(over, isFreeBatch: true), + "Chronoframe found \(100.formatted()) photos and videos, and \(10.formatted()) are not accounted for in this copy. Open History for the full record." + ) + } + + func testNoLineEverSaysSafeToDelete() { + let metricsSamples: [RunMetrics] = [ + RunMetrics(), + balancedFinishedMetrics(), + RunMetrics(discoveredCount: 1), + RunMetrics(discoveredCount: 100, plannedCount: 50, alreadyInDestinationCount: 40, copiedCount: 50), + RunMetrics(discoveredCount: 100, plannedCount: 70, alreadyInDestinationCount: 40), + RunMetrics(discoveredCount: 4_263, plannedCount: 4_200, alreadyInDestinationCount: 63, duplicateCount: 37, copiedCount: 4_188, failedCount: 12), + RunMetrics(discoveredCount: 4_263, plannedCount: 500, duplicateCount: 20, copiedCount: 500), + ] + var lines: [String] = [] + for metrics in metricsSamples { + lines.append(RunAccountingText.previewLine(preview(metrics)) ?? "") + for isFreeBatch in [false, true] { + lines.append(RunAccountingText.finishedLine(finished(metrics), isFreeBatch: isFreeBatch) ?? "") + } + } + for line in lines { + let lowered = line.lowercased() + XCTAssertFalse(lowered.contains("safe to delete"), line) + XCTAssertFalse(lowered.contains("delete"), line) + XCTAssertFalse(lowered.contains("remove"), line) + XCTAssertFalse(lowered.contains("erase"), line) + } + XCTAssertTrue(lines.contains { !$0.isEmpty }, "The samples must produce real sentences") + } + + // MARK: Unlock the rest (FRX C-07, last paragraph) + + func testUnlockRestShowsOnlyForAFreeBatchWithPhotosWaitingAndAKnownAllowance() { + let waiting = finished(RunMetrics(discoveredCount: 4_263, plannedCount: 500, duplicateCount: 20, copiedCount: 500)) + XCTAssertTrue(RunAccountingText.showsUnlockRest(waiting, isFreeBatch: true, allowanceRemaining: 0)) + XCTAssertFalse(RunAccountingText.showsUnlockRest(waiting, isFreeBatch: true, allowanceRemaining: nil)) + XCTAssertFalse(RunAccountingText.showsUnlockRest(waiting, isFreeBatch: false, allowanceRemaining: 0)) + + let done = finished(balancedFinishedMetrics()) + XCTAssertFalse(RunAccountingText.showsUnlockRest(done, isFreeBatch: true, allowanceRemaining: 0)) + + let notCopied = finished(RunMetrics( + discoveredCount: 4_263, plannedCount: 4_200, alreadyInDestinationCount: 63, + duplicateCount: 37, copiedCount: 4_188, failedCount: 12 + )) + XCTAssertFalse(RunAccountingText.showsUnlockRest(notCopied, isFreeBatch: true, allowanceRemaining: 0)) + } +} diff --git a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift index adbd7dc9..68da8a25 100644 --- a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift @@ -685,6 +685,127 @@ final class RunWorkspaceModelTests: XCTestCase { XCTAssertTrue(RunFreeCopyText.isMenuOptionEnabled(partial[0], suggested: FreeMonthBatchPlanner.suggestedOption(partial))) } + // MARK: - Accounted-for line (FRX C-02) + + private func accountingModel( + status: RunStatus, + metrics: RunMetrics, + previewReviewIsStale: Bool = false, + copiedBatchSourcePaths: Set<String>? = nil + ) -> RunWorkspaceModel { + RunWorkspaceModel( + context: RunWorkspaceContext( + status: status, + currentMode: nil, + currentTaskTitle: "", + currentPhase: nil, + progress: 0, + metrics: metrics, + summary: RunSummary( + status: status, + title: "", + metrics: metrics, + artifacts: RunArtifactPaths(), + copiedBatchSourcePaths: copiedBatchSourcePaths + ), + lastErrorMessage: nil, + warningCount: 0, + errorCount: 0, + issueCount: 0, + logEntries: [], + historyDestinationRoot: "", + currentSourceRoot: "", + canStartRun: true, + previewReviewIsStale: previewReviewIsStale + ) + ) + } + + func testAccountingLineOnlyForReadyPreviewAndFinishedCopy() { + // 4,263 found = 4,163 new + 37 exact copies + 63 already there. + let metrics = RunMetrics( + discoveredCount: 4_263, + plannedCount: 4_200, + alreadyInDestinationCount: 63, + duplicateCount: 37, + copiedCount: 4_200 + ) + + XCTAssertEqual( + accountingModel(status: .dryRunFinished, metrics: metrics).accountingLine, + "Every one of the \(4_263.formatted()) photos and videos Chronoframe found is listed below." + ) + XCTAssertNil( + accountingModel(status: .dryRunFinished, metrics: metrics, previewReviewIsStale: true).accountingLine, + "A stale preview no longer describes the folders" + ) + XCTAssertEqual( + accountingModel(status: .finished, metrics: metrics).accountingLine, + "All \(4_263.formatted()) photos and videos Chronoframe found are accounted for: \(4_200.formatted()) copied, \(63.formatted()) already in your library." + ) + + for status in [RunStatus.nothingToCopy, .reverted, .reorganized, .failed, .running] { + XCTAssertNil(accountingModel(status: status, metrics: metrics).accountingLine, "\(status)") + } + for status in [RunStatus.idle, .preflighting, .cancelled, .revertEmpty, .nothingToReorganize] { + XCTAssertNil(accountingModel(status: status, metrics: metrics).accountingLine, "\(status)") + } + XCTAssertNil(accountingModel(status: .dryRunFinished, metrics: RunMetrics()).accountingLine) + XCTAssertNil(accountingModel(status: .finished, metrics: RunMetrics()).accountingLine) + } + + func testAccountingLineReadsTheFreeBatchFromTheSummary() { + let metrics = RunMetrics(discoveredCount: 4_263, plannedCount: 500, duplicateCount: 20, copiedCount: 500) + + XCTAssertEqual( + accountingModel(status: .finished, metrics: metrics, copiedBatchSourcePaths: ["/a.jpg"]).accountingLine, + "Chronoframe found \(4_263.formatted()) photos and videos. This free copy handled \(500.formatted()); \(3_763.formatted()) are waiting for the next copy." + ) + XCTAssertEqual( + accountingModel(status: .finished, metrics: metrics).accountingLine, + "Chronoframe found \(4_263.formatted()) photos and videos, and \(3_763.formatted()) are not accounted for in this copy. Open History for the full record." + ) + } + + @MainActor + func testCopyCompleteAndPreviewFixturesAreBalanced() async { + let complete = UITestAppStateFactory.make(scenario: .runCopyComplete) + let completeFinished = await waitForCondition(timeoutNanoseconds: 2_000_000_000) { + complete.runSessionStore.summary?.status == .finished + } + XCTAssertTrue(completeFinished) + let completeModel = RunWorkspaceModel( + runSessionStore: complete.runSessionStore, + runLogStore: complete.runLogStore, + historyStore: complete.historyStore, + canStartRun: complete.canStartRun + ) + XCTAssertEqual(completeModel.outcomeMetrics.discoveredCount, 4_263) + XCTAssertTrue(RunAccounting.finished(completeModel.outcomeMetrics).isBalanced) + XCTAssertEqual( + completeModel.accountingLine, + "All \(4_263.formatted()) photos and videos Chronoframe found are accounted for: \(4_200.formatted()) copied, \(63.formatted()) already in your library." + ) + + let review = UITestAppStateFactory.make(scenario: .runPreviewReview) + let reviewFinished = await waitForCondition(timeoutNanoseconds: 2_000_000_000) { + review.runSessionStore.summary?.status == .dryRunFinished + } + XCTAssertTrue(reviewFinished) + let reviewModel = RunWorkspaceModel( + runSessionStore: review.runSessionStore, + runLogStore: review.runLogStore, + historyStore: review.historyStore, + canStartRun: review.canStartRun + ) + XCTAssertEqual(reviewModel.context.metrics.discoveredCount, 72) + XCTAssertTrue(RunAccounting.preview(reviewModel.context.metrics).isBalanced) + XCTAssertEqual( + reviewModel.accountingLine, + "Every one of the \(72.formatted()) photos and videos Chronoframe found is listed below." + ) + } + // MARK: - Helpers private func makeModel(status: RunStatus, discoveredCount: Int = 0) -> RunWorkspaceModel { From 1268aaf88a4fb7c175de11da48ff93edee7e867a Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:31:26 -0800 Subject: [PATCH 09/30] FRX WP-06: strings and docs Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 8 +- docs/FAQ.md | 10 +- docs/QUICK_START.md | 24 +- docs/SAFETY_AND_RECOVERY.md | 26 + docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 8 +- .../first-run-experience/strings/M1-app.json | 158 +++++ .../first-run-experience/strings/M1-core.json | 38 + .../Resources/Localizable.xcstrings | 650 +++++++++++++++++- .../Resources/LocalizableCore.xcstrings | 153 +++++ 10 files changed, 1063 insertions(+), 13 deletions(-) create mode 100644 docs/plan/first-run-experience/strings/M1-app.json create mode 100644 docs/plan/first-run-experience/strings/M1-core.json diff --git a/README.md b/README.md index f513f64e..90d7470f 100644 --- a/README.md +++ b/README.md @@ -43,6 +43,8 @@ Chronoframe always shows you a plan before it changes anything. Your source fold [Download Chronoframe from the Mac App Store](https://apps.apple.com/us/app/chronoframe/id6771245052?mt=12). It is free to download: organize 500 files and move 100 duplicates to the Trash before you decide. Scanning, previews, duplicate review, and History are free and unlimited, and revert is never gated. A one-time $14.99 US lifetime unlock removes the limits and includes Reorganize, with Family Sharing. No subscription, account, analytics, or uploads. +When a plan is larger than what is left of the free allowance, the preview says so before you click anything. **Start Copying** is replaced by a free copy of one whole month of new photos and videos (the newest month that fits, or the first days of the newest month when none fits) and an **Unlock to Copy Everything** button. A free month never includes exact copies or files with no date, and nothing is copied until you review the listed files and confirm. + The current source targets **macOS 14.0 or later** on Apple Silicon and Intel Macs. Organizing also requires enough free space for a copy of the source library. ## Organize Photos @@ -56,8 +58,8 @@ Organize has these tabs: **Choose Folders**, **Preview & Copy**, **History**, ** ![Preview Ready for Review — a timeline of the library by month, with discovered, planned, and issue counts.](docs/screenshots/preview-timeline.jpg) -5. On **Preview & Copy**, inspect the preview: the timeline shows your library by month, and the counts cover what's ready, what's already there, duplicates, and anything that needs attention. Open **Review** to fix uncertain dates. -6. Click **Start Copying** when the preview looks right. Chronoframe copies files into the destination, verifies them, and writes a receipt — your source is never touched. +5. On **Preview & Copy**, inspect the preview: the timeline shows your library by month, and the counts cover what's ready, what's already there, duplicates, and anything that needs attention. The first line of **What will happen** says whether every photo and video Chronoframe found is listed below; if the numbers do not add up, it says so and asks you to rebuild the preview. Open **Review** to fix uncertain dates. +6. Click **Start Copying** when the preview looks right. Chronoframe copies files into the destination, verifies them, and writes a receipt — your source is never touched. The completion screen says whether every photo and video found is accounted for, and offers **Undo This Copy…** and **Add Another Folder**. ![Transfer Complete — every frame copied, with a run summary and links to open the destination, report, and logs.](docs/screenshots/transfer-complete.jpg) @@ -69,7 +71,7 @@ The **Health** tab scans the destination on demand and surfaces cleanup opportun ### Review and undo from History -The **History** tab keeps every run's reports and receipts. Reuse a past source, inspect logs, or open the **Undo Center** to revert a transfer, dedupe commit, or reorganize run when its files still match the receipt. If a run was interrupted, History distinguishes work that was recovered from work that needs a drive reconnected or manual attention. +The **History** tab keeps every run's reports and receipts. Reuse a past source, inspect logs, or open the **Undo Center** to revert a transfer, dedupe commit, or reorganize run when its files still match the receipt. Right after a copy, **Undo This Copy…** on the completion screen does the same hash-checked undo. If a run was interrupted, History distinguishes work that was recovered from work that needs a drive reconnected or manual attention. ![Run History — archived frames, reusable sources, an undo center, and a list of run reports and receipts.](docs/screenshots/run-history.jpg) diff --git a/docs/FAQ.md b/docs/FAQ.md index 7738a21a..9de9ecd4 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -20,11 +20,11 @@ A: Only one organize, deduplicate, reorganize, undo, CLI, or system-integrated m **Q: Can I undo an organize operation?** -A: Yes. Open **Organize** → **History** and click **Undo** next to the copy you want to undo in the **Undo Center**. You can also open the ⋯ menu on a receipt in **Reports and Logs** and choose **Undo…**. Chronoframe will delete only the files it copied (not anything that was already in the destination). Undo verifies content hashes, so it won't delete files if they've been modified since the copy. +A: Yes. Open **Organize** → **History** and click **Undo** next to the copy you want to undo in the **Undo Center**. You can also open the ⋯ menu on a receipt in **Reports and Logs** and choose **Undo…**. Right after a copy finishes, the **Summary** card on the completion screen has an **Undo This Copy…** button that does the same thing; it appears once History has found the receipt. Chronoframe will delete only the files it copied (not anything that was already in the destination). Undo verifies content hashes, so it won't delete files if they've been modified since the copy. **Q: How do I know what Chronoframe will copy?** -A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. +A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. --- @@ -95,7 +95,11 @@ A: Yes. **Add Folders…** in **Organize → Choose Folders** accepts several fo **Q: What happens after a copy finishes?** -A: The **Preview & Copy** screen shows **Copy complete**, and the report and undo receipt are in **History**. See [What happens after a copy](./QUICK_START.md#what-happens-after-a-copy). +A: The **Preview & Copy** screen shows **Copy complete**. The first line of the **Summary** card says whether every photo and video Chronoframe found is accounted for (copied, already in your library, or could not be read). If the numbers do not add up, it says so and points you to **History**. If some planned files were not copied, it says how many and points you to **Problems**. The card also has **Undo This Copy…** and **Add Another Folder** buttons, and the report and undo receipt are in **History**. See [What happens after a copy](./QUICK_START.md#what-happens-after-a-copy). + +**Q: What can I copy for free in the Mac App Store build?** + +A: Previews are always free. When a plan has more files than your free allowance has left, the **Preview & Copy** screen says so before you click anything, and **Start Copying** is replaced by **Copy {Month Year} Free…**, **Choose Another Month**, and **Unlock to Copy Everything**. See [If your plan is larger than the free limit](./QUICK_START.md#if-your-plan-is-larger-than-the-free-limit). **Q: Can Chronoframe find duplicate photos?** diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md index 9d024b38..1c560193 100644 --- a/docs/QUICK_START.md +++ b/docs/QUICK_START.md @@ -24,6 +24,7 @@ Use this when you want Chronoframe to copy messy folders into a cleaner date-bas - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet - This takes 10–60 seconds depending on your library size 6. When it finishes, **Preview & Copy** shows the plan: a headline saying how many photos and videos will be copied, a **What will happen** card that lists anything unusual, a timeline of your library, and counts for what was found, what will be copied, what is already there, exact copies, and problems + - The first line of the **What will happen** card says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, the line says how many do not add up and asks you to rebuild the preview before copying ### Step 3: Review (Optional) @@ -44,12 +45,13 @@ Use this when you want Chronoframe to copy messy folders into a cleaner date-bas 11. Click **Start Copying** on the **Preview & Copy** screen (or choose **Start Copying** from the **Organize** menu), then confirm in the **Start copying?** prompt - Files are copied to destination, written safely, and verified - You'll see live progress and a summary when done + - If the plan is larger than your free limit, **Start Copying** is replaced by a free copy of one month and an unlock button. See [If your plan is larger than the free limit](#if-your-plan-is-larger-than-the-free-limit) ### Step 5: Keep Your Originals Safe 12. **Your original folders stay untouched.** Nothing is deleted or modified. Preview Plan copies nothing; Chronoframe copies only after you click **Start Copying** and confirm. 13. You can review the report and the receipt for each copy under **History** -14. If something went wrong, open **History** and click **Undo** next to the copy in the **Undo Center** to undo the copy +14. If something went wrong, click **Undo This Copy…** on the completion screen, or open **History** and click **Undo** next to the copy in the **Undo Center** 15. If a copy was interrupted, reopen Chronoframe with the destination drive connected. History will reconcile recorded work or show **Needs Drive** / **Manual Recovery Needed** when it cannot safely finish on its own. That's it. Your photos are now organized. @@ -65,11 +67,29 @@ Use this when your photos are spread across more than one folder. - **The list is remembered.** Chronoframe restores your list when you reopen it. A folder it can no longer find is dropped from the list. - **Profiles hold one folder.** A saved profile stores a single folder, so Chronoframe won't save a profile while two or more folders are listed. It keeps remembering the list instead. +## If your plan is larger than the free limit + +This applies to the Mac App Store build while its free allowance is in use. Scanning and previews are always free. + +When a plan has more files than the free allowance has left, the **Preview & Copy** screen says so before you click anything: it shows how many files you can copy free and how many the plan has. **Start Copying** is not shown. You get these instead: + +- **Copy {Month Year} Free…** copies one whole month of new photos and videos for free. Chronoframe suggests the newest month that fits in what is left. If no month fits, it suggests the first days of the newest month instead. +- **Choose Another Month** lists each month that has new photos or videos, with its file count. A month that is too large for the free limit is greyed out unless it is the suggested one. +- **Unlock to Copy Everything** opens the unlock sheet. It says how many files unlocking lets you organize, and that it is a one-time purchase with Family Sharing and no subscription. + +A free month holds only new photos and videos and their edit and metadata (sidecar) files. It never includes exact copies of other files, and it never includes files with no date. + +Pressing **Copy {Month Year} Free…** copies nothing. A sheet opens with the files listed under **Show these {N} files**, and Chronoframe copies only those files after you click **Copy These {N} Files**. If your free copies are already used up, the screen says so and shows only **Unlock to Copy Everything**. If no month has new dated files, only **Unlock to Copy Everything** is shown. + +After a free copy, the completion screen says how many photos and videos it handled and how many are waiting for the next copy, with an **Unlock to Copy the Rest** button while the free limit applies. + ## What happens after a copy When a copy finishes, the **Preview & Copy** screen says **Copy complete** and how many photos and videos are now in your organized library. Your originals were not changed. -- **Receipt and undo.** The report and the receipt for undoing that copy are in **History**. +- **Is everything accounted for?** The first line of the **Summary** card says whether every photo and video Chronoframe found is accounted for: copied, already in your library, or could not be read. If the numbers do not add up, the line says so and points you to **History** for the full record. If some planned files were not copied, it says how many, says your originals were not changed, and points you to **Problems**. After a free copy, it says how many are waiting for the next copy. +- **Receipt and undo.** The report and the receipt for undoing that copy are in **History**. You can also click **Undo This Copy…** in the **Summary** card. It asks you to confirm, then does the same thing as **Undo** in **History**: it removes only the files that copy made, and only if their contents still match the receipt. The button appears once History has found the receipt. +- **More folders.** Click **Add Another Folder** to go back to **Choose Folders**. Photos already in your library are skipped. - **Next step.** If at least one file was copied, a **Next: remove extra copies** card appears directly under the **Copy complete** message. If the copy set aside exact copies, it says how many went to the `Duplicate` folder. Click **Find Duplicates** to open **Deduplicate**. - **Find Duplicates only opens Deduplicate.** It doesn't start a scan or change the folder to scan; you choose that and click **Start Scan** yourself. Deduplicate removes nothing until you approve it, and approved files go to the macOS Trash. diff --git a/docs/SAFETY_AND_RECOVERY.md b/docs/SAFETY_AND_RECOVERY.md index 9f78c1c7..b36ad276 100644 --- a/docs/SAFETY_AND_RECOVERY.md +++ b/docs/SAFETY_AND_RECOVERY.md @@ -37,6 +37,32 @@ important library, especially before a large first run or filesystem migration. | Guardian mirror | New/updated files on the mirror volume | Copies only from a currently-verified primary, verified copy + atomic no-overwrite rename, divergent mirror quarantined, deletions never propagated, library never written | | Guardian restore | A corrupt/missing library file is healed from the mirror | Mirror re-verified against the trusted digest at commit time, review-gated, same-directory quarantine before install, journaled crash recovery | +## What The Preview And Completion Screens Say + +- **Accounting line.** The first line of the preview summary says whether every + photo and video Chronoframe found is listed below. The first line of the + completion summary says whether each one is accounted for as copied, already in + your library, or could not be read. The balanced wording appears only when + those counts add up to the files found and every planned file was copied. When + they do not add up, the screen says how many are not in the plan or not + accounted for and tells you to rebuild the preview or open History. When + planned files were not copied, it says how many, that your originals were not + changed, and points to Problems. After a free copy it says how many are waiting + for the next copy. The line counts files; it never changes a file. +- **Undo This Copy….** The completion summary offers it for the copy that just + finished, once History has found that copy's receipt. It asks for confirmation + and then runs the same revert History runs for that receipt, with the same + receipt scope, content check and path containment described under Revert + above. It is not a separate deletion path. +- **Free whole month (Mac App Store build).** When a plan is larger than the + free allowance that is left, the preview says so and offers a free copy of one + month in place of Start Copying. A month is only a proposal. It holds new + photos and videos and their sidecar files, never exact copies or files with no + date. A sheet lists the files. The copy runs through the same Organize copy + path, with the same safeguards, and copies only files from that list; a file + that changed since it was listed is skipped. Nothing is copied before you + confirm. + ## One Destination-Changing Operation At A Time Chronoframe keeps `.organize_logs/.chronoframe-operation.lock` open for the diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index aa936297..a6e931a0 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -52,3 +52,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-104 Free-month sheet details (WP-03).** (a) `proposingFreeMonth` sets `wasRequested: true` on the suggested-month fallback too; the title names the month actually offered. (b) It does not apply the covers-whole-plan check (C-06 gives that rule only to `offeringFreeMonthBatch`); the sheet's existing `offerableBatch` still drops such a batch. (c) With a failed price load a requested-month sheet keeps the requested message. (d) Singular forms added per the copy rule: `Organize all %@ file`, `Remove all %@ duplicate`, `This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.` (e) `TrialRemaining.value` is also nil while the entitlement is resolving. (f) The two builders are internal, not public. (g) `TrialAuthorizer.swift` gained one private helper `monthBatch` shared by the two builders. - **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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index ec366881..6149c820 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -17,8 +17,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-02 | Core: accounting, free month, model fields | done | build exit 0 | RunAccounting 8, FreeMonthBatchPlanner 14, FreeTestBatchPlanner 19 tests, all exit 0 | approve (round 1) | 682f714 | orchestrator read the FreeTestBatchPlanner.swift and RunModels.swift diffs: additions only; D-FRX-102 | | WP-03 | AppCore: engine, offer, unlock presentation | done | build exit 0 | TrialRemaining 4, FreeMonthBatchOffer 11, UnlockPresentation 19, UnlockSheetBatchOffer 14, FreeTestBatchOffer 9, FreeTestBatchRun 4, SwiftOrganizerEngineIntegration 43 tests, all exit 0 | approve (round 1) | c1dee6f | orchestrator read the full SwiftOrganizerEngine.swift and TrialAuthorizer.swift diffs: every changed line traces to C-03/C-06; the month-request branch throws before `plan.reduced(to:)`, so it reaches neither `authorizeTransfer` nor the job queue; D-FRX-103, D-FRX-104 | | 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) | (WP-05 commit) | 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 | in-progress | | | | | | +| 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) | (WP-06 commit) | 38 App keys + 9 Core keys added; D-FRX-107 | | G1 | Gate, M1 | todo | | | n/a | | | | WP-10 | Branch and baseline, M2 | todo | | | n/a | | | | WP-11 | Core: review lane, free removal batch | todo | | | | | safety-critical; extra opus review | @@ -54,3 +54,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - Noticed, not fixed: in the `runPreviewOverAllowance` fixture the Timeline header reads "21,140 planned files" while the plan has 18,412 (the fixture histogram does not sum to the plan). Fixture-only. - 2026-11-28 WP-05 Done-when (orchestrator): `cf_swift.sh test` exit 0 for RunAccountingTextTests (9), RunWorkspaceModelTests (29), AppStateTests (49), RunOutcomeAccuracyTests (14), AccessibilityTests (8), ScreenRenderEvidenceTests (4 run with marker, 4 PNGs); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `script/check_no_raw_animations.sh` exit 0; `git diff --check` exit 0. No test assertion changed; two fixture values changed (table above). - For G1 step 4: `ui/Xcode/UITests/A11yBaseline.json:48,50` hold "84, FOUND" for `runPreviewReview` and `:343` is the `runCopyComplete` baseline (gains the accounting line, Undo and Add Another Folder elements). +- 2026-11-28 WP-06: `add_translated_keys.py … Localizable.xcstrings … M1-app.json` exit 0 (added 38, kept 1); `… LocalizableCore.xcstrings … M1-core.json` exit 0 (added 9). German review (cf-reviewer): three corrections applied (`Kopie` → `Kopiervorgang` twice; parentheses in the month batch detail). Docs (C-26): QUICK_START, FAQ, README, SAFETY_AND_RECOVERY; review round 1 asked for two corrections (subset guarantee; the not-copied case) and six tidy-ups, all applied; round 2 approve. `cf_swift.sh build` exit 0 after the symbol-collision fix (D-FRX-107); `git diff --check` exit 0. +- Noticed, not fixed: C-02's unbalanced preview line uses `abs(remainder)`, so when the plan holds more files than were found it still says "N are not in this plan yet". Contract wording; left as is. +- Noticed, not fixed: `docs/QUICK_START.md` keeps the older tip "Don't delete your originals yet. Keep them for a few days…", which gently implies originals may be deleted later. Pre-existing, outside M1. + diff --git a/docs/plan/first-run-experience/strings/M1-app.json b/docs/plan/first-run-experience/strings/M1-app.json new file mode 100644 index 00000000..d4bab059 --- /dev/null +++ b/docs/plan/first-run-experience/strings/M1-app.json @@ -0,0 +1,158 @@ +[ + { + "key": "Undo This Copy…", + "de": "Diesen Kopiervorgang rückgängig machen…" + }, + { + "key": "Unlock to Copy the Rest", + "de": "Freischalten, um den Rest zu kopieren" + }, + { + "key": "Have more photos somewhere else? Add that folder next. Photos already in your library are skipped.", + "de": "Hast du noch Fotos an einem anderen Ort? Füge diesen Ordner als Nächstes hinzu. Fotos, die bereits in deiner Mediathek sind, werden übersprungen." + }, + { + "key": "Add Another Folder", + "de": "Weiteren Ordner hinzufügen" + }, + { + "key": "The 1 photo or video Chronoframe found is listed below.", + "de": "Das 1 Foto oder Video, das Chronoframe gefunden hat, ist unten aufgeführt." + }, + { + "key": "Every one of the %@ photos and videos Chronoframe found is listed below.", + "de": "Jedes der %@ Fotos und Videos, die Chronoframe gefunden hat, ist unten aufgeführt." + }, + { + "key": "Chronoframe found %1$@, and %2$@. Rebuild the preview before copying.", + "de": "Chronoframe hat %1$@ gefunden, und %2$@. Erstelle die Vorschau vor dem Kopieren neu." + }, + { + "key": "1 is not in this plan yet", + "de": "1 ist noch nicht in diesem Plan" + }, + { + "key": "%@ are not in this plan yet", + "de": "%@ sind noch nicht in diesem Plan" + }, + { + "key": "The 1 photo or video Chronoframe found is accounted for: %@.", + "de": "Das 1 Foto oder Video, das Chronoframe gefunden hat, ist erfasst: %@." + }, + { + "key": "All %1$@ photos and videos Chronoframe found are accounted for: %2$@.", + "de": "Alle %1$@ Fotos und Videos, die Chronoframe gefunden hat, sind erfasst: %2$@." + }, + { + "key": "%@ copied", + "de": "%@ kopiert" + }, + { + "key": "%@ already in your library", + "de": "%@ bereits in deiner Mediathek" + }, + { + "key": "%@ could not be read", + "de": "%@ nicht lesbar" + }, + { + "key": "1 planned photo or video was not copied. Your originals were not changed. See Problems.", + "de": "1 geplantes Foto oder Video wurde nicht kopiert. Deine Originale wurden nicht verändert. Siehe „Probleme“." + }, + { + "key": "%@ planned photos and videos were not copied. Your originals were not changed. See Problems.", + "de": "%@ geplante Fotos und Videos wurden nicht kopiert. Deine Originale wurden nicht verändert. Siehe „Probleme“." + }, + { + "key": "Chronoframe found %1$@. This free copy handled %2$@; %3$@.", + "de": "Chronoframe hat %1$@ gefunden. Dieser kostenlose Kopiervorgang hat %2$@ verarbeitet; %3$@." + }, + { + "key": "1 is waiting for the next copy", + "de": "1 wartet auf den nächsten Kopiervorgang" + }, + { + "key": "%@ are waiting for the next copy", + "de": "%@ warten auf den nächsten Kopiervorgang" + }, + { + "key": "Chronoframe found %1$@, and %2$@. Open History for the full record.", + "de": "Chronoframe hat %1$@ gefunden, und %2$@. Öffne den Verlauf für die vollständige Aufzeichnung." + }, + { + "key": "1 is not accounted for in this copy", + "de": "1 ist in diesem Kopiervorgang nicht erfasst" + }, + { + "key": "%@ are not accounted for in this copy", + "de": "%@ sind in diesem Kopiervorgang nicht erfasst" + }, + { + "key": "Shows the files first. Nothing is copied until you confirm", + "de": "Zeigt zuerst die Dateien. Es wird nichts kopiert, bis du bestätigst" + }, + { + "key": "Choose Another Month", + "de": "Anderen Monat wählen" + }, + { + "key": "Unlock to Copy Everything", + "de": "Freischalten, um alles zu kopieren" + }, + { + "key": "You can copy %1$@ free. This plan has %2$@.", + "de": "Du kannst %1$@ kostenlos kopieren. Dieser Plan umfasst %2$@." + }, + { + "key": "The newest month that fits is %1$@: %2$@.", + "de": "Der neueste Monat, der hineinpasst, ist %1$@: %2$@." + }, + { + "key": "%@ is larger than that, so the free copy takes its first days.", + "de": "%@ ist größer, daher übernimmt der kostenlose Kopiervorgang die ersten Tage davon." + }, + { + "key": "Your free copies are used up. This plan has %@.", + "de": "Deine kostenlosen Kopien sind aufgebraucht. Dieser Plan umfasst %@." + }, + { + "key": "Copy %@ Free…", + "de": "%@ kostenlos kopieren…" + }, + { + "key": "Copies %@ now, %@, and leaves %@ for later.", + "de": "Kopiert jetzt %1$@ (%2$@) und lässt %3$@ für später übrig." + }, + { + "key": "Organize all %@ file", + "de": "Die %@ Datei organisieren" + }, + { + "key": "Organize all %@ files", + "de": "Alle %@ Dateien organisieren" + }, + { + "key": "Remove all %@ duplicate", + "de": "Das %@ Duplikat entfernen" + }, + { + "key": "Remove all %@ duplicates", + "de": "Alle %@ Duplikate entfernen" + }, + { + "key": "One-time purchase with Family Sharing. No subscription.", + "de": "Einmaliger Kauf mit Familienfreigabe. Kein Abo." + }, + { + "key": "Copy %@ free", + "de": "%@ kostenlos kopieren" + }, + { + "key": "This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.", + "de": "Dieses %@ neue Foto oder Video wird in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + }, + { + "key": "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.", + "de": "Diese %@ neuen Fotos und Videos werden in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + } +] diff --git a/docs/plan/first-run-experience/strings/M1-core.json b/docs/plan/first-run-experience/strings/M1-core.json new file mode 100644 index 00000000..d8ea25b3 --- /dev/null +++ b/docs/plan/first-run-experience/strings/M1-core.json @@ -0,0 +1,38 @@ +[ + { + "key": "Copies %@ now, %@, and leaves %@ for later.", + "de": "Kopiert jetzt %1$@ (%2$@) und lässt %3$@ für später übrig." + }, + { + "key": "Organize all %@ file", + "de": "Die %@ Datei organisieren" + }, + { + "key": "Organize all %@ files", + "de": "Alle %@ Dateien organisieren" + }, + { + "key": "Remove all %@ duplicate", + "de": "Das %@ Duplikat entfernen" + }, + { + "key": "Remove all %@ duplicates", + "de": "Alle %@ Duplikate entfernen" + }, + { + "key": "One-time purchase with Family Sharing. No subscription.", + "de": "Einmaliger Kauf mit Familienfreigabe. Kein Abo." + }, + { + "key": "Copy %@ free", + "de": "%@ kostenlos kopieren" + }, + { + "key": "This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.", + "de": "Dieses %@ neue Foto oder Video wird in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + }, + { + "key": "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.", + "de": "Diese %@ neuen Fotos und Videos werden in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + } +] diff --git a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings index ebe3daf1..ddda9cf0 100644 --- a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings +++ b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings @@ -100,6 +100,23 @@ } } }, + "%@ already in your library" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ bereits in deiner Mediathek" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ already in your library" + } + } + } + }, "%@ and %@ saved %@. Scanning again restores them for files that haven't changed. Nothing is moved to the Trash until you review and confirm." : { "extractionState" : "manual", "localizations" : { @@ -117,6 +134,57 @@ } } }, + "%@ are not accounted for in this copy" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ sind in diesem Kopiervorgang nicht erfasst" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ are not accounted for in this copy" + } + } + } + }, + "%@ are not in this plan yet" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ sind noch nicht in diesem Plan" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ are not in this plan yet" + } + } + } + }, + "%@ are waiting for the next copy" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ warten auf den nächsten Kopiervorgang" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ are waiting for the next copy" + } + } + } + }, "%@ copied" : { "comment" : "A label that shows the number of files that were copied from a source.", "isCommentAutoGenerated" : true, @@ -129,6 +197,23 @@ } } }, + "%@ could not be read" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ nicht lesbar" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ could not be read" + } + } + } + }, "%@ edited photos will also be saved" : { "extractionState" : "manual", "localizations" : { @@ -197,6 +282,23 @@ } } }, + "%@ is larger than that, so the free copy takes its first days." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ ist größer, daher übernimmt der kostenlose Kopiervorgang die ersten Tage davon." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ is larger than that, so the free copy takes its first days." + } + } + } + }, "%@ of %@ reviewed" : { "comment" : "A step indicator showing the current step number and the total number of steps.", "isCommentAutoGenerated" : true, @@ -227,6 +329,23 @@ } } }, + "%@ planned photos and videos were not copied. Your originals were not changed. See Problems." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ geplante Fotos und Videos wurden nicht kopiert. Deine Originale wurden nicht verändert. Siehe „Probleme“." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ planned photos and videos were not copied. Your originals were not changed. See Problems." + } + } + } + }, "%@ reclaimable" : { "comment" : "A label that indicates the amount of storage space that can be reclaimed by deleting the files in the current cluster. The argument is the amount of reclaimable storage space.", "isCommentAutoGenerated" : true, @@ -622,6 +741,57 @@ } } }, + "1 is not accounted for in this copy" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 ist in diesem Kopiervorgang nicht erfasst" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 is not accounted for in this copy" + } + } + } + }, + "1 is not in this plan yet" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 ist noch nicht in diesem Plan" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 is not in this plan yet" + } + } + } + }, + "1 is waiting for the next copy" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 wartet auf den nächsten Kopiervorgang" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 is waiting for the next copy" + } + } + } + }, "1 photo or video" : { "extractionState" : "manual", "localizations" : { @@ -639,6 +809,23 @@ } } }, + "1 planned photo or video was not copied. Your originals were not changed. See Problems." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 geplantes Foto oder Video wurde nicht kopiert. Deine Originale wurden nicht verändert. Siehe „Probleme“." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 planned photo or video was not copied. Your originals were not changed. See Problems." + } + } + } + }, "1 reviewed group" : { "extractionState" : "manual", "localizations" : { @@ -1196,6 +1383,23 @@ } } }, + "Add Another Folder" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Weiteren Ordner hinzufügen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Add Another Folder" + } + } + } + }, "Add Folders" : { "extractionState" : "manual", "localizations" : { @@ -1418,6 +1622,23 @@ } } }, + "All %1$@ photos and videos Chronoframe found are accounted for: %2$@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Alle %1$@ Fotos und Videos, die Chronoframe gefunden hat, sind erfasst: %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "All %1$@ photos and videos Chronoframe found are accounted for: %2$@." + } + } + } + }, "All clusters reviewed" : { "comment" : "A title displayed after all clusters have been reviewed.", "isCommentAutoGenerated" : true, @@ -1977,6 +2198,23 @@ } } }, + "Choose Another Month" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Anderen Monat wählen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose Another Month" + } + } + } + }, "Choose Destination…" : { "extractionState" : "manual", "localizations" : { @@ -2332,6 +2570,57 @@ } } }, + "Chronoframe found %1$@, and %2$@. Open History for the full record." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe hat %1$@ gefunden, und %2$@. Öffne den Verlauf für die vollständige Aufzeichnung." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe found %1$@, and %2$@. Open History for the full record." + } + } + } + }, + "Chronoframe found %1$@, and %2$@. Rebuild the preview before copying." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe hat %1$@ gefunden, und %2$@. Erstelle die Vorschau vor dem Kopieren neu." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe found %1$@, and %2$@. Rebuild the preview before copying." + } + } + } + }, + "Chronoframe found %1$@. This free copy handled %2$@; %3$@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe hat %1$@ gefunden. Dieser kostenlose Kopiervorgang hat %2$@ verarbeitet; %3$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe found %1$@. This free copy handled %2$@; %3$@." + } + } + } + }, "Chronoframe is a darkroom for time. Point it at a folder of photos and videos and it organizes a clean, dated copy at your destination — never moving, never overwriting your originals." : { "comment" : "A description of the functionality of Chronoframe.", "isCommentAutoGenerated" : true, @@ -2641,6 +2930,23 @@ } } }, + "Copies %@ now, %@, and leaves %@ for later." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kopiert jetzt %1$@ (%2$@) und lässt %3$@ für später übrig." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Copies %@ now, %@, and leaves %@ for later." + } + } + } + }, "Copies are validated before completion." : { "extractionState" : "manual", "localizations" : { @@ -2751,13 +3057,46 @@ "en" : { "stringUnit" : { "state" : "translated", - "value" : "Copies, duplicate cleanups, and reorganizes write receipts here when they can be undone safely." + "value" : "Copies, duplicate cleanups, and reorganizes write receipts here when they can be undone safely." + } + }, + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Kopiervorgänge, Duplikatbereinigungen und Neuordnungen speichern hier Belege, wenn sie sicher rückgängig gemacht werden können." + } + } + } + }, + "Copy %@ free" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ kostenlos kopieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Copy %@ free" + } + } + } + }, + "Copy %@ Free…" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ kostenlos kopieren…" } }, - "de" : { + "en" : { "stringUnit" : { "state" : "translated", - "value" : "Kopiervorgänge, Duplikatbereinigungen und Neuordnungen speichern hier Belege, wenn sie sicher rückgängig gemacht werden können." + "value" : "Copy %@ Free…" } } } @@ -3852,6 +4191,23 @@ } } }, + "Every one of the %@ photos and videos Chronoframe found is listed below." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Jedes der %@ Fotos und Videos, die Chronoframe gefunden hat, ist unten aufgeführt." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Every one of the %@ photos and videos Chronoframe found is listed below." + } + } + } + }, "Everything here is already in your organized library. Nothing needs copying." : { "extractionState" : "manual", "localizations" : { @@ -4585,6 +4941,23 @@ } } }, + "Have more photos somewhere else? Add that folder next. Photos already in your library are skipped." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hast du noch Fotos an einem anderen Ort? Füge diesen Ordner als Nächstes hinzu. Fotos, die bereits in deiner Mediathek sind, werden übersprungen." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Have more photos somewhere else? Add that folder next. Photos already in your library are skipped." + } + } + } + }, "Health Dashboard" : { "extractionState" : "manual", "localizations" : { @@ -5944,6 +6317,23 @@ } } }, + "One-time purchase with Family Sharing. No subscription." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Einmaliger Kauf mit Familienfreigabe. Kein Abo." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "One-time purchase with Family Sharing. No subscription." + } + } + } + }, "Open History" : { "extractionState" : "manual", "localizations" : { @@ -6200,6 +6590,40 @@ } } }, + "Organize all %@ file" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Die %@ Datei organisieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Organize all %@ file" + } + } + } + }, + "Organize all %@ files" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Alle %@ Dateien organisieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Organize all %@ files" + } + } + } + }, "Organize already sets aside exact copies it meets while copying. Deduplicate checks the whole library, including look-alikes." : { "extractionState" : "manual", "localizations" : { @@ -7150,6 +7574,40 @@ } } }, + "Remove all %@ duplicate" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Das %@ Duplikat entfernen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Remove all %@ duplicate" + } + } + } + }, + "Remove all %@ duplicates" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Alle %@ Duplikate entfernen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Remove all %@ duplicates" + } + } + } + }, "Reorganize" : { "comment" : "A heading displayed above the reorganize section.", "isCommentAutoGenerated" : true, @@ -8332,6 +8790,23 @@ } } }, + "Shows the files first. Nothing is copied until you confirm" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Zeigt zuerst die Dateien. Es wird nichts kopiert, bis du bestätigst" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Shows the files first. Nothing is copied until you confirm" + } + } + } + }, "Skipped because the same file is already in the library." : { "extractionState" : "manual", "localizations" : { @@ -8823,6 +9298,40 @@ } } }, + "The 1 photo or video Chronoframe found is accounted for: %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Das 1 Foto oder Video, das Chronoframe gefunden hat, ist erfasst: %@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The 1 photo or video Chronoframe found is accounted for: %@." + } + } + } + }, + "The 1 photo or video Chronoframe found is listed below." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Das 1 Foto oder Video, das Chronoframe gefunden hat, ist unten aufgeführt." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The 1 photo or video Chronoframe found is listed below." + } + } + } + }, "The app uses macOS sandboxed folder access. Choose your folders and destination with the standard folder picker; access is scoped to those choices and saved with security-scoped bookmarks." : { "extractionState" : "manual", "localizations" : { @@ -8891,6 +9400,57 @@ } } }, + "The newest month that fits is %1$@: %2$@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Der neueste Monat, der hineinpasst, ist %1$@: %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The newest month that fits is %1$@: %2$@." + } + } + } + }, + "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Diese %@ neuen Fotos und Videos werden in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed." + } + } + } + }, + "This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dieses %@ neue Foto oder Video wird in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed." + } + } + } + }, "This Is the Same Library" : { "extractionState" : "manual", "localizations" : { @@ -9299,6 +9859,22 @@ } } }, + "Undo This Copy…" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Diesen Kopiervorgang rückgängig machen…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Undo This Copy…" + } + } + } + }, "Undone" : { "extractionState" : "manual", "localizations" : { @@ -9332,6 +9908,40 @@ } } }, + "Unlock to Copy Everything" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Freischalten, um alles zu kopieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unlock to Copy Everything" + } + } + } + }, + "Unlock to Copy the Rest" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Freischalten, um den Rest zu kopieren" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unlock to Copy the Rest" + } + } + } + }, "Untested" : { "comment" : "A badge that indicates that a test has not yet been run.", "isCommentAutoGenerated" : true, @@ -9910,6 +10520,23 @@ } } }, + "You can copy %1$@ free. This plan has %2$@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Du kannst %1$@ kostenlos kopieren. Dieser Plan umfasst %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "You can copy %1$@ free. This plan has %2$@." + } + } + } + }, "You can keep using your Mac. Nothing is being copied." : { "extractionState" : "manual", "localizations" : { @@ -10080,6 +10707,23 @@ } } }, + "Your free copies are used up. This plan has %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Deine kostenlosen Kopien sind aufgebraucht. Dieser Plan umfasst %@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your free copies are used up. This plan has %@." + } + } + } + }, "Your organized library already has everything it needs." : { "extractionState" : "manual", "localizations" : { diff --git a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings index ca3dceaa..80f542cf 100644 --- a/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings +++ b/ui/Sources/ChronoframeAppCore/Resources/LocalizableCore.xcstrings @@ -1953,6 +1953,23 @@ } } }, + "Copies %@ now, %@, and leaves %@ for later.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Kopiert jetzt %1$@ (%2$@) und lässt %3$@ für später übrig." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Copies %@ now, %@, and leaves %@ for later." + } + } + } + }, "Copy": { "extractionState": "manual", "localizations": { @@ -1970,6 +1987,23 @@ } } }, + "Copy %@ free": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ kostenlos kopieren" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Copy %@ free" + } + } + } + }, "Copy from Apple Photos": { "extractionState": "manual", "localizations": { @@ -2433,6 +2467,57 @@ } } }, + "One-time purchase with Family Sharing. No subscription.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Einmaliger Kauf mit Familienfreigabe. Kein Abo." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "One-time purchase with Family Sharing. No subscription." + } + } + } + }, + "Organize all %@ file": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Die %@ Datei organisieren" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Organize all %@ file" + } + } + } + }, + "Organize all %@ files": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Alle %@ Dateien organisieren" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Organize all %@ files" + } + } + } + }, "Past copies, reports and undo": { "extractionState": "manual", "localizations": { @@ -2484,6 +2569,40 @@ } } }, + "Remove all %@ duplicate": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Das %@ Duplikat entfernen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Remove all %@ duplicate" + } + } + } + }, + "Remove all %@ duplicates": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Alle %@ Duplikate entfernen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Remove all %@ duplicates" + } + } + } + }, "Remove extra copies": { "extractionState": "manual", "localizations": { @@ -2745,6 +2864,40 @@ } } }, + "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Diese %@ neuen Fotos und Videos werden in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "These %@ new photos and videos will be copied into your library. Nothing else is copied, and your originals are not changed." + } + } + } + }, + "This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed.": { + "extractionState": "manual", + "localizations": { + "de": { + "stringUnit": { + "state": "translated", + "value": "Dieses %@ neue Foto oder Video wird in deine Mediathek kopiert. Sonst wird nichts kopiert, und deine Originale werden nicht verändert." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "This %@ new photo or video will be copied into your library. Nothing else is copied, and your originals are not changed." + } + } + } + }, "This file changed while Chronoframe was checking it, so it wasn't compared.": { "extractionState": "manual", "localizations": { From f461bfe847972e8bc6915457aefb6dcd27160dce Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:38:23 -0800 Subject: [PATCH 10/30] FRX G1: gate Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../first-run-experience/ACCEPTANCE_MATRIX.md | 12 ++++++------ docs/plan/first-run-experience/PROGRESS.md | 16 ++++++++++++---- script/swift_meaningful_coverage.sh | 2 ++ ui/Xcode/UITests/A11yBaseline.json | 4 ++-- ui/Xcode/UITests/ChronoframeUITests.swift | 4 ++-- 5 files changed, 24 insertions(+), 14 deletions(-) diff --git a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md index 74e39ce7..84e46305 100644 --- a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md +++ b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md @@ -1,14 +1,14 @@ # First-run experience — acceptance matrix -Status: not started. No row is 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 and 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 | |---|---|---|---|---|---| -| A-FRX-01 | Preview and completion say whether every file found is accounted for, and never claim it when the numbers disagree (rec 2) | ChronoframeCoreRunAccountingTests/*; RunAccountingTextTests/*; RunWorkspaceModelTests/testAccountingLineOnlyForReadyPreviewAndFinishedCopy, testCopyCompleteAndPreviewFixturesAreBalanced | H-FRX-1 | todo | todo-owner | -| A-FRX-02 | The completion screen can undo that copy through the hash-checked revert (rec 2) | SwiftOrganizerEngineIntegrationTests/testTransferSummaryCarriesReceiptPath; AppStateTests/testLastCopyUndoEntryMatchesReceiptPath, testNoUndoEntryWithoutReceiptPath, testUndoLastCopyRevertsThatReceiptOnly | H-FRX-1 | todo | todo-owner | -| 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 | todo | 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 | todo | 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 | todo | todo-owner | +| A-FRX-01 | Preview and completion say whether every file found is accounted for, and never claim it when the numbers disagree (rec 2) | ChronoframeCoreRunAccountingTests/*; RunAccountingTextTests/*; RunWorkspaceModelTests/testAccountingLineOnlyForReadyPreviewAndFinishedCopy, testCopyCompleteAndPreviewFixturesAreBalanced | H-FRX-1 | pass-auto | todo-owner | +| A-FRX-02 | The completion screen can undo that copy through the hash-checked revert (rec 2) | SwiftOrganizerEngineIntegrationTests/testTransferSummaryCarriesReceiptPath; AppStateTests/testLastCopyUndoEntryMatchesReceiptPath, testNoUndoEntryWithoutReceiptPath, testUndoLastCopyRevertsThatReceiptOnly | H-FRX-1 | pass-auto | todo-owner | +| 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 | diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 6149c820..5388572f 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). +Status: in progress. M1 gate G1 passed 2026-11-28; M2 next. 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). @@ -18,8 +18,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-03 | AppCore: engine, offer, unlock presentation | done | build exit 0 | TrialRemaining 4, FreeMonthBatchOffer 11, UnlockPresentation 19, UnlockSheetBatchOffer 14, FreeTestBatchOffer 9, FreeTestBatchRun 4, SwiftOrganizerEngineIntegration 43 tests, all exit 0 | approve (round 1) | c1dee6f | orchestrator read the full SwiftOrganizerEngine.swift and TrialAuthorizer.swift diffs: every changed line traces to C-03/C-06; the month-request branch throws before `plan.reduced(to:)`, so it reaches neither `authorizeTransfer` nor the job queue; D-FRX-103, D-FRX-104 | | 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) | (WP-06 commit) | 38 App keys + 9 Core keys added; D-FRX-107 | -| G1 | Gate, M1 | todo | | | n/a | | | +| 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 | @@ -38,10 +38,16 @@ 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 | +| G1 | ui/Xcode/UITests/A11yBaseline.json:48, :50 | "84, FOUND" | "72, FOUND" | C-08, D-FRX-23 | ## Renders checked | Gate | File | Checked against | Result | |---|---|---|---| +| 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 | +| G1 | .tmp/frx-evidence/m1-unlock-dedupe.png | C-06 | matches: title "Remove all 25 duplicates"; same terms line | ## Log - 2026-11-28 WP-01 Done-when (orchestrator): `cf_swift.sh test ScreenRenderEvidenceTests` exit 0 without marker (3 skipped); with `.tmp/frx-evidence/.enabled` exit 0, 3 PNGs (`m1-copy-complete`, `m1-unlock-organize`, `m1-unlock-dedupe`); `cf_swift.sh build` exit 0; `git diff --check` exit 0. Marker removed afterwards. @@ -57,4 +63,6 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 2026-11-28 WP-06: `add_translated_keys.py … Localizable.xcstrings … M1-app.json` exit 0 (added 38, kept 1); `… LocalizableCore.xcstrings … M1-core.json` exit 0 (added 9). German review (cf-reviewer): three corrections applied (`Kopie` → `Kopiervorgang` twice; parentheses in the month batch detail). Docs (C-26): QUICK_START, FAQ, README, SAFETY_AND_RECOVERY; review round 1 asked for two corrections (subset guarantee; the not-copied case) and six tidy-ups, all applied; round 2 approve. `cf_swift.sh build` exit 0 after the symbol-collision fix (D-FRX-107); `git diff --check` exit 0. - Noticed, not fixed: C-02's unbalanced preview line uses `abs(remainder)`, so when the plan holds more files than were found it still says "N are not in this plan yet". Contract wording; left as is. - Noticed, not fixed: `docs/QUICK_START.md` keeps the older tip "Don't delete your originals yet. Keep them for a few days…", which gently implies originals may be deleted later. Pre-existing, outside M1. - +- 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. diff --git a/script/swift_meaningful_coverage.sh b/script/swift_meaningful_coverage.sh index 1ea5ea67..58c49a6b 100755 --- a/script/swift_meaningful_coverage.sh +++ b/script/swift_meaningful_coverage.sh @@ -73,6 +73,8 @@ fi # can't silently shrink when a file is renamed or removed. MEANINGFUL_BASENAMES=( BLAKE2bHasher + RunAccounting + FreeMonthBatchPlanner CopyPlanBuilder DryRunPlanner EditedVariantDestinations diff --git a/ui/Xcode/UITests/A11yBaseline.json b/ui/Xcode/UITests/A11yBaseline.json index ef19e307..4e58c368 100644 --- a/ui/Xcode/UITests/A11yBaseline.json +++ b/ui/Xcode/UITests/A11yBaseline.json @@ -45,9 +45,9 @@ "role": "staticText", "identifier": "", "label": "", - "value": "84, FOUND", + "value": "72, FOUND", "compactDescription": "Contrast failed", - "detailedDescription": "Contrast failed for 84, FOUND" + "detailedDescription": "Contrast failed for 72, FOUND" }, { "scenario": "runPreviewReview", diff --git a/ui/Xcode/UITests/ChronoframeUITests.swift b/ui/Xcode/UITests/ChronoframeUITests.swift index 085852cd..2015962f 100644 --- a/ui/Xcode/UITests/ChronoframeUITests.swift +++ b/ui/Xcode/UITests/ChronoframeUITests.swift @@ -542,9 +542,9 @@ final class ChronoframeUITests: XCTestCase { role: "staticText", identifier: "", label: "", - value: "discovered: 84, planned: 42, copied: 0, already there: 29, duplicates: 7, issues: 1", + value: "discovered: 72, planned: 42, copied: 0, already there: 29, duplicates: 7, issues: 1", compactDescription: "Contrast failed", - detailedDescription: "Contrast failed for discovered: 84, planned: 42, copied: 0, already there: 29, duplicates: 7, issues: 1" + detailedDescription: "Contrast failed for discovered: 72, planned: 42, copied: 0, already there: 29, duplicates: 7, issues: 1" ) XCTAssertFalse(Self.isAllowedAccessibilityAuditIssue( tickerIssue, From ef6dc6977911672a0e180702a72cb8122140bf3d Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:40:21 -0800 Subject: [PATCH 11/30] FRX WP-10: Branch and baseline, M2 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/PROGRESS.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 5388572f..17e2a949 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -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,9 +20,9 @@ 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 | +| 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 | (WP-10 commit) | anchors recorded under Baseline | +| WP-11 | Core: review lane, free removal batch | in-progress | | | | | 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 | | | | | | From f5593622fac96f7efad88805ac511baf85edec31 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:52:16 -0800 Subject: [PATCH 12/30] FRX WP-11: Core: review lane and free removal batch Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/BLOCKED.md | 13 +- docs/plan/first-run-experience/DECISIONS.md | 3 +- docs/plan/first-run-experience/PROGRESS.md | 10 +- .../DeduplicateReviewLane.swift | 38 ++ .../FreeDedupeBatchPlanner.swift | 92 +++ ...oframeCoreDeduplicateReviewLaneTests.swift | 132 +++++ ...frameCoreFreeDedupeBatchPlannerTests.swift | 547 ++++++++++++++++++ 7 files changed, 830 insertions(+), 5 deletions(-) create mode 100644 ui/Sources/ChronoframeCore/DeduplicateReviewLane.swift create mode 100644 ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreDeduplicateReviewLaneTests.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift diff --git a/docs/plan/first-run-experience/BLOCKED.md b/docs/plan/first-run-experience/BLOCKED.md index 6ceb6c65..a8132f12 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: one open item (B-1). It does not block any work package; it needs an owner decision before M2 is merged. 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:** open diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index a6e931a0..ecb00cf2 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -38,7 +38,7 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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.` ## 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,4 @@ 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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 17e2a949..2591f966 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -21,9 +21,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | 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 | (WP-10 commit) | anchors recorded under Baseline | -| WP-11 | Core: review lane, free removal batch | in-progress | | | | | safety-critical; extra opus review | -| WP-12 | AppCore: store lanes, accept by lane, batch plan | todo | | | | | orchestrator reads the full diff | +| 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 | (WP-11 commit) | 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 | in-progress | | | | | 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 | | | @@ -67,3 +67,7 @@ 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. + 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<UUID> = [] + 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..56356134 --- /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..<full.count { + if let batch = fixture.batch(limit: limit) { + XCTAssertLessThanOrEqual(batch.plan.count, limit, "limit \(limit)") + XCTAssertGreaterThan(batch.plan.count, 0, "limit \(limit)") + } + } + // Limit 1 cannot take any group here: the smallest identical group has two files. + XCTAssertNil(fixture.batch(limit: 1)) + XCTAssertEqual(fixture.batch(limit: 2)?.plan.count, 2) + // Limit 7 takes a, b and c (6 files); d would make 8, so the walk stops there. + XCTAssertEqual(fixture.batch(limit: 7)?.plan.count, 6) + } + + func testIdenticalGroupsAreTakenFirst() throws { + var fixture = Fixture() + let lookAtEach = fixture.addGroup("look", deletes: 2, lane: .lookAtEach) + let nearly = fixture.addGroup("nearly", deletes: 2, lane: .nearlyIdentical) + let identical = fixture.addGroup("same", deletes: 2, lane: .identical) + XCTAssertEqual(DeduplicateReviewLane.lane(for: identical, snapshot: fixture.snapshot), .identical) + XCTAssertEqual(DeduplicateReviewLane.lane(for: nearly, snapshot: fixture.snapshot), .nearlyIdentical) + XCTAssertEqual(DeduplicateReviewLane.lane(for: lookAtEach, snapshot: fixture.snapshot), .lookAtEach) + XCTAssertEqual(fixture.fullPlan().count, 6) + + let first = try XCTUnwrap(fixture.batch(limit: 2)) + XCTAssertEqual(first.includedClusterIDs, [identical.id]) + XCTAssertEqual(Set(first.plan.items.map(\.path)), identical.deletePaths) + + let second = try XCTUnwrap(fixture.batch(limit: 4)) + XCTAssertEqual(second.includedClusterIDs, [identical.id, nearly.id]) + XCTAssertEqual(second.plan.count, 4) + + // Limit 3 takes the identical group, then stops when the next group no longer fits. + let third = try XCTUnwrap(fixture.batch(limit: 3)) + XCTAssertEqual(third.includedClusterIDs, [identical.id]) + } + + func testStopsAtFirstGroupThatDoesNotFit() throws { + var fixture = Fixture() + let small = fixture.addGroup("small", deletes: 1, lane: .lookAtEach) + _ = fixture.addGroup("large", deletes: 3, lane: .lookAtEach) + let later = fixture.addGroup("later", deletes: 1, lane: .lookAtEach) + XCTAssertEqual(fixture.fullPlan().count, 5) + + let batch = try XCTUnwrap(fixture.batch(limit: 3)) + XCTAssertEqual(batch.includedClusterIDs, [small.id]) + XCTAssertEqual(batch.plan.count, 1) + XCTAssertTrue(batch.plan.items.allSatisfy { !later.deletePaths.contains($0.path) }, + "a later group that would fit is not taken once the walk has stopped") + } + + // MARK: Safety + + // AGENTS-INVARIANT: 17 + func testBatchPlanIsSubsetOfFullPlanWithSameIdentities() throws { + var fixture = Fixture() + fixture.addGroup("a", deletes: 2, lane: .identical) + fixture.addGroup("b", deletes: 2, lane: .nearlyIdentical) + fixture.addGroup("c", deletes: 2, lane: .lookAtEach) { members in + members[1].pairedPath = "/fx/c/d1.mov" + members[1].isLivePhotoStill = true + } + let full = fixture.fullPlan() + let fullByPath = Dictionary(uniqueKeysWithValues: full.items.map { ($0.path, $0) }) + XCTAssertEqual(full.count, 7, "six direct deletions plus the Live Photo partner") + + for limit in 1..<full.count { + guard let batch = fixture.batch(limit: limit) else { continue } + for item in batch.plan.items { + let fullItem = try XCTUnwrap(fullByPath[item.path], "limit \(limit): \(item.path) is not in the full plan") + XCTAssertEqual(item.expectedIdentity, fullItem.expectedIdentity) + XCTAssertEqual(item.expectedIdentity, fixture.snapshot.identitiesByPath[item.path]) + } + } + } + + // AGENTS-INVARIANT: 14 + func testPairPartnerInLeftOutGroupKeepsBothHalves() throws { + var fixture = Fixture() + // Group C is identical-lane and fits the limit on its own. + let c = fixture.addGroup("c", deletes: 1, lane: .identical) + // a/d1 and b/d1 are a RAW+JPEG pair; both are marked Delete in the full review. + let a = fixture.addGroup("a", deletes: 1, lane: .lookAtEach) { members in + members[1].pairedPath = "/fx/b/d1.jpg" + } + let b = fixture.addGroup("b", deletes: 1, lane: .lookAtEach) { members in + members[1].pairedPath = "/fx/a/d1.jpg" + } + let full = fixture.fullPlan() + XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/c/d1.jpg", "/fx/a/d1.jpg", "/fx/b/d1.jpg"]) + + let batch = try XCTUnwrap(fixture.batch(limit: 1)) + XCTAssertEqual(batch.includedClusterIDs, [c.id]) + let paths = Set(batch.plan.items.map(\.path)) + XCTAssertEqual(paths, ["/fx/c/d1.jpg"]) + XCTAssertFalse(paths.contains("/fx/a/d1.jpg"), "a pair half whose partner's group is left out stays") + XCTAssertFalse(paths.contains("/fx/b/d1.jpg")) + XCTAssertFalse(batch.plan.items.contains { $0.owningClusterID == a.id || $0.owningClusterID == b.id }) + + // With limit 2 the pair still never splits: group A alone would have to + // drop its half because B is forced Keep, so the walk accepts it empty + // and then B joins only when the whole unit fits. + let wide = try XCTUnwrap(fixture.batch(limit: 2)) + let widePaths = Set(wide.plan.items.map(\.path)) + XCTAssertEqual(widePaths.contains("/fx/a/d1.jpg"), widePaths.contains("/fx/b/d1.jpg")) + } + + // AGENTS-INVARIANT: 14 + func testSharedSidecarSurvivesWhenAnOwnerIsLeftOut() throws { + var fixture = Fixture() + fixture.addGroup("a", deletes: 1, lane: .lookAtEach) { members in + members[1].sidecarPaths = ["/fx/shared.xmp"] + } + fixture.addGroup("b", deletes: 1, lane: .lookAtEach) { members in + members[1].sidecarPaths = ["/fx/shared.xmp"] + } + fixture.sidecarOwners["/fx/shared.xmp"] = ["/fx/a/d1.jpg", "/fx/b/d1.jpg"] + + let full = fixture.fullPlan() + XCTAssertEqual( + Set(full.items.map(\.path)), + ["/fx/a/d1.jpg", "/fx/b/d1.jpg", "/fx/shared.xmp"], + "premise: when both owners go, the shared sidecar goes with them" + ) + + let batch = try XCTUnwrap(fixture.batch(limit: 1)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/a/d1.jpg"]) + XCTAssertFalse(batch.plan.items.contains { $0.path == "/fx/shared.xmp" }, + "a sidecar is deleted only when every owner is deleted") + } + + func testNoGroupIsEmptiedByTheBatch() throws { + var fixture = Fixture() + fixture.addGroup("a", deletes: 2, lane: .identical) + // Every member explicitly Delete: the planner's rail skips this group. + let allDelete = fixture.addGroup("allDelete", deletes: 2, lane: .lookAtEach) + fixture.decisions.byPath[allDelete.members[0].path] = .delete + fixture.addGroup("b", deletes: 2, lane: .nearlyIdentical) + fixture.addGroup("c", deletes: 1, lane: .lookAtEach) + + let full = fixture.fullPlan() + XCTAssertFalse(full.items.contains { allDelete.deletePaths.contains($0.path) }, + "premise: the all-Delete group is skipped by the planner") + + for limit in 1..<full.count { + guard let batch = fixture.batch(limit: limit) else { continue } + let deleted = Set(batch.plan.items.map(\.path)) + for cluster in fixture.clusters { + let members = Set(cluster.members.map(\.path)) + XCTAssertFalse(members.isSubset(of: deleted), "limit \(limit): group \(cluster.id) was emptied") + } + } + } + + func testDeferredCountIsFullMinusBatch() throws { + var fixture = Fixture() + fixture.addGroup("a", deletes: 2, lane: .identical) + fixture.addGroup("b", deletes: 3, lane: .nearlyIdentical) + fixture.addGroup("c", deletes: 2, lane: .lookAtEach) + let fullCount = fixture.fullPlan().count + XCTAssertEqual(fullCount, 7) + + for limit in 2..<fullCount { + guard let batch = fixture.batch(limit: limit) else { continue } + XCTAssertEqual(batch.deferredFileCount, fullCount - batch.plan.count, "limit \(limit)") + XCTAssertGreaterThan(batch.deferredFileCount, 0) + } + XCTAssertEqual(try XCTUnwrap(fixture.batch(limit: 5)).deferredFileCount, 2) + } + + func testPairKeepOverridesArePreserved() throws { + var fixture = Fixture() + // a/d1 is a Live Photo still whose MOV is not in any cluster; the person kept the MOV. + fixture.addGroup("a", deletes: 1, lane: .lookAtEach) { members in + members[1].pairedPath = "/fx/a/d1.mov" + members[1].isLivePhotoStill = true + } + fixture.addGroup("c", deletes: 2, lane: .lookAtEach) + fixture.decisions.pairKeepOverrides = ["/fx/a/d1.mov"] + + // Premise: without the override the MOV would follow its still. + var withoutOverride = fixture.decisions + withoutOverride.pairKeepOverrides = [] + let unprotected = DeduplicationPlanner.plan( + decisions: withoutOverride, + clusters: fixture.clusters, + configuration: fixture.configuration, + snapshot: fixture.snapshot + ) + XCTAssertTrue(unprotected.items.contains { $0.path == "/fx/a/d1.mov" }) + + let full = fixture.fullPlan() + XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/a/d1.jpg", "/fx/c/d1.jpg", "/fx/c/d2.jpg"]) + + let batch = try XCTUnwrap(fixture.batch(limit: 2)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/a/d1.jpg"]) + XCTAssertFalse(batch.plan.items.contains { $0.path == "/fx/a/d1.mov" }) + } + + func testForcedKeepThatWouldUnskipAGroupStopsTheWalk() { + var fixture = Fixture() + // Group Y: y1 and y2 are both Delete (the planner's rail skips Y), and y1 is + // paired with z1. Group Z: z1 is Delete, z2 is Keep. + fixture.addGroup("y", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/y/y1.jpg" + members[1].path = "/fx/y/y2.jpg" + members[0].pairedPath = "/fx/z/z1.jpg" + } + let z = fixture.addGroup("z", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/z/z2.jpg" + members[1].path = "/fx/z/z1.jpg" + members[1].pairedPath = "/fx/y/y1.jpg" + } + let w = fixture.addGroup("w", deletes: 1, lane: .lookAtEach) + fixture.decisions.byPath = [ + "/fx/y/y1.jpg": .delete, + "/fx/y/y2.jpg": .delete, + "/fx/z/z1.jpg": .delete, + "/fx/z/z2.jpg": .keep, + "/fx/w/keep.jpg": .keep, + "/fx/w/d1.jpg": .delete, + ] + // Y's members: members[0] and [1] are y1 and y2, both Delete. + + let full = fixture.fullPlan() + XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/z/z1.jpg", "/fx/y/y1.jpg", "/fx/w/d1.jpg"], + "premise: Y is skipped, z1 is deleted and fans out to y1") + + // The candidate the walk builds first: Y selected, Z and W forced Keep. + var yOnly = fixture.decisions + for cluster in [z, w] { + for member in cluster.members { yOnly.byPath[member.path] = .keep } + } + let rejected = DeduplicationPlanner.plan( + decisions: yOnly, + clusters: fixture.clusters, + configuration: fixture.configuration, + snapshot: fixture.snapshot + ) + XCTAssertEqual(rejected.items.map(\.path), ["/fx/y/y2.jpg"], + "forcing Z to Keep flips y1 to Keep and un-skips Y, which deletes y2") + XCTAssertFalse(full.items.contains { $0.path == "/fx/y/y2.jpg" }) + + // Limit 2: the Y-only candidate fits the limit but is not in the full plan, so + // the walk stops. It must not skip ahead to Y+Z = {z1, y1}, which would fit. + XCTAssertNil(fixture.batch(limit: 2)) + + // Sanity: the walk without that trap would have been able to take Y+Z. + var yAndZ = fixture.decisions + for member in w.members { yAndZ.byPath[member.path] = .keep } + let skipped = DeduplicationPlanner.plan( + decisions: yAndZ, + clusters: fixture.clusters, + configuration: fixture.configuration, + snapshot: fixture.snapshot + ) + XCTAssertEqual(Set(skipped.items.map(\.path)), ["/fx/z/z1.jpg", "/fx/y/y1.jpg"]) + } + + // MARK: Property + + func testPropertyRandomReviewsNeverExceedLimitOrLeaveTheFullPlan() { + var prng = FreeBatchPRNG(seed: 0xF4EE_BA7C_0DED_0001) + let cases = 300 + var nonNil = 0 + var rejectedWalks = 0 + + for iteration in 0..<cases { + let fixture = randomFixture(prng: &prng) + let full = fixture.fullPlan() + let limit = prng.intInRange(0...(max(1, full.count) + 1)) + let batch = fixture.batch(limit: limit) + + if full.count <= limit || limit <= 0 { + XCTAssertNil(batch, "iteration \(iteration): limit \(limit), full \(full.count)") + continue + } + guard let batch else { + rejectedWalks += 1 + continue + } + nonNil += 1 + + XCTAssertLessThanOrEqual(batch.plan.count, limit, "iteration \(iteration)") + XCTAssertGreaterThan(batch.plan.count, 0, "iteration \(iteration)") + XCTAssertEqual(batch.deferredFileCount, full.count - batch.plan.count, "iteration \(iteration)") + + let fullByPath = Dictionary(uniqueKeysWithValues: full.items.map { ($0.path, $0) }) + for item in batch.plan.items { + guard let fullItem = fullByPath[item.path] else { + XCTFail("iteration \(iteration): \(item.path) is in the batch but not in the full plan") + continue + } + XCTAssertEqual(item.expectedIdentity, fullItem.expectedIdentity, "iteration \(iteration)") + } + + let deleted = Set(batch.plan.items.map(\.path)) + for cluster in fixture.clusters { + let members = Set(cluster.members.map(\.path)) + XCTAssertFalse( + members.isSubset(of: deleted), + "iteration \(iteration): batch deleted every member of \(cluster.id)" + ) + } + + let fullOwners = Set(batch.plan.items.map(\.owningClusterID)) + XCTAssertEqual(Set(batch.includedClusterIDs), fullOwners, "iteration \(iteration)") + } + + // The generator must exercise both outcomes or the property proves nothing. + XCTAssertGreaterThan(nonNil, 40, "too few cases produced a batch (\(nonNil) of \(cases))") + XCTAssertGreaterThan(rejectedWalks, 0, "no case ended without a batch") + } +} + +// MARK: - Fixture + +private struct Fixture { + var clusters: [DuplicateCluster] = [] + var decisions = DedupeDecisions() + var sidecarOwners: [String: Set<String>] = [:] + 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<String> { 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..<clusterCount { + let memberCount = prng.intInRange(2...4) + let members = (0..<memberCount).map { memberIndex in + PhotoCandidate(path: "/fx/c\(clusterIndex)/m\(memberIndex).jpg", size: 1_000, modificationTime: 0) + } + membersByCluster.append(members) + lanes.append(DeduplicateReviewLane.allCases[prng.intInRange(0...2)]) + } + + // Cross-group pairs, so one group's Delete can be a partner of another group's file. + var paired: Set<String> = [] + for _ in 0..<prng.intInRange(0...3) { + let a = prng.intInRange(0...(clusterCount - 1)) + let b = prng.intInRange(0...(clusterCount - 1)) + guard a != b else { continue } + let ai = prng.intInRange(0...(membersByCluster[a].count - 1)) + let bi = prng.intInRange(0...(membersByCluster[b].count - 1)) + let pathA = membersByCluster[a][ai].path + let pathB = membersByCluster[b][bi].path + guard !paired.contains(pathA), !paired.contains(pathB) else { continue } + paired.insert(pathA) + paired.insert(pathB) + let live = prng.bool() + membersByCluster[a][ai].pairedPath = pathB + membersByCluster[b][bi].pairedPath = pathA + membersByCluster[a][ai].isLivePhotoStill = live + membersByCluster[b][bi].isLivePhotoStill = live + } + + // Singleton partners that no cluster contains, some with a per-pair Keep override. + for clusterIndex in 0..<clusterCount where prng.intInRange(0...3) == 0 { + let memberIndex = prng.intInRange(0...(membersByCluster[clusterIndex].count - 1)) + guard !paired.contains(membersByCluster[clusterIndex][memberIndex].path) else { continue } + let partner = "/fx/c\(clusterIndex)/m\(memberIndex).mov" + membersByCluster[clusterIndex][memberIndex].pairedPath = partner + membersByCluster[clusterIndex][memberIndex].isLivePhotoStill = true + paired.insert(membersByCluster[clusterIndex][memberIndex].path) + if prng.bool() { fixture.decisions.pairKeepOverrides.insert(partner) } + } + + // A sidecar shared by two members of different groups. + if clusterCount >= 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..<clusterCount { + let cluster = Fixture.makeCluster(members: membersByCluster[clusterIndex], lane: lanes[clusterIndex]) + fixture.clusters.append(cluster) + // Mostly explicit choices; the rest fall to the planner's own defaults. + for member in cluster.members where prng.intInRange(0...4) != 0 { + fixture.decisions.byPath[member.path] = prng.intInRange(0...2) == 0 ? .keep : .delete + } + } + return fixture +} + +private struct FreeBatchPRNG { + private var state: UInt64 + + init(seed: UInt64) { + state = seed == 0 ? 0xDEAD_BEEF_5A5A_C0DE : seed + } + + mutating func next() -> UInt64 { + state ^= state >> 12 + state ^= state << 25 + state ^= state >> 27 + return state &* 0x2545_F491_4F6C_DD1D + } + + mutating func intInRange(_ range: ClosedRange<Int>) -> Int { + let span = UInt64(range.upperBound - range.lowerBound + 1) + return range.lowerBound + Int(next() % span) + } + + mutating func bool() -> Bool { + next() & 1 == 1 + } +} From 89b21a842459892048cf32cbe28763c76f2e40cb Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 18:59:06 -0800 Subject: [PATCH 13/30] FRX WP-12: AppCore: store lanes, accept by lane, free batch plan Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 10 +- .../Stores/DeduplicateSessionStore.swift | 140 +++++- .../DeduplicateSessionStoreTests.swift | 445 ++++++++++++++++++ 4 files changed, 588 insertions(+), 8 deletions(-) diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index ecb00cf2..50dbfdce 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -54,3 +54,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 2591f966..5f31bc18 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -22,9 +22,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | 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 | (WP-11 commit) | 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 | in-progress | | | | | orchestrator reads the full diff | -| WP-13 | App: three lanes, Quick Review, footer, free removal | todo | | | | | | +| 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) | (WP-12 commit) | 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 | in-progress | | | | | | | WP-14 | Docs and strings, M2 | todo | | | | | | | G2 | Gate, M2 | todo | | | n/a | | | | WP-20 | Branch and baseline, M3 | todo | | | n/a | | lists FolderAccessServicing conformers | @@ -70,4 +70,6 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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. 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<DuplicateCluster.ID> = [] + @Published public var approvedClusterIDs: Set<DuplicateCluster.ID> = [] { + 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<DuplicateCluster.ID>, + 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<DuplicateCluster.ID> { + 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/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) + } } From e32144528e0dde4d751b8dc68d147545f94c4b4f Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 19:17:38 -0800 Subject: [PATCH 14/30] FRX WP-13: App: three lanes, Quick Review scope, footer, free removal Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 2 + docs/plan/first-run-experience/PROGRESS.md | 12 +- .../App/AccessibilityIdentifiers.swift | 5 + ui/Sources/ChronoframeApp/App/AppState.swift | 28 ++ ui/Sources/ChronoframeApp/App/Tips.swift | 4 +- .../App/UITesting/UITestAppStateFactory.swift | 83 +++++- .../App/UITesting/UITestDoubles.swift | 9 +- .../App/UITesting/UITestScenario.swift | 5 +- .../Deduplicate/DeduplicateReviewLanes.swift | 253 ++++++++++++++++-- .../Views/Deduplicate/DeduplicateView.swift | 195 +++++++++++--- .../Views/Deduplicate/RapidTriageView.swift | 69 ++++- .../Views/Purchase/UnlockSheet.swift | 44 ++- .../ChronoframeApp/Views/RootSplitView.swift | 2 + .../Services/UnlockPresentation.swift | 31 ++- .../UnlockPresentationTests.swift | 100 +++++++ .../UnlockSheetBatchOfferTests.swift | 1 + .../ChronoframeAppTests/AppStateTests.swift | 169 +++++++++++- .../DeduplicateReviewLanesTests.swift | 115 ++++++++ .../DeduplicateReviewViewsTests.swift | 227 ++++++++++++++++ .../DeduplicateStatusViewTests.swift | 23 +- .../ScreenRenderEvidenceTests.swift | 11 + ui/Tests/ChronoframeAppTests/TipsTests.swift | 2 +- .../UITestWindowFitTests.swift | 18 ++ 23 files changed, 1314 insertions(+), 94 deletions(-) diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 50dbfdce..d53e51bb 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -55,3 +55,5 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 5f31bc18..9a0bf413 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -23,9 +23,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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) | (WP-12 commit) | 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 | in-progress | | | | | | -| WP-14 | Docs and strings, M2 | todo | | | | | | +| 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) | (WP-13 commit) | 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 | in-progress | | | | | | | G2 | Gate, M2 | todo | | | n/a | | | | WP-20 | Branch and baseline, M3 | todo | | | n/a | | lists FolderAccessServicing conformers | | WP-21 | Core and AppCore groundwork | todo | | | | | | @@ -40,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 @@ -73,3 +77,5 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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. 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..70211b1b 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -551,6 +551,34 @@ 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 + 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/Views/Deduplicate/DeduplicateReviewLanes.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift index 46f02660..46caca6d 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<DuplicateCluster.ID>, + 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,87 @@ 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 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..7725737a 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,19 @@ struct DeduplicateView: View { Divider() Button("Quick Review") { - showingRapidTriage = true + openQuickReview(.lookAtEach) } .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 +811,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 +825,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 +846,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 +1232,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 +1243,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 +1327,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<DuplicateCluster.ID>, + 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/Services/UnlockPresentation.swift b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift index 216e6421..951a512f 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,15 @@ 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(Self.batchDetail) + let batchDetail = batch.flatMap(Self.batchDetail) ?? dedupeBatch.map(Self.dedupeBatchDetail) let purchaseTermsLine = Self.purchaseTermsLine(for: refusal) // Never offer a purchase this customer may not need. `purchaseUnconfirmed` @@ -194,6 +203,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/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift index 87269d3c..3c906765 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift @@ -316,6 +316,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..b74bcd06 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,170 @@ 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) + } + + @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<DuplicateCluster.ID>, 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..3f87e98c 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,228 @@ 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") + } } 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) From b4a1774c8b109daecc72373442206930e3e66216 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 19:24:16 -0800 Subject: [PATCH 15/30] FRX WP-14: strings and docs Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 6 +- docs/FAQ.md | 10 + docs/QUICK_START.md | 18 +- docs/SAFETY_AND_RECOVERY.md | 37 +- docs/TECHNICAL.md | 2 +- docs/TROUBLESHOOTING.md | 2 +- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 6 +- .../first-run-experience/strings/M2-app.json | 118 +++++ .../first-run-experience/strings/M2-core.json | 14 + .../Resources/Localizable.xcstrings | 492 ++++++++++++++++++ .../Resources/LocalizableCore.xcstrings | 51 ++ 12 files changed, 747 insertions(+), 10 deletions(-) create mode 100644 docs/plan/first-run-experience/strings/M2-app.json create mode 100644 docs/plan/first-run-experience/strings/M2-core.json diff --git a/README.md b/README.md index 90d7470f..8a6237d9 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 normally skips that group until you mark one Keep. This is not a guarantee: a group whose RAW+JPEG or Live Photo partners are being removed along with another group can still lose every photo. Check pairs before you confirm. 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..e8a98cc1 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: No. 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 normally skips that group until you mark one Keep. That is not a guarantee. RAW+JPEG and Live Photo partners are removed together, so a group whose files are paired with files you are removing from another group can still lose every photo. Check paired files and 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 `<name>-edited.<ext>` 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..7f3ba002 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 normally skips that group until you mark one photo Keep. This is not a guarantee: a group whose RAW+JPEG or Live Photo partners are being removed along with another group can still lose every photo. Check pairs before you confirm. 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..11231fae 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,36 @@ 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 +normally skips that group until one is marked Keep. This is not a guarantee. +Pair expansion runs after that check, so a group whose files are paired with +files being removed from another group can still end up with nothing kept. +Check RAW+JPEG and Live Photo pairs, and 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/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index d53e51bb..eac0eb6b 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -57,3 +57,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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). diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 9a0bf413..bc31804e 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -24,8 +24,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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) | (WP-13 commit) | 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 | in-progress | | | | | | +| 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) | (WP-14 commit) | 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 | todo | | | n/a | | | | WP-20 | Branch and baseline, M3 | todo | | | n/a | | lists FolderAccessServicing conformers | | WP-21 | Core and AppCore groundwork | todo | | | | | | @@ -79,3 +79,5 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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). 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/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/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": { From 0351db67a66b9a67de33243291cdc8319798e6d9 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 19:28:48 -0800 Subject: [PATCH 16/30] FRX G2: gate Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md | 8 ++++---- docs/plan/first-run-experience/PROGRESS.md | 10 +++++++--- script/swift_meaningful_coverage.sh | 2 ++ 3 files changed, 13 insertions(+), 7 deletions(-) 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/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index bc31804e..f235157f 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). @@ -25,8 +25,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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) | (WP-14 commit) | 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 | todo | | | n/a | | | +| 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 | | | | | | @@ -52,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 @@ -81,3 +82,6 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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. 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 From 6f91c903edf6f16baae4245992f31db55c2bbf99 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 19:31:41 -0800 Subject: [PATCH 17/30] FRX WP-20: Branch and baseline, M3 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/PROGRESS.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index f235157f..c1c8fe30 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -9,6 +9,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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". +- M3: branch `feature/first-run-guided` cut from `feature/first-run-duplicates` 0351db6. `cf_swift.sh build` exit 0. M3 anchor refresh (Explore, haiku): facts 7, 13, 14, 15 still true. Moved: `AppState.folderAccessService` :55 (cited :52) and the `.organize(.setup)` default :223 (cited :220); `FolderStructure.default` `EngineDomainModels.swift:332`; the histogram call `DryRunPlanner.swift:476–477`; the overview tab with `RunSnapshotPanel`/`RunArtifactsPanel` is `RunWorkspaceShell` `case .overview` at `RunSectionViews.swift:485–498` (cited :410–423; WP-23's read range should be :445–511); the running-preview message is `RunWorkspaceModel.swift:362–364`. `FolderAccessServicing` conformers: `FolderAccessService` (`FolderAccessService.swift:119`), `MockFolderAccessService` (`UITestDoubles.swift:179`), `NASViewTestFolderAccess` (`NASLibraryViewTests.swift:59`), `MockNASFolderAccess` (`NASWorkspaceStoreTests.swift:85`); protocol at :93, existing extension default :112–116. Tests: histogram in `ChronoframeCoreCopyPlanTests.swift` (:165–226; no assertion pins 4 samples); `initialPanelDirectoryURL` in `ModelAndServiceTests.swift:82–126`; no test pins the fresh-preference layout; the running-preview message is pinned at `RunWorkspaceModelTests.swift:208–210`. `UITestAppStateFactory`: `PreferencesStore(` :35, `AppState(` :245; 21 scenarios. UI tests contain none of "2019/07/14", "yyyyMMDD", "didOnboard", "Run Snapshot"; they do not reset `UserDefaults.standard`. ## Work packages | WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | @@ -26,9 +27,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | | | | | | +| 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 | 0351db6 | 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 | done | build exit 0 | n/a | n/a | (WP-20 commit) | anchors and FolderAccessServicing conformers recorded under Baseline | +| WP-21 | Core and AppCore groundwork | in-progress | | | | | | | WP-22 | App: guided setup | todo | | | | | | | WP-23 | App: photos and folder picture on the preview | todo | | | | | | | WP-24 | Docs and strings, M3 | todo | | | | | | From b2d8704d082224c7da00a3ba39484cbc26c08fcd Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 19:41:55 -0800 Subject: [PATCH 18/30] FRX WP-21: Core and AppCore groundwork Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 8 +- .../App/UITesting/UITestAppStateFactory.swift | 2 + .../App/UITesting/UITestDoubles.swift | 8 + .../Services/FolderAccessService.swift | 41 +++++ .../Stores/PreferencesStore.swift | 19 +- .../ChronoframeCore/CopyPlanBuilder.swift | 25 ++- .../ChronoframeCore/FolderSizeEstimator.swift | 94 ++++++++++ .../ChronoframeCoreCopyPlanTests.swift | 60 +++++++ ...onoframeCoreFolderSizeEstimatorTests.swift | 168 ++++++++++++++++++ .../ModelAndServiceTests.swift | 78 ++++++++ .../PreferencesStoreTests.swift | 74 ++++++++ 12 files changed, 567 insertions(+), 11 deletions(-) create mode 100644 ui/Sources/ChronoframeCore/FolderSizeEstimator.swift create mode 100644 ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index eac0eb6b..425808a8 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -58,3 +58,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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-113 Groundwork details (WP-21).** (a) `FolderSizeEstimator` returns nil for a root that is itself a symbolic link, is not a directory or cannot be listed; a failed entry below the root makes `isComplete` false; a cancelled run returns the partial counts with `isComplete == false`. Cost of the symlink-root rule: a Pictures folder that is a symlink shows "could not measure"; the copy itself is unaffected and the space line never blocks. (b) `PreferencesStore`: a stored but unrecognised `folderStructure` value keeps `.yyyyMMDD` and writes nothing (the old behaviour; "a stored value is never changed"). The prior-use check is inlined at the one assignment and uses the store's own literal keys; archive-destination bookmarks are stored as `bookmark.history.destination.…`, so the `bookmark.` prefix already covers them and both prefixes are checked as C-21 lists. (c) Histogram samples: new files in plan order, then exact copies fill what is left up to 12; counts are untouched. (d) `FolderAccessService.panelDirectoryURL(openingAt:)` is an internal pure helper so the rule is testable without a panel; its fallback is the `FileManager` home as C-22 says. `realHomeDirectoryURL()` is `nonisolated`. (e) The two new histogram tests live in `ChronoframeCoreCopyPlanTests.swift` and the four folder-access tests in `ModelAndServiceTests.swift`. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index c1c8fe30..f558b97f 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -28,9 +28,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | 0351db6 | 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 | done | build exit 0 | n/a | n/a | (WP-20 commit) | anchors and FolderAccessServicing conformers recorded under Baseline | -| WP-21 | Core and AppCore groundwork | in-progress | | | | | | -| WP-22 | App: guided setup | todo | | | | | | +| WP-20 | Branch and baseline, M3 | done | build exit 0 | n/a | n/a | 6f91c90 | anchors and FolderAccessServicing conformers recorded under Baseline | +| WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | (WP-21 commit) | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | +| WP-22 | App: guided setup | in-progress | | | | | | | WP-23 | App: photos and folder picture on the preview | todo | | | | | | | WP-24 | Docs and strings, M3 | todo | | | | | | | G3 | Final gate | todo | | | n/a | | | @@ -86,3 +86,5 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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-28 WP-21 Done-when (orchestrator): `cf_swift.sh test` exit 0 for ChronoframeCoreFolderSizeEstimatorTests (6), ChronoframeCoreCopyPlanTests (14), PreferencesStoreTests (16), ModelAndServiceTests (14), ChronoframeCoreDryRunPlannerParityTests (16), FreeTestBatchPlannerTests (19), UITestWindowFitTests (9); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0; extra: `cf_swift.sh suite` exit 0 (2670 passed, 0 failed) because the fresh-defaults layout changed. No strings, no existing assertions changed. Four stray `.tmp_*.log` files the implementer left in the repo root were removed by the orchestrator (created in this run, never committed). +- Noticed, not fixed (M3): `panelDirectoryURL(openingAt:)` does not apply the protected-media-library check that `initialPanelDirectoryURL` applies (unreachable from the guided places; C-22 does not ask for it). diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index 9a19e8f4..a8168507 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -33,6 +33,8 @@ enum UITestAppStateFactory { defaults.removePersistentDomain(forName: suiteName) let preferencesStore = PreferencesStore(defaults: defaults) + // New installs default to Year/Month; every existing scenario keeps the layout its screens were built with. + preferencesStore.folderStructure = .yyyyMMDD let setupStore = SetupStore() let runLogStore = RunLogStore(capacity: 500) let repository = MockProfilesRepository() diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift index 0532a479..079c2f1b 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift @@ -197,6 +197,14 @@ final class MockFolderAccessService: FolderAccessServicing { return nextChosenFolder } + /// Every `chooseFolder(openingAt:prompt:)` request, in call order. + var openingAtCalls: [(directory: URL, prompt: String)] = [] + + func chooseFolder(openingAt directory: URL, prompt: String) -> URL? { + openingAtCalls.append((directory: directory, prompt: prompt)) + return nextChosenFolder + } + var nextChosenFolders: [URL] = [] func chooseFolders(startingAt path: String?, prompt: String) -> [URL] { diff --git a/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift b/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift index 98e81ec1..15fb6927 100644 --- a/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift +++ b/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift @@ -98,6 +98,9 @@ public protocol FolderAccessServicing: AnyObject, Sendable { @MainActor func chooseFolder(startingAt path: String?, prompt: String, allowNetworkStart: Bool) -> URL? /// One panel, several folders. Returns an empty array when the user cancels. @MainActor func chooseFolders(startingAt path: String?, prompt: String) -> [URL] + /// Opens the panel inside `directory` itself (not at its parent). Falls back to the usual + /// start place when `directory` does not exist on a local volume. + @MainActor func chooseFolder(openingAt directory: URL, prompt: String) -> URL? func makeBookmark(for url: URL, key: String) throws -> FolderBookmark @MainActor func resolveBookmark(_ bookmark: FolderBookmark) -> ResolvedFolderBookmark? @MainActor func scopedAccess(for bookmarks: [FolderBookmark]) -> SecurityScopedFolderAccess @@ -113,6 +116,10 @@ public extension FolderAccessServicing { @MainActor func chooseFolder(startingAt path: String?, prompt: String, allowNetworkStart: Bool) -> URL? { chooseFolder(startingAt: path, prompt: prompt) } + + @MainActor func chooseFolder(openingAt directory: URL, prompt: String) -> URL? { + chooseFolder(startingAt: directory.path, prompt: prompt) + } } @MainActor @@ -134,6 +141,40 @@ public final class FolderAccessService: FolderAccessServicing { return panel.runModal() == .OK ? panel.url : nil } + public func chooseFolder(openingAt directory: URL, prompt: String) -> URL? { + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.allowsMultipleSelection = false + panel.prompt = CoreL10n.text(String.LocalizationValue(prompt)) + panel.directoryURL = Self.panelDirectoryURL(openingAt: directory) + + return panel.runModal() == .OK ? panel.url : nil + } + + /// `directory` itself when it is an existing folder on a local volume, otherwise the place + /// `initialPanelDirectoryURL` uses when it is given no path. + static func panelDirectoryURL(openingAt directory: URL) -> URL { + var isDirectory: ObjCBool = false + if FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), + isDirectory.boolValue, + let values = try? directory.resourceValues(forKeys: [.volumeIsLocalKey]), + values.volumeIsLocal == true { + return directory + } + return initialPanelDirectoryURL(startingAt: nil) + } + + /// The person's real home folder from the password database. In a sandboxed build + /// `FileManager.homeDirectoryForCurrentUser` is the app's container, which is never + /// where the person keeps Pictures, Desktop or Downloads. + public nonisolated static func realHomeDirectoryURL() -> URL { + if let entry = getpwuid(getuid()), let directory = entry.pointee.pw_dir { + return URL(fileURLWithPath: String(cString: directory), isDirectory: true) + } + return FileManager.default.homeDirectoryForCurrentUser + } + public func chooseFolders(startingAt path: String?, prompt: String) -> [URL] { let panel = NSOpenPanel() panel.canChooseFiles = false diff --git a/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift b/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift index e9dd6a33..c61ad55b 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift @@ -194,7 +194,24 @@ public final class PreferencesStore: ObservableObject { self.lastDeduplicateDestinationPath = defaults.string(forKey: "lastDeduplicateDestinationPath") ?? "" self.lastSelectedProfileName = defaults.string(forKey: "lastSelectedProfileName") ?? "" let storedStructure = defaults.string(forKey: "folderStructure").flatMap(FolderStructure.init(rawValue:)) - self.folderStructure = storedStructure ?? .yyyyMMDD + if let storedStructure { + self.folderStructure = storedStructure + } else if defaults.object(forKey: "folderStructure") != nil { + // A value is stored but is not a layout this build knows: keep the old default, write nothing. + self.folderStructure = .yyyyMMDD + } else { + // Prior use: a saved folder path, or any folder bookmark (`bookmark.` prefix) or + // archive-destination bookmark (`history.destination.` prefix). + let hasSavedPath = !(defaults.string(forKey: "lastManualDestinationPath") ?? "").isEmpty + || !(defaults.string(forKey: "lastManualSourcePath") ?? "").isEmpty + || !(defaults.stringArray(forKey: "manualSourceItemPaths") ?? []).isEmpty + let hasBookmark = defaults.dictionaryRepresentation().keys.contains { + $0.hasPrefix("bookmark.") || $0.hasPrefix("history.destination.") + } + let resolved: FolderStructure = hasSavedPath || hasBookmark ? .yyyyMMDD : .yyyyMM + defaults.set(resolved.rawValue, forKey: "folderStructure") + self.folderStructure = resolved + } self.smartEventSuggestionsEnabled = defaults.object(forKey: "smartEventSuggestionsEnabled") as? Bool ?? false self.dedupeTimeWindowSeconds = defaults.object(forKey: "dedupeTimeWindowSeconds") as? Int ?? 30 self.dedupeBurstModeEnabled = defaults.object(forKey: "dedupeBurstModeEnabled") as? Bool ?? true diff --git a/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift b/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift index af07694c..c69b3aa5 100644 --- a/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift +++ b/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift @@ -271,17 +271,24 @@ public enum CopyPlanBuilder { from transfers: [PlannedTransfer], namingRules: PlannerNamingRules ) -> [DateHistogramBucket] { - // Cap on how many source paths each bucket carries forward. Four - // is enough for the UI's hover peek (a small grid) without bloating - // the receipt/snapshot — even a 50K-file run with 200 buckets only - // adds ~800 path strings to the histogram. - let samplePathLimit = 4 + // Cap on how many source paths each bucket carries forward. Twelve + // fills the timeline's sample grid without bloating the + // receipt/snapshot — even a 50K-file run with 200 buckets only + // adds ~2,400 path strings to the histogram. + let samplePathLimit = 12 var countsByBucket: [String: Int] = [:] var samplesByBucket: [String: [String]] = [:] + // Exact copies are kept apart so they only top up a bucket that has + // fewer than `samplePathLimit` new files. + var duplicateSamplesByBucket: [String: [String]] = [:] for transfer in transfers { let key = histogramKey(for: transfer.dateBucket, namingRules: namingRules) countsByBucket[key, default: 0] += 1 - if (samplesByBucket[key]?.count ?? 0) < samplePathLimit { + if transfer.isDuplicate { + if (duplicateSamplesByBucket[key]?.count ?? 0) < samplePathLimit { + duplicateSamplesByBucket[key, default: []].append(transfer.sourcePath) + } + } else if (samplesByBucket[key]?.count ?? 0) < samplePathLimit { samplesByBucket[key, default: []].append(transfer.sourcePath) } } @@ -290,7 +297,11 @@ public enum CopyPlanBuilder { DateHistogramBucket( key: key, plannedCount: countsByBucket[key] ?? 0, - samplePaths: samplesByBucket[key] ?? [] + samplePaths: { + let newFiles = samplesByBucket[key] ?? [] + let exactCopies = duplicateSamplesByBucket[key] ?? [] + return newFiles + exactCopies.prefix(max(0, samplePathLimit - newFiles.count)) + }() ) } } diff --git a/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift b/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift new file mode 100644 index 00000000..0c4812c8 --- /dev/null +++ b/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift @@ -0,0 +1,94 @@ +import Foundation + +public struct FolderSizeEstimate: Equatable, Sendable { + public let fileCount: Int + public let totalBytes: Int64 + /// False when cancelled or any entry could not be read. + public let isComplete: Bool + + public init(fileCount: Int, totalBytes: Int64, isComplete: Bool) { + self.fileCount = fileCount + self.totalBytes = totalBytes + self.isComplete = isComplete + } +} + +/// A read-only count of the regular files under a folder and their size. It lists directories +/// and reads file attributes; it never opens, creates, modifies or follows anything. It counts +/// every regular file, so callers say "files", never "photos". +public enum FolderSizeEstimator { + private static let cancellationCheckInterval = 500 + + /// Returns nil when the root cannot be enumerated at all. Hidden entries and package + /// contents are skipped, and symbolic links are never followed (INV-15), including a + /// root that is itself a symbolic link. + public static func estimate(root: URL, isCancelled: @Sendable () -> Bool = { false }) -> FolderSizeEstimate? { + let fileManager = FileManager.default + let keys: [URLResourceKey] = [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey] + + guard let rootValues = try? root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), + rootValues.isDirectory == true, + rootValues.isSymbolicLink != true + else { + return nil + } + + var rootFailed = false + var sawUnreadableEntry = false + let rootPath = root.standardizedFileURL.path + guard let enumerator = fileManager.enumerator( + at: root, + includingPropertiesForKeys: keys, + options: [.skipsHiddenFiles, .skipsPackageDescendants], + errorHandler: { url, _ in + if url.standardizedFileURL.path == rootPath { + rootFailed = true + } else { + sawUnreadableEntry = true + } + return true + } + ) else { + return nil + } + + var fileCount = 0 + var totalBytes: Int64 = 0 + var entriesSeen = 0 + var cancelled = false + + while let next = enumerator.nextObject() { + if entriesSeen.isMultiple(of: cancellationCheckInterval), isCancelled() { + cancelled = true + break + } + entriesSeen += 1 + + guard let url = next as? URL else { + sawUnreadableEntry = true + continue + } + guard let values = try? url.resourceValues(forKeys: Set(keys)) else { + sawUnreadableEntry = true + continue + } + if values.isSymbolicLink == true { + continue + } + guard values.isRegularFile == true else { + continue + } + fileCount += 1 + totalBytes += Int64(values.fileSize ?? 0) + } + + if rootFailed { + return nil + } + return FolderSizeEstimate( + fileCount: fileCount, + totalBytes: totalBytes, + isComplete: !cancelled && !sawUnreadableEntry + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift index 1896e8de..8efbd20a 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift @@ -277,6 +277,66 @@ final class ChronoframeCoreCopyPlanTests: XCTestCase { XCTAssertEqual(result.sequenceState.duplicatesByDate, ["2024-03-01": 1]) } + func testHistogramSamplesPreferNewFilesUpToTwelve() { + // Exact copies come first in plan order, but a bucket's samples must be + // new files first; exact copies only top up when fewer than 12 new files exist. + var transfers: [PlannedTransfer] = [] + for index in 0..<10 { + transfers.append(transfer("/source/dup\(index).jpg", bucket: "2026-03-05", isDuplicate: true)) + } + for index in 0..<5 { + transfers.append(transfer("/source/few\(index).jpg", bucket: "2026-03-05", isDuplicate: false)) + } + for index in 0..<20 { + transfers.append(transfer("/source/dup-april\(index).jpg", bucket: "2026-04-01", isDuplicate: true)) + } + for index in 0..<15 { + transfers.append(transfer("/source/new-april\(index).jpg", bucket: "2026-04-01", isDuplicate: false)) + } + for index in 0..<3 { + transfers.append(transfer("/source/only-dup\(index).jpg", bucket: "2026-05-01", isDuplicate: true)) + } + + let buckets = CopyPlanBuilder.dateHistogram(from: transfers, namingRules: .chronoframeDefault) + let byKey = Dictionary(uniqueKeysWithValues: buckets.map { ($0.key, $0) }) + + // Fewer than 12 new files: all of them, then exact copies to fill up to 12. + XCTAssertEqual( + byKey["2026-03"]?.samplePaths, + (0..<5).map { "/source/few\($0).jpg" } + (0..<7).map { "/source/dup\($0).jpg" } + ) + // 12 or more new files: only new files, first 12 in plan order. + XCTAssertEqual(byKey["2026-04"]?.samplePaths, (0..<12).map { "/source/new-april\($0).jpg" }) + // Only exact copies: they are used. + XCTAssertEqual(byKey["2026-05"]?.samplePaths, (0..<3).map { "/source/only-dup\($0).jpg" }) + } + + func testHistogramCountsUnchangedBySampleRule() { + var transfers: [PlannedTransfer] = [] + for index in 0..<30 { + transfers.append(transfer("/source/a\(index).jpg", bucket: "2026-03-05", isDuplicate: index % 3 == 0)) + } + for index in 0..<2 { + transfers.append(transfer("/source/u\(index).jpg", bucket: "Unknown_Date", isDuplicate: false)) + } + + let buckets = CopyPlanBuilder.dateHistogram(from: transfers, namingRules: .chronoframeDefault) + + XCTAssertEqual(buckets.map(\.key), ["2026-03", "Unknown"]) + XCTAssertEqual(buckets.map(\.plannedCount), [30, 2]) + XCTAssertEqual(buckets.map { $0.samplePaths.count }, [12, 2]) + } + + private func transfer(_ path: String, bucket: String, isDuplicate: Bool) -> PlannedTransfer { + PlannedTransfer( + sourcePath: path, + destinationPath: "/dest/" + (path as NSString).lastPathComponent, + identity: FileIdentity(size: 1, digest: path), + dateBucket: bucket, + isDuplicate: isDuplicate + ) + } + private func candidate(_ path: String, identity: String, date: String?) -> PlanningFileCandidate { PlanningFileCandidate( sourcePath: path, diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift new file mode 100644 index 00000000..eb379e48 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift @@ -0,0 +1,168 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +final class ChronoframeCoreFolderSizeEstimatorTests: XCTestCase { + private var root: URL! + private let fileManager = FileManager.default + + override func setUpWithError() throws { + try super.setUpWithError() + root = fileManager.temporaryDirectory + .appendingPathComponent("FolderSizeEstimator-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + // Restore any permission a test removed before deleting what the test created. + if let root, fileManager.fileExists(atPath: root.path) { + try? fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: root.path) + try fileManager.removeItem(at: root) + } + root = nil + try super.tearDownWithError() + } + + func testCountsRegularFilesAndBytes() throws { + try write(Data(repeating: 1, count: 100), to: "a.jpg") + try write(Data(repeating: 2, count: 250), to: "2024/06/b.heic") + try write(Data(), to: "2024/06/empty.txt") + try fileManager.createDirectory(at: root.appendingPathComponent("empty-dir"), withIntermediateDirectories: true) + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + XCTAssertEqual(estimate.fileCount, 3) + XCTAssertEqual(estimate.totalBytes, 350) + XCTAssertTrue(estimate.isComplete) + } + + // AGENTS-INVARIANT: 15 + func testSkipsSymlinksWithoutFollowing() throws { + let outside = fileManager.temporaryDirectory + .appendingPathComponent("FolderSizeEstimatorOutside-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: outside, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: outside) } + try Data(repeating: 9, count: 5_000).write(to: outside.appendingPathComponent("big.bin")) + try Data(repeating: 9, count: 777).write(to: outside.appendingPathComponent("target.jpg")) + + try write(Data(repeating: 1, count: 10), to: "real.jpg") + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("linked-folder"), + withDestinationURL: outside + ) + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("linked-file.jpg"), + withDestinationURL: outside.appendingPathComponent("target.jpg") + ) + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + XCTAssertEqual(estimate.fileCount, 1) + XCTAssertEqual(estimate.totalBytes, 10) + } + + func testSkipsHiddenFilesAndPackages() throws { + try write(Data(repeating: 1, count: 10), to: "visible.jpg") + try write(Data(repeating: 1, count: 20), to: ".hidden.jpg") + try write(Data(repeating: 1, count: 30), to: ".hidden-dir/inside.jpg") + try write(Data(repeating: 1, count: 40), to: "Thing.app/Contents/Info.plist") + try write(Data(repeating: 1, count: 50), to: "Photos.photoslibrary/original.jpg") + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + XCTAssertEqual(estimate.fileCount, 1) + XCTAssertEqual(estimate.totalBytes, 10) + } + + func testNilForUnreadableRoot() throws { + let missing = root.appendingPathComponent("does-not-exist", isDirectory: true) + XCTAssertNil(FolderSizeEstimator.estimate(root: missing)) + + let locked = root.appendingPathComponent("locked", isDirectory: true) + try fileManager.createDirectory(at: locked, withIntermediateDirectories: true) + try write(Data(repeating: 1, count: 10), to: "locked/x.jpg") + try fileManager.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path) + defer { try? fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } + + XCTAssertNil(FolderSizeEstimator.estimate(root: locked)) + } + + func testIncompleteWhenCancelled() throws { + for index in 0..<1_200 { + try write(Data(repeating: 1, count: 1), to: "bulk/\(index).jpg") + } + + let alwaysCancelled = try XCTUnwrap(FolderSizeEstimator.estimate(root: root, isCancelled: { true })) + XCTAssertFalse(alwaysCancelled.isComplete) + XCTAssertLessThan(alwaysCancelled.fileCount, 1_200) + + let cancelAfterFirstCheck = CallCounter() + let partial = try XCTUnwrap( + FolderSizeEstimator.estimate(root: root, isCancelled: { cancelAfterFirstCheck.next() > 1 }) + ) + XCTAssertFalse(partial.isComplete) + XCTAssertGreaterThan(partial.fileCount, 0) + XCTAssertLessThan(partial.fileCount, 1_200) + + let finished = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + XCTAssertTrue(finished.isComplete) + XCTAssertEqual(finished.fileCount, 1_200) + } + + // AGENTS-INVARIANT: 1 + func testCreatesAndModifiesNothing() throws { + try write(Data(repeating: 1, count: 100), to: "a.jpg") + try write(Data(repeating: 2, count: 200), to: "sub/b.jpg") + try write(Data(repeating: 3, count: 300), to: ".hidden/c.jpg") + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("link.jpg"), + withDestinationURL: root.appendingPathComponent("a.jpg") + ) + + let before = try snapshot() + _ = FolderSizeEstimator.estimate(root: root) + let after = try snapshot() + + XCTAssertEqual(before, after) + } + + // MARK: - Helpers + + private func write(_ data: Data, to relativePath: String) throws { + let url = root.appendingPathComponent(relativePath) + try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url) + } + + /// Every path under the root (hidden entries included) with its size and modification date. + private func snapshot() throws -> [String] { + let keys: [URLResourceKey] = [.fileSizeKey, .contentModificationDateKey, .isDirectoryKey] + var lines: [String] = [] + guard let enumerator = fileManager.enumerator( + at: root, + includingPropertiesForKeys: keys, + options: [], + errorHandler: nil + ) else { + return lines + } + for case let url as URL in enumerator { + let values = try url.resourceValues(forKeys: Set(keys)) + lines.append( + "\(url.path)|\(values.fileSize ?? -1)|\(values.contentModificationDate?.timeIntervalSince1970 ?? -1)|\(values.isDirectory ?? false)" + ) + } + return lines.sorted() + } +} + +private final class CallCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func next() -> Int { + lock.lock() + defer { lock.unlock() } + count += 1 + return count + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift b/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift index 58fb9098..2e9ad0f6 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift @@ -136,6 +136,59 @@ final class ModelAndServiceTests: XCTestCase { ) } + @MainActor + func testOpeningAtExistingLocalFolderStartsThere() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderAccessOpeningAt-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + // Unlike `initialPanelDirectoryURL`, which opens at the parent, this opens in the folder itself. + XCTAssertEqual( + FolderAccessService.panelDirectoryURL(openingAt: root).standardizedFileURL.path, + root.standardizedFileURL.path + ) + } + + @MainActor + func testOpeningAtMissingFolderFallsBack() throws { + let missing = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderAccessMissing-\(UUID().uuidString)", isDirectory: true) + let fallback = FolderAccessService.initialPanelDirectoryURL(startingAt: nil).path + + XCTAssertEqual(FolderAccessService.panelDirectoryURL(openingAt: missing).path, fallback) + + // A regular file is not a folder to open in. + let file = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderAccessFile-\(UUID().uuidString)") + try Data([1]).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + XCTAssertEqual(FolderAccessService.panelDirectoryURL(openingAt: file).path, fallback) + } + + @MainActor + func testProtocolDefaultForwardsToStartingAt() { + let recorder = StartingAtRecordingFolderAccess() + recorder.chosen = URL(fileURLWithPath: "/tmp/chosen") + let directory = URL(fileURLWithPath: "/Users/example/Pictures", isDirectory: true) + + let result = (recorder as any FolderAccessServicing).chooseFolder(openingAt: directory, prompt: "Choose Source") + + XCTAssertEqual(result?.path, "/tmp/chosen") + XCTAssertEqual(recorder.requests.count, 1) + XCTAssertEqual(recorder.requests.first?.startingAt, "/Users/example/Pictures") + XCTAssertEqual(recorder.requests.first?.prompt, "Choose Source") + } + + func testRealHomeDirectoryIsNotInsideAContainer() throws { + let home = FolderAccessService.realHomeDirectoryURL() + + XCTAssertFalse(home.path.contains("/Library/Containers/")) + XCTAssertTrue(home.path.hasPrefix("/")) + let entry = try XCTUnwrap(getpwuid(getuid())) + XCTAssertEqual(home.path, URL(fileURLWithPath: String(cString: entry.pointee.pw_dir)).path) + } + @MainActor func testFolderAccessServiceValidatesDirectoryCapabilities() throws { let service = FolderAccessService() @@ -165,3 +218,28 @@ final class ModelAndServiceTests: XCTestCase { } } } + +/// Conforms with only the requirements a protocol-extension default cannot supply, so the +/// `chooseFolder(openingAt:prompt:)` default is the code under test. +private final class StartingAtRecordingFolderAccess: FolderAccessServicing, @unchecked Sendable { + var chosen: URL? + private(set) var requests: [(startingAt: String?, prompt: String)] = [] + + @MainActor func chooseFolder(startingAt path: String?, prompt: String) -> URL? { + requests.append((path, prompt)) + return chosen + } + + @MainActor func chooseFolders(startingAt path: String?, prompt: String) -> [URL] { [] } + + func makeBookmark(for url: URL, key: String) throws -> FolderBookmark { + FolderBookmark(key: key, path: url.path, data: Data()) + } + + @MainActor func resolveBookmark(_ bookmark: FolderBookmark) -> ResolvedFolderBookmark? { nil } + @MainActor func scopedAccess(for bookmarks: [FolderBookmark]) -> SecurityScopedFolderAccess { SecurityScopedFolderAccess() } + @MainActor func verifiedScopedAccess(for bookmarks: [FolderBookmark]) -> ScopedAccessOutcome { + ScopedAccessOutcome(access: SecurityScopedFolderAccess(), startedKeys: []) + } + func validateFolder(_ url: URL, role: FolderRole) throws {} +} diff --git a/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift index 7e537397..23475011 100644 --- a/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift @@ -29,6 +29,80 @@ final class PreferencesStoreTests: XCTestCase { try await super.tearDown() } + @MainActor + func testFreshDefaultsUseYearMonth() { + let store = PreferencesStore(defaults: defaults) + XCTAssertEqual(store.folderStructure, .yyyyMM) + } + + @MainActor + func testPriorUseWithoutStoredLayoutKeepsYearMonthDay() { + let priorUseSetups: [(String, (UserDefaults) -> Void)] = [ + ("destination path", { $0.set("/Volumes/Archive", forKey: "lastManualDestinationPath") }), + ("source path", { $0.set("/Users/example/Unsorted", forKey: "lastManualSourcePath") }), + ("source items", { $0.set(["/Users/example/Unsorted"], forKey: "manualSourceItemPaths") }), + ("bookmark", { $0.set(Data([1]), forKey: "bookmark.manual.destination.data") }), + ("history destination", { $0.set(Data([1]), forKey: "history.destination.QUJD") }), + ] + + for (label, setup) in priorUseSetups { + let suite = "PreferencesStoreTests-prior-\(UUID().uuidString)" + let scoped = UserDefaults(suiteName: suite)! + defer { scoped.removePersistentDomain(forName: suite) } + setup(scoped) + + let store = PreferencesStore(defaults: scoped) + + XCTAssertEqual(store.folderStructure, .yyyyMMDD, label) + } + + // Empty values are not prior use. + defaults.set("", forKey: "lastManualDestinationPath") + defaults.set("", forKey: "lastManualSourcePath") + defaults.set([String](), forKey: "manualSourceItemPaths") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMM) + } + + @MainActor + func testStoredLayoutIsNeverChanged() { + defaults.set(FolderStructure.yyyy.rawValue, forKey: "folderStructure") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyy) + XCTAssertEqual(defaults.string(forKey: "folderStructure"), FolderStructure.yyyy.rawValue) + + // A stored Year/Month/Day stays even with no sign of prior use. + defaults.set(FolderStructure.yyyyMMDD.rawValue, forKey: "folderStructure") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMMDD) + + // A stored Year/Month stays even when prior use is present. + defaults.set(FolderStructure.yyyyMM.rawValue, forKey: "folderStructure") + defaults.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMM) + XCTAssertEqual(defaults.string(forKey: "folderStructure"), FolderStructure.yyyyMM.rawValue) + } + + @MainActor + func testResolvedLayoutIsWrittenOnce() { + XCTAssertNil(defaults.string(forKey: "folderStructure")) + let first = PreferencesStore(defaults: defaults) + XCTAssertEqual(first.folderStructure, .yyyyMM) + XCTAssertEqual(defaults.string(forKey: "folderStructure"), FolderStructure.yyyyMM.rawValue) + + // Later use does not flip a person who started fresh to Year/Month/Day. + defaults.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + defaults.set(Data([1]), forKey: "bookmark.manual.destination.data") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMM) + + // And prior use is written as Year/Month/Day once, then stays. + let suite = "PreferencesStoreTests-once-\(UUID().uuidString)" + let scoped = UserDefaults(suiteName: suite)! + defer { scoped.removePersistentDomain(forName: suite) } + scoped.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + XCTAssertEqual(PreferencesStore(defaults: scoped).folderStructure, .yyyyMMDD) + XCTAssertEqual(scoped.string(forKey: "folderStructure"), FolderStructure.yyyyMMDD.rawValue) + scoped.set("", forKey: "lastManualDestinationPath") + XCTAssertEqual(PreferencesStore(defaults: scoped).folderStructure, .yyyyMMDD) + } + @MainActor func testGuardianPreferenceDefaults() { let store = PreferencesStore(defaults: defaults) From f3192d2f142bf647bb708db7c2d574ac94e27178 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 19:51:29 -0800 Subject: [PATCH 19/30] FRX WP-22: App: guided setup Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 8 +- .../App/AccessibilityIdentifiers.swift | 18 +- ui/Sources/ChronoframeApp/App/AppState.swift | 12 + .../App/Coordinators/SetupCoordinator.swift | 21 ++ .../App/UITesting/UITestAppStateFactory.swift | 7 + .../App/UITesting/UITestScenario.swift | 3 +- .../Views/Setup/GuidedSetupModel.swift | 203 +++++++++++ .../Views/Setup/GuidedSetupView.swift | 314 ++++++++++++++++++ .../Views/Setup/SetupView.swift | 63 +++- .../ChronoframeAppTests/AppStateTests.swift | 27 ++ .../GuidedSetupModelTests.swift | 205 ++++++++++++ .../ScreenRenderEvidenceTests.swift | 43 +++ .../SetupCoordinatorTests.swift | 54 +++ .../UITestWindowFitTests.swift | 17 + 15 files changed, 988 insertions(+), 8 deletions(-) create mode 100644 ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift create mode 100644 ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift create mode 100644 ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 425808a8..b3e0925a 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -59,3 +59,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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-113 Groundwork details (WP-21).** (a) `FolderSizeEstimator` returns nil for a root that is itself a symbolic link, is not a directory or cannot be listed; a failed entry below the root makes `isComplete` false; a cancelled run returns the partial counts with `isComplete == false`. Cost of the symlink-root rule: a Pictures folder that is a symlink shows "could not measure"; the copy itself is unaffected and the space line never blocks. (b) `PreferencesStore`: a stored but unrecognised `folderStructure` value keeps `.yyyyMMDD` and writes nothing (the old behaviour; "a stored value is never changed"). The prior-use check is inlined at the one assignment and uses the store's own literal keys; archive-destination bookmarks are stored as `bookmark.history.destination.…`, so the `bookmark.` prefix already covers them and both prefixes are checked as C-21 lists. (c) Histogram samples: new files in plan order, then exact copies fill what is left up to 12; counts are untouched. (d) `FolderAccessService.panelDirectoryURL(openingAt:)` is an internal pure helper so the rule is testable without a panel; its fallback is the `FileManager` home as C-22 says. `realHomeDirectoryURL()` is `nonisolated`. (e) The two new histogram tests live in `ChronoframeCoreCopyPlanTests.swift` and the four folder-access tests in `ModelAndServiceTests.swift`. +- **D-FRX-114 Guided setup details (WP-22).** (a) Latch: choosing the source fills `sourcePath`, which would turn the C-23 gate off before the second question. `SetupView` therefore remembers that the full gate was true while this view was alive and keeps the guided screen up as long as the person is still eligible, not onboarded and has no history or profiles. The latch can only be set by the untouched gate, starts false on every relaunch, and ends for good when `didOnboard` becomes true. (b) `SetupView.init(appState:didOnboard: Binding<Bool>? = nil)`: production passes nothing and reads the same `@AppStorage("didOnboard")` key; renders pass a constant so `UserDefaults.standard` is never written. (c) The measure line fills `Your folder holds about %@ in %@.` with the existing files phrase, so one file reads "1 file". (d) Incomplete estimate: free space below the lower bound still warns; free space above it shows only `{free} free here.` ("enough for about X" would overclaim). While measuring, the space line ignores an old estimate. (e) `chooseSourceFolder(openingAt:)` returns true only when the chosen folder became the single source. (f) The estimator never runs on `/` or `/Volumes`, only on the validated chosen source, in a detached task cancelled when the step is left. (g) `GuidedSetupView` has an internal `fixedModel` used only by the destination render; with it no task runs. (h) Identifiers live in a nested `AccessibilityIdentifiers.Guided`; the Apple Photos primary reuses `guided.start`. (i) The place buttons are plain bordered SwiftUI buttons. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index f558b97f..97483357 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -29,9 +29,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | 0351db6 | 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 | done | build exit 0 | n/a | n/a | 6f91c90 | anchors and FolderAccessServicing conformers recorded under Baseline | -| WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | (WP-21 commit) | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | -| WP-22 | App: guided setup | in-progress | | | | | | -| WP-23 | App: photos and folder picture on the preview | todo | | | | | | +| WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | b2d8704 | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | +| WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | (WP-22 commit) | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | +| WP-23 | App: photos and folder picture on the preview | in-progress | | | | | | | WP-24 | Docs and strings, M3 | todo | | | | | | | G3 | Final gate | todo | | | n/a | | | @@ -88,3 +88,5 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - G2 PNG sent to the owner. Rendered, not verified in the running app. - 2026-11-28 WP-21 Done-when (orchestrator): `cf_swift.sh test` exit 0 for ChronoframeCoreFolderSizeEstimatorTests (6), ChronoframeCoreCopyPlanTests (14), PreferencesStoreTests (16), ModelAndServiceTests (14), ChronoframeCoreDryRunPlannerParityTests (16), FreeTestBatchPlannerTests (19), UITestWindowFitTests (9); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0; extra: `cf_swift.sh suite` exit 0 (2670 passed, 0 failed) because the fresh-defaults layout changed. No strings, no existing assertions changed. Four stray `.tmp_*.log` files the implementer left in the repo root were removed by the orchestrator (created in this run, never committed). - Noticed, not fixed (M3): `panelDirectoryURL(openingAt:)` does not apply the protected-media-library check that `initialPanelDirectoryURL` applies (unreachable from the guided places; C-22 does not ask for it). +- 2026-11-28 WP-22 Done-when (orchestrator): `cf_swift.sh test` exit 0 for GuidedSetupModelTests (10), SetupCoordinatorTests (40), AppStateTests (56), UITestWindowFitTests (10), AccessibilityTests (8), ScreenRenderEvidenceTests (7 run with marker, 7 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `script/check_detail_views_set_navigation_title.sh` exit 0; `git diff --check` exit 0. No existing assertions changed. +- Noticed, not fixed (M3): the guided destination step can show the previous destination's free-space figure for a moment after a new destination is chosen; with the guided screen latched, adding a source from the menu on the first question leaves the person on that question (a drop ends guided setup). diff --git a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift index a961ad48..c8144d48 100644 --- a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift +++ b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift @@ -148,6 +148,22 @@ enum AccessibilityIdentifiers { ] } + // MARK: - Guided setup + + /// Identifiers for the guided first-run setup. The place buttons are keyed by + /// `GuidedSourcePlace.rawValue`. + enum Guided { + static func source(_ place: GuidedSourcePlace) -> String { "guided.source.\(place.rawValue)" } + static let sourceApplePhotos = "guided.source.applePhotos" + static let destinationChoose = "guided.destination.choose" + static let start = "guided.start" + static let useFullSetup = "guided.useFullSetup" + + static let all: [String] = GuidedSourcePlace.allCases.map { source($0) } + [ + sourceApplePhotos, destinationChoose, start, useFullSetup, + ] + } + // MARK: - Free trial static let trialIndicatorOrganize = "trialIndicator.organize" @@ -208,5 +224,5 @@ enum AccessibilityIdentifiers { activeProfileBadge, trialIndicatorOrganize, trialIndicatorDedupe, diagnosticsLogBufferStepper, smartEventSuggestionsToggle, - ] + NAS.all + ] + NAS.all + Guided.all } diff --git a/ui/Sources/ChronoframeApp/App/AppState.swift b/ui/Sources/ChronoframeApp/App/AppState.swift index 70211b1b..13e0c92a 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -59,6 +59,9 @@ final class AppState: ObservableObject { private let droppedItemStager: DroppedItemStager private let showSettingsWindowAction: @MainActor () -> Void private let volumeClassifier: NASVolumeClassifier + /// Whether Choose Folders may open as the two-question guided setup. UI-test scenarios that + /// show another screen turn it off. + let guidedSetupEligible: Bool /// Keeps the trial status in step with the entitlement (T16). private var trialStatusObservation: AnyCancellable? /// Writes a pending Deduplicate review save before the app quits. @@ -243,6 +246,7 @@ final class AppState: ObservableObject { entitlementStore: EntitlementStore? = nil, trialEntitlementResolver: (@MainActor () async -> TrialEntitlementSnapshot)? = nil, volumeClassifier: NASVolumeClassifier = .live, + guidedSetupEligible: Bool = true, showSettingsWindowAction: @escaping @MainActor () -> Void = { NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) } @@ -287,6 +291,7 @@ final class AppState: ObservableObject { self.droppedItemStager = droppedItemStager self.showSettingsWindowAction = showSettingsWindowAction self.volumeClassifier = volumeClassifier + self.guidedSetupEligible = guidedSetupEligible self.previewReviewStore.setDestinationScopeProvider { [weak self] destinationRoot in self?.destinationSecurityScope(destinationRoot: destinationRoot) } @@ -396,6 +401,13 @@ final class AppState: ObservableObject { await setupCoordinator.chooseSourceFolder() } + /// Opens the picker at `directory` (nil: the default start) and, when a folder is chosen, makes it the one source folder. True when chosen. + @discardableResult + func chooseSourceFolder(openingAt directory: URL?) async -> Bool { + runCoordinator.invalidateWatchedImportContext() + return await setupCoordinator.chooseSourceFolder(openingAt: directory) + } + func addSourceItems(_ urls: [URL]) async { runCoordinator.invalidateWatchedImportContext() await setupCoordinator.addSourceItems(urls) diff --git a/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift b/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift index e267ee33..d59e8e94 100644 --- a/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift +++ b/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift @@ -80,6 +80,27 @@ final class SetupCoordinator { await addSourceItems(chosen) } + /// Guided setup's single-folder choice. The panel opens at `directory` (nil: the default start); a + /// chosen folder goes through the same validation and bookmark path as every other source and becomes + /// the one source folder. True only when that folder is now the source. + func chooseSourceFolder(openingAt directory: URL?) async -> Bool { + let prompt = "Choose This Folder" + let chosen: URL? + if let directory { + chosen = folderAccessService.chooseFolder(openingAt: directory, prompt: prompt) + } else { + chosen = folderAccessService.chooseFolder(startingAt: nil, prompt: prompt) + } + guard let chosen else { + return false + } + + await selectSourceFolder(chosen) + let items = setupStore.sourceItems + return items.count == 1 + && items[0].resolvingSymlinksInPath().path == chosen.resolvingSymlinksInPath().path + } + func addSourceItems(_ urls: [URL]) async { _ = await addSourceItemsReportingApplied(urls) } diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index a8168507..0c827d3e 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -193,6 +193,12 @@ enum UITestAppStateFactory { engine = previewReviewEngine(sourcePath: setupStore.sourcePath, destinationPath: setupStore.destinationPath) route = .organize(.setup) + case .guidedFirstRun: + // A person with nothing configured: empty stores, so the guided setup shows. + historyStore = HistoryStore() + engine = previewReviewEngine(sourcePath: "", destinationPath: "") + route = .organize(.setup) + case .deduplicateReviewWide, .deduplicateReviewCompact, .deduplicateReviewLanes: setupStore.destinationPath = "/Volumes/Archive/Chronoframe Library" historyStore = HistoryStore(destinationRoot: setupStore.destinationPath) @@ -262,6 +268,7 @@ enum UITestAppStateFactory { isAppStoreChannel: scenario.usesMeteredTrialUI, entitlementStore: trialFixture?.entitlementStore, trialEntitlementResolver: trialEntitlementResolver, + guidedSetupEligible: scenario == .guidedFirstRun, showSettingsWindowAction: showSettingsWindowAction ) appStateBox.value = appState diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift index f6d41661..296abe06 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift @@ -23,6 +23,7 @@ enum UITestScenario: String, CaseIterable { case deduplicateReviewWide case deduplicateReviewCompact case deduplicateReviewLanes + case guidedFirstRun static func current( environment: [String: String] = ProcessInfo.processInfo.environment, @@ -77,7 +78,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, .deduplicateReviewLanes: + case .deduplicateReviewWide, .deduplicateReviewLanes, .guidedFirstRun: return NSSize(width: 1180, height: 820) case .deduplicateReviewCompact: return NSSize(width: 900, height: 700) diff --git a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift new file mode 100644 index 00000000..7cddf68c --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift @@ -0,0 +1,203 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// The two questions of the first-run guided setup. +enum GuidedSetupStep: Equatable { case source, destination } + +/// The places the first question offers. The raw value is part of each button's +/// accessibility identifier, so it is never renamed. +enum GuidedSourcePlace: String, CaseIterable { case pictures, desktop, downloads, externalDrive, other } + +enum GuidedSourceKind: Equatable { case folder, applePhotos } + +/// What `GuidedSetupGate` reads. Everything but `isEligible` describes whether +/// the person has already set anything up. +struct GuidedSetupGateInputs: Equatable { + var isEligible: Bool + var didOnboard: Bool + var sourcePath: String + var sourceItemCount: Int + var destinationPath: String + var hasHistory: Bool + var hasProfiles: Bool +} + +enum GuidedSetupGate { + /// True only for an eligible person who has not been through onboarding and + /// has no folders, history or saved setups. + static func shouldShow(_ inputs: GuidedSetupGateInputs) -> Bool { + inputs.isEligible + && !inputs.didOnboard + && inputs.sourcePath.isEmpty + && inputs.sourceItemCount == 0 + && inputs.destinationPath.isEmpty + && !inputs.hasHistory + && !inputs.hasProfiles + } +} + +/// Copy and decisions for the guided setup screen. Holds no state of its own +/// beyond what the view gives it, so every sentence is testable. +struct GuidedSetupModel: Equatable { + var step: GuidedSetupStep + var sourceKind: GuidedSourceKind + var sourcePath: String + var destinationPath: String + var isMeasuring: Bool + var estimate: FolderSizeEstimate? + var destinationFreeBytes: Int64? + + init( + step: GuidedSetupStep = .source, + sourceKind: GuidedSourceKind = .folder, + sourcePath: String = "", + destinationPath: String = "", + isMeasuring: Bool = false, + estimate: FolderSizeEstimate? = nil, + destinationFreeBytes: Int64? = nil + ) { + self.step = step + self.sourceKind = sourceKind + self.sourcePath = sourcePath + self.destinationPath = destinationPath + self.isMeasuring = isMeasuring + self.estimate = estimate + self.destinationFreeBytes = destinationFreeBytes + } + + var title: String { + switch step { + case .source: + return AppLocalization.string("Where are most of your photos?") + case .destination: + return AppLocalization.string("Where should the organized copy go?") + } + } + + var body: String { + switch step { + case .source: + return AppLocalization.string( + "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." + ) + case .destination: + switch sourceKind { + case .folder: + return AppLocalization.string( + "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." + ) + case .applePhotos: + return AppLocalization.string( + "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." + ) + } + } + } + + /// The line about the size of the chosen folder; nil for Apple Photos and on the first step. + var measureLine: String? { + guard step == .destination, sourceKind == .folder else { return nil } + if isMeasuring { + return AppLocalization.string("Measuring your folder…") + } + guard let estimate else { + return AppLocalization.string( + "Chronoframe could not measure this folder. Space is checked again before copying." + ) + } + let size = Self.sizeText(estimate.totalBytes) + if estimate.isComplete { + return Self.format( + "Your folder holds about %@ in %@.", + size, + PluralPhrases.files(estimate.fileCount) + ) + } + return AppLocalization.format("Your folder holds at least %@.", size) + } + + /// The line about room on the destination drive, once a destination is chosen. + var spaceLine: String? { + guard step == .destination, !destinationPath.isEmpty else { return nil } + guard let free = destinationFreeBytes else { + return AppLocalization.string("Free space on this drive is unknown.") + } + let freeText = Self.sizeText(free) + guard let estimate = settledEstimate else { + return AppLocalization.format("%@ free here.", freeText) + } + if free < estimate.totalBytes { + return Self.format( + "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out.", + freeText, + Self.sizeText(estimate.totalBytes) + ) + } + // An incomplete estimate is only a lower bound, so it cannot promise the folder fits. + guard estimate.isComplete else { + return AppLocalization.format("%@ free here.", freeText) + } + return Self.format( + "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts).", + freeText, + Self.sizeText(estimate.totalBytes) + ) + } + + /// True when the folder is bigger than the free space. A warning only: it never stops the person. + var spaceIsWarning: Bool { + guard step == .destination, + !destinationPath.isEmpty, + let free = destinationFreeBytes, + let estimate = settledEstimate + else { return false } + return free < estimate.totalBytes + } + + var primaryTitle: String { + guard step == .destination else { return "" } + switch sourceKind { + case .folder: + return AppLocalization.string("Look at My Photos") + case .applePhotos: + return AppLocalization.string("Choose Photos to Copy") + } + } + + var canContinue: Bool { + step == .destination && !destinationPath.isEmpty + } + + /// Where the folder picker opens for each place. `home` is the person's real home folder. + static func startingDirectory(for place: GuidedSourcePlace, home: URL) -> URL? { + switch place { + case .pictures: + return home.appendingPathComponent("Pictures", isDirectory: true) + case .desktop: + return home.appendingPathComponent("Desktop", isDirectory: true) + case .downloads: + return home.appendingPathComponent("Downloads", isDirectory: true) + case .externalDrive: + return URL(fileURLWithPath: "/Volumes", isDirectory: true) + case .other: + return nil + } + } + + /// The estimate for a folder, once measuring has finished and only for a folder source. + private var settledEstimate: FolderSizeEstimate? { + guard sourceKind == .folder, !isMeasuring else { return nil } + return estimate + } + + private static func sizeText(_ bytes: Int64) -> String { + ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) + } + + /// Looks the template up first and fills both values in afterwards. + private static func format(_ key: String, _ first: String, _ second: String) -> String { + String(format: AppLocalization.string(key), first, second) + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift new file mode 100644 index 00000000..2edbff6d --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift @@ -0,0 +1,314 @@ +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import SwiftUI + +/// The two questions a person with nothing set up answers before the normal +/// screens: where the photos are, and where the organized copy should go. It +/// only chooses folders through the existing coordinator paths and measures the +/// chosen folder read-only; nothing is copied here. +struct GuidedSetupView: View { + let appState: AppState + @Binding var didOnboard: Bool + @ObservedObject private var setupStore: SetupStore + @State private var model: GuidedSetupModel + @State private var isChoosingSource = false + @State private var isStarting = false + /// A fixed starting state for renders. While it is set nothing is measured, so the screen shows + /// exactly the estimate and free space it was given. + private let fixedModel: GuidedSetupModel? + + init(appState: AppState, didOnboard: Binding<Bool>, fixedModel: GuidedSetupModel? = nil) { + self.appState = appState + self._didOnboard = didOnboard + self._setupStore = ObservedObject(wrappedValue: appState.setupStore) + self._model = State(initialValue: fixedModel ?? GuidedSetupModel()) + self.fixedModel = fixedModel + } + + /// The state the copy is built from: the view's own step and measurements, with the folders the + /// store actually holds. + private var current: GuidedSetupModel { + var value = model + value.sourcePath = setupStore.sourcePath + value.destinationPath = setupStore.destinationPath + return value + } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: DesignTokens.Layout.sectionSpacing) { + switch model.step { + case .source: + sourceStep + case .destination: + destinationStep + } + + Button("Use the full setup screen") { + didOnboard = true + } + .buttonStyle(.link) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.useFullSetup) + } + .padding(DesignTokens.Layout.contentPadding) + .frame(maxWidth: 560, alignment: .leading) + .frame(maxWidth: .infinity, alignment: .center) + } + .task(id: measurementRoot) { await measureFolder() } + .task(id: freeSpaceKey) { await refreshFreeSpace() } + } + + // MARK: Source step + + private var sourceStep: some View { + let copy = current + return VStack(alignment: .leading, spacing: DesignTokens.Layout.sectionSpacing) { + heading(copy) + + VStack(alignment: .leading, spacing: 8) { + ForEach(GuidedSourcePlace.allCases, id: \.self) { place in + Button { + chooseSource(place) + } label: { + placeLabel(place) + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(.bordered) + .controlSize(.large) + .disabled(isChoosingSource) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.source(place)) + } + } + + Button("My photos are in the Apple Photos app") { + chooseApplePhotos() + } + .buttonStyle(.link) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.sourceApplePhotos) + } + } + + @ViewBuilder + private func placeLabel(_ place: GuidedSourcePlace) -> some View { + switch place { + case .pictures: Text("Pictures Folder") + case .desktop: Text("Desktop") + case .downloads: Text("Downloads") + case .externalDrive: Text("An External Drive") + case .other: Text("Somewhere Else…") + } + } + + // MARK: Destination step + + private var destinationStep: some View { + let copy = current + return VStack(alignment: .leading, spacing: DesignTokens.Layout.sectionSpacing) { + heading(copy) + + if let measureLine = copy.measureLine { + HStack(alignment: .firstTextBaseline, spacing: 8) { + if copy.isMeasuring { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + } + Text(verbatim: measureLine) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + VStack(alignment: .leading, spacing: 8) { + Button("Choose a Folder…") { + Task { await appState.chooseDestinationFolder() } + } + .buttonStyle(.bordered) + .controlSize(.large) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.destinationChoose) + + if !copy.destinationPath.isEmpty { + Text(verbatim: copy.destinationPath) + .scaledFont(.mono) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .lineLimit(2) + .truncationMode(.middle) + .textSelection(.enabled) + } + + if let spaceLine = copy.spaceLine { + HStack(alignment: .firstTextBaseline, spacing: 6) { + if copy.spaceIsWarning { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(DesignTokens.ColorSystem.statusWarning) + .accessibilityHidden(true) + } + Text(verbatim: spaceLine) + .scaledFont(.body) + .foregroundStyle( + copy.spaceIsWarning + ? DesignTokens.ColorSystem.inkPrimary + : DesignTokens.ColorSystem.inkSecondary + ) + .fixedSize(horizontal: false, vertical: true) + } + } + } + + VStack(alignment: .leading, spacing: 8) { + Button { + start() + } label: { + Text(verbatim: copy.primaryTitle) + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(!copy.canContinue || isStarting) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.start) + + if copy.sourceKind == .folder { + Text("Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read.") + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + Button("Back") { + goBack() + } + .buttonStyle(.link) + } + } + + private func heading(_ copy: GuidedSetupModel) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(verbatim: copy.title) + .scaledFont(.title) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .accessibilityAddTraits(.isHeader) + Text(verbatim: copy.body) + .scaledFont(.subtitle) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + // MARK: Actions + + private func chooseSource(_ place: GuidedSourcePlace) { + guard !isChoosingSource else { return } + isChoosingSource = true + Task { + let directory = GuidedSetupModel.startingDirectory( + for: place, + home: FolderAccessService.realHomeDirectoryURL() + ) + let chosen = await appState.chooseSourceFolder(openingAt: directory) + isChoosingSource = false + if chosen { + enterDestinationStep(sourceKind: .folder) + } + } + } + + private func chooseApplePhotos() { + enterDestinationStep(sourceKind: .applePhotos) + } + + private func enterDestinationStep(sourceKind: GuidedSourceKind) { + model.sourceKind = sourceKind + model.estimate = nil + model.destinationFreeBytes = nil + model.isMeasuring = sourceKind == .folder + model.step = .destination + } + + /// Leaving the step ends the measurement: its task id becomes nil, which cancels it. + private func goBack() { + model.step = .source + model.isMeasuring = false + model.estimate = nil + model.destinationFreeBytes = nil + } + + private func start() { + guard !isStarting else { return } + isStarting = true + let sourceKind = model.sourceKind + didOnboard = true + switch sourceKind { + case .folder: + Task { + await appState.startPreview() + isStarting = false + } + case .applePhotos: + appState.navigate(to: .photos) + isStarting = false + } + } + + // MARK: Measuring + + /// The folder to measure: only the one the person chose, and only on the destination step. + private var measurementRoot: String? { + guard fixedModel == nil, + model.step == .destination, + model.sourceKind == .folder, + !setupStore.sourcePath.isEmpty + else { return nil } + return setupStore.sourcePath + } + + /// Never measure a drive's root or the list of every mounted volume. + private static func isMeasurable(_ path: String) -> Bool { + let standardized = URL(fileURLWithPath: path).standardizedFileURL.path + return standardized != "/" && standardized != "/Volumes" + } + + /// Runs the read-only estimate off the main actor. Cancelling this task (the step is left, or the + /// view goes away) cancels the walk, which stops within a few hundred entries. + private func measureFolder() async { + guard let path = measurementRoot else { return } + model.estimate = nil + guard Self.isMeasurable(path) else { + model.isMeasuring = false + return + } + model.isMeasuring = true + let root = URL(fileURLWithPath: path, isDirectory: true) + let work = Task.detached(priority: .utility) { + FolderSizeEstimator.estimate(root: root, isCancelled: { Task.isCancelled }) + } + let result = await withTaskCancellationHandler { + await work.value + } onCancel: { + work.cancel() + } + guard !Task.isCancelled else { return } + model.estimate = result + model.isMeasuring = false + } + + private var freeSpaceKey: String { + guard fixedModel == nil, model.step == .destination else { return "" } + return setupStore.destinationPath + } + + private func refreshFreeSpace() async { + let path = freeSpaceKey + guard !path.isEmpty else { return } + let free = await Task.detached(priority: .utility) { + PhotosExportExecutor.liveFreeSpace(at: URL(fileURLWithPath: path, isDirectory: true)) + }.value + guard !Task.isCancelled else { return } + model.destinationFreeBytes = free + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift b/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift index 21782262..d7bcbd9d 100644 --- a/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift +++ b/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift @@ -9,12 +9,20 @@ struct SetupView: View { @ObservedObject private var setupStore: SetupStore @ObservedObject private var preferencesStore: PreferencesStore @ObservedObject private var runSessionStore: RunSessionStore + @ObservedObject private var historyStore: HistoryStore @State private var isDropTargeted = false - @AppStorage("didOnboard") private var didOnboard = false + /// Once the guided setup has shown, it stays up while the person answers its questions, even + /// though choosing a folder fills the paths the gate checks. + @State private var guidedSetupLatched = false + @AppStorage("didOnboard") private var storedDidOnboard = false + /// Renders and tests supply the flag here so they never read or write `UserDefaults.standard`. + private let didOnboardOverride: Binding<Bool>? @Environment(\.accessibilityReduceMotion) private var reduceMotion - init(appState: AppState) { + init(appState: AppState, didOnboard: Binding<Bool>? = nil) { self.appState = appState + self.didOnboardOverride = didOnboard + self._historyStore = ObservedObject(wrappedValue: appState.historyStore) self._setupStore = ObservedObject(wrappedValue: appState.setupStore) self._preferencesStore = ObservedObject(wrappedValue: appState.preferencesStore) self._runSessionStore = ObservedObject(wrappedValue: appState.runSessionStore) @@ -28,7 +36,43 @@ struct SetupView: View { ) } - var body: some View { + private var didOnboard: Bool { + get { didOnboardOverride?.wrappedValue ?? storedDidOnboard } + nonmutating set { + if let didOnboardOverride { + didOnboardOverride.wrappedValue = newValue + } else { + storedDidOnboard = newValue + } + } + } + + private var didOnboardBinding: Binding<Bool> { + didOnboardOverride ?? $storedDidOnboard + } + + private var guidedGateShows: Bool { + GuidedSetupGate.shouldShow(GuidedSetupGateInputs( + isEligible: appState.guidedSetupEligible, + didOnboard: didOnboard, + sourcePath: setupStore.sourcePath, + sourceItemCount: setupStore.sourceItems.count, + destinationPath: setupStore.destinationPath, + hasHistory: !historyStore.entries.isEmpty, + hasProfiles: !setupStore.profiles.isEmpty + )) + } + + private var showsGuidedSetup: Bool { + guidedGateShows + || (guidedSetupLatched + && appState.guidedSetupEligible + && !didOnboard + && historyStore.entries.isEmpty + && setupStore.profiles.isEmpty) + } + + private var fullSetupContent: some View { GeometryReader { geometry in let isWide = geometry.size.width >= 1024 ScrollViewReader { proxy in @@ -177,6 +221,19 @@ struct SetupView: View { } } } + } + + var body: some View { + Group { + if showsGuidedSetup { + GuidedSetupView(appState: appState, didOnboard: didOnboardBinding) + } else { + fullSetupContent + } + } + .onChange(of: guidedGateShows, initial: true) { _, shows in + if shows { guidedSetupLatched = true } + } .darkroom() .navigationTitle("Choose Folders") .onDrop(of: [UTType.fileURL], isTargeted: $isDropTargeted) { providers in diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index b74bcd06..e7fd49cb 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -84,6 +84,33 @@ final class AppStateTests: XCTestCase { XCTAssertEqual(appState.selection, .organize) } + @MainActor + func testGuidedSetupEligibleDefaultsTrue() { + let harness = AppStateHarness() + let appState = harness.makeAppState(performInitialBootstrap: false) + XCTAssertTrue(appState.guidedSetupEligible) + } + + @MainActor + func testEveryExistingScenarioDisablesGuidedSetup() { + for scenario in UITestScenario.allCases where scenario != .guidedFirstRun { + XCTAssertFalse( + UITestAppStateFactory.make(scenario: scenario).guidedSetupEligible, + "\(scenario.rawValue) must keep its existing screen" + ) + } + + let guided = UITestAppStateFactory.make(scenario: .guidedFirstRun) + XCTAssertTrue(guided.guidedSetupEligible) + XCTAssertEqual(guided.selection, .organize) + XCTAssertEqual(guided.organizeSubSelection, .setup) + XCTAssertTrue(guided.setupStore.sourcePath.isEmpty) + XCTAssertTrue(guided.setupStore.destinationPath.isEmpty) + XCTAssertTrue(guided.setupStore.sourceItems.isEmpty) + XCTAssertTrue(guided.setupStore.profiles.isEmpty) + XCTAssertTrue(guided.historyStore.entries.isEmpty) + } + @MainActor func testUITestAppStateFactorySeedsHistoryAndProfilesScenarios() { let historyState = UITestAppStateFactory.make(scenario: .historyPopulated) diff --git a/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift b/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift new file mode 100644 index 00000000..f26610d0 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift @@ -0,0 +1,205 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation +import XCTest +@testable import ChronoframeApp + +@MainActor +final class GuidedSetupModelTests: XCTestCase { + private func size(_ bytes: Int64) -> String { + ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) + } + + private func untouched() -> GuidedSetupGateInputs { + GuidedSetupGateInputs( + isEligible: true, + didOnboard: false, + sourcePath: "", + sourceItemCount: 0, + destinationPath: "", + hasHistory: false, + hasProfiles: false + ) + } + + private func destinationModel( + kind: GuidedSourceKind = .folder, + destinationPath: String = "", + isMeasuring: Bool = false, + estimate: FolderSizeEstimate? = nil, + free: Int64? = nil + ) -> GuidedSetupModel { + GuidedSetupModel( + step: .destination, + sourceKind: kind, + sourcePath: kind == .folder ? "/Photos" : "", + destinationPath: destinationPath, + isMeasuring: isMeasuring, + estimate: estimate, + destinationFreeBytes: free + ) + } + + // MARK: Gate + + func testGateShowsOnlyForUntouchedEligibleState() { + XCTAssertTrue(GuidedSetupGate.shouldShow(untouched())) + + var ineligible = untouched() + ineligible.isEligible = false + XCTAssertFalse(GuidedSetupGate.shouldShow(ineligible)) + } + + func testGateHiddenAfterOnboardOrAnyConfiguredPath() { + var onboarded = untouched() + onboarded.didOnboard = true + XCTAssertFalse(GuidedSetupGate.shouldShow(onboarded)) + + var withSource = untouched() + withSource.sourcePath = "/Photos" + XCTAssertFalse(GuidedSetupGate.shouldShow(withSource)) + + var withItems = untouched() + withItems.sourceItemCount = 2 + XCTAssertFalse(GuidedSetupGate.shouldShow(withItems)) + + var withDestination = untouched() + withDestination.destinationPath = "/Archive" + XCTAssertFalse(GuidedSetupGate.shouldShow(withDestination)) + } + + func testGateHiddenWithHistoryOrProfiles() { + var history = untouched() + history.hasHistory = true + XCTAssertFalse(GuidedSetupGate.shouldShow(history)) + + var profiles = untouched() + profiles.hasProfiles = true + XCTAssertFalse(GuidedSetupGate.shouldShow(profiles)) + } + + // MARK: Copy + + func testSourceStepCopy() { + let model = GuidedSetupModel(step: .source) + XCTAssertEqual(model.title, "Where are most of your photos?") + XCTAssertEqual( + model.body, + "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." + ) + XCTAssertNil(model.measureLine) + XCTAssertNil(model.spaceLine) + XCTAssertFalse(model.spaceIsWarning) + XCTAssertFalse(model.canContinue) + } + + func testDestinationStepCopyForFolderAndApplePhotos() { + let folder = destinationModel(kind: .folder) + XCTAssertEqual(folder.title, "Where should the organized copy go?") + XCTAssertEqual( + folder.body, + "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." + ) + XCTAssertEqual(folder.primaryTitle, "Look at My Photos") + + let photos = destinationModel(kind: .applePhotos) + XCTAssertEqual(photos.title, "Where should the organized copy go?") + XCTAssertEqual( + photos.body, + "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." + ) + XCTAssertEqual(photos.primaryTitle, "Choose Photos to Copy") + XCTAssertNil(photos.measureLine) + } + + func testMeasureLineStates() { + XCTAssertEqual(destinationModel(isMeasuring: true).measureLine, "Measuring your folder…") + + let complete = FolderSizeEstimate(fileCount: 12_345, totalBytes: 48_000_000_000, isComplete: true) + XCTAssertEqual( + destinationModel(estimate: complete).measureLine, + "Your folder holds about \(size(48_000_000_000)) in \(12_345.formatted()) files." + ) + + let single = FolderSizeEstimate(fileCount: 1, totalBytes: 2_000_000, isComplete: true) + XCTAssertEqual( + destinationModel(estimate: single).measureLine, + "Your folder holds about \(size(2_000_000)) in 1 file." + ) + + let partial = FolderSizeEstimate(fileCount: 40, totalBytes: 5_000_000_000, isComplete: false) + XCTAssertEqual( + destinationModel(estimate: partial).measureLine, + "Your folder holds at least \(size(5_000_000_000))." + ) + + XCTAssertEqual( + destinationModel(estimate: nil).measureLine, + "Chronoframe could not measure this folder. Space is checked again before copying." + ) + + // Measuring wins over a stale estimate. + XCTAssertEqual(destinationModel(isMeasuring: true, estimate: complete).measureLine, "Measuring your folder…") + } + + func testSpaceLineWarnsButNeverBlocks() { + let estimate = FolderSizeEstimate(fileCount: 900, totalBytes: 80_000_000_000, isComplete: true) + let tight = destinationModel(destinationPath: "/Archive", estimate: estimate, free: 20_000_000_000) + XCTAssertEqual( + tight.spaceLine, + "\(size(20_000_000_000)) free here, and your folder holds about \(size(80_000_000_000)). It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out." + ) + XCTAssertTrue(tight.spaceIsWarning) + // A shortfall warns; it never stops the person continuing. + XCTAssertTrue(tight.canContinue) + + let unknown = destinationModel(destinationPath: "/Archive", estimate: estimate, free: nil) + XCTAssertEqual(unknown.spaceLine, "Free space on this drive is unknown.") + XCTAssertFalse(unknown.spaceIsWarning) + XCTAssertTrue(unknown.canContinue) + + XCTAssertNil(destinationModel(destinationPath: "", estimate: estimate, free: 1).spaceLine) + } + + func testSpaceLineSaysEstimate() { + let estimate = FolderSizeEstimate(fileCount: 900, totalBytes: 10_000_000_000, isComplete: true) + let roomy = destinationModel(destinationPath: "/Archive", estimate: estimate, free: 500_000_000_000) + XCTAssertEqual( + roomy.spaceLine, + "\(size(500_000_000_000)) free here. That is enough for about \(size(10_000_000_000)) (estimate, checked again when the copy starts)." + ) + XCTAssertFalse(roomy.spaceIsWarning) + + // No estimate, or Apple Photos: free space only. + let unmeasured = destinationModel(destinationPath: "/Archive", estimate: nil, free: 500_000_000_000) + XCTAssertEqual(unmeasured.spaceLine, "\(size(500_000_000_000)) free here.") + let photos = destinationModel(kind: .applePhotos, destinationPath: "/Archive", estimate: estimate, free: 500_000_000_000) + XCTAssertEqual(photos.spaceLine, "\(size(500_000_000_000)) free here.") + XCTAssertFalse(photos.spaceIsWarning) + + // While measuring, a stale estimate is not used. + let measuring = destinationModel(destinationPath: "/Archive", isMeasuring: true, estimate: estimate, free: 1) + XCTAssertEqual(measuring.spaceLine, "\(size(1)) free here.") + XCTAssertFalse(measuring.spaceIsWarning) + } + + // MARK: Places and continuing + + func testStartingDirectoryForEachPlace() { + let home = URL(fileURLWithPath: "/Users/someone", isDirectory: true) + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .pictures, home: home)?.path, "/Users/someone/Pictures") + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .desktop, home: home)?.path, "/Users/someone/Desktop") + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .downloads, home: home)?.path, "/Users/someone/Downloads") + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .externalDrive, home: home)?.path, "/Volumes") + XCTAssertNil(GuidedSetupModel.startingDirectory(for: .other, home: home)) + XCTAssertEqual(GuidedSourcePlace.allCases.map(\.rawValue), ["pictures", "desktop", "downloads", "externalDrive", "other"]) + } + + func testCanContinueNeedsDestination() { + XCTAssertFalse(destinationModel(destinationPath: "").canContinue) + XCTAssertTrue(destinationModel(destinationPath: "/Archive").canContinue) + XCTAssertTrue(destinationModel(kind: .applePhotos, destinationPath: "/Archive").canContinue) + XCTAssertFalse(GuidedSetupModel(step: .source, destinationPath: "/Archive").canContinue) + } +} diff --git a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift index 48ba4096..5a24f7e8 100644 --- a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift +++ b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift @@ -101,6 +101,49 @@ final class ScreenRenderEvidenceTests: XCTestCase { assertWritten("m2-deduplicate-lanes") } + func testRenderGuidedSource() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .guidedFirstRun) + // A constant binding: the render must never read or write the real `didOnboard` default. + try await render( + SetupView(appState: appState, didOnboard: .constant(false)), + name: "m3-guided-source", + size: NSSize(width: 1180, height: 820) + ) + assertWritten("m3-guided-source") + } + + func testRenderGuidedDestination() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .guidedFirstRun) + // Temporary folders stand in for the person's: no panel opens and no real folder is read. + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("guided-render-\(UUID().uuidString)", isDirectory: true) + let source = root.appendingPathComponent("Pictures", isDirectory: true) + let destination = root.appendingPathComponent("Organized", isDirectory: true) + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + appState.setupStore.sourcePath = source.path + appState.setupStore.destinationPath = destination.path + + let model = GuidedSetupModel( + step: .destination, + sourceKind: .folder, + sourcePath: source.path, + destinationPath: destination.path, + isMeasuring: false, + estimate: FolderSizeEstimate(fileCount: 18_452, totalBytes: 96_400_000_000, isComplete: true), + destinationFreeBytes: 412_000_000_000 + ) + try await render( + GuidedSetupView(appState: appState, didOnboard: .constant(false), fixedModel: model).darkroom(), + name: "m3-guided-destination", + size: NSSize(width: 1180, height: 820) + ) + assertWritten("m3-guided-destination") + } + private func makeEntitlementStore() async -> EntitlementStore { let store = EntitlementStore( storeKit: EvidenceStore(), diff --git a/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift b/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift index 25ebbb06..1480e4fa 100644 --- a/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift +++ b/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift @@ -36,6 +36,60 @@ final class SetupCoordinatorTests: XCTestCase { XCTAssertEqual(harness.historyStore.destinationRoot, destinationURL.path) } + @MainActor + func testChooseSourceFolderOpeningAtSelectsThatFolder() async throws { + let fixture = try SetupCoordinatorFixture() + defer { fixture.tearDown() } + let chosen = try fixture.makeFolder("Pictures Pick") + let startingPlace = URL(fileURLWithPath: "/Users/someone/Pictures", isDirectory: true) + let harness = fixture.harness + + harness.folderAccessService.nextChosenFolder = chosen + let didChoose = await fixture.coordinator.chooseSourceFolder(openingAt: startingPlace) + + XCTAssertTrue(didChoose) + XCTAssertNil(fixture.errors.last) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.count, 1) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.first?.directory, startingPlace) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.first?.prompt, "Choose This Folder") + XCTAssertEqual(harness.setupStore.sourcePath, chosen.path) + XCTAssertEqual(harness.setupStore.sourceItems, [chosen]) + XCTAssertEqual(harness.preferencesStore.lastManualSourcePath, chosen.path) + XCTAssertEqual(harness.preferencesStore.bookmark(for: "manual.source")?.path, chosen.path) + + // No starting place: the default start, through the single-folder picker. + let other = try fixture.makeFolder("Somewhere Else") + harness.folderAccessService.nextChosenFolder = other + let didChooseOther = await fixture.coordinator.chooseSourceFolder(openingAt: nil) + + XCTAssertTrue(didChooseOther) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.count, 1) + XCTAssertNil(harness.folderAccessService.chooseFolderCalls.last?.startingAt) + XCTAssertEqual(harness.folderAccessService.chooseFolderCalls.last?.prompt, "Choose This Folder") + XCTAssertEqual(harness.setupStore.sourceItems, [other]) + } + + @MainActor + func testChooseSourceFolderCancelledChangesNothing() async throws { + let fixture = try SetupCoordinatorFixture() + defer { fixture.tearDown() } + let harness = fixture.harness + harness.folderAccessService.nextChosenFolder = nil + + let cancelledAtPlace = await fixture.coordinator.chooseSourceFolder( + openingAt: URL(fileURLWithPath: "/Users/someone/Desktop", isDirectory: true) + ) + let cancelledAtDefault = await fixture.coordinator.chooseSourceFolder(openingAt: nil) + + XCTAssertFalse(cancelledAtPlace) + XCTAssertFalse(cancelledAtDefault) + XCTAssertNil(fixture.errors.last) + XCTAssertEqual(harness.setupStore.sourcePath, "") + XCTAssertTrue(harness.setupStore.sourceItems.isEmpty) + XCTAssertEqual(harness.preferencesStore.lastManualSourcePath, "") + XCTAssertNil(harness.preferencesStore.bookmark(for: "manual.source")) + } + @MainActor func testChooseFolderValidationFailureSurfacesErrorWithoutChangingState() async { let sourceURL = URL(fileURLWithPath: "/Volumes/Locked") diff --git a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift index ec1a7b35..30e3d5ff 100644 --- a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift +++ b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift @@ -69,6 +69,23 @@ final class UITestWindowFitTests: XCTestCase { XCTAssertGreaterThanOrEqual(size.height, minimum.height) } + func testGuidedFirstRunScenarioIsSizedLikeTheWideReviewAndFitsASmallDisplay() { + let scenario = UITestScenario.guidedFirstRun + XCTAssertEqual(UITestScenario(rawValue: "guidedFirstRun"), scenario) + XCTAssertFalse(scenario.usesMeteredTrialUI) + XCTAssertFalse(scenario.opensSettingsOnLaunch) + 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) From db99994b8166637cc3da514909f86295bb69324d Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 20:01:20 -0800 Subject: [PATCH 20/30] FRX WP-23: App: photos and the folder picture on the preview Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 3 + docs/plan/first-run-experience/PROGRESS.md | 10 +- .../App/AccessibilityIdentifiers.swift | 7 + .../Views/Run/CurrentRunView.swift | 4 + .../Views/Run/LayoutPictureModel.swift | 113 ++++++++++++ .../Views/Run/RunLayoutPictureSection.swift | 171 ++++++++++++++++++ .../Views/Run/RunSectionViews.swift | 33 +++- .../Views/Run/RunTimelineView.swift | 52 +++++- .../Views/Run/RunWorkspaceModel.swift | 2 +- .../LayoutPictureModelTests.swift | 159 ++++++++++++++++ .../RunTimelinePresentationTests.swift | 38 ++++ .../RunWorkspaceModelTests.swift | 13 +- .../ScreenRenderEvidenceTests.swift | 13 ++ 13 files changed, 599 insertions(+), 19 deletions(-) create mode 100644 ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift create mode 100644 ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift create mode 100644 ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index b3e0925a..873d6cde 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -60,3 +60,6 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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-113 Groundwork details (WP-21).** (a) `FolderSizeEstimator` returns nil for a root that is itself a symbolic link, is not a directory or cannot be listed; a failed entry below the root makes `isComplete` false; a cancelled run returns the partial counts with `isComplete == false`. Cost of the symlink-root rule: a Pictures folder that is a symlink shows "could not measure"; the copy itself is unaffected and the space line never blocks. (b) `PreferencesStore`: a stored but unrecognised `folderStructure` value keeps `.yyyyMMDD` and writes nothing (the old behaviour; "a stored value is never changed"). The prior-use check is inlined at the one assignment and uses the store's own literal keys; archive-destination bookmarks are stored as `bookmark.history.destination.…`, so the `bookmark.` prefix already covers them and both prefixes are checked as C-21 lists. (c) Histogram samples: new files in plan order, then exact copies fill what is left up to 12; counts are untouched. (d) `FolderAccessService.panelDirectoryURL(openingAt:)` is an internal pure helper so the rule is testable without a panel; its fallback is the `FileManager` home as C-22 says. `realHomeDirectoryURL()` is `nonisolated`. (e) The two new histogram tests live in `ChronoframeCoreCopyPlanTests.swift` and the four folder-access tests in `ModelAndServiceTests.swift`. - **D-FRX-114 Guided setup details (WP-22).** (a) Latch: choosing the source fills `sourcePath`, which would turn the C-23 gate off before the second question. `SetupView` therefore remembers that the full gate was true while this view was alive and keeps the guided screen up as long as the person is still eligible, not onboarded and has no history or profiles. The latch can only be set by the untouched gate, starts false on every relaunch, and ends for good when `didOnboard` becomes true. (b) `SetupView.init(appState:didOnboard: Binding<Bool>? = nil)`: production passes nothing and reads the same `@AppStorage("didOnboard")` key; renders pass a constant so `UserDefaults.standard` is never written. (c) The measure line fills `Your folder holds about %@ in %@.` with the existing files phrase, so one file reads "1 file". (d) Incomplete estimate: free space below the lower bound still warns; free space above it shows only `{free} free here.` ("enough for about X" would overclaim). While measuring, the space line ignores an old estimate. (e) `chooseSourceFolder(openingAt:)` returns true only when the chosen folder became the single source. (f) The estimator never runs on `/` or `/Volumes`, only on the validated chosen source, in a detached task cancelled when the step is left. (g) `GuidedSetupView` has an internal `fixedModel` used only by the destination render; with it no task runs. (h) Identifiers live in a nested `AccessibilityIdentifiers.Guided`; the Apple Photos primary reuses `guided.start`. (i) The place buttons are plain bordered SwiftUI buttons. +- **D-FRX-115 Running-preview message (WP-23).** C-24 says the message "gains the sentence" `Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.` The existing message was already "You can keep using your Mac. Nothing is being copied.", so appending repeated both halves. The contract fact was wrong; the message is now the C-24 sentence alone. Title, badge and the running-copy message are unchanged; the old catalog key stays, unused. +- **D-FRX-116 Layout cards never restart a preview they cannot rebuild (WP-23).** C-25 says selecting a card sets the layout and calls `startPreview()`. On a watched-folder or Apple Photos import preview that call clears the import context, deletes the Photos staging export and previews the Choose Folders paths instead; and when `startPreview()` returns early the preference would change under a preview that is not rebuilt. So: on an import preview the section shows the one line `Layout: {title}. Change it in Settings.` instead of cards; cards are disabled while a run or Deduplicate is working; and a tap changes the preference only when the same checks `startPreview()` makes will pass (`appState.canStartRun`, no import, nothing running). Otherwise the tap does nothing. A narrowing of C-25 for cases it did not foresee; nothing in the coordinator changed. +- **D-FRX-117 Preview picture details (WP-23).** (a) The selected-month panel's count is the histogram bucket's planned count (as the old "files to copy" line was), which includes exact copies; the cards use `newFilesByMonth`. The old "{n} files to copy" drawer line is replaced by the title. (b) Singular forms: `%@: 1 photo or video`, `1 folder`, `1 exact copy goes to a separate Duplicate folder.` (c) Year/Month/Day card: the `one folder per day` line appears once, under the newest month; Year card: one line per year with its total. (d) The default selection is applied once per view; a later deselection is not overridden, and a re-preview does not reselect. (e) The whole section is hidden when there are no dated new files. (f) The collapsed `DisclosureGroup("Details")` sits under the shell's existing "Details" heading, so the word appears twice; contract copy kept. (g) The preview render uses a 1360×2400 frame so the new sections are in the PNG. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 97483357..5e8f6125 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -30,9 +30,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | 0351db6 | 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 | done | build exit 0 | n/a | n/a | 6f91c90 | anchors and FolderAccessServicing conformers recorded under Baseline | | WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | b2d8704 | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | -| WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | (WP-22 commit) | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | -| WP-23 | App: photos and folder picture on the preview | in-progress | | | | | | -| WP-24 | Docs and strings, M3 | todo | | | | | | +| WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | f3192d2 | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | +| WP-23 | App: photos and folder picture on the preview | done | build exit 0 | LayoutPictureModel 10, RunWorkspaceModel 30, RunTimelinePresentation 12, Accessibility 8, RunOutcomeAccuracy 14 tests exit 0 | changes required (round 1: a layout card on an import preview discarded the import) → approve (round 2) | (WP-23 commit) | rendered: `m3-preview-photos-layout.png` matches C-25 (sample thumbnail is a placeholder: the fixture path does not exist); D-FRX-115, D-FRX-116, D-FRX-117 | +| WP-24 | Docs and strings, M3 | in-progress | | | | | | | G3 | Final gate | todo | | | n/a | | | ## Existing assertions changed (D-FRX-20) @@ -45,6 +45,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | +| WP-23 | ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift:209 | running-preview message "You can keep using your Mac. Nothing is being copied." | "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." | C-24, D-FRX-115 | | G1 | ui/Xcode/UITests/A11yBaseline.json:48, :50 | "84, FOUND" | "72, FOUND" | C-08, D-FRX-23 | ## Renders checked @@ -90,3 +91,6 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - Noticed, not fixed (M3): `panelDirectoryURL(openingAt:)` does not apply the protected-media-library check that `initialPanelDirectoryURL` applies (unreachable from the guided places; C-22 does not ask for it). - 2026-11-28 WP-22 Done-when (orchestrator): `cf_swift.sh test` exit 0 for GuidedSetupModelTests (10), SetupCoordinatorTests (40), AppStateTests (56), UITestWindowFitTests (10), AccessibilityTests (8), ScreenRenderEvidenceTests (7 run with marker, 7 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `script/check_detail_views_set_navigation_title.sh` exit 0; `git diff --check` exit 0. No existing assertions changed. - Noticed, not fixed (M3): the guided destination step can show the previous destination's free-space figure for a moment after a new destination is chosen; with the guided screen latched, adding a source from the menu on the first question leaves the person on that question (a drop ends guided setup). +- 2026-11-28 WP-23 Done-when (orchestrator): `cf_swift.sh test` exit 0 for LayoutPictureModelTests (10), RunWorkspaceModelTests (30), RunTimelinePresentationTests (12), AccessibilityTests (8), RunOutcomeAccuracyTests (14), ScreenRenderEvidenceTests (8 run with marker, 8 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `git diff --check` exit 0. +- For G3 step 4: `testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs` (`ChronoframeUITests.swift:929–942`) asserts `openDestinationButton` and "Reports and Logs", which now sit behind the collapsed `runDetailsDisclosure` on a ready preview; the test must expand it first. `testTimelineSelectionUpdatesPreview` (~:1013–1040) still passes but its "clear button appears after selecting" step is now vacuous because a month is selected on arrival. +- Noticed, not fixed (M3): `TimelinePlurals.filesToCopy` is now unused in production (its test and catalog key remain); the timeline's existing caption "Every bar is a month of planned transfers waiting to land." is jargon; in the over-allowance fixture the selected month reads 2,420 while the card reads 212 (fixture histogram does not match its `newFilesByMonth`). diff --git a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift index c8144d48..bb43f2ad 100644 --- a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift +++ b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift @@ -48,6 +48,12 @@ enum AccessibilityIdentifiers { static let runOutcomeAddFolder = "runOutcomeAddFolder" static let runOutcomeUnlockRest = "runOutcomeUnlockRest" static let runPreviewSummary = "run.preview.summary" + static let runDetailsDisclosure = "runDetailsDisclosure" + /// `layoutPicture.<FolderStructure.rawValue>` for the three offered layouts. + static func layoutPicture(_ rawValue: String) -> String { "layoutPicture.\(rawValue)" } + static let layoutPictureYearMonth = layoutPicture("YYYY/MM") + static let layoutPictureYearMonthDay = layoutPicture("YYYY/MM/DD") + static let layoutPictureYear = layoutPicture("YYYY") static let runNextStepCard = "run.nextStep.card" static let runNextStepFindDuplicates = "run.nextStep.findDuplicates" static let previewReviewFilter = "previewReviewFilter" @@ -208,6 +214,7 @@ enum AccessibilityIdentifiers { runWorkspaceTabs, runIdleOnboardingCard, runOutcomeSummaryCard, runOutcomeUndoCopy, runOutcomeAddFolder, runOutcomeUnlockRest, runPreviewSummary, previewReviewFilter, + runDetailsDisclosure, layoutPictureYearMonth, layoutPictureYearMonthDay, layoutPictureYear, refreshLibraryHealthButton, reorganizeDestinationButton, dedupeAcceptAllSuggestionsButton, dedupeAcceptClusterSuggestionButton, dedupeAcceptHighConfidenceButton, dedupeCancelCommitButton, dedupeChangeFolderButton, diff --git a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift index 936a829d..845e3c7d 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift @@ -69,6 +69,10 @@ struct CurrentRunView: View { } else { RunTimelineView(model: model) + if model.context.status == .dryRunFinished { + RunLayoutPictureSection(model: model, appState: appState) + } + if showsNowCopying { NowCopyingCard(model: model) } diff --git a/ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift b/ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift new file mode 100644 index 00000000..d82604c4 --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift @@ -0,0 +1,113 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// One selectable picture of how the new files would be arranged (C-25). +struct LayoutPictureCard: Equatable, Identifiable { + var id: FolderStructure { structure } + let structure: FolderStructure + let title: String // FolderLayoutPresentation.title(structure) + let lines: [String] // real folders, newest first, at most 6 lines, e.g. "2026/", " 10/ · 212", " 09/ · 148" + let footer: String // .yyyy "{years} folders"; .yyyyMM "{months} folders"; .yyyyMMDD "One folder for each day" + let isSelected: Bool +} + +/// Builds the folder pictures from `RunMetrics.newFilesByMonth`: new files that +/// land in each month folder, sidecars included. The histogram is not used +/// because its counts include exact copies, which go to the Duplicate folder. +enum LayoutPictureModel { + static let offered: [FolderStructure] = [.yyyyMM, .yyyyMMDD, .yyyy] + + private static let maxLines = 6 + + static func cards(newFilesByMonth: [String: Int], selected: FolderStructure) -> [LayoutPictureCard] { + let months = datedMonths(newFilesByMonth) + guard !months.isEmpty else { return [] } + + return offered.map { structure in + LayoutPictureCard( + structure: structure, + title: FolderLayoutPresentation.title(structure), + lines: lines(for: structure, months: months), + footer: footer(for: structure, months: months), + isSelected: structure == selected + ) + } + } + + // MARK: - Private + + private struct Month { + let year: String + let month: String + let count: Int + } + + /// Dated months, newest first. Undated keys ("Unknown") and empty months are left out. + private static func datedMonths(_ newFilesByMonth: [String: Int]) -> [Month] { + newFilesByMonth.compactMap { key, count -> Month? in + let parts = key.split(separator: "-", omittingEmptySubsequences: false) + guard count > 0, + parts.count == 2, + parts[0].count == 4, parts[0].allSatisfy(\.isNumber), + parts[1].count == 2, let monthNumber = Int(parts[1]), (1...12).contains(monthNumber) + else { return nil } + return Month(year: String(parts[0]), month: String(parts[1]), count: count) + } + .sorted { ($0.year, $0.month) > ($1.year, $1.month) } + } + + private static func lines(for structure: FolderStructure, months: [Month]) -> [String] { + var result: [String] = [] + switch structure { + case .yyyy: + var yearTotals: [(year: String, count: Int)] = [] + for month in months { + if let last = yearTotals.last, last.year == month.year { + yearTotals[yearTotals.count - 1].count += month.count + } else { + yearTotals.append((month.year, month.count)) + } + } + result = yearTotals.map { "\($0.year)/ · \($0.count.formatted())" } + case .yyyyMM, .yyyyMMDD: + var currentYear: String? + var addedDayLine = false + for month in months { + if month.year != currentYear { + result.append("\(month.year)/") + currentYear = month.year + } + result.append(" \(month.month)/ · \(month.count.formatted())") + // One third-level line under the newest month is enough to show the shape. + if structure == .yyyyMMDD, !addedDayLine { + result.append(" " + AppLocalization.string("one folder per day")) + addedDayLine = true + } + } + case .yyyyMonEvent, .flat: + break + } + return Array(result.prefix(maxLines)) + } + + private static func footer(for structure: FolderStructure, months: [Month]) -> String { + switch structure { + case .yyyyMMDD: + return AppLocalization.string("One folder for each day") + case .yyyyMM: + return folderCount(months.count) + case .yyyy: + return folderCount(Set(months.map(\.year)).count) + case .yyyyMonEvent, .flat: + return "" + } + } + + private static func folderCount(_ count: Int) -> String { + count == 1 + ? AppLocalization.string("1 folder") + : AppLocalization.format("%@ folders", count.formatted()) + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift b/ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift new file mode 100644 index 00000000..2e4bcf15 --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift @@ -0,0 +1,171 @@ +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import SwiftUI + +/// The folder picture on a ready preview (C-25): how the new files will be +/// arranged, with real counts, in three layouts the person can pick between. +/// +/// Choosing a card only changes the folder-layout preference and re-runs the +/// preview (D-FRX-18). Nothing is copied, and the source is never written. +struct RunLayoutPictureSection: View { + let model: RunWorkspaceModel + let appState: AppState + @ObservedObject private var preferencesStore: PreferencesStore + @ObservedObject private var runSessionStore: RunSessionStore + @ObservedObject private var deduplicateSessionStore: DeduplicateSessionStore + + init(model: RunWorkspaceModel, appState: AppState) { + self.model = model + self.appState = appState + self._preferencesStore = ObservedObject(wrappedValue: appState.preferencesStore) + self._runSessionStore = ObservedObject(wrappedValue: appState.runSessionStore) + self._deduplicateSessionStore = ObservedObject(wrappedValue: appState.deduplicateSessionStore) + } + + private var metrics: RunMetrics { model.context.metrics } + + /// A watched-source or Apple Photos import preview. Rebuilding the preview + /// from Setup would discard that import, so no card is offered for it. + private var hasActiveImport: Bool { + appState.hasActiveWatchedImport || appState.hasActivePhotosImport + } + + private var canChooseLayout: Bool { + !runSessionStore.isRunning && !deduplicateSessionStore.isWorking + } + + var body: some View { + let cards = LayoutPictureModel.cards( + newFilesByMonth: metrics.newFilesByMonth, + selected: preferencesStore.folderStructure + ) + if !metrics.newFilesByMonth.isEmpty { + DarkroomPanel(variant: .panel) { + VStack(alignment: .leading, spacing: DesignTokens.Spacing.md) { + Text("How your library will be arranged") + .scaledFont(.cardTitle) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + + if let line = Self.layoutLine( + for: preferencesStore.folderStructure, + hasActiveImport: hasActiveImport + ) { + Text(line) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + } else { + HStack(alignment: .top, spacing: DesignTokens.Spacing.md) { + ForEach(cards) { card in + cardButton(card) + } + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("You can change this later with Reorganize, which needs the unlock.") + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) + .fixedSize(horizontal: false, vertical: true) + + if metrics.duplicateCount > 0 { + Text(Self.duplicateCaption(count: metrics.duplicateCount)) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) + .fixedSize(horizontal: false, vertical: true) + } + } + } + } + } + } + + private func cardButton(_ card: LayoutPictureCard) -> some View { + Button { + let chosen = card.structure + guard Self.shouldRestartPreview( + current: preferencesStore.folderStructure, + chosen: chosen, + isRunning: runSessionStore.isRunning, + isDedupeWorking: deduplicateSessionStore.isWorking, + hasActiveImport: hasActiveImport, + canStartPreview: appState.canStartRun + ) else { return } + preferencesStore.folderStructure = chosen + Task { await appState.startPreview() } + } label: { + VStack(alignment: .leading, spacing: 6) { + Text(card.title) + .scaledFont(.subtitle, weight: .bold) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(card.lines.enumerated()), id: \.offset) { _, line in + Text(line) + .scaledFont(.mono) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .lineLimit(1) + } + } + + Text(card.footer) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(DesignTokens.Spacing.md) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(DesignTokens.ColorSystem.imageStage.opacity(0.4)) + ) + .overlay { + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder( + card.isSelected ? DesignTokens.ColorSystem.accentWaypoint : DesignTokens.ColorSystem.hairline, + lineWidth: card.isSelected ? 2 : 1 + ) + } + .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + .buttonStyle(.plain) + .disabled(!canChooseLayout) + .accessibilityIdentifier(AccessibilityIdentifiers.layoutPicture(card.structure.rawValue)) + .accessibilityAddTraits(card.isSelected ? .isSelected : []) + } + + // MARK: - Pure helpers + + /// True only when choosing `chosen` will really rebuild the preview, so the + /// preference is never changed under a preview that stays as it was: a + /// different layout, no run or duplicate cleanup in progress, no import + /// preview (which a Setup preview would discard), and the same readiness + /// `AppState.startPreview()` itself requires (`canStartPreview`). + static func shouldRestartPreview( + current: FolderStructure, + chosen: FolderStructure, + isRunning: Bool, + isDedupeWorking: Bool, + hasActiveImport: Bool, + canStartPreview: Bool + ) -> Bool { + chosen != current && !isRunning && !isDedupeWorking && !hasActiveImport && canStartPreview + } + + /// `Layout: {title}. Change it in Settings.` for the layouts the picture does + /// not offer, and for any layout while an import preview is shown; `nil` + /// when the cards are offered. + static func layoutLine(for structure: FolderStructure, hasActiveImport: Bool = false) -> String? { + guard hasActiveImport || !LayoutPictureModel.offered.contains(structure) else { return nil } + return AppLocalization.format("Layout: %@. Change it in Settings.", FolderLayoutPresentation.title(structure)) + } + + /// `{duplicateCount} exact copies go to a separate Duplicate folder.` + static func duplicateCaption(count: Int) -> String { + count == 1 + ? AppLocalization.string("1 exact copy goes to a separate Duplicate folder.") + : AppLocalization.format("%@ exact copies go to a separate Duplicate folder.", count.formatted()) + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index 07a9b4e5..d2f8bc0b 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -447,6 +447,7 @@ struct RunWorkspaceShell: View { @Binding var workspaceTab: RunWorkspaceTab let appState: AppState @ObservedObject var previewReviewStore: PreviewReviewStore + @State private var showsOverviewDetails = false var body: some View { MeridianSurfaceCard(style: .section) { @@ -479,21 +480,35 @@ struct RunWorkspaceShell: View { } } + private var overviewPanels: some View { + ViewThatFits(in: .horizontal) { + HStack(alignment: .top, spacing: 16) { + RunSnapshotPanel(model: model) + RunArtifactsPanel(model: model, appState: appState) + } + + VStack(alignment: .leading, spacing: 16) { + RunSnapshotPanel(model: model) + RunArtifactsPanel(model: model, appState: appState) + } + } + } + @ViewBuilder private var workspaceContent: some View { switch workspaceTab { case .overview: VStack(alignment: .leading, spacing: 16) { - ViewThatFits(in: .horizontal) { - HStack(alignment: .top, spacing: 16) { - RunSnapshotPanel(model: model) - RunArtifactsPanel(model: model, appState: appState) - } - - VStack(alignment: .leading, spacing: 16) { - RunSnapshotPanel(model: model) - RunArtifactsPanel(model: model, appState: appState) + if model.context.status == .dryRunFinished { + // A ready preview leads with the photos and the folder + // picture; the technical panels stay one click away. + DisclosureGroup("Details", isExpanded: $showsOverviewDetails) { + overviewPanels + .padding(.top, DesignTokens.Spacing.sm) } + .accessibilityIdentifier(AccessibilityIdentifiers.runDetailsDisclosure) + } else { + overviewPanels } } case .review: diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift b/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift index d8abe5ce..ae353778 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift @@ -18,6 +18,9 @@ struct RunTimelineView: View { @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var selectedBucketKey: String? = nil @State private var isScrubbing = false + /// Set once the ready preview has been given its starting selection, so a + /// later deselection or choice by the person is never overridden. + @State private var didApplyDefaultSelection = false private let chartHeight: CGFloat = 136 private let minBarHeight: CGFloat = 3 @@ -62,6 +65,44 @@ struct RunTimelineView: View { .fixedSize(horizontal: false, vertical: true) } } + .onAppear { applyDefaultSelectionIfNeeded() } + .onChange(of: model.context.status) { _, _ in applyDefaultSelectionIfNeeded() } + .onChange(of: buckets) { _, _ in applyDefaultSelectionIfNeeded() } + } + + // MARK: - Default selection + + /// The newest dated bucket, chosen once when the preview is ready and nothing + /// is selected, so its photos are visible on arrival. Never `Unknown`. + static func defaultSelectionKey( + buckets: [DateHistogramBucket], + status: RunStatus, + selectedKey: String? + ) -> String? { + guard status == .dryRunFinished, selectedKey == nil else { return nil } + return buckets.map(\.key).filter { $0 != "Unknown" }.max() + } + + private func applyDefaultSelectionIfNeeded() { + guard !didApplyDefaultSelection, model.context.status == .dryRunFinished, !buckets.isEmpty else { return } + didApplyDefaultSelection = true + selectedBucketKey = Self.defaultSelectionKey( + buckets: buckets, + status: model.context.status, + selectedKey: selectedBucketKey + ) ?? selectedBucketKey + } + + /// `{Month Year}: {count} photos and videos`. The template is looked up first + /// and filled in afterwards. + static func selectedBucketTitle(key: String, count: Int) -> String { + let monthYear = formatMonthYear(key) + return count == 1 + ? AppLocalization.format("%@: 1 photo or video", monthYear) + : String( + format: AppLocalization.string("%@: %@ photos and videos"), + monthYear, count.formatted() + ) } // MARK: - Header @@ -88,12 +129,9 @@ struct RunTimelineView: View { VStack(alignment: .leading, spacing: DesignTokens.Spacing.sm) { HStack { VStack(alignment: .leading, spacing: 2) { - Text(formatMonthYear(bucket.key)) + Text(Self.selectedBucketTitle(key: bucket.key, count: bucket.plannedCount)) .scaledFont(.subtitle, weight: .bold) .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) - Text(TimelinePlurals.filesToCopy(bucket.plannedCount)) - .scaledFont(.label) - .foregroundStyle(DesignTokens.ColorSystem.captionText) } Spacer() @@ -121,13 +159,17 @@ struct RunTimelineView: View { } } .frame(height: 56) + + Text(AppLocalization.string("A sample from this month.")) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) } } .padding(DesignTokens.Spacing.md) .background(DesignTokens.ColorSystem.imageStage.opacity(0.4), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) } - private func formatMonthYear(_ key: String) -> String { + private static func formatMonthYear(_ key: String) -> String { guard key != "Unknown", key.count >= 7 else { return key == "Unknown" ? "Unknown Date" : key } diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift index 626d2dbf..4292f3a9 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift @@ -360,7 +360,7 @@ struct RunWorkspaceModel { return RunHeroState( title: mode == .preview ? String(localized: "Building the preview", bundle: .module) : String(localized: "Copying your photos", bundle: .module), message: mode == .preview - ? String(localized: "You can keep using your Mac. Nothing is being copied.", bundle: .module) + ? String(localized: "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", bundle: .module) : String(localized: "You can keep using your Mac. Originals are only read, never changed.", bundle: .module), badgeTitle: mode == .preview ? String(localized: "Previewing", bundle: .module) : String(localized: "Copying", bundle: .module), badgeSymbol: "arrow.triangle.2.circlepath", diff --git a/ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift b/ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift new file mode 100644 index 00000000..9ca5cce2 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift @@ -0,0 +1,159 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import XCTest +@testable import ChronoframeApp + +/// C-25: the folder picture on the preview. Counts come from `newFilesByMonth`, +/// never from the histogram, and undated files are left out. +@MainActor +final class LayoutPictureModelTests: XCTestCase { + private let months: [String: Int] = [ + "2026-10": 212, + "2026-09": 148, + "2025-12": 40, + ] + + func testCardsForThreeDateLayouts() { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: .yyyyMM) + + XCTAssertEqual(LayoutPictureModel.offered, [.yyyyMM, .yyyyMMDD, .yyyy]) + XCTAssertEqual(cards.map(\.structure), [.yyyyMM, .yyyyMMDD, .yyyy]) + XCTAssertEqual(cards.map(\.id), [.yyyyMM, .yyyyMMDD, .yyyy]) + XCTAssertEqual(cards.map(\.title), LayoutPictureModel.offered.map(FolderLayoutPresentation.title)) + } + + func testLinesUseNewFilesByMonthNewestFirst() { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: .yyyyMM) + + let monthCard = cards[0] + XCTAssertEqual(monthCard.lines, [ + "2026/", " 10/ · 212", " 09/ · 148", + "2025/", " 12/ · 40", + ]) + + let dayCard = cards[1] + XCTAssertEqual(dayCard.lines, [ + "2026/", " 10/ · 212", " one folder per day", " 09/ · 148", + "2025/", " 12/ · 40", + ]) + + let yearCard = cards[2] + XCTAssertEqual(yearCard.lines, ["2026/ · 360", "2025/ · 40"]) + + // Undated files are left out, not folded into a month. + let withUnknown = LayoutPictureModel.cards(newFilesByMonth: months.merging(["Unknown": 99]) { $1 }, selected: .yyyyMM) + XCTAssertEqual(withUnknown[0].lines, monthCard.lines) + XCTAssertEqual(withUnknown[2].lines, yearCard.lines) + } + + func testNoCardsWithoutMonthCounts() { + XCTAssertTrue(LayoutPictureModel.cards(newFilesByMonth: [:], selected: .yyyyMM).isEmpty) + XCTAssertTrue(LayoutPictureModel.cards(newFilesByMonth: ["Unknown": 12], selected: .yyyyMM).isEmpty) + } + + func testFooterCounts() { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: .yyyyMM) + XCTAssertEqual(cards[0].footer, "3 folders") + XCTAssertEqual(cards[1].footer, "One folder for each day") + XCTAssertEqual(cards[2].footer, "2 folders") + + let single = LayoutPictureModel.cards(newFilesByMonth: ["2026-10": 5], selected: .yyyyMM) + XCTAssertEqual(single[0].footer, "1 folder") + XCTAssertEqual(single[2].footer, "1 folder") + } + + func testSelectedCardMatchesPreference() { + for selected in LayoutPictureModel.offered { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: selected) + XCTAssertEqual(cards.filter(\.isSelected).map(\.structure), [selected]) + } + + // A layout that is not offered selects no card. + let none = LayoutPictureModel.cards(newFilesByMonth: months, selected: .flat) + XCTAssertTrue(none.allSatisfy { !$0.isSelected }) + } + + func testAtMostSixLines() { + var many: [String: Int] = [:] + for year in 2020...2026 { + for month in 1...12 { + many[String(format: "%04d-%02d", year, month)] = 10 + } + } + let cards = LayoutPictureModel.cards(newFilesByMonth: many, selected: .yyyyMM) + + for card in cards { + XCTAssertLessThanOrEqual(card.lines.count, 6, card.title) + } + XCTAssertEqual(cards[0].lines, ["2026/", " 12/ · 10", " 11/ · 10", " 10/ · 10", " 09/ · 10", " 08/ · 10"]) + XCTAssertEqual(cards[1].lines, ["2026/", " 12/ · 10", " one folder per day", " 11/ · 10", " 10/ · 10", " 09/ · 10"]) + XCTAssertEqual(cards[2].lines.count, 6) + XCTAssertEqual(cards[2].footer, "7 folders") + XCTAssertEqual(cards[0].footer, "84 folders") + } + + // MARK: - Section behavior + + private func restart( + current: FolderStructure = .yyyyMM, + chosen: FolderStructure = .yyyy, + isRunning: Bool = false, + isDedupeWorking: Bool = false, + hasActiveImport: Bool = false, + canStartPreview: Bool = true + ) -> Bool { + RunLayoutPictureSection.shouldRestartPreview( + current: current, + chosen: chosen, + isRunning: isRunning, + isDedupeWorking: isDedupeWorking, + hasActiveImport: hasActiveImport, + canStartPreview: canStartPreview + ) + } + + func testSectionStartsAPreviewOnlyForADifferentIdleChoice() { + // A normal ready preview restarts. + XCTAssertTrue(restart()) + // The same card is a no-op. + XCTAssertFalse(restart(chosen: .yyyyMM)) + // A run in progress blocks it. + XCTAssertFalse(restart(isRunning: true)) + } + + func testSectionDoesNotChangeLayoutWhenThePreviewCannotBeRebuilt() { + // Duplicate cleanup in flight: startPreview() would return early. + XCTAssertFalse(restart(isDedupeWorking: true)) + // Setup paths not ready: startPreview() would return early. + XCTAssertFalse(restart(canStartPreview: false)) + // An import preview would be discarded and replaced by a Setup preview. + XCTAssertFalse(restart(hasActiveImport: true)) + } + + func testSectionShowsTheOneLineInsteadOfCardsForAnImportPreview() { + XCTAssertNil(RunLayoutPictureSection.layoutLine(for: .yyyyMM, hasActiveImport: false)) + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .yyyyMM, hasActiveImport: true), + "Layout: Year / Month. Change it in Settings." + ) + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .flat, hasActiveImport: true), + "Layout: One folder. Change it in Settings." + ) + } + + func testSectionShowsOneLineForLayoutsThatAreNotOffered() { + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .flat), + "Layout: One folder. Change it in Settings." + ) + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .yyyyMonEvent), + "Layout: Year / Month / Event. Change it in Settings." + ) + XCTAssertNil(RunLayoutPictureSection.layoutLine(for: .yyyyMM)) + XCTAssertEqual(RunLayoutPictureSection.duplicateCaption(count: 1_204), "\((1_204).formatted()) exact copies go to a separate Duplicate folder.") + XCTAssertEqual(RunLayoutPictureSection.duplicateCaption(count: 1), "1 exact copy goes to a separate Duplicate folder.") + } +} diff --git a/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift b/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift index 8d9eeb4a..6e08159a 100644 --- a/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift @@ -160,4 +160,42 @@ final class RunTimelinePresentationTests: XCTestCase { XCTAssertEqual(TimelinePlurals.acrossMonths(3, bundle: german), "in 3 Monaten") XCTAssertEqual(TimelinePlurals.filesToCopy(1, bundle: german), "1 Datei zu kopieren") } + + // MARK: - Photos on arrival (C-25) + + func testDefaultSelectionIsNewestDatedBucket() { + let buckets = [ + DateHistogramBucket(key: "2021-04", plannedCount: 40), + DateHistogramBucket(key: "2022-01", plannedCount: 30), + DateHistogramBucket(key: "2021-05", plannedCount: 30), + DateHistogramBucket(key: "Unknown", plannedCount: 9), + ] + XCTAssertEqual( + RunTimelineView.defaultSelectionKey(buckets: buckets, status: .dryRunFinished, selectedKey: nil), + "2022-01" + ) + // Only a ready preview selects anything, and never over a choice already made. + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: buckets, status: .running, selectedKey: nil)) + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: buckets, status: .finished, selectedKey: nil)) + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: buckets, status: .dryRunFinished, selectedKey: "2021-04")) + } + + func testNoDefaultSelectionWithoutDatedBuckets() { + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: [], status: .dryRunFinished, selectedKey: nil)) + XCTAssertNil(RunTimelineView.defaultSelectionKey( + buckets: [DateHistogramBucket(key: "Unknown", plannedCount: 9)], + status: .dryRunFinished, + selectedKey: nil + )) + } + + func testSelectedBucketTitle() { + XCTAssertEqual(RunTimelineView.selectedBucketTitle(key: "2026-10", count: 212), "October 2026: 212 photos and videos") + XCTAssertEqual(RunTimelineView.selectedBucketTitle(key: "2026-10", count: 1), "October 2026: 1 photo or video") + XCTAssertEqual( + RunTimelineView.selectedBucketTitle(key: "2026-10", count: 1_204), + "October 2026: \((1_204).formatted()) photos and videos" + ) + XCTAssertEqual(RunTimelineView.selectedBucketTitle(key: "Unknown", count: 9), "Unknown Date: 9 photos and videos") + } } diff --git a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift index 68da8a25..2c0618bb 100644 --- a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift @@ -206,7 +206,7 @@ final class RunWorkspaceModelTests: XCTestCase { badge: "Preparing"), HeroRow(label: "running preview", status: .running, mode: .preview, canStart: true, title: "Building the preview", - message: "You can keep using your Mac. Nothing is being copied.", + message: "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", badge: "Previewing"), HeroRow(label: "running transfer", status: .running, mode: .transfer, canStart: true, title: "Copying your photos", @@ -272,6 +272,17 @@ final class RunWorkspaceModelTests: XCTestCase { ) } + func testRunningPreviewMessageSaysOnlyReading() { + let message = heroModel(status: .running, mode: .preview).heroState.message + XCTAssertEqual(message, "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.") + + // The running transfer message is unchanged. + XCTAssertEqual( + heroModel(status: .running, mode: .transfer).heroState.message, + "You can keep using your Mac. Originals are only read, never changed." + ) + } + func testHeroCopyNeverSaysTransferOrRun() { let statuses: [RunStatus] = [ .idle, .preflighting, .running, .dryRunFinished, .finished, .nothingToCopy, diff --git a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift index 5a24f7e8..5a0817bb 100644 --- a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift +++ b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift @@ -57,6 +57,19 @@ final class ScreenRenderEvidenceTests: XCTestCase { assertWritten("m1-preview-over-allowance") } + func testRenderPreviewWithPhotosAndLayout() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .runPreviewOverAllowance) + // Tall frame: the preview is a scroll view, and the selected month, the folder + // picture and the Details disclosure sit below the first screen. + try await render( + RootSplitView(appState: appState), + name: "m3-preview-photos-layout", + size: NSSize(width: 1360, height: 2400) + ) + assertWritten("m3-preview-photos-layout") + } + func testRenderCopyComplete() async throws { try requireEvidenceMarker() let appState = UITestAppStateFactory.make(scenario: .runCopyComplete) From 31ecb8e07c72f3fd43f6b280b86644a4713626f0 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 20:08:35 -0800 Subject: [PATCH 21/30] FRX WP-24: strings and docs Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 8 +- docs/FAQ.md | 8 +- docs/QUICK_START.md | 14 +- docs/SAFETY_AND_RECOVERY.md | 25 + docs/plan/first-run-experience/DECISIONS.md | 1 + docs/plan/first-run-experience/PROGRESS.md | 5 +- .../first-run-experience/strings/M3-app.json | 158 +++++ .../first-run-experience/strings/M3-core.json | 1 + docs/plan/next-half/README.md | 2 +- .../Resources/Localizable.xcstrings | 610 ++++++++++++++++++ 10 files changed, 822 insertions(+), 10 deletions(-) create mode 100644 docs/plan/first-run-experience/strings/M3-app.json create mode 100644 docs/plan/first-run-experience/strings/M3-core.json diff --git a/README.md b/README.md index 8a6237d9..f3394991 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Chronoframe always shows you a plan before it changes anything. Your source fold | Need | Use Chronoframe to | | :--- | :--- | -| Make sense of a messy folder | Copy photos and videos into folders like `2024/06/15` | +| Make sense of a messy folder | Copy photos and videos into folders like `2024/06` | | Combine old backups | Skip files that are already in the destination | | Fix uncertain dates | Review unknown or low-confidence dates before copying | | Keep an eye on the library | Run a Health check for unknown dates, duplicates, and interrupted work | @@ -51,14 +51,16 @@ The current source targets **macOS 14.0 or later** on Apple Silicon and Intel Ma Organize has these tabs: **Choose Folders**, **Preview & Copy**, **History**, **Watched Folders**, and **Health**. +When you open Chronoframe with nothing set up, **Choose Folders** asks two questions instead of showing the full screen: **Where are most of your photos?** (**Pictures Folder**, **Desktop**, **Downloads**, **An External Drive**, **Somewhere Else…**, or **My photos are in the Apple Photos app**) and **Where should the organized copy go?** It shows how much your folder holds (an estimate, counted in files) and how much free space the destination has, and warns without ever blocking you if it may not fit. **Look at My Photos** builds the preview and copies nothing. **Use the full setup screen** skips the questions, and they do not come back. If you quit before finishing, the questions return on the next launch only when you had not yet chosen a folder; once a folder is chosen you see the full screen from then on. If you already have folders, history or saved setups, you see the full screen. The steps below are the full screen. + 1. Open **Organize → Choose Folders**. 2. Click **Add Folders…** and pick the folders with your unsorted photos and videos. 3. Click **Choose Destination…** and pick where organized copies should go. -4. Click **Preview Plan**. Chronoframe scans the source, resolves dates, and builds a transfer plan — nothing is copied yet. +4. Click **Preview Plan**. Chronoframe scans the source, resolves dates, and builds a transfer plan. While it works, the screen says Chronoframe is only reading and nothing is copied yet. A new install organizes into **Year / Month** folders by default; if Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day**, and a layout you chose is never changed. ![Preview Ready for Review — a timeline of the library by month, with discovered, planned, and issue counts.](docs/screenshots/preview-timeline.jpg) -5. On **Preview & Copy**, inspect the preview: the timeline shows your library by month, and the counts cover what's ready, what's already there, duplicates, and anything that needs attention. The first line of **What will happen** says whether every photo and video Chronoframe found is listed below; if the numbers do not add up, it says so and asks you to rebuild the preview. Open **Review** to fix uncertain dates. +5. On **Preview & Copy**, inspect the preview: the timeline shows your library by month, and the counts cover what's ready, what's already there, duplicates, and anything that needs attention. The first line of **What will happen** says whether every photo and video Chronoframe found is listed below; if the numbers do not add up, it says so and asks you to rebuild the preview. Open **Review** to fix uncertain dates. The newest month is selected so a sample from that month is on screen, and **How your library will be arranged** shows the newest folders and how many new files each will get, for **Year / Month**, **Year / Month / Day** and **Year**. Clicking another layout rebuilds the preview and copies nothing. The technical panels are under **Details**. 6. Click **Start Copying** when the preview looks right. Chronoframe copies files into the destination, verifies them, and writes a receipt — your source is never touched. The completion screen says whether every photo and video found is accounted for, and offers **Undo This Copy…** and **Add Another Folder**. ![Transfer Complete — every frame copied, with a run summary and links to open the destination, report, and logs.](docs/screenshots/transfer-complete.jpg) diff --git a/docs/FAQ.md b/docs/FAQ.md index e8a98cc1..c21a323b 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -24,7 +24,7 @@ A: Yes. Open **Organize** → **History** and click **Undo** next to the copy yo **Q: How do I know what Chronoframe will copy?** -A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. +A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. While the preview is being built, the screen says Chronoframe is only reading and nothing is copied yet. When it is ready, the newest month is selected so a sample from that month is on screen, and **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets. --- @@ -36,7 +36,7 @@ A: macOS 14.0 or later. Chronoframe works on Intel and Apple Silicon Macs. **Q: How much disk space do I need?** -A: Enough for your destination folder to hold copies of your original files. Chronoframe doesn't compress; it copies files as-is. You'll need roughly the same amount of free space as the size of the folders you are organizing. +A: Enough for your destination folder to hold copies of your original files. Chronoframe doesn't compress; it copies files as-is. You'll need roughly the same amount of free space as the size of the folders you are organizing. The first-time setup shows this for you: once you have chosen the folder to organize it shows how much it holds (an estimate, counted in files), and once you choose the destination it shows how much free space that drive has. If your folder may not fit, it warns you but never stops you. The screen says the copy pauses safely if space runs out. **Q: Why is the first scan taking so long?** @@ -77,6 +77,10 @@ A: Yes. In the **Review** tab on the **Preview & Copy** screen, change an item's A: It means Chronoframe isn't sure about the date—maybe the filename looks like a date but doesn't match metadata, or it's relying on filesystem dates. You can accept it or override it in Review. +**Q: Which folder layout does Chronoframe use, and can I change it?** + +A: A new install uses **Year / Month** (`2019/07`). If Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day** (`2019/07/14`). A layout you chose yourself is never changed. You can change it in **Settings → Layout**, with the **Folder layout** menu on **Choose Folders**, or, once a preview is ready, by clicking **Year / Month**, **Year / Month / Day** or **Year** under **How your library will be arranged**. That rebuilds the preview, and nothing is copied. If the preview came from a watched folder or the Apple Photos app, or you use **Year / Month / Event** or **One folder**, it shows your layout on one line instead, and you change it in **Settings**. To change the layout of a library you have already copied, use Reorganize, which needs the unlock. + **Q: Can I use custom event names?** A: If your folder layout is `YYYY/Mon/Event`, Chronoframe suggests event names based on proximity and source folder names. You can accept suggestions in Review, or manually edit them. diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md index 7f3ba002..9cf9a685 100644 --- a/docs/QUICK_START.md +++ b/docs/QUICK_START.md @@ -13,18 +13,28 @@ Use this when you want Chronoframe to copy messy folders into a cleaner date-bas ### Step 1: Choose Folders +When you open Chronoframe with nothing set up, **Choose Folders** asks two questions instead of showing the full screen: + +- **Where are most of your photos?** Click **Pictures Folder**, **Desktop**, **Downloads**, **An External Drive** or **Somewhere Else…**. The first four open the folder picker at that place (**An External Drive** opens the list of drives); **Somewhere Else…** opens it where it usually starts. You still choose the folder in the picker. Chronoframe only reads it. If your photos are in the Apple Photos app, click **My photos are in the Apple Photos app** instead. +- **Where should the organized copy go?** Click **Choose a Folder…**. Chronoframe shows how much your folder holds, with the number of files when it could read everything, and how much free space the destination drive has. The size is an estimate ("about"), and when Chronoframe cannot read everything it says "at least". If the folder may not fit, it warns you but does not stop you. The screen says the copy pauses safely if space runs out. Click **Look at My Photos** to build the preview. Nothing is copied. A very large collection can take 5 to 15 minutes to read. For Apple Photos, the button is **Choose Photos to Copy**, which opens the Apple Photos screen instead of building a preview. No folder size is shown for Photos. + +**Use the full setup screen** is on both questions and takes you to the full **Choose Folders** screen, and the questions do not come back. If you quit before finishing, the questions return on the next launch only when you had not yet chosen a folder; once a folder is chosen you see the full screen from then on. If you already have folders, history or saved setups, you see the full screen from the start. The numbered steps below are the full screen. + 1. Open **Organize → Choose Folders** 2. Click **Add Folders…** and choose the folders that hold your photos. You can pick more than one — see [Organizing several folders at once](#organizing-several-folders-at-once) 3. Click **Choose Destination…** and choose where organized photos should go -4. Chronoframe organizes into **Year / Month / Day** folders (`YYYY/MM/DD`) by default. To use **Year / Month**, **Year**, **Year / Month / Event** or **One folder** instead, change the **Folder layout** menu under the destination, or change it in **Settings → Layout**. +4. A new install organizes into **Year / Month** folders (`YYYY/MM`) by default. If Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day** (`YYYY/MM/DD`). A layout you chose yourself is never changed. To use **Year / Month / Day**, **Year / Month**, **Year**, **Year / Month / Event** or **One folder**, change the **Folder layout** menu under the destination, or change it in **Settings → Layout**. When the preview is ready, you can also switch between **Year / Month**, **Year / Month / Day** and **Year** there (see step 6). ### Step 2: Preview Your Plan 5. Click **Preview Plan** - - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet + - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet. While it works, the screen says Chronoframe is only reading, and you can keep using your Mac - This takes 10–60 seconds depending on your library size 6. When it finishes, **Preview & Copy** shows the plan: a headline saying how many photos and videos will be copied, a **What will happen** card that lists anything unusual, a timeline of your library, and counts for what was found, what will be copied, what is already there, exact copies, and problems - The first line of the **What will happen** card says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, the line says how many do not add up and asks you to rebuild the preview before copying + - The newest month is selected in the timeline, so a sample from that month is on screen when the preview opens. Select another month to see a sample from it + - **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets, in three layouts: **Year / Month**, **Year / Month / Day** (a line notes each day gets its own folder) and **Year**. Click a layout to use it. Chronoframe rebuilds the preview, and nothing is copied. While a copy or Deduplicate is running, or when the preview cannot be rebuilt, the layouts cannot be changed. If the preview came from a watched folder or the Apple Photos app, or you use **Year / Month / Event** or **One folder**, it shows your layout on one line instead, and you change it in **Settings**. Under it: "You can change this later with Reorganize, which needs the unlock." + - **Details** is closed on a ready preview. Open it for the **Status** card and **Reports and Logs**, with buttons to open the destination and the preview report ### Step 3: Review (Optional) diff --git a/docs/SAFETY_AND_RECOVERY.md b/docs/SAFETY_AND_RECOVERY.md index 11231fae..b922ea67 100644 --- a/docs/SAFETY_AND_RECOVERY.md +++ b/docs/SAFETY_AND_RECOVERY.md @@ -49,6 +49,31 @@ important library, especially before a large first run or filesystem migration. planned files were not copied, it says how many, that your originals were not changed, and points to Problems. After a free copy it says how many are waiting for the next copy. The line counts files; it never changes a file. +- **While the preview is built.** The screen says Chronoframe is only reading + and nothing is copied yet. Building a preview never changes your source + folders, and nothing is copied. It writes only its own report, log, review data and cache in the destination. +- **First-time setup and free space.** The two-question first-time setup + measures the folder you chose by listing it and reading file attributes. It + never opens, changes or follows anything: it counts regular files, and skips + hidden files, package contents and symbolic links. The result is an estimate, + worded "about" or "at least", and it counts every file, not only photos. It + compares that with the free space on the destination drive. If the folder may + not fit, the screen warns you but does not block you, and says the copy pauses + safely if space runs out. When there is room, it says space is checked again + when the copy starts. **Look at My Photos** builds a preview and copies + nothing. +- **Choosing a layout on a ready preview.** **How your library will be + arranged** shows the newest folders and the number of new files in each for + **Year / Month**, **Year / Month / Day** and **Year**. Choosing another one + changes only the folder-layout setting and, when the preview can be rebuilt, + rebuilds it; nothing is copied and your source is not written. While a copy or + Deduplicate is running, or when the preview cannot be rebuilt, the layouts + cannot be changed. On a watched-folder or Apple Photos import preview, or when + you use **Year / Month / Event** or **One folder**, it shows the layout on one + line, and you change it in Settings. The default layout is **Year / Month** on + a new install and stays **Year / Month / Day** where Chronoframe finds folders + saved from earlier use; a layout you chose is never changed. Changing the + layout of files you have already copied is Reorganize, which needs the unlock. - **Undo This Copy….** The completion summary offers it for the copy that just finished, once History has found that copy's receipt. It asks for confirmation and then runs the same revert History runs for that receipt, with the same diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 873d6cde..850a39cb 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -63,3 +63,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-115 Running-preview message (WP-23).** C-24 says the message "gains the sentence" `Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.` The existing message was already "You can keep using your Mac. Nothing is being copied.", so appending repeated both halves. The contract fact was wrong; the message is now the C-24 sentence alone. Title, badge and the running-copy message are unchanged; the old catalog key stays, unused. - **D-FRX-116 Layout cards never restart a preview they cannot rebuild (WP-23).** C-25 says selecting a card sets the layout and calls `startPreview()`. On a watched-folder or Apple Photos import preview that call clears the import context, deletes the Photos staging export and previews the Choose Folders paths instead; and when `startPreview()` returns early the preference would change under a preview that is not rebuilt. So: on an import preview the section shows the one line `Layout: {title}. Change it in Settings.` instead of cards; cards are disabled while a run or Deduplicate is working; and a tap changes the preference only when the same checks `startPreview()` makes will pass (`appState.canStartRun`, no import, nothing running). Otherwise the tap does nothing. A narrowing of C-25 for cases it did not foresee; nothing in the coordinator changed. - **D-FRX-117 Preview picture details (WP-23).** (a) The selected-month panel's count is the histogram bucket's planned count (as the old "files to copy" line was), which includes exact copies; the cards use `newFilesByMonth`. The old "{n} files to copy" drawer line is replaced by the title. (b) Singular forms: `%@: 1 photo or video`, `1 folder`, `1 exact copy goes to a separate Duplicate folder.` (c) Year/Month/Day card: the `one folder per day` line appears once, under the newest month; Year card: one line per year with its total. (d) The default selection is applied once per view; a later deselection is not overridden, and a re-preview does not reselect. (e) The whole section is hidden when there are no dated new files. (f) The collapsed `DisclosureGroup("Details")` sits under the shell's existing "Details" heading, so the word appears twice; contract copy kept. (g) The preview render uses a 1360×2400 frame so the new sections are in the PNG. +- **D-FRX-118 M3 strings and docs (WP-24).** (a) 36 App keys added, 3 kept (`%@ folders`, `1 folder`, `Details` already had German); no Core strings. `%@: %@ photos and videos` and `%@: 1 photo or video` carry no `extractionState` because their generated symbols collide with existing keys (same handling as D-FRX-107). (b) The picker prompt `Choose This Folder` is a plain string passed to the panel, like the existing `Add Folders` and `Choose Destination Folder` prompts, and is not in the catalog. (c) Docs: the README example path is now `2024/06` (the new-person default); the default-layout sentence says "new install" versus "folders saved from earlier use", which is how the code decides; the safety document says a preview writes its own report, log, review data and cache in the destination and never changes the source (the screen's "only reading" is about the photos). (d) The docs review needed two rounds; round 2 left two one-sentence items, applied by the orchestrator with the reviewer's wording (as in D-FRX-112c). diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 5e8f6125..fd0016ea 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -31,8 +31,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-20 | Branch and baseline, M3 | done | build exit 0 | n/a | n/a | 6f91c90 | anchors and FolderAccessServicing conformers recorded under Baseline | | WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | b2d8704 | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | | WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | f3192d2 | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | -| WP-23 | App: photos and folder picture on the preview | done | build exit 0 | LayoutPictureModel 10, RunWorkspaceModel 30, RunTimelinePresentation 12, Accessibility 8, RunOutcomeAccuracy 14 tests exit 0 | changes required (round 1: a layout card on an import preview discarded the import) → approve (round 2) | (WP-23 commit) | rendered: `m3-preview-photos-layout.png` matches C-25 (sample thumbnail is a placeholder: the fixture path does not exist); D-FRX-115, D-FRX-116, D-FRX-117 | -| WP-24 | Docs and strings, M3 | in-progress | | | | | | +| WP-23 | App: photos and folder picture on the preview | done | build exit 0 | LayoutPictureModel 10, RunWorkspaceModel 30, RunTimelinePresentation 12, Accessibility 8, RunOutcomeAccuracy 14 tests exit 0 | changes required (round 1: a layout card on an import preview discarded the import) → approve (round 2) | db99994 | rendered: `m3-preview-photos-layout.png` matches C-25 (sample thumbnail is a placeholder: the fixture path does not exist); D-FRX-115, D-FRX-116, D-FRX-117 | +| WP-24 | Docs and strings, M3 | done | build exit 0 | n/a (strings and docs; checked at G3) | German: changes required → 4 fixes applied; docs: changes required (round 1, 11 items), changes required (round 2, two one-sentence items applied by the orchestrator) | (WP-24 commit) | 36 App keys; `docs/plan/next-half/README.md` row set to "built, not merged"; D-FRX-118 | | G3 | Final gate | todo | | | n/a | | | ## Existing assertions changed (D-FRX-20) @@ -94,3 +94,4 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 2026-11-28 WP-23 Done-when (orchestrator): `cf_swift.sh test` exit 0 for LayoutPictureModelTests (10), RunWorkspaceModelTests (30), RunTimelinePresentationTests (12), AccessibilityTests (8), RunOutcomeAccuracyTests (14), ScreenRenderEvidenceTests (8 run with marker, 8 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `git diff --check` exit 0. - For G3 step 4: `testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs` (`ChronoframeUITests.swift:929–942`) asserts `openDestinationButton` and "Reports and Logs", which now sit behind the collapsed `runDetailsDisclosure` on a ready preview; the test must expand it first. `testTimelineSelectionUpdatesPreview` (~:1013–1040) still passes but its "clear button appears after selecting" step is now vacuous because a month is selected on arrival. - Noticed, not fixed (M3): `TimelinePlurals.filesToCopy` is now unused in production (its test and catalog key remain); the timeline's existing caption "Every bar is a month of planned transfers waiting to land." is jargon; in the over-allowance fixture the selected month reads 2,420 while the card reads 212 (fixture histogram does not match its `newFilesByMonth`). +- 2026-11-28 WP-24: `add_translated_keys.py … Localizable.xcstrings … M3-app.json` exit 0 (added 36, kept 3); `… LocalizableCore.xcstrings … M3-core.json` exit 0 (added 0); `cf_swift.sh build` exit 0 after the symbol-collision fix; early German check exit 0 (app 1829, core 330; zero missing keys of 927 app / 287 core). German review: four corrections applied ("Apple Fotos", "ermittelt" twice, a verb in one heading). Docs: QUICK_START, FAQ, README, SAFETY_AND_RECOVERY; `git diff --check` exit 0. diff --git a/docs/plan/first-run-experience/strings/M3-app.json b/docs/plan/first-run-experience/strings/M3-app.json new file mode 100644 index 00000000..f1836698 --- /dev/null +++ b/docs/plan/first-run-experience/strings/M3-app.json @@ -0,0 +1,158 @@ +[ + { + "key": "Where are most of your photos?", + "de": "Wo liegen die meisten deiner Fotos?" + }, + { + "key": "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted.", + "de": "Wähle einen Ort für den Anfang. Weitere kannst du später hinzufügen. Chronoframe liest diesen Ort nur: Nichts darin wird verschoben, umbenannt oder gelöscht." + }, + { + "key": "Pictures Folder", + "de": "Ordner „Bilder“" + }, + { + "key": "Desktop", + "de": "Schreibtisch" + }, + { + "key": "Downloads", + "de": "Downloads" + }, + { + "key": "An External Drive", + "de": "Ein externes Laufwerk" + }, + { + "key": "Somewhere Else…", + "de": "Woanders…" + }, + { + "key": "My photos are in the Apple Photos app", + "de": "Meine Fotos sind in Apple Fotos" + }, + { + "key": "Where should the organized copy go?", + "de": "Wohin soll die organisierte Kopie kommen?" + }, + { + "key": "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are.", + "de": "Chronoframe erstellt dort eine neue, organisierte Kopie. Deine Originale bleiben genau dort, wo sie sind." + }, + { + "key": "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed.", + "de": "Chronoframe kopiert deine Fotos aus Apple Fotos in diesen Ordner. Deine Fotos-Mediathek wird nie verändert." + }, + { + "key": "Measuring your folder…", + "de": "Die Größe deines Ordners wird ermittelt…" + }, + { + "key": "Your folder holds about %@ in %@.", + "de": "Dein Ordner enthält etwa %1$@ in %2$@." + }, + { + "key": "Your folder holds at least %@.", + "de": "Dein Ordner enthält mindestens %@." + }, + { + "key": "Chronoframe could not measure this folder. Space is checked again before copying.", + "de": "Chronoframe konnte die Größe dieses Ordners nicht ermitteln. Der Speicherplatz wird vor dem Kopieren erneut geprüft." + }, + { + "key": "Choose a Folder…", + "de": "Ordner wählen…" + }, + { + "key": "Free space on this drive is unknown.", + "de": "Der freie Speicherplatz auf diesem Laufwerk ist unbekannt." + }, + { + "key": "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out.", + "de": "Hier sind %1$@ frei, und dein Ordner enthält etwa %2$@. Möglicherweise passt nicht alles. Wähle ein größeres Laufwerk oder fahre fort: Der Kopiervorgang pausiert sicher, wenn der Speicherplatz ausgeht." + }, + { + "key": "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts).", + "de": "Hier sind %1$@ frei. Das reicht für etwa %2$@ (Schätzung, wird beim Start des Kopiervorgangs erneut geprüft)." + }, + { + "key": "%@ free here.", + "de": "Hier sind %@ frei." + }, + { + "key": "Look at My Photos", + "de": "Meine Fotos ansehen" + }, + { + "key": "Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read.", + "de": "In diesem Schritt wird nichts kopiert. Das Einlesen einer sehr großen Sammlung kann 5 bis 15 Minuten dauern." + }, + { + "key": "Choose Photos to Copy", + "de": "Fotos zum Kopieren auswählen" + }, + { + "key": "Back", + "de": "Zurück" + }, + { + "key": "Use the full setup screen", + "de": "Vollständige Einrichtung verwenden" + }, + { + "key": "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", + "de": "Chronoframe liest nur. Es wird noch nichts kopiert, und du kannst deinen Mac weiterverwenden." + }, + { + "key": "%@: %@ photos and videos", + "de": "%1$@: %2$@ Fotos und Videos" + }, + { + "key": "%@: 1 photo or video", + "de": "%@: 1 Foto oder Video" + }, + { + "key": "A sample from this month.", + "de": "Eine Auswahl aus diesem Monat." + }, + { + "key": "How your library will be arranged", + "de": "So wird deine Mediathek angeordnet" + }, + { + "key": "You can change this later with Reorganize, which needs the unlock.", + "de": "Du kannst das später mit „Neu strukturieren“ ändern. Dafür ist die Freischaltung nötig." + }, + { + "key": "%@ exact copies go to a separate Duplicate folder.", + "de": "%@ identische Kopien kommen in einen separaten Ordner Duplicate." + }, + { + "key": "1 exact copy goes to a separate Duplicate folder.", + "de": "1 identische Kopie kommt in einen separaten Ordner Duplicate." + }, + { + "key": "Layout: %@. Change it in Settings.", + "de": "Struktur: %@. Ändere sie in den Einstellungen." + }, + { + "key": "One folder for each day", + "de": "Ein Ordner für jeden Tag" + }, + { + "key": "one folder per day", + "de": "ein Ordner pro Tag" + }, + { + "key": "%@ folders", + "de": "%@ Ordner" + }, + { + "key": "1 folder", + "de": "1 Ordner" + }, + { + "key": "Details", + "de": "Details" + } +] diff --git a/docs/plan/first-run-experience/strings/M3-core.json b/docs/plan/first-run-experience/strings/M3-core.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/docs/plan/first-run-experience/strings/M3-core.json @@ -0,0 +1 @@ +[] diff --git a/docs/plan/next-half/README.md b/docs/plan/next-half/README.md index 5b741d8a..ad5e2c9d 100644 --- a/docs/plan/next-half/README.md +++ b/docs/plan/next-half/README.md @@ -14,7 +14,7 @@ Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as | 3a | [`clear-path/`](../clear-path/) | `feature/clear-path` | `feature/photos-import-resume` (stacked, D-CLP-01) | `CLP` | UX review 2026-11-12 — plain-language Organize and Deduplicate flow, several folders at once | shipped in #269, follow-up #274 | | 4 | [`find-and-account/`](../find-and-account/) | `feature/find-and-account` | `main` after #3 merges | `FAA` | 4 — item-level reconciliation and original-name lookup | not started | | 5 | [`first-ten-minutes/`](../first-ten-minutes/) | `feature/first-ten-minutes` | `main` after #4 merges | `FTM` | 5 — preflight, free batch, proof | superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | -| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | in progress, not merged | +| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | built, not merged | Each plan is self-contained: `CONTRACTS.md`, `DECISIONS.md`, `IMPLEMENTATION_PLAN.md`, `PROGRESS.md`, `ACCEPTANCE_MATRIX.md`, `BLOCKED.md`, `EVIDENCE_LEDGER.md`. Shared files live here: [`AGENT_RULES.md`](AGENT_RULES.md), [`bin/cf_swift.sh`](bin/cf_swift.sh), [`ORCHESTRATOR_KICKOFF.md`](ORCHESTRATOR_KICKOFF.md), [`claude-config/`](claude-config/) (install into the gitignored `.claude/`). diff --git a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings index f5fa282a..90c6f0aa 100644 --- a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings +++ b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings @@ -282,6 +282,74 @@ } } }, + "%@ exact copies go to a separate Duplicate folder." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ identische Kopien kommen in einen separaten Ordner Duplicate." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ exact copies go to a separate Duplicate folder." + } + } + } + }, + "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hier sind %1$@ frei, und dein Ordner enthält etwa %2$@. Möglicherweise passt nicht alles. Wähle ein größeres Laufwerk oder fahre fort: Der Kopiervorgang pausiert sicher, wenn der Speicherplatz ausgeht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out." + } + } + } + }, + "%@ free here." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hier sind %@ frei." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ free here." + } + } + } + }, + "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts)." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hier sind %1$@ frei. Das reicht für etwa %2$@ (Schätzung, wird beim Start des Kopiervorgangs erneut geprüft)." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts)." + } + } + } + }, "%@ 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" : { @@ -564,6 +632,38 @@ } } }, + "%@: %@ photos and videos" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@: %2$@ Fotos und Videos" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: %@ photos and videos" + } + } + } + }, + "%@: 1 photo or video" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: 1 Foto oder Video" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: 1 photo or video" + } + } + } + }, "%@s" : { "comment" : "A label displaying the time window for burst mode. The value is automatically updated to reflect the user's selection.", "isCommentAutoGenerated" : true, @@ -758,6 +858,23 @@ } } }, + "1 exact copy goes to a separate Duplicate folder." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 identische Kopie kommt in einen separaten Ordner Duplicate." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 exact copy goes to a separate Duplicate folder." + } + } + } + }, "1 file changed, so its choice was cleared." : { "extractionState" : "manual", "localizations" : { @@ -1297,6 +1414,23 @@ } } }, + "A sample from this month." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Eine Auswahl aus diesem Monat." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "A sample from this month." + } + } + } + }, "A saved profile holds one folder. Keep this list as it is (Chronoframe remembers it), or remove the extra folders to save a profile." : { "extractionState" : "manual", "localizations" : { @@ -2041,6 +2175,23 @@ } } }, + "An External Drive" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ein externes Laufwerk" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "An External Drive" + } + } + } + }, "An import was interrupted." : { "extractionState" : "manual", "localizations" : { @@ -2300,6 +2451,23 @@ } } }, + "Back" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Zurück" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Back" + } + } + } + }, "Before you start" : { "extractionState" : "manual", "localizations" : { @@ -2520,6 +2688,23 @@ } } }, + "Choose a Folder…" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ordner wählen…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose a Folder…" + } + } + } + }, "Choose Another Month" : { "extractionState" : "manual", "localizations" : { @@ -2657,6 +2842,23 @@ } } }, + "Choose Photos to Copy" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fotos zum Kopieren auswählen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose Photos to Copy" + } + } + } + }, "Choose the folders or the destination again so macOS refreshes access." : { "extractionState" : "manual", "localizations" : { @@ -2841,6 +3043,40 @@ } } }, + "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe erstellt dort eine neue, organisierte Kopie. Deine Originale bleiben genau dort, wo sie sind." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." + } + } + } + }, + "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe kopiert deine Fotos aus Apple Fotos in diesen Ordner. Deine Fotos-Mediathek wird nie verändert." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." + } + } + } + }, "Chronoframe could not finish. Your original files were left untouched." : { "extractionState" : "manual", "localizations" : { @@ -2875,6 +3111,23 @@ } } }, + "Chronoframe could not measure this folder. Space is checked again before copying." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe konnte die Größe dieses Ordners nicht ermitteln. Der Speicherplatz wird vor dem Kopieren erneut geprüft." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe could not measure this folder. Space is checked again before copying." + } + } + } + }, "Chronoframe couldn't save that choice. Your library and the assessment weren't changed. Try again." : { "extractionState" : "manual", "localizations" : { @@ -3001,6 +3254,23 @@ } } }, + "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe liest nur. Es wird noch nichts kopiert, und du kannst deinen Mac weiterverwenden." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." + } + } + } + }, "Chronoframe moved the files in your organized library into the new folder layout." : { "extractionState" : "manual", "localizations" : { @@ -3985,6 +4255,23 @@ } } }, + "Desktop" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Schreibtisch" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Desktop" + } + } + } + }, "Destination Folder" : { "extractionState" : "manual", "localizations" : { @@ -4291,6 +4578,23 @@ } } }, + "Downloads" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Downloads" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Downloads" + } + } + } + }, "Drag folders onto the window or click Add Folders. Chronoframe only reads them — nothing is moved." : { "extractionState" : "manual", "localizations" : { @@ -5063,6 +5367,23 @@ } } }, + "Free space on this drive is unknown." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Der freie Speicherplatz auf diesem Laufwerk ist unbekannt." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Free space on this drive is unknown." + } + } + } + }, "From" : { "extractionState" : "manual", "localizations" : { @@ -5449,6 +5770,23 @@ } } }, + "How your library will be arranged" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "So wird deine Mediathek angeordnet" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "How your library will be arranged" + } + } + } + }, "Identical copies" : { "extractionState" : "manual", "localizations" : { @@ -5764,6 +6102,23 @@ } } }, + "Layout: %@. Change it in Settings." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Struktur: %@. Ändere sie in den Einstellungen." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Layout: %@. Change it in Settings." + } + } + } + }, "Library" : { "extractionState" : "manual", "localizations" : { @@ -5885,6 +6240,23 @@ } } }, + "Look at My Photos" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Meine Fotos ansehen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Look at My Photos" + } + } + } + }, "Look-alikes" : { "extractionState" : "manual", "localizations" : { @@ -5931,6 +6303,23 @@ } } }, + "Measuring your folder…" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Die Größe deines Ordners wird ermittelt…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Measuring your folder…" + } + } + } + }, "More worker threads can improve throughput on faster storage. Parallel copies let several files copy at once and only affect future copies." : { "extractionState" : "manual", "localizations" : { @@ -6093,6 +6482,23 @@ } } }, + "My photos are in the Apple Photos app" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Meine Fotos sind in Apple Fotos" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "My photos are in the Apple Photos app" + } + } + } + }, "Needs attention" : { "extractionState" : "manual", "localizations" : { @@ -6558,6 +6964,23 @@ } } }, + "Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "In diesem Schritt wird nichts kopiert. Das Einlesen einer sehr großen Sammlung kann 5 bis 15 Minuten dauern." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read." + } + } + } + }, "Nothing is removed until you approve it." : { "extractionState" : "manual", "localizations" : { @@ -6741,6 +7164,40 @@ } } }, + "One folder for each day" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ein Ordner für jeden Tag" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "One folder for each day" + } + } + } + }, + "one folder per day" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "ein Ordner pro Tag" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "one folder per day" + } + } + } + }, "One more step" : { "extractionState" : "manual", "localizations" : { @@ -7304,6 +7761,23 @@ } } }, + "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Wähle einen Ort für den Anfang. Weitere kannst du später hinzufügen. Chronoframe liest diesen Ort nur: Nichts darin wird verschoben, umbenannt oder gelöscht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." + } + } + } + }, "Pick up where you left off" : { "extractionState" : "manual", "localizations" : { @@ -7321,6 +7795,23 @@ } } }, + "Pictures Folder" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ordner „Bilder“" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pictures Folder" + } + } + } + }, "Preferences" : { "extractionState" : "manual", "localizations" : { @@ -9282,6 +9773,23 @@ } } }, + "Somewhere Else…" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Woanders…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Somewhere Else…" + } + } + } + }, "Source Folder" : { "extractionState" : "manual", "localizations" : { @@ -10475,6 +10983,23 @@ } } }, + "Use the full setup screen" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vollständige Einrichtung verwenden" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Use the full setup screen" + } + } + } + }, "Verification re-checks each copied file after it is copied. It adds work, but it provides stronger confidence that destination files match the originals." : { "extractionState" : "manual", "localizations" : { @@ -10854,6 +11379,40 @@ } } }, + "Where are most of your photos?" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Wo liegen die meisten deiner Fotos?" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Where are most of your photos?" + } + } + } + }, + "Where should the organized copy go?" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Wohin soll die organisierte Kopie kommen?" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Where should the organized copy go?" + } + } + } + }, "Where the organized copies go." : { "extractionState" : "manual", "localizations" : { @@ -10978,6 +11537,23 @@ } } }, + "You can change this later with Reorganize, which needs the unlock." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Du kannst das später mit „Neu strukturieren“ ändern. Dafür ist die Freischaltung nötig." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "You can change this later with Reorganize, which needs the unlock." + } + } + } + }, "You can copy %1$@ free. This plan has %2$@." : { "extractionState" : "manual", "localizations" : { @@ -11165,6 +11741,40 @@ } } }, + "Your folder holds about %@ in %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dein Ordner enthält etwa %1$@ in %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your folder holds about %@ in %@." + } + } + } + }, + "Your folder holds at least %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dein Ordner enthält mindestens %@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your folder holds at least %@." + } + } + } + }, "Your folders will appear here once you choose them." : { "extractionState" : "manual", "localizations" : { From 5fc08781231f10a5d3cbcbf678f7483f565eddc8 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 20:20:21 -0800 Subject: [PATCH 22/30] FRX G3: final gate Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../plan/first-run-experience/ACCEPTANCE_MATRIX.md | 14 +++++++------- docs/plan/first-run-experience/PROGRESS.md | 13 ++++++++++--- script/swift_meaningful_coverage.sh | 1 + ui/Xcode/UITests/ChronoframeUITests.swift | 10 ++++++++++ 4 files changed, 28 insertions(+), 10 deletions(-) diff --git a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md index 4c949344..663bfa3c 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 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. +Status: every row pass-auto at gate G3 (2026-11-28). Owner rows are not run. 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 | |---|---|---|---|---|---| @@ -12,9 +12,9 @@ Status: M1 rows pass-auto at gate G1 (2026-11-28); M2 rows pass-auto at gate G2 | 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 | -| A-FRX-12 | The ready preview shows photos without a click, the folder picture with real counts, and the technical panels behind Details (rec 6) | histogram tests (2 new); RunTimelinePresentationTests (3 new); LayoutPictureModelTests/*; RunWorkspaceModelTests/testRunningPreviewMessageSaysOnlyReading | H-FRX-6 | todo | todo-owner | -| A-FRX-13 | Every new string ships in German; no baseline key is lost | script/check_german_localization.py at G1, G2, G3 | — | todo | n/a | -| A-FRX-14 | No safety invariant is weakened; source folders and the Photos library stay read-only | script/check_agents_invariants_have_tests.sh; cf_swift.sh guards; tagged tests (INV 1, 6, 8, 14, 15, 17, 29) | — | todo | n/a | +| 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 | pass-auto | 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 | pass-auto | 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 | pass-auto | todo-owner | +| A-FRX-12 | The ready preview shows photos without a click, the folder picture with real counts, and the technical panels behind Details (rec 6) | histogram tests (2 new); RunTimelinePresentationTests (3 new); LayoutPictureModelTests/*; RunWorkspaceModelTests/testRunningPreviewMessageSaysOnlyReading | H-FRX-6 | pass-auto | todo-owner | +| A-FRX-13 | Every new string ships in German; no baseline key is lost | script/check_german_localization.py at G1, G2, G3 | — | pass-auto | n/a | +| A-FRX-14 | No safety invariant is weakened; source folders and the Photos library stay read-only | script/check_agents_invariants_have_tests.sh; cf_swift.sh guards; tagged tests (INV 1, 6, 8, 14, 15, 17, 29) | — | pass-auto | n/a | diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index fd0016ea..c86feba6 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. Gates G1 and G2 passed 2026-11-28; M3 next. One open BLOCKED item (B-1, owner decision, blocks no work package). +Status: built, not merged. Gates G1, G2 and G3 passed 2026-11-28 on three stacked branches. One open BLOCKED item (B-1, owner decision). Owner rows H-FRX-1 to H-FRX-8 are not run. 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). @@ -32,8 +32,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | b2d8704 | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | | WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | f3192d2 | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | | WP-23 | App: photos and folder picture on the preview | done | build exit 0 | LayoutPictureModel 10, RunWorkspaceModel 30, RunTimelinePresentation 12, Accessibility 8, RunOutcomeAccuracy 14 tests exit 0 | changes required (round 1: a layout card on an import preview discarded the import) → approve (round 2) | db99994 | rendered: `m3-preview-photos-layout.png` matches C-25 (sample thumbnail is a placeholder: the fixture path does not exist); D-FRX-115, D-FRX-116, D-FRX-117 | -| WP-24 | Docs and strings, M3 | done | build exit 0 | n/a (strings and docs; checked at G3) | German: changes required → 4 fixes applied; docs: changes required (round 1, 11 items), changes required (round 2, two one-sentence items applied by the orchestrator) | (WP-24 commit) | 36 App keys; `docs/plan/next-half/README.md` row set to "built, not merged"; D-FRX-118 | -| G3 | Final gate | todo | | | n/a | | | +| WP-24 | Docs and strings, M3 | done | build exit 0 | n/a (strings and docs; checked at G3) | German: changes required → 4 fixes applied; docs: changes required (round 1, 11 items), changes required (round 2, two one-sentence items applied by the orchestrator) | 31ecb8e | 36 App keys; `docs/plan/next-half/README.md` row set to "built, not merged"; D-FRX-118 | +| G3 | Final gate | done | build exit 0; xcode exit 0 (twice); build-for-testing exit 0 | suite exit 0 (2699 passed, 0 failed; run twice); coverage exit 0 (96.15%, 96.17%) | n/a | (G3 commit) | guards feature/first-run-duplicates exit 0 and guards origin/main exit 0 (14 of 14 each); invariants exit 0; German check exit 0; 8 renders, 3 new ones checked | ## Existing assertions changed (D-FRX-20) | WP | Test file:line | Old expectation | New expectation | Contract | @@ -46,6 +46,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | 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 | | WP-23 | ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift:209 | running-preview message "You can keep using your Mac. Nothing is being copied." | "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." | C-24, D-FRX-115 | +| G3 | ui/Xcode/UITests/ChronoframeUITests.swift `testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs` (~:939) | asserts `openDestinationButton` exists directly | first expands `runDetailsDisclosure`, then waits for `openDestinationButton` (compiled with build-for-testing, not run) | C-25, D-FRX-23 | | G1 | ui/Xcode/UITests/A11yBaseline.json:48, :50 | "84, FOUND" | "72, FOUND" | C-08, D-FRX-23 | ## Renders checked @@ -54,6 +55,9 @@ 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 | +| G3 | .tmp/frx-evidence/m3-guided-source.png | C-23 | matches: title "Where are most of your photos?", the body, the five place buttons, `My photos are in the Apple Photos app`, `Use the full setup screen`; single column, no illustration | +| G3 | .tmp/frx-evidence/m3-guided-destination.png | C-23 | matches: title "Where should the organized copy go?", folder body, "Your folder holds about 96.4 GB in 18,452 files.", `Choose a Folder…`, "412 GB free here. That is enough for about 96.4 GB (estimate, checked again when the copy starts).", `Look at My Photos`, the line under it, `Back`, `Use the full setup screen` | +| G3 | .tmp/frx-evidence/m3-preview-photos-layout.png (1360×2400) | C-25 | matches: newest month selected on arrival with "October 2026: 2,420 photos and videos" and "A sample from this month." (thumbnail is a placeholder: fixture path does not exist); "How your library will be arranged" with Year / Month, Year / Month / Day (selected) and Year cards, real folder lines and footers, both captions; collapsed `Details` under the tabs | | 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 | @@ -95,3 +99,6 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - For G3 step 4: `testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs` (`ChronoframeUITests.swift:929–942`) asserts `openDestinationButton` and "Reports and Logs", which now sit behind the collapsed `runDetailsDisclosure` on a ready preview; the test must expand it first. `testTimelineSelectionUpdatesPreview` (~:1013–1040) still passes but its "clear button appears after selecting" step is now vacuous because a month is selected on arrival. - Noticed, not fixed (M3): `TimelinePlurals.filesToCopy` is now unused in production (its test and catalog key remain); the timeline's existing caption "Every bar is a month of planned transfers waiting to land." is jargon; in the over-allowance fixture the selected month reads 2,420 while the card reads 212 (fixture histogram does not match its `newFilesByMonth`). - 2026-11-28 WP-24: `add_translated_keys.py … Localizable.xcstrings … M3-app.json` exit 0 (added 36, kept 3); `… LocalizableCore.xcstrings … M3-core.json` exit 0 (added 0); `cf_swift.sh build` exit 0 after the symbol-collision fix; early German check exit 0 (app 1829, core 330; zero missing keys of 927 app / 287 core). German review: four corrections applied ("Apple Fotos", "ermittelt" twice, a verb in one heading). Docs: QUICK_START, FAQ, README, SAFETY_AND_RECOVERY; `git diff --check` exit 0. +- 2026-11-28 G3 commands (orchestrator), on `feature/first-run-guided`: `cf_swift.sh build` exit 0; `cf_swift.sh suite` exit 0 (2699 passed, 0 failed); `cf_swift.sh coverage` exit 0 (96.15%; FolderSizeEstimator 90.6%, the aggregate gate passes); `cf_swift.sh guards feature/first-run-duplicates` exit 0 (14 guards); `cf_swift.sh xcode` exit 0; `git diff --check` exit 0; `xcodebuild … SWIFT_EMIT_LOC_STRINGS=YES build` exit 0; `check_german_localization.py --baseline-ref origin/main …` exit 0 (app 1829, core 330; zero missing keys of 927 app / 287 core); `xcodebuild … build-for-testing` exit 0; `cf_swift.sh test ScreenRenderEvidenceTests` with the marker exit 0 (8 PNGs). Then the stack as one change against `origin/main`: `cf_swift.sh suite` exit 0 (2699 passed, 0 failed); `cf_swift.sh coverage` exit 0 (96.17%); `cf_swift.sh guards origin/main` exit 0 (14 guards); `cf_swift.sh xcode` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0 (30 invariants); the German check above already uses the `origin/main` baseline. +- G3 step 4: one UI test edited (table above) so it opens the Details disclosure before looking for the report panel; compiled, not run. `testTimelineSelectionUpdatesPreview` left as is (still passes by reading; its "clear button appears after selecting" step is now vacuous). The accessibility baselines for `runPreviewReview`, `runCopyComplete` and the dedupe scenarios were not regenerated (owner row H-FRX-8 runs the UI suite). +- G3 PNGs sent to the owner. Rendered, not verified in the running app. diff --git a/script/swift_meaningful_coverage.sh b/script/swift_meaningful_coverage.sh index dd140822..f6d89a6f 100755 --- a/script/swift_meaningful_coverage.sh +++ b/script/swift_meaningful_coverage.sh @@ -77,6 +77,7 @@ MEANINGFUL_BASENAMES=( FreeMonthBatchPlanner DeduplicateReviewLane FreeDedupeBatchPlanner + FolderSizeEstimator CopyPlanBuilder DryRunPlanner EditedVariantDestinations diff --git a/ui/Xcode/UITests/ChronoframeUITests.swift b/ui/Xcode/UITests/ChronoframeUITests.swift index 2015962f..394a7024 100644 --- a/ui/Xcode/UITests/ChronoframeUITests.swift +++ b/ui/Xcode/UITests/ChronoframeUITests.swift @@ -936,6 +936,16 @@ final class ChronoframeUITests: XCTestCase { XCTAssertFalse(app.buttons["transferButton"].exists) XCTAssertFalse(app.toolbars.buttons["Transfer"].exists) XCTAssertFalse(app.toolbars.buttons["Preview"].exists) + // FRX C-25: on a ready preview the report and log panels sit behind a collapsed Details disclosure. + let details = Self.element(identifier: "runDetailsDisclosure", in: app) + XCTAssertTrue(details.waitForExistence(timeout: 5)) + let detailsTriangle = app.disclosureTriangles["runDetailsDisclosure"] + if detailsTriangle.exists { + detailsTriangle.click() + } else { + details.click() + } + XCTAssertTrue(Self.button(identifier: "openDestinationButton", in: app).waitForExistence(timeout: 5)) XCTAssertTrue(app.buttons["openDestinationButton"].exists) XCTAssertTrue(app.descendants(matching: .any)["runWorkspaceTabs"].exists) XCTAssertTrue(app.staticTexts["Reports and Logs"].exists) From d2f53812f845baf6ef8fb146e0cfa0a0a0ae2f08 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sat, 28 Nov 2026 20:20:24 -0800 Subject: [PATCH 23/30] FRX G3: record the gate commit Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/PROGRESS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index c86feba6..b00bb13e 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -33,7 +33,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | f3192d2 | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | | WP-23 | App: photos and folder picture on the preview | done | build exit 0 | LayoutPictureModel 10, RunWorkspaceModel 30, RunTimelinePresentation 12, Accessibility 8, RunOutcomeAccuracy 14 tests exit 0 | changes required (round 1: a layout card on an import preview discarded the import) → approve (round 2) | db99994 | rendered: `m3-preview-photos-layout.png` matches C-25 (sample thumbnail is a placeholder: the fixture path does not exist); D-FRX-115, D-FRX-116, D-FRX-117 | | WP-24 | Docs and strings, M3 | done | build exit 0 | n/a (strings and docs; checked at G3) | German: changes required → 4 fixes applied; docs: changes required (round 1, 11 items), changes required (round 2, two one-sentence items applied by the orchestrator) | 31ecb8e | 36 App keys; `docs/plan/next-half/README.md` row set to "built, not merged"; D-FRX-118 | -| G3 | Final gate | done | build exit 0; xcode exit 0 (twice); build-for-testing exit 0 | suite exit 0 (2699 passed, 0 failed; run twice); coverage exit 0 (96.15%, 96.17%) | n/a | (G3 commit) | guards feature/first-run-duplicates exit 0 and guards origin/main exit 0 (14 of 14 each); invariants exit 0; German check exit 0; 8 renders, 3 new ones checked | +| G3 | Final gate | done | build exit 0; xcode exit 0 (twice); build-for-testing exit 0 | suite exit 0 (2699 passed, 0 failed; run twice); coverage exit 0 (96.15%, 96.17%) | n/a | 5fc0878 | guards feature/first-run-duplicates exit 0 and guards origin/main exit 0 (14 of 14 each); invariants exit 0; German check exit 0; 8 renders, 3 new ones checked | ## Existing assertions changed (D-FRX-20) | WP | Test file:line | Old expectation | New expectation | Contract | From 2f8954f3ef964bab0280c9e378d7b1e03a165977 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 00:24:13 -0800 Subject: [PATCH 24/30] Dedupe planner: a skipped group's members stay (INV-32) The per-group rail skips a group whose members are all marked Delete, but its members could still be removed by pair fan-out from another group or by a second group that lists the same files. Members of a skipped group are now protected from direct deletes and from fan-out. Adds INV-32, fixed regressions for both routes, and a property test whose generator builds cross-group pairs and overlapping groups. Fixes #300 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- AGENTS.md | 1 + .../DeduplicationPlanner.swift | 13 +- .../DeduplicationPlannerGroupRailTests.swift | 138 ++++++++++++++++++ .../DeduplicationPlannerPropertyTests.swift | 76 +++++++++- 4 files changed, 225 insertions(+), 3 deletions(-) create mode 100644 ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift diff --git a/AGENTS.md b/AGENTS.md index a2570b05..f6795489 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -76,6 +76,7 @@ Do not weaken these unless the user explicitly asks for a product change. - **INV-28:** Network or unclassifiable destinations use the remote copy policy. Copy verification can't be turned off; flushing uses `F_FULLFSYNC` and falls back only to `fsync`, whose failure fails the copy; installation needs native `renamex_np`/`RENAME_EXCL`, an ENOTSUP aborts the run, and the placeholder check-then-rename fallback is never used; a destination volume change aborts before the next copy; `.organize_cache.db` opens with rollback `journal_mode=DELETE` verified by readback; app mutations hold the per-share Application Support lease (a network destination with no lease directory configured is refused, never run without it); Organize preview/transfer and Reorganize/Undo Reorganize prove atomic no-replace before planning or moving; an Organize transfer with verification off is refused in `prepare` before anything is written; and the CLI refuses these destinations before writing anything. - **INV-29:** Saved Deduplicate review state (`Application Support/Chronoframe/dedupe_reviews/*.json`) is review state only. On restore, a saved Keep/Delete choice applies to a path only when the current scan identity equals the saved identity, and a saved group approval applies only when the group's member identities are unchanged; everything else is dropped and reported. Restoring never builds a plan, never pre-approves a commit, and never bypasses the reviewed-plan confirmation. - **INV-31:** An edited variant exported from Apple Photos (`<stem>-edited.<ext>` beside `<stem>.<ext>` in one folder, matched case-insensitively) is never Trashed unless the user explicitly marks that file Delete. It is never selected by a cluster's automatic suggestion, never added by pair, sidecar or fanout rules, and is never a deletion consequence of its original being Deleted. Deleting the original leaves the variant in place. +- **INV-32:** A Deduplicate plan never empties a group. A group whose members are all marked Delete is skipped, and its members then stay whichever route would remove them: neither pair fan-out from another group nor a second group that lists the same files adds them to the plan. Invariant IDs are permanent: do not renumber or reuse them. Add new invariants with a new unused ID; `// AGENTS-INVARIANT: N` test tags refer to that explicit ID, not list position. diff --git a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift index f5074f9a..49aa62ed 100644 --- a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift +++ b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift @@ -14,7 +14,8 @@ import Foundation /// where an explicit Keep on one half got silently overridden by a /// Delete on the other half. /// 3. Per-cluster safety rail: skip any cluster whose effective decisions -/// are all Delete after step 2 (never empty a cluster). +/// are all Delete after step 2 (never empty a cluster). Its members are +/// then protected from steps 4 and 5 as well (INV-32). /// 4. Emit Items for direct cluster-member Deletes, with cluster ownership. /// 5. Pair expansion for partners outside any cluster (Live Photo MOV /// halves, mainly). Each toggle is honored independently — disabling @@ -112,12 +113,21 @@ public enum DeduplicationPlanner { } if allDelete { skipped.insert(cluster.id) } } + // INV-32: the members of a skipped cluster stay, whichever route + // would remove them. Without this a cluster the rail skipped could + // still be emptied by pair fanout from another cluster (step 5) or + // by an overlapping cluster that lists the same files (step 4). + var railProtectedPaths: Set<String> = [] + for cluster in clusters where skipped.contains(cluster.id) { + railProtectedPaths.formUnion(cluster.members.map(\.path)) + } // 4. Direct deletes (cluster members marked Delete). var planItems: [String: DeduplicationPlan.Item] = [:] for cluster in clusters where !skipped.contains(cluster.id) { for member in cluster.members { guard effective[member.path]?.decision == .delete else { continue } + if railProtectedPaths.contains(member.path) { continue } guard let expectedIdentity = snapshot.identitiesByPath[member.path] else { continue } @@ -150,6 +160,7 @@ public enum DeduplicationPlanner { if effective[partner]?.decision == .keep { continue } + if railProtectedPaths.contains(partner) { continue } // INV-31: pair fanout never adds an edited variant. A partner // outside every cluster carries no scanner flag, so the file // name convention is the fail-closed fallback. diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift new file mode 100644 index 00000000..59dfdafc --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift @@ -0,0 +1,138 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +/// Fixed regressions for the per-group safety rail: a group whose members +/// are all marked Delete is skipped, and nothing else in the plan may then +/// remove its members by another route. +final class DeduplicationPlannerGroupRailTests: XCTestCase { + // AGENTS-INVARIANT: 32 + func testPairFanoutNeverEmptiesAGroupTheRailSkipped() { + // The same RAW+JPEG folder imported twice, plus a third JPEG copy. + let rawA = candidate("/lib/A/1.CR2", isRaw: true, pairedPath: "/lib/A/1.JPG") + let rawB = candidate("/lib/B/1.CR2", isRaw: true, pairedPath: "/lib/B/1.JPG") + let jpegA = candidate("/lib/A/1.JPG", pairedPath: "/lib/A/1.CR2") + let jpegB = candidate("/lib/B/1.JPG", pairedPath: "/lib/B/1.CR2") + let jpegC = candidate("/lib/C/1.JPG") + let raws = cluster([rawA, rawB]) + let jpegs = cluster([jpegC, jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [ + rawA.path: .delete, rawB.path: .delete, + jpegA.path: .delete, jpegB.path: .delete, + jpegC.path: .keep, + ]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [raws, jpegs], + configuration: configuration(), + snapshot: testScanSnapshot(for: [raws, jpegs]) + ) + + let planned = Set(plan.items.map(\.path)) + XCTAssertEqual(planned, [jpegA.path, jpegB.path]) + XCTAssertFalse(planned.contains(rawA.path), "the skipped group must stay whole") + XCTAssertFalse(planned.contains(rawB.path), "the skipped group must stay whole") + } + + // AGENTS-INVARIANT: 32 + func testPairFanoutNeverEmptiesASkippedGroupWhateverTheGroupOrder() { + let rawA = candidate("/lib/A/1.CR2", isRaw: true, pairedPath: "/lib/A/1.JPG") + let rawB = candidate("/lib/B/1.CR2", isRaw: true, pairedPath: "/lib/B/1.JPG") + let jpegA = candidate("/lib/A/1.JPG", pairedPath: "/lib/A/1.CR2") + let jpegB = candidate("/lib/B/1.JPG", pairedPath: "/lib/B/1.CR2") + let jpegC = candidate("/lib/C/1.JPG") + let raws = cluster([rawA, rawB]) + let jpegs = cluster([jpegC, jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [ + rawA.path: .delete, rawB.path: .delete, + jpegA.path: .delete, jpegB.path: .delete, + jpegC.path: .keep, + ]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [jpegs, raws], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, raws]) + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [jpegA.path, jpegB.path]) + } + + // AGENTS-INVARIANT: 32 + func testOverlappingGroupNeverEmptiesAGroupTheRailSkipped() { + // Two identical copies form an exact group; the same two plus a + // look-alike form a second group. Deleting both copies would empty + // the exact group, so the rail skips it and the copies stay. + let copyA = candidate("/lib/A/1.jpg") + let copyB = candidate("/lib/B/1.jpg") + let lookAlike = candidate("/lib/A/1b.jpg") + let exact = cluster([copyA, copyB], kind: .exactDuplicate) + let near = cluster([lookAlike, copyA, copyB], kind: .nearDuplicate) + let decisions = DedupeDecisions(byPath: [ + copyA.path: .delete, copyB.path: .delete, lookAlike.path: .keep, + ]) + + for clusters in [[exact, near], [near, exact]] { + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: clusters, + configuration: configuration(), + snapshot: testScanSnapshot(for: clusters) + ) + XCTAssertEqual(plan.items.map(\.path), [], "both copies must survive") + } + } + + func testAGroupWithAKeptMemberStillFansOutToItsPairPartner() { + // The rail change must not stop ordinary pair fan-out. + let rawA = candidate("/lib/A/1.CR2", isRaw: true, pairedPath: "/lib/A/1.JPG") + let rawB = candidate("/lib/B/1.CR2", isRaw: true, pairedPath: "/lib/B/1.JPG") + let jpegA = candidate("/lib/A/1.JPG", pairedPath: "/lib/A/1.CR2") + let jpegB = candidate("/lib/B/1.JPG", pairedPath: "/lib/B/1.CR2") + let raws = cluster([rawA, rawB]) + let jpegs = cluster([jpegA, jpegB]) + let decisions = DedupeDecisions(byPath: [ + rawA.path: .keep, rawB.path: .delete, + jpegA.path: .keep, jpegB.path: .delete, + ]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [raws, jpegs], + configuration: configuration(), + snapshot: testScanSnapshot(for: [raws, jpegs]) + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [rawB.path, jpegB.path]) + } + + // MARK: Helpers + + private func candidate(_ path: String, isRaw: Bool = false, pairedPath: String? = nil) -> PhotoCandidate { + PhotoCandidate(path: path, size: 1_000, modificationTime: 0, isRaw: isRaw, pairedPath: pairedPath) + } + + private func cluster(_ members: [PhotoCandidate], kind: ClusterKind = .exactDuplicate) -> DuplicateCluster { + DuplicateCluster( + id: UUID(), + kind: kind, + members: members, + suggestedKeeperIDs: [members[0].id], + bytesIfPruned: 0, + annotation: ClusterAnnotation(confidence: .high, matchReason: MatchReason(kind: kind), warnings: []) + ) + } + + private func configuration() -> DeduplicateConfiguration { + DeduplicateConfiguration( + destinationPath: "/tmp/destination", + timeWindowSeconds: 30, + similarityThreshold: 0.9, + dhashHammingThreshold: 5, + treatRawJpegPairsAsUnit: true, + treatLivePhotoPairsAsUnit: true + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift index cb94869f..9833fc22 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPropertyTests.swift @@ -115,6 +115,33 @@ final class DeduplicationPlannerPropertyTests: XCTestCase { } } + /// The same property when pairs cross clusters (the RAW halves in one + /// cluster, the JPEG halves in another) and when a cluster lists files + /// another cluster also lists. + // AGENTS-INVARIANT: 32 + func testPropertyNoClusterIsEmptiedWithCrossClusterPairsAndOverlap() { + var prng = SeededPRNG(seed: 0x0C12_055C_1A57_E125) + for iteration in 0..<(Self.iterations * 4) { + let scenario = randomScenario(prng: &prng, crossClusterStructure: true) + let plan = DeduplicationPlanner.plan( + decisions: scenario.decisions, + clusters: scenario.clusters, + configuration: scenario.configuration, + snapshot: testScanSnapshot(for: scenario.clusters) + ) + let deletedPaths = Set(plan.items.map(\.path)) + for cluster in scenario.clusters { + let memberPaths = Set(cluster.members.map(\.path)) + let survivors = memberPaths.subtracting(deletedPaths) + XCTAssertFalse( + survivors.isEmpty, + "iteration \(iteration): cluster \(cluster.id) was completely emptied. " + + "members=\(memberPaths) deleted=\(deletedPaths)" + ) + } + } + } + /// Per-pair-kind toggles are independent. /// AGENTS.md: "disabling RAW pairing must not affect Live Photo /// behaviour and vice versa." @@ -255,7 +282,8 @@ private func scenarioPairKind( private func randomScenario( prng: inout SeededPRNG, - forbidExplicitDecisions: Bool = false + forbidExplicitDecisions: Bool = false, + crossClusterStructure: Bool = false ) -> GeneratedScenario { let clusterCount = prng.intInRange(1...4) var clusters: [DuplicateCluster] = [] @@ -265,6 +293,9 @@ private func randomScenario( var autoSuggestedKeepers: [UUID: Set<String>] = [:] var counter = 0 + var memberLists: [[PhotoCandidate]] = [] + var confidences: [ConfidenceLevel] = [] + var kinds: [ClusterKind] = [] for _ in 0..<clusterCount { let memberCount = prng.intInRange(2...4) let conf: ConfidenceLevel = [.high, .medium, .low][prng.intInRange(0...2)] @@ -273,7 +304,7 @@ private func randomScenario( for _ in 0..<memberCount { let pathIndex = counter counter += 1 - let path = "/test/c\(clusters.count)/m\(pathIndex).jpg" + let path = "/test/c\(memberLists.count)/m\(pathIndex).jpg" let isRaw = prng.bool() members.append( PhotoCandidate( @@ -298,7 +329,48 @@ private func randomScenario( pairKinds[a] = kind pairKinds[b] = kind } + memberLists.append(members) + confidences.append(conf) + kinds.append(kind) + } + + if crossClusterStructure { + // Pair still-unpaired members of neighbouring clusters, index by index. + for index in 0..<(memberLists.count - 1) { + for position in 0..<min(memberLists[index].count, memberLists[index + 1].count) where prng.bool() { + let a = memberLists[index][position] + let b = memberLists[index + 1][position] + guard a.pairedPath == nil, b.pairedPath == nil else { continue } + let kind: DeduplicatePairDetector.Pair.Kind = prng.bool() ? .rawJpeg : .livePhoto + memberLists[index][position] = withPairedPath(a, partner: b.path, isLivePhoto: kind == .livePhoto) + memberLists[index + 1][position] = withPairedPath(b, partner: a.path, isLivePhoto: kind == .livePhoto) + pairPartners[a.path] = b.path + pairPartners[b.path] = a.path + pairKinds[a.path] = kind + pairKinds[b.path] = kind + } + } + // Sometimes add a cluster that lists another cluster's members + // again, plus one file of its own. + if prng.bool() { + let source = prng.intInRange(0...(memberLists.count - 1)) + let extra = PhotoCandidate( + path: "/test/overlap/m\(counter).jpg", + size: 1_000, + modificationTime: 0, + isRaw: false + ) + let conf: ConfidenceLevel = [.high, .medium, .low][prng.intInRange(0...2)] + clusterConfidence[extra.path] = conf + memberLists.append([extra] + memberLists[source]) + confidences.append(conf) + kinds.append(.nearDuplicate) + } + } + for (index, members) in memberLists.enumerated() { + let conf = confidences[index] + let kind = kinds[index] let id = UUID() let suggestedKeeperID = members.first?.id ?? "" let clusterMembers = members From e08f408736330729ad927403e9ef57e24a7428cd Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 00:24:40 -0800 Subject: [PATCH 25/30] FRX: record owner confirmations and the B-1 fix; docs state the skip as a fact Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- README.md | 2 +- docs/FAQ.md | 2 +- docs/QUICK_START.md | 2 +- docs/SAFETY_AND_RECOVERY.md | 9 ++++----- docs/plan/first-run-experience/BLOCKED.md | 4 ++-- docs/plan/first-run-experience/DECISIONS.md | 5 +++-- docs/plan/first-run-experience/PROGRESS.md | 1 + 7 files changed, 13 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index 8a6237d9..0c9e5d6e 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ The **History** tab keeps every run's reports and receipts. Reuse a past source, 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 normally skips that group until you mark one Keep. This is not a guarantee: a group whose RAW+JPEG or Live Photo partners are being removed along with another group can still lose every photo. Check pairs before you confirm. 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. +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 e8a98cc1..970ef7b4 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -116,7 +116,7 @@ The lanes bar at the top of review starts with identical copies. **Accept Identi **Q: Does Deduplicate guarantee that a photo is kept from every group?** -A: No. 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 normally skips that group until you mark one Keep. That is not a guarantee. RAW+JPEG and Live Photo partners are removed together, so a group whose files are paired with files you are removing from another group can still lose every photo. Check paired files and the file count in the confirmation before you move anything to the Trash. +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?** diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md index 7f3ba002..44c80b7c 100644 --- a/docs/QUICK_START.md +++ b/docs/QUICK_START.md @@ -111,7 +111,7 @@ Review sorts the groups into three lanes: 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 normally skips that group until you mark one photo Keep. This is not a guarantee: a group whose RAW+JPEG or Live Photo partners are being removed along with another group can still lose every photo. Check pairs before you 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. diff --git a/docs/SAFETY_AND_RECOVERY.md b/docs/SAFETY_AND_RECOVERY.md index 11231fae..28093387 100644 --- a/docs/SAFETY_AND_RECOVERY.md +++ b/docs/SAFETY_AND_RECOVERY.md @@ -270,11 +270,10 @@ 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 -normally skips that group until one is marked Keep. This is not a guarantee. -Pair expansion runs after that check, so a group whose files are paired with -files being removed from another group can still end up with nothing kept. -Check RAW+JPEG and Live Photo pairs, and the file count in the confirmation, -before you confirm. +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 diff --git a/docs/plan/first-run-experience/BLOCKED.md b/docs/plan/first-run-experience/BLOCKED.md index a8132f12..960c22c9 100644 --- a/docs/plan/first-run-experience/BLOCKED.md +++ b/docs/plan/first-run-experience/BLOCKED.md @@ -1,6 +1,6 @@ # First-run experience — blocked items -Status: one open item (B-1). It does not block any work package; it needs an owner decision before M2 is merged. +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. @@ -13,4 +13,4 @@ Entry format: see "Blocked items" in `docs/plan/next-half/AGENT_RULES.md`. Only - **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:** open +- **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 eac0eb6b..355a2035 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,7 +35,7 @@ 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. **Update 2026-11-28 (WP-11): confirmed and reproduced with the unmodified planner; see BLOCKED.md B-1. Still not touched by this plan.** @@ -58,3 +58,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index f235157f..0d962625 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -85,3 +85,4 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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. From 3ca0e256e342ac5a69752745fd8c0fb61250c71e Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 00:27:50 -0800 Subject: [PATCH 26/30] FRX: free-batch test premises follow INV-32 Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/PROGRESS.md | 1 + .../ChronoframeCoreFreeDedupeBatchPlannerTests.swift | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 0d962625..0debd2cc 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -86,3 +86,4 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 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/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift index 56356134..2aafe4e7 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift @@ -263,8 +263,8 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { // Y's members: members[0] and [1] are y1 and y2, both Delete. let full = fixture.fullPlan() - XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/z/z1.jpg", "/fx/y/y1.jpg", "/fx/w/d1.jpg"], - "premise: Y is skipped, z1 is deleted and fans out to y1") + XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/z/z1.jpg", "/fx/w/d1.jpg"], + "premise: Y is skipped and stays whole (INV-32); z1 is deleted without fanning out to y1") // The candidate the walk builds first: Y selected, Z and W forced Keep. var yOnly = fixture.decisions @@ -282,7 +282,7 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { XCTAssertFalse(full.items.contains { $0.path == "/fx/y/y2.jpg" }) // Limit 2: the Y-only candidate fits the limit but is not in the full plan, so - // the walk stops. It must not skip ahead to Y+Z = {z1, y1}, which would fit. + // the walk stops. It must not skip ahead to Y+Z = {z1}, which would fit. XCTAssertNil(fixture.batch(limit: 2)) // Sanity: the walk without that trap would have been able to take Y+Z. @@ -294,7 +294,7 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { configuration: fixture.configuration, snapshot: fixture.snapshot ) - XCTAssertEqual(Set(skipped.items.map(\.path)), ["/fx/z/z1.jpg", "/fx/y/y1.jpg"]) + XCTAssertEqual(Set(skipped.items.map(\.path)), ["/fx/z/z1.jpg"]) } // MARK: Property From ae98f045e7c737998a63f7c3a2d78092bbcdb5fa Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 06:28:55 -0800 Subject: [PATCH 27/30] First run: unconfirmed purchases get no spent-trial UI; a requested month may be the whole plan TrialRemaining returns nil for verificationUnavailable and unverified, so the preview never describes a spent trial or offers a purchase to someone who may already have paid. The unlock sheet offers a requested month even when the plan has shrunk to exactly that month. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../Services/TrialRemaining.swift | 9 ++++++-- .../Services/UnlockPresentation.swift | 9 +++++--- .../TrialRemainingTests.swift | 18 ++++++++++++++++ .../UnlockPresentationTests.swift | 21 +++++++++++++++++++ 4 files changed, 52 insertions(+), 5 deletions(-) diff --git a/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift b/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift index 82411908..a6f3118c 100644 --- a/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift +++ b/ui/Sources/ChronoframeAppCore/Services/TrialRemaining.swift @@ -9,12 +9,16 @@ import Foundation /// One definition, shared with the indicator's rules: a number is only returned /// when it is a real, readable balance for someone the allowance applies to. public enum TrialRemaining { - /// Nil when not the App Store channel, unlocked, loading, unknown or - /// unavailable. + /// Nil when not the App Store channel, unlocked, loading, unconfirmed, + /// unknown or unavailable. /// /// - Not the App Store channel: that build is unrestricted and meters /// nothing, so a count would describe a limit that does not exist. /// - Unlocked: there is no limit. + /// - Unconfirmed (`verificationUnavailable`, `unverified`): this customer + /// may already have paid. The screens that quote this number describe a + /// spent trial and offer a purchase, which the gate deliberately does not + /// do for them (`purchaseUnconfirmed`). /// - Loading, unknown or unavailable: nothing is known. An unreadable /// ledger reports zero to the gate so it fails closed, and that zero must /// never be quoted as the customer's own balance. @@ -25,6 +29,7 @@ public enum TrialRemaining { ) -> Int? { guard isAppStoreChannel else { return nil } guard !status.isUnlocked, !status.entitlement.isResolving else { return nil } + guard !status.entitlement.isUnconfirmed else { return nil } return status.remaining(for: meter) } } diff --git a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift index 216e6421..6cddc18f 100644 --- a/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift +++ b/ui/Sources/ChronoframeAppCore/Services/UnlockPresentation.swift @@ -112,7 +112,7 @@ public struct UnlockSheetModel: Equatable, Sendable { } ?? [] let leadingBatchAction = requestedMonth == nil ? [] : batchAction let trailingBatchAction = requestedMonth == nil ? batchAction : [] - let batchDetail = batch.flatMap(Self.batchDetail) + let batchDetail = batch.flatMap { $0.coversWholePlan ? nil : Self.batchDetail($0) } let purchaseTermsLine = Self.purchaseTermsLine(for: refusal) // Never offer a purchase this customer may not need. `purchaseUnconfirmed` @@ -189,8 +189,11 @@ public struct UnlockSheetModel: Equatable, Sendable { ) -> FreeTestBatch? { guard case .allowanceSpent = refusal, let batch, - !batch.included.isEmpty, - !batch.coversWholePlan else { return nil } + !batch.included.isEmpty else { return nil } + // A batch nobody asked for that covers the whole plan is not a + // smaller run. A month the person asked for is theirs to confirm + // even when the plan has shrunk to exactly that month. + guard batch.wasRequested || !batch.coversWholePlan else { return nil } return batch } diff --git a/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift b/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift index 6f93c390..6af736c5 100644 --- a/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/TrialRemainingTests.swift @@ -69,6 +69,24 @@ final class TrialRemainingTests: XCTestCase { ) } + /// A purchase that could not be confirmed is metered like the trial, but + /// its balance is never quoted: the screens that read this value offer a + /// purchase, and this customer may already have paid. + func testNilWhenThePurchaseCouldNotBeConfirmed() { + for entitlement in [EntitlementState.verificationUnavailable, .unverified] { + for used in [0, 120, 500] { + XCTAssertNil( + TrialRemaining.value( + status: status(entitlement, organizeUsed: used), + meter: .organize, + isAppStoreChannel: true + ), + "\(entitlement), \(used) used" + ) + } + } + } + func testRemainingForEachMeter() { let locked = status(.locked, organizeUsed: 120, dedupeUsed: 4) diff --git a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift index 87269d3c..aaef3270 100644 --- a/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/UnlockPresentationTests.swift @@ -279,6 +279,27 @@ final class UnlockPresentationTests: XCTestCase { XCTAssertTrue(one.message.contains("1 new photo or video"), one.message) } + /// The plan can shrink between the preview and the request, so the month + /// the person asked for may be the whole plan. That is still their free + /// copy to confirm; only an offer nobody asked for is withheld. + func testRequestedMonthThatCoversTheWholePlanIsStillOffered() { + let wholePlan = requestedMonthBatch(included: 3, deferred: 0) + let requested = requestedModel(product: product, batch: wholePlan) + + XCTAssertEqual(requested.title, "Copy October 2026 free") + XCTAssertEqual(requested.actions.first, .runFreeTestBatch(fileCount: 3, deferredCount: 0)) + XCTAssertNil(requested.batchDetail, "nothing is left for later, so the detail line has nothing to say") + + let notRequested = requestedModel( + product: product, + batch: FreeTestBatch(included: wholePlan.included, deferredCount: 0, monthKey: "2026-10") + ) + XCTAssertFalse(notRequested.actions.contains { action in + if case .runFreeTestBatch = action { return true } + return false + }) + } + func testRequestedMonthPutsFreeCopyFirst() { let requested = requestedModel(product: product) XCTAssertEqual( From 21603468a8e091c0a0e5a02b8a72100bc9c6a77f Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 06:30:44 -0800 Subject: [PATCH 28/30] First run: free removal resumes a paused review; menu Quick Review reaches both lanes Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- docs/plan/first-run-experience/DECISIONS.md | 1 + ui/Sources/ChronoframeApp/App/AppState.swift | 3 ++ .../Deduplicate/DeduplicateReviewLanes.swift | 8 ++++++ .../Views/Deduplicate/DeduplicateView.swift | 4 ++- .../ChronoframeAppTests/AppStateTests.swift | 28 +++++++++++++++++++ .../DeduplicateReviewViewsTests.swift | 8 ++++++ 6 files changed, 51 insertions(+), 1 deletion(-) diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index 355a2035..c98fdc8d 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -59,3 +59,4 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **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/ui/Sources/ChronoframeApp/App/AppState.swift b/ui/Sources/ChronoframeApp/App/AppState.swift index 70211b1b..89964fac 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -576,6 +576,9 @@ final class AppState: ObservableObject { 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 } diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift index 46caca6d..01d5b3b6 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateReviewLanes.swift @@ -324,6 +324,14 @@ enum DeduplicateFooterCopy { 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) { diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift index 7725737a..0cf9b86d 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/DeduplicateView.swift @@ -788,7 +788,9 @@ struct DeduplicateView: View { Divider() Button("Quick Review") { - openQuickReview(.lookAtEach) + openQuickReview(DeduplicateFooterCopy.menuQuickReviewLane( + nearlyIdenticalGroups: sessionStore.laneSummaries[.nearlyIdentical]?.groups ?? 0 + )) } .accessibilityIdentifier(AccessibilityIdentifiers.dedupeRapidTriageButton) diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index b74bcd06..8079f421 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -1381,6 +1381,34 @@ final class AppStateTests: XCTestCase { 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() diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift index 3f87e98c..2ed92ac8 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift @@ -441,4 +441,12 @@ final class DeduplicateReviewViewsTests: XCTestCase { 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) + } } From bb92f3aae972a3d438e73b825c2a0b3d369b0595 Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 06:31:30 -0800 Subject: [PATCH 29/30] First run: Details disclosure keeps its children's identifiers The identifier sat on a bare container, so it replaced the identifiers of the panels inside it and the UI test could not find openDestinationButton after expanding. The UI test now clicks the triangle inside the group. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- .../ChronoframeApp/Views/Run/RunSectionViews.swift | 3 +++ ui/Xcode/UITests/ChronoframeUITests.swift | 9 +++------ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index d2f8bc0b..d83d6800 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -506,6 +506,9 @@ struct RunWorkspaceShell: View { overviewPanels .padding(.top, DesignTokens.Spacing.sm) } + // `.contain` first: an identifier on a bare container + // replaces the identifiers of everything inside it. + .accessibilityElement(children: .contain) .accessibilityIdentifier(AccessibilityIdentifiers.runDetailsDisclosure) } else { overviewPanels diff --git a/ui/Xcode/UITests/ChronoframeUITests.swift b/ui/Xcode/UITests/ChronoframeUITests.swift index 394a7024..8c5fc139 100644 --- a/ui/Xcode/UITests/ChronoframeUITests.swift +++ b/ui/Xcode/UITests/ChronoframeUITests.swift @@ -939,12 +939,9 @@ final class ChronoframeUITests: XCTestCase { // FRX C-25: on a ready preview the report and log panels sit behind a collapsed Details disclosure. let details = Self.element(identifier: "runDetailsDisclosure", in: app) XCTAssertTrue(details.waitForExistence(timeout: 5)) - let detailsTriangle = app.disclosureTriangles["runDetailsDisclosure"] - if detailsTriangle.exists { - detailsTriangle.click() - } else { - details.click() - } + let detailsTriangle = details.disclosureTriangles.firstMatch + XCTAssertTrue(detailsTriangle.waitForExistence(timeout: 5)) + detailsTriangle.click() XCTAssertTrue(Self.button(identifier: "openDestinationButton", in: app).waitForExistence(timeout: 5)) XCTAssertTrue(app.buttons["openDestinationButton"].exists) XCTAssertTrue(app.descendants(matching: .any)["runWorkspaceTabs"].exists) From e8870aa4dedeca3c052638463f0c44dc2c320bbf Mon Sep 17 00:00:00 2001 From: Nishith Nand <nishith.nand@gmail.com> Date: Sun, 29 Nov 2026 07:17:10 -0800 Subject: [PATCH 30/30] First run: the whole Details row opens the disclosure The UI test clicks the centre of the disclosure element, which is the label, and only the triangle toggled it. [skip-app-test-check] covered by the existing UI test testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> --- ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index d83d6800..98503f5b 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -502,9 +502,15 @@ struct RunWorkspaceShell: View { if model.context.status == .dryRunFinished { // A ready preview leads with the photos and the folder // picture; the technical panels stay one click away. - DisclosureGroup("Details", isExpanded: $showsOverviewDetails) { + DisclosureGroup(isExpanded: $showsOverviewDetails) { overviewPanels .padding(.top, DesignTokens.Spacing.sm) + } label: { + // The whole row opens it, not only the small triangle. + Text("Details") + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + .onTapGesture { showsOverviewDetails.toggle() } } // `.contain` first: an identifier on a bare container // replaces the identifiers of everything inside it.