From a09eca6b7fb0d59c637bfa080114cc5eb5e81843 Mon Sep 17 00:00:00 2001 From: Nishith Nand Date: Sat, 28 Nov 2026 17:45:19 -0800 Subject: [PATCH 01/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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/11] 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 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 11/11] 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(