diff --git a/README.md b/README.md index 0c9e5d6e..eeda5afa 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Chronoframe always shows you a plan before it changes anything. Your source fold | Need | Use Chronoframe to | | :--- | :--- | -| Make sense of a messy folder | Copy photos and videos into folders like `2024/06/15` | +| Make sense of a messy folder | Copy photos and videos into folders like `2024/06` | | Combine old backups | Skip files that are already in the destination | | Fix uncertain dates | Review unknown or low-confidence dates before copying | | Keep an eye on the library | Run a Health check for unknown dates, duplicates, and interrupted work | @@ -51,14 +51,16 @@ The current source targets **macOS 14.0 or later** on Apple Silicon and Intel Ma Organize has these tabs: **Choose Folders**, **Preview & Copy**, **History**, **Watched Folders**, and **Health**. +When you open Chronoframe with nothing set up, **Choose Folders** asks two questions instead of showing the full screen: **Where are most of your photos?** (**Pictures Folder**, **Desktop**, **Downloads**, **An External Drive**, **Somewhere Else…**, or **My photos are in the Apple Photos app**) and **Where should the organized copy go?** It shows how much your folder holds (an estimate, counted in files) and how much free space the destination has, and warns without ever blocking you if it may not fit. **Look at My Photos** builds the preview and copies nothing. **Use the full setup screen** skips the questions, and they do not come back. If you quit before finishing, the questions return on the next launch only when you had not yet chosen a folder; once a folder is chosen you see the full screen from then on. If you already have folders, history or saved setups, you see the full screen. The steps below are the full screen. + 1. Open **Organize → Choose Folders**. 2. Click **Add Folders…** and pick the folders with your unsorted photos and videos. 3. Click **Choose Destination…** and pick where organized copies should go. -4. Click **Preview Plan**. Chronoframe scans the source, resolves dates, and builds a transfer plan — nothing is copied yet. +4. Click **Preview Plan**. Chronoframe scans the source, resolves dates, and builds a transfer plan. While it works, the screen says Chronoframe is only reading and nothing is copied yet. A new install organizes into **Year / Month** folders by default; if Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day**, and a layout you chose is never changed. ![Preview Ready for Review — a timeline of the library by month, with discovered, planned, and issue counts.](docs/screenshots/preview-timeline.jpg) -5. On **Preview & Copy**, inspect the preview: the timeline shows your library by month, and the counts cover what's ready, what's already there, duplicates, and anything that needs attention. The first line of **What will happen** says whether every photo and video Chronoframe found is listed below; if the numbers do not add up, it says so and asks you to rebuild the preview. Open **Review** to fix uncertain dates. +5. On **Preview & Copy**, inspect the preview: the timeline shows your library by month, and the counts cover what's ready, what's already there, duplicates, and anything that needs attention. The first line of **What will happen** says whether every photo and video Chronoframe found is listed below; if the numbers do not add up, it says so and asks you to rebuild the preview. Open **Review** to fix uncertain dates. The newest month is selected so a sample from that month is on screen, and **How your library will be arranged** shows the newest folders and how many new files each will get, for **Year / Month**, **Year / Month / Day** and **Year**. Clicking another layout rebuilds the preview and copies nothing. The technical panels are under **Details**. 6. Click **Start Copying** when the preview looks right. Chronoframe copies files into the destination, verifies them, and writes a receipt — your source is never touched. The completion screen says whether every photo and video found is accounted for, and offers **Undo This Copy…** and **Add Another Folder**. ![Transfer Complete — every frame copied, with a run summary and links to open the destination, report, and logs.](docs/screenshots/transfer-complete.jpg) diff --git a/docs/FAQ.md b/docs/FAQ.md index 970ef7b4..4fb37ebe 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -24,7 +24,7 @@ A: Yes. Open **Organize** → **History** and click **Undo** next to the copy yo **Q: How do I know what Chronoframe will copy?** -A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. +A: **Preview Plan** shows the exact plan before anything is copied. You can review the plan and edit uncertain dates in the **Review** tab on the **Preview & Copy** screen. **Start Copying** uses the same plan you approved. The first line of the **What will happen** card also says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, it says how many do not add up and asks you to rebuild the preview before copying. While the preview is being built, the screen says Chronoframe is only reading and nothing is copied yet. When it is ready, the newest month is selected so a sample from that month is on screen, and **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets. --- @@ -36,7 +36,7 @@ A: macOS 14.0 or later. Chronoframe works on Intel and Apple Silicon Macs. **Q: How much disk space do I need?** -A: Enough for your destination folder to hold copies of your original files. Chronoframe doesn't compress; it copies files as-is. You'll need roughly the same amount of free space as the size of the folders you are organizing. +A: Enough for your destination folder to hold copies of your original files. Chronoframe doesn't compress; it copies files as-is. You'll need roughly the same amount of free space as the size of the folders you are organizing. The first-time setup shows this for you: once you have chosen the folder to organize it shows how much it holds (an estimate, counted in files), and once you choose the destination it shows how much free space that drive has. If your folder may not fit, it warns you but never stops you. The screen says the copy pauses safely if space runs out. **Q: Why is the first scan taking so long?** @@ -77,6 +77,10 @@ A: Yes. In the **Review** tab on the **Preview & Copy** screen, change an item's A: It means Chronoframe isn't sure about the date—maybe the filename looks like a date but doesn't match metadata, or it's relying on filesystem dates. You can accept it or override it in Review. +**Q: Which folder layout does Chronoframe use, and can I change it?** + +A: A new install uses **Year / Month** (`2019/07`). If Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day** (`2019/07/14`). A layout you chose yourself is never changed. You can change it in **Settings → Layout**, with the **Folder layout** menu on **Choose Folders**, or, once a preview is ready, by clicking **Year / Month**, **Year / Month / Day** or **Year** under **How your library will be arranged**. That rebuilds the preview, and nothing is copied. If the preview came from a watched folder or the Apple Photos app, or you use **Year / Month / Event** or **One folder**, it shows your layout on one line instead, and you change it in **Settings**. To change the layout of a library you have already copied, use Reorganize, which needs the unlock. + **Q: Can I use custom event names?** A: If your folder layout is `YYYY/Mon/Event`, Chronoframe suggests event names based on proximity and source folder names. You can accept suggestions in Review, or manually edit them. diff --git a/docs/QUICK_START.md b/docs/QUICK_START.md index 44c80b7c..d1c32f1e 100644 --- a/docs/QUICK_START.md +++ b/docs/QUICK_START.md @@ -13,18 +13,28 @@ Use this when you want Chronoframe to copy messy folders into a cleaner date-bas ### Step 1: Choose Folders +When you open Chronoframe with nothing set up, **Choose Folders** asks two questions instead of showing the full screen: + +- **Where are most of your photos?** Click **Pictures Folder**, **Desktop**, **Downloads**, **An External Drive** or **Somewhere Else…**. The first four open the folder picker at that place (**An External Drive** opens the list of drives); **Somewhere Else…** opens it where it usually starts. You still choose the folder in the picker. Chronoframe only reads it. If your photos are in the Apple Photos app, click **My photos are in the Apple Photos app** instead. +- **Where should the organized copy go?** Click **Choose a Folder…**. Chronoframe shows how much your folder holds, with the number of files when it could read everything, and how much free space the destination drive has. The size is an estimate ("about"), and when Chronoframe cannot read everything it says "at least". If the folder may not fit, it warns you but does not stop you. The screen says the copy pauses safely if space runs out. Click **Look at My Photos** to build the preview. Nothing is copied. A very large collection can take 5 to 15 minutes to read. For Apple Photos, the button is **Choose Photos to Copy**, which opens the Apple Photos screen instead of building a preview. No folder size is shown for Photos. + +**Use the full setup screen** is on both questions and takes you to the full **Choose Folders** screen, and the questions do not come back. If you quit before finishing, the questions return on the next launch only when you had not yet chosen a folder; once a folder is chosen you see the full screen from then on. If you already have folders, history or saved setups, you see the full screen from the start. The numbered steps below are the full screen. + 1. Open **Organize → Choose Folders** 2. Click **Add Folders…** and choose the folders that hold your photos. You can pick more than one — see [Organizing several folders at once](#organizing-several-folders-at-once) 3. Click **Choose Destination…** and choose where organized photos should go -4. Chronoframe organizes into **Year / Month / Day** folders (`YYYY/MM/DD`) by default. To use **Year / Month**, **Year**, **Year / Month / Event** or **One folder** instead, change the **Folder layout** menu under the destination, or change it in **Settings → Layout**. +4. A new install organizes into **Year / Month** folders (`YYYY/MM`) by default. If Chronoframe finds folders saved from earlier use, the default stays **Year / Month / Day** (`YYYY/MM/DD`). A layout you chose yourself is never changed. To use **Year / Month / Day**, **Year / Month**, **Year**, **Year / Month / Event** or **One folder**, change the **Folder layout** menu under the destination, or change it in **Settings → Layout**. When the preview is ready, you can also switch between **Year / Month**, **Year / Month / Day** and **Year** there (see step 6). ### Step 2: Preview Your Plan 5. Click **Preview Plan** - - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet + - Chronoframe scans your folders, resolves dates, and builds a plan — nothing is copied yet. While it works, the screen says Chronoframe is only reading, and you can keep using your Mac - This takes 10–60 seconds depending on your library size 6. When it finishes, **Preview & Copy** shows the plan: a headline saying how many photos and videos will be copied, a **What will happen** card that lists anything unusual, a timeline of your library, and counts for what was found, what will be copied, what is already there, exact copies, and problems - The first line of the **What will happen** card says whether every photo and video Chronoframe found is listed below. If the numbers do not add up, the line says how many do not add up and asks you to rebuild the preview before copying + - The newest month is selected in the timeline, so a sample from that month is on screen when the preview opens. Select another month to see a sample from it + - **How your library will be arranged** shows the newest folders the copy will make and how many new files each gets, in three layouts: **Year / Month**, **Year / Month / Day** (a line notes each day gets its own folder) and **Year**. Click a layout to use it. Chronoframe rebuilds the preview, and nothing is copied. While a copy or Deduplicate is running, or when the preview cannot be rebuilt, the layouts cannot be changed. If the preview came from a watched folder or the Apple Photos app, or you use **Year / Month / Event** or **One folder**, it shows your layout on one line instead, and you change it in **Settings**. Under it: "You can change this later with Reorganize, which needs the unlock." + - **Details** is closed on a ready preview. Open it for the **Status** card and **Reports and Logs**, with buttons to open the destination and the preview report ### Step 3: Review (Optional) diff --git a/docs/SAFETY_AND_RECOVERY.md b/docs/SAFETY_AND_RECOVERY.md index 28093387..0bfd270c 100644 --- a/docs/SAFETY_AND_RECOVERY.md +++ b/docs/SAFETY_AND_RECOVERY.md @@ -49,6 +49,31 @@ important library, especially before a large first run or filesystem migration. planned files were not copied, it says how many, that your originals were not changed, and points to Problems. After a free copy it says how many are waiting for the next copy. The line counts files; it never changes a file. +- **While the preview is built.** The screen says Chronoframe is only reading + and nothing is copied yet. Building a preview never changes your source + folders, and nothing is copied. It writes only its own report, log, review data and cache in the destination. +- **First-time setup and free space.** The two-question first-time setup + measures the folder you chose by listing it and reading file attributes. It + never opens, changes or follows anything: it counts regular files, and skips + hidden files, package contents and symbolic links. The result is an estimate, + worded "about" or "at least", and it counts every file, not only photos. It + compares that with the free space on the destination drive. If the folder may + not fit, the screen warns you but does not block you, and says the copy pauses + safely if space runs out. When there is room, it says space is checked again + when the copy starts. **Look at My Photos** builds a preview and copies + nothing. +- **Choosing a layout on a ready preview.** **How your library will be + arranged** shows the newest folders and the number of new files in each for + **Year / Month**, **Year / Month / Day** and **Year**. Choosing another one + changes only the folder-layout setting and, when the preview can be rebuilt, + rebuilds it; nothing is copied and your source is not written. While a copy or + Deduplicate is running, or when the preview cannot be rebuilt, the layouts + cannot be changed. On a watched-folder or Apple Photos import preview, or when + you use **Year / Month / Event** or **One folder**, it shows the layout on one + line, and you change it in Settings. The default layout is **Year / Month** on + a new install and stays **Year / Month / Day** where Chronoframe finds folders + saved from earlier use; a layout you chose is never changed. Changing the + layout of files you have already copied is Reorganize, which needs the unlock. - **Undo This Copy….** The completion summary offers it for the copy that just finished, once History has found that copy's receipt. It asks for confirmation and then runs the same revert History runs for that receipt, with the same diff --git a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md index 4c949344..663bfa3c 100644 --- a/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md +++ b/docs/plan/first-run-experience/ACCEPTANCE_MATRIX.md @@ -1,6 +1,6 @@ # First-run experience — acceptance matrix -Status: M1 rows pass-auto at gate G1 (2026-11-28); M2 rows pass-auto at gate G2 (2026-11-28); M3 rows not built. Auto status values: todo, pass-auto, blocked. Owner status values: todo-owner, pass-owner, fail-owner, n/a. +Status: every row pass-auto at gate G3 (2026-11-28). Owner rows are not run. Auto status values: todo, pass-auto, blocked. Owner status values: todo-owner, pass-owner, fail-owner, n/a. | ID | Requirement (recommendation) | Automated coverage | Owner row | Auto status | Owner status | |---|---|---|---|---|---| @@ -12,9 +12,9 @@ Status: M1 rows pass-auto at gate G1 (2026-11-28); M2 rows pass-auto at gate G2 | A-FRX-06 | One click accepts only byte-identical groups; nearly identical groups go through Quick Review (rec 4) | ChronoframeCoreDeduplicateReviewLaneTests/*; DeduplicateSessionStoreTests (accept-by-lane, 5 new); DeduplicateReviewLanesTests (4 new); DeduplicateReviewViewsTests/testQuickReviewScopeIsUnreviewedGroupsOfLane, testAcceptTheRestOnlyForNearlyIdenticalAfterFirstGroup, testFooterAcceptCallsIdenticalLaneOnly | H-FRX-3 | pass-auto | todo-owner | | A-FRX-07 | The screen says Chronoframe always suggests keeping one photo per group, and tells the person when a fully marked group is being skipped (rec 4) | DeduplicateTests/testPlannerRefusesAllDelete (existing); DeduplicationPlannerPropertyTests/testPropertyNoClusterIsCompletelyEmptiedByThePlan (existing); DeduplicateSessionStoreTests/testFullyMarkedClusterIDs; DeduplicateReviewViewsTests/testFullyMarkedNoticeText | H-FRX-3 | pass-auto | todo-owner | | A-FRX-08 | Duplicates can be removed free in whole groups up to the allowance, through the normal planner and confirmation (rec 3) | ChronoframeCoreFreeDedupeBatchPlannerTests/*; DeduplicateSessionStoreTests (7 free-batch tests); UnlockPresentationTests (2 new in WP-13); AppStateTests (3 new); DeduplicateReviewViewsTests/testFreeRemovalLineAndButtonTitles, testConfirmationCountUsesPreparedPlan | H-FRX-4 | pass-auto | todo-owner | -| A-FRX-09 | A person with nothing configured answers two questions and reaches the preview; everyone else keeps the full screen (rec 1) | GuidedSetupModelTests/*; AppStateTests/testGuidedSetupEligibleDefaultsTrue, testEveryExistingScenarioDisablesGuidedSetup; folder-access tests (4 new); SetupCoordinatorTests (2 new) | H-FRX-5 | todo | todo-owner | -| A-FRX-10 | The destination step shows the folder's size against free space, labeled as an estimate, and never blocks (rec 1) | ChronoframeCoreFolderSizeEstimatorTests/*; GuidedSetupModelTests/testMeasureLineStates, testSpaceLineWarnsButNeverBlocks, testSpaceLineSaysEstimate | H-FRX-5 | todo | todo-owner | -| A-FRX-11 | New people get Year/Month; anyone with prior use keeps their layout (rec 6, D-FRX-06) | PreferencesStoreTests (4 new) | H-FRX-7 | todo | todo-owner | -| A-FRX-12 | The ready preview shows photos without a click, the folder picture with real counts, and the technical panels behind Details (rec 6) | histogram tests (2 new); RunTimelinePresentationTests (3 new); LayoutPictureModelTests/*; RunWorkspaceModelTests/testRunningPreviewMessageSaysOnlyReading | H-FRX-6 | todo | todo-owner | -| A-FRX-13 | Every new string ships in German; no baseline key is lost | script/check_german_localization.py at G1, G2, G3 | — | todo | n/a | -| A-FRX-14 | No safety invariant is weakened; source folders and the Photos library stay read-only | script/check_agents_invariants_have_tests.sh; cf_swift.sh guards; tagged tests (INV 1, 6, 8, 14, 15, 17, 29) | — | todo | n/a | +| A-FRX-09 | A person with nothing configured answers two questions and reaches the preview; everyone else keeps the full screen (rec 1) | GuidedSetupModelTests/*; AppStateTests/testGuidedSetupEligibleDefaultsTrue, testEveryExistingScenarioDisablesGuidedSetup; folder-access tests (4 new); SetupCoordinatorTests (2 new) | H-FRX-5 | pass-auto | todo-owner | +| A-FRX-10 | The destination step shows the folder's size against free space, labeled as an estimate, and never blocks (rec 1) | ChronoframeCoreFolderSizeEstimatorTests/*; GuidedSetupModelTests/testMeasureLineStates, testSpaceLineWarnsButNeverBlocks, testSpaceLineSaysEstimate | H-FRX-5 | pass-auto | todo-owner | +| A-FRX-11 | New people get Year/Month; anyone with prior use keeps their layout (rec 6, D-FRX-06) | PreferencesStoreTests (4 new) | H-FRX-7 | pass-auto | todo-owner | +| A-FRX-12 | The ready preview shows photos without a click, the folder picture with real counts, and the technical panels behind Details (rec 6) | histogram tests (2 new); RunTimelinePresentationTests (3 new); LayoutPictureModelTests/*; RunWorkspaceModelTests/testRunningPreviewMessageSaysOnlyReading | H-FRX-6 | pass-auto | todo-owner | +| A-FRX-13 | Every new string ships in German; no baseline key is lost | script/check_german_localization.py at G1, G2, G3 | — | pass-auto | n/a | +| A-FRX-14 | No safety invariant is weakened; source folders and the Photos library stay read-only | script/check_agents_invariants_have_tests.sh; cf_swift.sh guards; tagged tests (INV 1, 6, 8, 14, 15, 17, 29) | — | pass-auto | n/a | diff --git a/docs/plan/first-run-experience/DECISIONS.md b/docs/plan/first-run-experience/DECISIONS.md index c98fdc8d..bb2091ff 100644 --- a/docs/plan/first-run-experience/DECISIONS.md +++ b/docs/plan/first-run-experience/DECISIONS.md @@ -58,5 +58,11 @@ Keep every invariant; fewest changed lines; copy the named reference pattern; wh - **D-FRX-110 TipsTests expectation (WP-13).** `ui/Tests/ChronoframeAppTests/TipsTests.swift:34` asserted the old tip message that C-13 replaces. The file was not in WP-13's owned list; it was added for that one expectation under D-FRX-20 (the `never selects uncertain matches` assertion and the test name are unchanged). Not logged in BLOCKED.md because the orchestrator could resolve it inside D-FRX-20. - **D-FRX-111 Review UI details (WP-13).** (a) Singular templates added per the copy rule (`1 safe group is identical copies. Accept it now: %@, %@.`, `1 safe group is nearly identical. Look through it quickly.`, `1 group has every photo marked Delete. … Mark one Keep in it to include it.`, `Move 1 File to Trash Free`, `1 duplicate`). (b) The old `DeduplicateReviewLanes` initializer keeps its meaning with `identicalGroupCount = 0`; the lane initializer counts a group as safe only if the planner would auto-select it, whatever the closure says. (c) `Accept the Rest ({remaining})` counts and accepts every unreviewed nearly identical group, including ones skipped earlier in the walk; the number shown is the number accepted, and nothing reaches the Trash without the commit dialog. (d) Quick Review freezes its group list when it opens so accepting a group does not shift the walk. (e) `DeduplicateView.swift` edits outside the listed ranges, each needed by C-13: an observed `trialStatusStore`, `quickReviewLane` and `freeBatchDeferredCount` state, the `wantsFreeBatchConfirmation` reaction (`onChange` and `onAppear` on the footer), a defaulted `deferredFileCount` on `completedStatusCopy`, and removal of the now-unused `highCount` parameter. (f) A prepared free batch is discarded only by the dialog's Cancel button; every path that opens a confirmation dialog prepares a fresh plan first, so a dismissed, stale plan is never committed (same pattern as before this plan). (g) The "more are waiting" line is view state; if the view is rebuilt during the commit the line is lost (the saved review is not). (h) Accessibility labels and hints on the accept button and menu item now say "identical copies"; identifiers are unchanged. (i) The unlock sheet's dedupe action shows its detail line and no file list. (j) With a free-batch offer the destructive button carries `dedupeFreeBatchCommit` (as C-13 says), so `dedupeCommitButton` is absent in that one state. (k) The lanes bar is stacked vertically. - **D-FRX-112 M2 docs (WP-14).** (a) Because B-1 is open, the docs do not say a fully marked group "is skipped" as a fact: all four say Chronoframe always suggests keeping one photo, that such a group is normally skipped, that this is not a guarantee, and to check RAW+JPEG and Live Photo pairs. The in-app notice keeps the C-13 wording. If the owner fixes the planner (B-1 option 1), these sentences can be simplified. (b) Two more documents named controls that no longer exist, so one phrase each was changed outside C-26's list: `docs/TROUBLESHOOTING.md` ("Accept All Safe" → "Accept Identical Copies for groups of identical copies") and `docs/TECHNICAL.md` ("`Space` opens Rapid Triage" was already untrue; it now says "`Space` previews the focused photo", which is what `ClusterDetailPane.swift:50–53` binds). (c) The docs review needed two rounds; round 2 left three one-sentence items, which the orchestrator applied itself with the reviewer's replacement text instead of a third round (WP-14 is an orchestrator work package; no code is involved). (d) The M2 strings add 29 App keys and 3 Core keys; `Accept identical copies` (accessibility label) carries no `extractionState` because its symbol would collide with `Accept Identical Copies` (same handling as D-FRX-107). +- **D-FRX-113 Groundwork details (WP-21).** (a) `FolderSizeEstimator` returns nil for a root that is itself a symbolic link, is not a directory or cannot be listed; a failed entry below the root makes `isComplete` false; a cancelled run returns the partial counts with `isComplete == false`. Cost of the symlink-root rule: a Pictures folder that is a symlink shows "could not measure"; the copy itself is unaffected and the space line never blocks. (b) `PreferencesStore`: a stored but unrecognised `folderStructure` value keeps `.yyyyMMDD` and writes nothing (the old behaviour; "a stored value is never changed"). The prior-use check is inlined at the one assignment and uses the store's own literal keys; archive-destination bookmarks are stored as `bookmark.history.destination.…`, so the `bookmark.` prefix already covers them and both prefixes are checked as C-21 lists. (c) Histogram samples: new files in plan order, then exact copies fill what is left up to 12; counts are untouched. (d) `FolderAccessService.panelDirectoryURL(openingAt:)` is an internal pure helper so the rule is testable without a panel; its fallback is the `FileManager` home as C-22 says. `realHomeDirectoryURL()` is `nonisolated`. (e) The two new histogram tests live in `ChronoframeCoreCopyPlanTests.swift` and the four folder-access tests in `ModelAndServiceTests.swift`. +- **D-FRX-114 Guided setup details (WP-22).** (a) Latch: choosing the source fills `sourcePath`, which would turn the C-23 gate off before the second question. `SetupView` therefore remembers that the full gate was true while this view was alive and keeps the guided screen up as long as the person is still eligible, not onboarded and has no history or profiles. The latch can only be set by the untouched gate, starts false on every relaunch, and ends for good when `didOnboard` becomes true. (b) `SetupView.init(appState:didOnboard: Binding? = nil)`: production passes nothing and reads the same `@AppStorage("didOnboard")` key; renders pass a constant so `UserDefaults.standard` is never written. (c) The measure line fills `Your folder holds about %@ in %@.` with the existing files phrase, so one file reads "1 file". (d) Incomplete estimate: free space below the lower bound still warns; free space above it shows only `{free} free here.` ("enough for about X" would overclaim). While measuring, the space line ignores an old estimate. (e) `chooseSourceFolder(openingAt:)` returns true only when the chosen folder became the single source. (f) The estimator never runs on `/` or `/Volumes`, only on the validated chosen source, in a detached task cancelled when the step is left. (g) `GuidedSetupView` has an internal `fixedModel` used only by the destination render; with it no task runs. (h) Identifiers live in a nested `AccessibilityIdentifiers.Guided`; the Apple Photos primary reuses `guided.start`. (i) The place buttons are plain bordered SwiftUI buttons. +- **D-FRX-115 Running-preview message (WP-23).** C-24 says the message "gains the sentence" `Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.` The existing message was already "You can keep using your Mac. Nothing is being copied.", so appending repeated both halves. The contract fact was wrong; the message is now the C-24 sentence alone. Title, badge and the running-copy message are unchanged; the old catalog key stays, unused. +- **D-FRX-116 Layout cards never restart a preview they cannot rebuild (WP-23).** C-25 says selecting a card sets the layout and calls `startPreview()`. On a watched-folder or Apple Photos import preview that call clears the import context, deletes the Photos staging export and previews the Choose Folders paths instead; and when `startPreview()` returns early the preference would change under a preview that is not rebuilt. So: on an import preview the section shows the one line `Layout: {title}. Change it in Settings.` instead of cards; cards are disabled while a run or Deduplicate is working; and a tap changes the preference only when the same checks `startPreview()` makes will pass (`appState.canStartRun`, no import, nothing running). Otherwise the tap does nothing. A narrowing of C-25 for cases it did not foresee; nothing in the coordinator changed. +- **D-FRX-117 Preview picture details (WP-23).** (a) The selected-month panel's count is the histogram bucket's planned count (as the old "files to copy" line was), which includes exact copies; the cards use `newFilesByMonth`. The old "{n} files to copy" drawer line is replaced by the title. (b) Singular forms: `%@: 1 photo or video`, `1 folder`, `1 exact copy goes to a separate Duplicate folder.` (c) Year/Month/Day card: the `one folder per day` line appears once, under the newest month; Year card: one line per year with its total. (d) The default selection is applied once per view; a later deselection is not overridden, and a re-preview does not reselect. (e) The whole section is hidden when there are no dated new files. (f) The collapsed `DisclosureGroup("Details")` sits under the shell's existing "Details" heading, so the word appears twice; contract copy kept. (g) The preview render uses a 1360×2400 frame so the new sections are in the PNG. +- **D-FRX-118 M3 strings and docs (WP-24).** (a) 36 App keys added, 3 kept (`%@ folders`, `1 folder`, `Details` already had German); no Core strings. `%@: %@ photos and videos` and `%@: 1 photo or video` carry no `extractionState` because their generated symbols collide with existing keys (same handling as D-FRX-107). (b) The picker prompt `Choose This Folder` is a plain string passed to the panel, like the existing `Add Folders` and `Choose Destination Folder` prompts, and is not in the catalog. (c) Docs: the README example path is now `2024/06` (the new-person default); the default-layout sentence says "new install" versus "folders saved from earlier use", which is how the code decides; the safety document says a preview writes its own report, log, review data and cache in the destination and never changes the source (the screen's "only reading" is about the photos). (d) The docs review needed two rounds; round 2 left two one-sentence items, applied by the orchestrator with the reviewer's wording (as in D-FRX-112c). - **D-FRX-119 Planner fix for B-1 (approved 2026-11-29).** The owner confirmed D-FRX-11 and D-FRX-25 and asked for B-1 option 1. The fix is its own branch off `main`, `fix/dedupe-planner-rail-protects-fanout` (`2f8954f`, issue #300), merged into `feature/first-run-duplicates` with a merge commit (owner's choice; no history rewrite). The members of a group the all-Delete rail skipped are now protected from direct deletes and from pair fan-out; both B-1 routes (cross-group pairs, overlapping groups) reproduced as failing tests first. New invariant INV-32 in `AGENTS.md`. This replaces D-FRX-11's "No planner change, no new invariant" and D-FRX-112(a): the four docs now state the skip as a fact. - **D-FRX-120 Review fixes after the PRs opened (2026-11-29).** Four automated review findings on #307 and #308, each reproduced as a failing test first. (a) `TrialRemaining.value` returns nil for `verificationUnavailable` and `unverified`, so the preview shows no spent-trial line and offers no purchase to someone who may already have paid; the gate's `purchaseUnconfirmed` path is unchanged. (b) The unlock sheet offers a requested month even when the plan has shrunk to exactly that month, and drops the "leaves N for later" detail line in that case; an offer nobody asked for is still withheld. (c) The sheet's free removal resumes a review that a refused commit paused, because the confirmation dialog lives on the review footer; nothing is prepared or moved before the dialog. (d) The Options menu's Quick Review opens the nearly identical lane while it has groups waiting, then the look-at-each lane. C-13 had it always open look-at-each, which left nearly identical unreachable when the lanes bar is compact. No new strings. diff --git a/docs/plan/first-run-experience/PROGRESS.md b/docs/plan/first-run-experience/PROGRESS.md index 0debd2cc..606b12db 100644 --- a/docs/plan/first-run-experience/PROGRESS.md +++ b/docs/plan/first-run-experience/PROGRESS.md @@ -1,6 +1,6 @@ # First-run experience — progress -Status: in progress. Gates G1 and G2 passed 2026-11-28; M3 next. One open BLOCKED item (B-1, owner decision, blocks no work package). +Status: built, not merged. Gates G1, G2 and G3 passed 2026-11-28 on three stacked branches. One open BLOCKED item (B-1, owner decision). Owner rows H-FRX-1 to H-FRX-8 are not run. Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled", "Tested" and "Rendered" are recorded separately; "Verified in the running app" is never claimed here (owner rows). @@ -9,6 +9,7 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - M1 anchor refresh (Explore, haiku, 2026-11-28): every fact 1–16 still true. Moved: fact 13 `FolderStructure.default` is at `EngineDomainModels.swift:332` (cited :325). Notes: the `"audit_receipt_"` literal is `auditReceiptPrefix` at `EngineDomainModels.swift:321` (stem helper still `TransferExecutor.swift:1425`); `"Unknown_Date"` is `namingRules.unknownDateDirectoryName` at `EngineDomainModels.swift:359`; `acceptAllHighConfidence()` is at `DeduplicateView.swift:717`. All WP-01 to WP-05 ranges resolve. CONTRACTS not edited. - Baseline on aa56f84: `cf_swift.sh build` exit 0; `cf_swift.sh suite` exit 0, 2513 test cases passed, 0 failed, 1 skipped. - M2: branch `feature/first-run-duplicates` cut from `feature/first-run-trust` f461bfe. `cf_swift.sh build` exit 0. M2 anchor refresh (Explore, haiku): facts 9–12 still true. Moved: the `UnlockSheetAction` switch in `UnlockSheet.swift` is at :143–175 (cited ~133–165); in `UITestAppStateFactory.swift` the dedupe fixture is `sampleDeduplicateClusters()` at :728–785 (cited :606–653) and the dedupe scenario wiring is :192–224 (cited :167–199). `lastScanConfiguration` is at `DeduplicateSessionStore.swift:87`, outside WP-12's reference range. Callers: `acceptAllSuggestions()` at `DeduplicateView.swift:366` and `:761`; `acceptAllHighConfidence()` at `:717`. For G2 step 4: UI tests use identifiers `dedupeCommitButton`, `dedupeAcceptAllSuggestionsButton`, `dedupeCommitFooter`, the confirm button matched by "Move to Trash" (:1177), `staticTexts["96 of 100 duplicates left"]` (:1223), and A11yBaseline `deduplicateReviewWide`/`Compact` "0 groups reviewed · 12 still suggested". +- M3: branch `feature/first-run-guided` cut from `feature/first-run-duplicates` 0351db6. `cf_swift.sh build` exit 0. M3 anchor refresh (Explore, haiku): facts 7, 13, 14, 15 still true. Moved: `AppState.folderAccessService` :55 (cited :52) and the `.organize(.setup)` default :223 (cited :220); `FolderStructure.default` `EngineDomainModels.swift:332`; the histogram call `DryRunPlanner.swift:476–477`; the overview tab with `RunSnapshotPanel`/`RunArtifactsPanel` is `RunWorkspaceShell` `case .overview` at `RunSectionViews.swift:485–498` (cited :410–423; WP-23's read range should be :445–511); the running-preview message is `RunWorkspaceModel.swift:362–364`. `FolderAccessServicing` conformers: `FolderAccessService` (`FolderAccessService.swift:119`), `MockFolderAccessService` (`UITestDoubles.swift:179`), `NASViewTestFolderAccess` (`NASLibraryViewTests.swift:59`), `MockNASFolderAccess` (`NASWorkspaceStoreTests.swift:85`); protocol at :93, existing extension default :112–116. Tests: histogram in `ChronoframeCoreCopyPlanTests.swift` (:165–226; no assertion pins 4 samples); `initialPanelDirectoryURL` in `ModelAndServiceTests.swift:82–126`; no test pins the fresh-preference layout; the running-preview message is pinned at `RunWorkspaceModelTests.swift:208–210`. `UITestAppStateFactory`: `PreferencesStore(` :35, `AppState(` :245; 21 scenarios. UI tests contain none of "2019/07/14", "yyyyMMDD", "didOnboard", "Run Snapshot"; they do not reset `UserDefaults.standard`. ## Work packages | WP | Title | Status | Compiled | Tested | Reviewer | Commit | Notes | @@ -26,13 +27,13 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-12 | AppCore: store lanes, accept by lane, batch plan | done | build exit 0 | DeduplicateSessionStoreTests 49 tests exit 0 | approve (round 1) | 89b21a8 | orchestrator read the full DeduplicateSessionStore.swift diff: every changed line traces to C-12 (recompute trigger; two flag resets; the three saved-review lines wrapped for a free-batch commit, D-FRX-25); `commitReviewed`, `acceptAllSuggestions()`, `acceptAllHighConfidence()` untouched; D-FRX-109 | | WP-13 | App: three lanes, Quick Review, footer, free removal | done | build exit 0 | DeduplicateReviewLanes 15, DeduplicateReviewViews 10, DeduplicateStatusView 30, UnlockPresentation 21, UnlockSheetBatchOffer 14, AppState 54, Tips 4, UITestWindowFit 9, Accessibility 8 tests exit 0 | approve (round 1) | e321445 | orchestrator read the full DeduplicateView.swift diff: commit is reachable only through the two confirmation dialogs, each opened after a fresh prepare; no view calls `acceptAllSuggestions()`/`acceptAllHighConfidence()`; rendered: `m2-deduplicate-lanes.png` matches C-13; D-FRX-110, D-FRX-111 | | WP-14 | Docs and strings, M2 | done | build exit 0 | n/a (strings and docs; checked at G2) | German: approve, no changes; docs: changes required (round 1), changes required (round 2, three one-sentence items applied by the orchestrator) | b4a1774 | 29 App keys + 3 Core keys; docs word the keep rule as "not a guarantee" because of B-1; D-FRX-112 | -| G2 | Gate, M2 | done | build exit 0; xcode exit 0; build-for-testing exit 0 | suite exit 0 (2654 passed, 0 failed); coverage exit 0 (96.17%) | n/a | (G2 commit) | guards feature/first-run-trust exit 0 (14 of 14); invariants exit 0; German check exit 0; 1 render checked | -| WP-20 | Branch and baseline, M3 | todo | | | n/a | | lists FolderAccessServicing conformers | -| WP-21 | Core and AppCore groundwork | todo | | | | | | -| 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 | | | +| G2 | Gate, M2 | done | build exit 0; xcode exit 0; build-for-testing exit 0 | suite exit 0 (2654 passed, 0 failed); coverage exit 0 (96.17%) | n/a | 0351db6 | guards feature/first-run-trust exit 0 (14 of 14); invariants exit 0; German check exit 0; 1 render checked | +| WP-20 | Branch and baseline, M3 | done | build exit 0 | n/a | n/a | 6f91c90 | anchors and FolderAccessServicing conformers recorded under Baseline | +| WP-21 | Core and AppCore groundwork | done | build exit 0 | FolderSizeEstimator 6, CopyPlan 14, PreferencesStore 16, ModelAndService 14, DryRunPlannerParity 16, FreeTestBatchPlanner 19, UITestWindowFit 9 tests exit 0; full suite exit 0 (2670 passed) | approve (round 1) | b2d8704 | orchestrator read the CopyPlanBuilder.swift, PreferencesStore.swift and FolderSizeEstimator.swift changes: histogram counts untouched, a stored layout is never overwritten, the estimator only lists and reads attributes; D-FRX-113 | +| WP-22 | App: guided setup | done | build exit 0 | GuidedSetupModel 10, SetupCoordinator 40, AppState 56, UITestWindowFit 10, Accessibility 8 tests exit 0 | approve (round 1) | f3192d2 | rendered: `m3-guided-source.png` and `m3-guided-destination.png` match C-23; D-FRX-114 | +| WP-23 | App: photos and folder picture on the preview | done | build exit 0 | LayoutPictureModel 10, RunWorkspaceModel 30, RunTimelinePresentation 12, Accessibility 8, RunOutcomeAccuracy 14 tests exit 0 | changes required (round 1: a layout card on an import preview discarded the import) → approve (round 2) | db99994 | rendered: `m3-preview-photos-layout.png` matches C-25 (sample thumbnail is a placeholder: the fixture path does not exist); D-FRX-115, D-FRX-116, D-FRX-117 | +| WP-24 | Docs and strings, M3 | done | build exit 0 | n/a (strings and docs; checked at G3) | German: changes required → 4 fixes applied; docs: changes required (round 1, 11 items), changes required (round 2, two one-sentence items applied by the orchestrator) | 31ecb8e | 36 App keys; `docs/plan/next-half/README.md` row set to "built, not merged"; D-FRX-118 | +| G3 | Final gate | done | build exit 0; xcode exit 0 (twice); build-for-testing exit 0 | suite exit 0 (2699 passed, 0 failed; run twice); coverage exit 0 (96.15%, 96.17%) | n/a | 5fc0878 | guards feature/first-run-duplicates exit 0 and guards origin/main exit 0 (14 of 14 each); invariants exit 0; German check exit 0; 8 renders, 3 new ones checked | ## Existing assertions changed (D-FRX-20) | WP | Test file:line | Old expectation | New expectation | Contract | @@ -44,6 +45,8 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | WP-13 | ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift:239 | acceptAllTitle (compact) == "Accept Safe" | == "Accept Identical" | C-13 | | WP-13 | ui/Tests/ChronoframeAppTests/DeduplicateStatusViewTests.swift:256 | acceptAllTitle contains the Safe label | the identical-lane sentence contains the Safe label, case-insensitively | C-13 | | WP-13 | ui/Tests/ChronoframeAppTests/TipsTests.swift:34 | old tip message "Safe groups are matches Chronoframe has verified. …" | C-13 tip message "Identical copies are the same file saved more than once. …" | C-13, D-FRX-110 | +| WP-23 | ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift:209 | running-preview message "You can keep using your Mac. Nothing is being copied." | "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." | C-24, D-FRX-115 | +| G3 | ui/Xcode/UITests/ChronoframeUITests.swift `testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs` (~:939) | asserts `openDestinationButton` exists directly | first expands `runDetailsDisclosure`, then waits for `openDestinationButton` (compiled with build-for-testing, not run) | C-25, D-FRX-23 | | G1 | ui/Xcode/UITests/A11yBaseline.json:48, :50 | "84, FOUND" | "72, FOUND" | C-08, D-FRX-23 | ## Renders checked @@ -52,6 +55,9 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled | G1 | .tmp/frx-evidence/m1-preview-over-allowance.png | C-07 | matches: "You can copy 500 files free. This plan has 18,412. The newest month that fits is October 2026: 212 files."; buttons `Copy October 2026 Free…`, `Choose Another Month`, `Unlock to Copy Everything`; no Start Copying | | G1 | .tmp/frx-evidence/m1-copy-complete.png | C-02, C-04 | matches: "All 4,263 photos and videos Chronoframe found are accounted for: 4,200 copied, 63 already in your library."; `Undo This Copy…` beside `Open History`; add-folder text and `Add Another Folder` | | G1 | .tmp/frx-evidence/m1-unlock-organize.png | C-06 | matches: title "Organize all 250 files"; terms line "One-time purchase with Family Sharing. No subscription." under the message, secondary ink; price from the StoreKit stub only | +| G3 | .tmp/frx-evidence/m3-guided-source.png | C-23 | matches: title "Where are most of your photos?", the body, the five place buttons, `My photos are in the Apple Photos app`, `Use the full setup screen`; single column, no illustration | +| G3 | .tmp/frx-evidence/m3-guided-destination.png | C-23 | matches: title "Where should the organized copy go?", folder body, "Your folder holds about 96.4 GB in 18,452 files.", `Choose a Folder…`, "412 GB free here. That is enough for about 96.4 GB (estimate, checked again when the copy starts).", `Look at My Photos`, the line under it, `Back`, `Use the full setup screen` | +| G3 | .tmp/frx-evidence/m3-preview-photos-layout.png (1360×2400) | C-25 | matches: newest month selected on arrival with "October 2026: 2,420 photos and videos" and "A sample from this month." (thumbnail is a placeholder: fixture path does not exist); "How your library will be arranged" with Year / Month, Year / Month / Day (selected) and Year cards, real folder lines and footers, both captions; collapsed `Details` under the tabs | | G2 | .tmp/frx-evidence/m2-deduplicate-lanes.png | C-13 | matches: "4 safe groups are identical copies. Accept them together: 8 files, 19.2 MB." + `Accept Identical Copies`; "3 safe groups are nearly identical. Look through them quickly." + `Quick Review`; the unchanged look-alikes row + `Quick Review`; "Chronoframe always suggests keeping one photo in every group."; footer "You can remove 2 duplicates free. Your reviewed groups hold 4.", `Unlock to Remove All 4`, `Move 2 Files to Trash Free`; Safe / Check / Risky filter unchanged | | G1 | .tmp/frx-evidence/m1-unlock-dedupe.png | C-06 | matches: title "Remove all 25 duplicates"; same terms line | @@ -85,5 +91,16 @@ Prefix `FRX`. Status values: todo, in-progress, review, done, blocked. "Compiled - 2026-11-28 G2 commands (orchestrator): `cf_swift.sh suite` exit 0 (2654 passed, 0 failed); `cf_swift.sh coverage` exit 0 (96.17%; DeduplicateReviewLane 100%, FreeDedupeBatchPlanner 98.7%); `cf_swift.sh guards feature/first-run-trust` exit 0 (14 guards); `script/check_agents_invariants_have_tests.sh` exit 0 (30 invariants); `cf_swift.sh xcode` exit 0; `xcodebuild … SWIFT_EMIT_LOC_STRINGS=YES build` exit 0; `check_german_localization.py --baseline-ref origin/main …` exit 0 (app 1793, core 330; zero missing keys of 914 app / 287 core); `xcodebuild … build-for-testing` exit 0; `cf_swift.sh test ScreenRenderEvidenceTests` with the marker exit 0; `git diff --check` exit 0. - G2 step 4: no literal in `ui/Xcode/UITests/ChronoframeUITests.swift` or `A11yBaseline.json` matches a string M2 changed (the dedupe UI tests use identifiers, all kept); nothing edited. In the existing wide and compact scenarios the reviewed plan stays under the 96 free removals left, so `dedupeCommitButton` is still the commit control there. - G2 PNG sent to the owner. Rendered, not verified in the running app. +- 2026-11-28 WP-21 Done-when (orchestrator): `cf_swift.sh test` exit 0 for ChronoframeCoreFolderSizeEstimatorTests (6), ChronoframeCoreCopyPlanTests (14), PreferencesStoreTests (16), ModelAndServiceTests (14), ChronoframeCoreDryRunPlannerParityTests (16), FreeTestBatchPlannerTests (19), UITestWindowFitTests (9); `cf_swift.sh build` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0; `git diff --check` exit 0; extra: `cf_swift.sh suite` exit 0 (2670 passed, 0 failed) because the fresh-defaults layout changed. No strings, no existing assertions changed. Four stray `.tmp_*.log` files the implementer left in the repo root were removed by the orchestrator (created in this run, never committed). +- Noticed, not fixed (M3): `panelDirectoryURL(openingAt:)` does not apply the protected-media-library check that `initialPanelDirectoryURL` applies (unreachable from the guided places; C-22 does not ask for it). +- 2026-11-28 WP-22 Done-when (orchestrator): `cf_swift.sh test` exit 0 for GuidedSetupModelTests (10), SetupCoordinatorTests (40), AppStateTests (56), UITestWindowFitTests (10), AccessibilityTests (8), ScreenRenderEvidenceTests (7 run with marker, 7 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `script/check_detail_views_set_navigation_title.sh` exit 0; `git diff --check` exit 0. No existing assertions changed. +- Noticed, not fixed (M3): the guided destination step can show the previous destination's free-space figure for a moment after a new destination is chosen; with the guided screen latched, adding a source from the menu on the first question leaves the person on that question (a drop ends guided setup). +- 2026-11-28 WP-23 Done-when (orchestrator): `cf_swift.sh test` exit 0 for LayoutPictureModelTests (10), RunWorkspaceModelTests (30), RunTimelinePresentationTests (12), AccessibilityTests (8), RunOutcomeAccuracyTests (14), ScreenRenderEvidenceTests (8 run with marker, 8 PNGs); `cf_swift.sh build` exit 0; `script/check_no_raw_animations.sh` exit 0; `git diff --check` exit 0. +- For G3 step 4: `testRunPreviewReviewScenarioShowsTransferArtifactsAndTabs` (`ChronoframeUITests.swift:929–942`) asserts `openDestinationButton` and "Reports and Logs", which now sit behind the collapsed `runDetailsDisclosure` on a ready preview; the test must expand it first. `testTimelineSelectionUpdatesPreview` (~:1013–1040) still passes but its "clear button appears after selecting" step is now vacuous because a month is selected on arrival. +- Noticed, not fixed (M3): `TimelinePlurals.filesToCopy` is now unused in production (its test and catalog key remain); the timeline's existing caption "Every bar is a month of planned transfers waiting to land." is jargon; in the over-allowance fixture the selected month reads 2,420 while the card reads 212 (fixture histogram does not match its `newFilesByMonth`). +- 2026-11-28 WP-24: `add_translated_keys.py … Localizable.xcstrings … M3-app.json` exit 0 (added 36, kept 3); `… LocalizableCore.xcstrings … M3-core.json` exit 0 (added 0); `cf_swift.sh build` exit 0 after the symbol-collision fix; early German check exit 0 (app 1829, core 330; zero missing keys of 927 app / 287 core). German review: four corrections applied ("Apple Fotos", "ermittelt" twice, a verb in one heading). Docs: QUICK_START, FAQ, README, SAFETY_AND_RECOVERY; `git diff --check` exit 0. +- 2026-11-28 G3 commands (orchestrator), on `feature/first-run-guided`: `cf_swift.sh build` exit 0; `cf_swift.sh suite` exit 0 (2699 passed, 0 failed); `cf_swift.sh coverage` exit 0 (96.15%; FolderSizeEstimator 90.6%, the aggregate gate passes); `cf_swift.sh guards feature/first-run-duplicates` exit 0 (14 guards); `cf_swift.sh xcode` exit 0; `git diff --check` exit 0; `xcodebuild … SWIFT_EMIT_LOC_STRINGS=YES build` exit 0; `check_german_localization.py --baseline-ref origin/main …` exit 0 (app 1829, core 330; zero missing keys of 927 app / 287 core); `xcodebuild … build-for-testing` exit 0; `cf_swift.sh test ScreenRenderEvidenceTests` with the marker exit 0 (8 PNGs). Then the stack as one change against `origin/main`: `cf_swift.sh suite` exit 0 (2699 passed, 0 failed); `cf_swift.sh coverage` exit 0 (96.17%); `cf_swift.sh guards origin/main` exit 0 (14 guards); `cf_swift.sh xcode` exit 0; `script/check_agents_invariants_have_tests.sh` exit 0 (30 invariants); the German check above already uses the `origin/main` baseline. +- G3 step 4: one UI test edited (table above) so it opens the Details disclosure before looking for the report panel; compiled, not run. `testTimelineSelectionUpdatesPreview` left as is (still passes by reading; its "clear button appears after selecting" step is now vacuous). The accessibility baselines for `runPreviewReview`, `runCopyComplete` and the dedupe scenarios were not regenerated (owner row H-FRX-8 runs the UI suite). +- G3 PNGs sent to the owner. Rendered, not verified in the running app. - 2026-11-29 after G3: owner confirmed D-FRX-11 and D-FRX-25 and asked for B-1 option 1 (D-FRX-119). `fix/dedupe-planner-rail-protects-fanout` `2f8954f` from `origin/main`: red first (`cf_swift.sh test DeduplicationPlannerGroupRailTests` exit 1, 6 failures), then `cf_swift.sh test DeduplicationPlanner` exit 0 (11 tests), `coverage` exit 0 (2518 passed; 96.17%), `guards origin/main` exit 0 (14), `xcode` exit 0, `git diff --check` exit 0. Merged into `feature/first-run-duplicates`; the "not a guarantee" sentences in QUICK_START, FAQ, README and SAFETY_AND_RECOVERY now state the skip as a fact. - 2026-11-29: the planner fix changed two premise assertions in `ChronoframeCoreFreeDedupeBatchPlannerTests.testForcedKeepThatWouldUnskipAGroupStopsTheWalk` (`:266`, `:297`): the full plan and the Y+Z plan no longer contain `y1`, because a skipped group now stays whole. The trap the test covers (a forced Keep un-skips Y) and its `XCTAssertNil` are unchanged. `cf_swift.sh test ChronoframeCoreFreeDedupeBatchPlannerTests` exit 0 (13 tests). diff --git a/docs/plan/first-run-experience/strings/M3-app.json b/docs/plan/first-run-experience/strings/M3-app.json new file mode 100644 index 00000000..f1836698 --- /dev/null +++ b/docs/plan/first-run-experience/strings/M3-app.json @@ -0,0 +1,158 @@ +[ + { + "key": "Where are most of your photos?", + "de": "Wo liegen die meisten deiner Fotos?" + }, + { + "key": "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted.", + "de": "Wähle einen Ort für den Anfang. Weitere kannst du später hinzufügen. Chronoframe liest diesen Ort nur: Nichts darin wird verschoben, umbenannt oder gelöscht." + }, + { + "key": "Pictures Folder", + "de": "Ordner „Bilder“" + }, + { + "key": "Desktop", + "de": "Schreibtisch" + }, + { + "key": "Downloads", + "de": "Downloads" + }, + { + "key": "An External Drive", + "de": "Ein externes Laufwerk" + }, + { + "key": "Somewhere Else…", + "de": "Woanders…" + }, + { + "key": "My photos are in the Apple Photos app", + "de": "Meine Fotos sind in Apple Fotos" + }, + { + "key": "Where should the organized copy go?", + "de": "Wohin soll die organisierte Kopie kommen?" + }, + { + "key": "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are.", + "de": "Chronoframe erstellt dort eine neue, organisierte Kopie. Deine Originale bleiben genau dort, wo sie sind." + }, + { + "key": "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed.", + "de": "Chronoframe kopiert deine Fotos aus Apple Fotos in diesen Ordner. Deine Fotos-Mediathek wird nie verändert." + }, + { + "key": "Measuring your folder…", + "de": "Die Größe deines Ordners wird ermittelt…" + }, + { + "key": "Your folder holds about %@ in %@.", + "de": "Dein Ordner enthält etwa %1$@ in %2$@." + }, + { + "key": "Your folder holds at least %@.", + "de": "Dein Ordner enthält mindestens %@." + }, + { + "key": "Chronoframe could not measure this folder. Space is checked again before copying.", + "de": "Chronoframe konnte die Größe dieses Ordners nicht ermitteln. Der Speicherplatz wird vor dem Kopieren erneut geprüft." + }, + { + "key": "Choose a Folder…", + "de": "Ordner wählen…" + }, + { + "key": "Free space on this drive is unknown.", + "de": "Der freie Speicherplatz auf diesem Laufwerk ist unbekannt." + }, + { + "key": "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out.", + "de": "Hier sind %1$@ frei, und dein Ordner enthält etwa %2$@. Möglicherweise passt nicht alles. Wähle ein größeres Laufwerk oder fahre fort: Der Kopiervorgang pausiert sicher, wenn der Speicherplatz ausgeht." + }, + { + "key": "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts).", + "de": "Hier sind %1$@ frei. Das reicht für etwa %2$@ (Schätzung, wird beim Start des Kopiervorgangs erneut geprüft)." + }, + { + "key": "%@ free here.", + "de": "Hier sind %@ frei." + }, + { + "key": "Look at My Photos", + "de": "Meine Fotos ansehen" + }, + { + "key": "Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read.", + "de": "In diesem Schritt wird nichts kopiert. Das Einlesen einer sehr großen Sammlung kann 5 bis 15 Minuten dauern." + }, + { + "key": "Choose Photos to Copy", + "de": "Fotos zum Kopieren auswählen" + }, + { + "key": "Back", + "de": "Zurück" + }, + { + "key": "Use the full setup screen", + "de": "Vollständige Einrichtung verwenden" + }, + { + "key": "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", + "de": "Chronoframe liest nur. Es wird noch nichts kopiert, und du kannst deinen Mac weiterverwenden." + }, + { + "key": "%@: %@ photos and videos", + "de": "%1$@: %2$@ Fotos und Videos" + }, + { + "key": "%@: 1 photo or video", + "de": "%@: 1 Foto oder Video" + }, + { + "key": "A sample from this month.", + "de": "Eine Auswahl aus diesem Monat." + }, + { + "key": "How your library will be arranged", + "de": "So wird deine Mediathek angeordnet" + }, + { + "key": "You can change this later with Reorganize, which needs the unlock.", + "de": "Du kannst das später mit „Neu strukturieren“ ändern. Dafür ist die Freischaltung nötig." + }, + { + "key": "%@ exact copies go to a separate Duplicate folder.", + "de": "%@ identische Kopien kommen in einen separaten Ordner Duplicate." + }, + { + "key": "1 exact copy goes to a separate Duplicate folder.", + "de": "1 identische Kopie kommt in einen separaten Ordner Duplicate." + }, + { + "key": "Layout: %@. Change it in Settings.", + "de": "Struktur: %@. Ändere sie in den Einstellungen." + }, + { + "key": "One folder for each day", + "de": "Ein Ordner für jeden Tag" + }, + { + "key": "one folder per day", + "de": "ein Ordner pro Tag" + }, + { + "key": "%@ folders", + "de": "%@ Ordner" + }, + { + "key": "1 folder", + "de": "1 Ordner" + }, + { + "key": "Details", + "de": "Details" + } +] diff --git a/docs/plan/first-run-experience/strings/M3-core.json b/docs/plan/first-run-experience/strings/M3-core.json new file mode 100644 index 00000000..fe51488c --- /dev/null +++ b/docs/plan/first-run-experience/strings/M3-core.json @@ -0,0 +1 @@ +[] diff --git a/docs/plan/next-half/README.md b/docs/plan/next-half/README.md index 5b741d8a..ad5e2c9d 100644 --- a/docs/plan/next-half/README.md +++ b/docs/plan/next-half/README.md @@ -14,7 +14,7 @@ Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as | 3a | [`clear-path/`](../clear-path/) | `feature/clear-path` | `feature/photos-import-resume` (stacked, D-CLP-01) | `CLP` | UX review 2026-11-12 — plain-language Organize and Deduplicate flow, several folders at once | shipped in #269, follow-up #274 | | 4 | [`find-and-account/`](../find-and-account/) | `feature/find-and-account` | `main` after #3 merges | `FAA` | 4 — item-level reconciliation and original-name lookup | not started | | 5 | [`first-ten-minutes/`](../first-ten-minutes/) | `feature/first-ten-minutes` | `main` after #4 merges | `FTM` | 5 — preflight, free batch, proof | superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | -| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | in progress, not merged | +| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | built, not merged | Each plan is self-contained: `CONTRACTS.md`, `DECISIONS.md`, `IMPLEMENTATION_PLAN.md`, `PROGRESS.md`, `ACCEPTANCE_MATRIX.md`, `BLOCKED.md`, `EVIDENCE_LEDGER.md`. Shared files live here: [`AGENT_RULES.md`](AGENT_RULES.md), [`bin/cf_swift.sh`](bin/cf_swift.sh), [`ORCHESTRATOR_KICKOFF.md`](ORCHESTRATOR_KICKOFF.md), [`claude-config/`](claude-config/) (install into the gitignored `.claude/`). diff --git a/script/swift_meaningful_coverage.sh b/script/swift_meaningful_coverage.sh index dd140822..f6d89a6f 100755 --- a/script/swift_meaningful_coverage.sh +++ b/script/swift_meaningful_coverage.sh @@ -77,6 +77,7 @@ MEANINGFUL_BASENAMES=( FreeMonthBatchPlanner DeduplicateReviewLane FreeDedupeBatchPlanner + FolderSizeEstimator CopyPlanBuilder DryRunPlanner EditedVariantDestinations diff --git a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift index a961ad48..bb43f2ad 100644 --- a/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift +++ b/ui/Sources/ChronoframeApp/App/AccessibilityIdentifiers.swift @@ -48,6 +48,12 @@ enum AccessibilityIdentifiers { static let runOutcomeAddFolder = "runOutcomeAddFolder" static let runOutcomeUnlockRest = "runOutcomeUnlockRest" static let runPreviewSummary = "run.preview.summary" + static let runDetailsDisclosure = "runDetailsDisclosure" + /// `layoutPicture.` for the three offered layouts. + static func layoutPicture(_ rawValue: String) -> String { "layoutPicture.\(rawValue)" } + static let layoutPictureYearMonth = layoutPicture("YYYY/MM") + static let layoutPictureYearMonthDay = layoutPicture("YYYY/MM/DD") + static let layoutPictureYear = layoutPicture("YYYY") static let runNextStepCard = "run.nextStep.card" static let runNextStepFindDuplicates = "run.nextStep.findDuplicates" static let previewReviewFilter = "previewReviewFilter" @@ -148,6 +154,22 @@ enum AccessibilityIdentifiers { ] } + // MARK: - Guided setup + + /// Identifiers for the guided first-run setup. The place buttons are keyed by + /// `GuidedSourcePlace.rawValue`. + enum Guided { + static func source(_ place: GuidedSourcePlace) -> String { "guided.source.\(place.rawValue)" } + static let sourceApplePhotos = "guided.source.applePhotos" + static let destinationChoose = "guided.destination.choose" + static let start = "guided.start" + static let useFullSetup = "guided.useFullSetup" + + static let all: [String] = GuidedSourcePlace.allCases.map { source($0) } + [ + sourceApplePhotos, destinationChoose, start, useFullSetup, + ] + } + // MARK: - Free trial static let trialIndicatorOrganize = "trialIndicator.organize" @@ -192,6 +214,7 @@ enum AccessibilityIdentifiers { runWorkspaceTabs, runIdleOnboardingCard, runOutcomeSummaryCard, runOutcomeUndoCopy, runOutcomeAddFolder, runOutcomeUnlockRest, runPreviewSummary, previewReviewFilter, + runDetailsDisclosure, layoutPictureYearMonth, layoutPictureYearMonthDay, layoutPictureYear, refreshLibraryHealthButton, reorganizeDestinationButton, dedupeAcceptAllSuggestionsButton, dedupeAcceptClusterSuggestionButton, dedupeAcceptHighConfidenceButton, dedupeCancelCommitButton, dedupeChangeFolderButton, @@ -208,5 +231,5 @@ enum AccessibilityIdentifiers { activeProfileBadge, trialIndicatorOrganize, trialIndicatorDedupe, diagnosticsLogBufferStepper, smartEventSuggestionsToggle, - ] + NAS.all + ] + NAS.all + Guided.all } diff --git a/ui/Sources/ChronoframeApp/App/AppState.swift b/ui/Sources/ChronoframeApp/App/AppState.swift index 89964fac..cb998e91 100644 --- a/ui/Sources/ChronoframeApp/App/AppState.swift +++ b/ui/Sources/ChronoframeApp/App/AppState.swift @@ -59,6 +59,9 @@ final class AppState: ObservableObject { private let droppedItemStager: DroppedItemStager private let showSettingsWindowAction: @MainActor () -> Void private let volumeClassifier: NASVolumeClassifier + /// Whether Choose Folders may open as the two-question guided setup. UI-test scenarios that + /// show another screen turn it off. + let guidedSetupEligible: Bool /// Keeps the trial status in step with the entitlement (T16). private var trialStatusObservation: AnyCancellable? /// Writes a pending Deduplicate review save before the app quits. @@ -243,6 +246,7 @@ final class AppState: ObservableObject { entitlementStore: EntitlementStore? = nil, trialEntitlementResolver: (@MainActor () async -> TrialEntitlementSnapshot)? = nil, volumeClassifier: NASVolumeClassifier = .live, + guidedSetupEligible: Bool = true, showSettingsWindowAction: @escaping @MainActor () -> Void = { NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil) } @@ -287,6 +291,7 @@ final class AppState: ObservableObject { self.droppedItemStager = droppedItemStager self.showSettingsWindowAction = showSettingsWindowAction self.volumeClassifier = volumeClassifier + self.guidedSetupEligible = guidedSetupEligible self.previewReviewStore.setDestinationScopeProvider { [weak self] destinationRoot in self?.destinationSecurityScope(destinationRoot: destinationRoot) } @@ -396,6 +401,13 @@ final class AppState: ObservableObject { await setupCoordinator.chooseSourceFolder() } + /// Opens the picker at `directory` (nil: the default start) and, when a folder is chosen, makes it the one source folder. True when chosen. + @discardableResult + func chooseSourceFolder(openingAt directory: URL?) async -> Bool { + runCoordinator.invalidateWatchedImportContext() + return await setupCoordinator.chooseSourceFolder(openingAt: directory) + } + func addSourceItems(_ urls: [URL]) async { runCoordinator.invalidateWatchedImportContext() await setupCoordinator.addSourceItems(urls) diff --git a/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift b/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift index e267ee33..d59e8e94 100644 --- a/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift +++ b/ui/Sources/ChronoframeApp/App/Coordinators/SetupCoordinator.swift @@ -80,6 +80,27 @@ final class SetupCoordinator { await addSourceItems(chosen) } + /// Guided setup's single-folder choice. The panel opens at `directory` (nil: the default start); a + /// chosen folder goes through the same validation and bookmark path as every other source and becomes + /// the one source folder. True only when that folder is now the source. + func chooseSourceFolder(openingAt directory: URL?) async -> Bool { + let prompt = "Choose This Folder" + let chosen: URL? + if let directory { + chosen = folderAccessService.chooseFolder(openingAt: directory, prompt: prompt) + } else { + chosen = folderAccessService.chooseFolder(startingAt: nil, prompt: prompt) + } + guard let chosen else { + return false + } + + await selectSourceFolder(chosen) + let items = setupStore.sourceItems + return items.count == 1 + && items[0].resolvingSymlinksInPath().path == chosen.resolvingSymlinksInPath().path + } + func addSourceItems(_ urls: [URL]) async { _ = await addSourceItemsReportingApplied(urls) } diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift index 9a19e8f4..0c827d3e 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestAppStateFactory.swift @@ -33,6 +33,8 @@ enum UITestAppStateFactory { defaults.removePersistentDomain(forName: suiteName) let preferencesStore = PreferencesStore(defaults: defaults) + // New installs default to Year/Month; every existing scenario keeps the layout its screens were built with. + preferencesStore.folderStructure = .yyyyMMDD let setupStore = SetupStore() let runLogStore = RunLogStore(capacity: 500) let repository = MockProfilesRepository() @@ -191,6 +193,12 @@ enum UITestAppStateFactory { engine = previewReviewEngine(sourcePath: setupStore.sourcePath, destinationPath: setupStore.destinationPath) route = .organize(.setup) + case .guidedFirstRun: + // A person with nothing configured: empty stores, so the guided setup shows. + historyStore = HistoryStore() + engine = previewReviewEngine(sourcePath: "", destinationPath: "") + route = .organize(.setup) + case .deduplicateReviewWide, .deduplicateReviewCompact, .deduplicateReviewLanes: setupStore.destinationPath = "/Volumes/Archive/Chronoframe Library" historyStore = HistoryStore(destinationRoot: setupStore.destinationPath) @@ -260,6 +268,7 @@ enum UITestAppStateFactory { isAppStoreChannel: scenario.usesMeteredTrialUI, entitlementStore: trialFixture?.entitlementStore, trialEntitlementResolver: trialEntitlementResolver, + guidedSetupEligible: scenario == .guidedFirstRun, showSettingsWindowAction: showSettingsWindowAction ) appStateBox.value = appState diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift index 0532a479..079c2f1b 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestDoubles.swift @@ -197,6 +197,14 @@ final class MockFolderAccessService: FolderAccessServicing { return nextChosenFolder } + /// Every `chooseFolder(openingAt:prompt:)` request, in call order. + var openingAtCalls: [(directory: URL, prompt: String)] = [] + + func chooseFolder(openingAt directory: URL, prompt: String) -> URL? { + openingAtCalls.append((directory: directory, prompt: prompt)) + return nextChosenFolder + } + var nextChosenFolders: [URL] = [] func chooseFolders(startingAt path: String?, prompt: String) -> [URL] { diff --git a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift index f6d41661..296abe06 100644 --- a/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift +++ b/ui/Sources/ChronoframeApp/App/UITesting/UITestScenario.swift @@ -23,6 +23,7 @@ enum UITestScenario: String, CaseIterable { case deduplicateReviewWide case deduplicateReviewCompact case deduplicateReviewLanes + case guidedFirstRun static func current( environment: [String: String] = ProcessInfo.processInfo.environment, @@ -77,7 +78,7 @@ enum UITestScenario: String, CaseIterable { return NSSize(width: 1360, height: 920) case .settingsSections, .settingsLayout, .settingsPerformance, .settingsDeduplicate, .settingsLicense, .settingsDiagnostics: return NSSize(width: 1360, height: 920) - case .deduplicateReviewWide, .deduplicateReviewLanes: + case .deduplicateReviewWide, .deduplicateReviewLanes, .guidedFirstRun: return NSSize(width: 1180, height: 820) case .deduplicateReviewCompact: return NSSize(width: 900, height: 700) diff --git a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings index f5fa282a..90c6f0aa 100644 --- a/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings +++ b/ui/Sources/ChronoframeApp/Resources/Localizable.xcstrings @@ -282,6 +282,74 @@ } } }, + "%@ exact copies go to a separate Duplicate folder." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ identische Kopien kommen in einen separaten Ordner Duplicate." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ exact copies go to a separate Duplicate folder." + } + } + } + }, + "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hier sind %1$@ frei, und dein Ordner enthält etwa %2$@. Möglicherweise passt nicht alles. Wähle ein größeres Laufwerk oder fahre fort: Der Kopiervorgang pausiert sicher, wenn der Speicherplatz ausgeht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out." + } + } + } + }, + "%@ free here." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hier sind %@ frei." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ free here." + } + } + } + }, + "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts)." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hier sind %1$@ frei. Das reicht für etwa %2$@ (Schätzung, wird beim Start des Kopiervorgangs erneut geprüft)." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts)." + } + } + } + }, "%@ groups have every photo marked Delete. Chronoframe skips a group when nothing in it is kept. Mark one Keep in each to include them." : { "extractionState" : "manual", "localizations" : { @@ -564,6 +632,38 @@ } } }, + "%@: %@ photos and videos" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%1$@: %2$@ Fotos und Videos" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: %@ photos and videos" + } + } + } + }, + "%@: 1 photo or video" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: 1 Foto oder Video" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@: 1 photo or video" + } + } + } + }, "%@s" : { "comment" : "A label displaying the time window for burst mode. The value is automatically updated to reflect the user's selection.", "isCommentAutoGenerated" : true, @@ -758,6 +858,23 @@ } } }, + "1 exact copy goes to a separate Duplicate folder." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 identische Kopie kommt in einen separaten Ordner Duplicate." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "1 exact copy goes to a separate Duplicate folder." + } + } + } + }, "1 file changed, so its choice was cleared." : { "extractionState" : "manual", "localizations" : { @@ -1297,6 +1414,23 @@ } } }, + "A sample from this month." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Eine Auswahl aus diesem Monat." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "A sample from this month." + } + } + } + }, "A saved profile holds one folder. Keep this list as it is (Chronoframe remembers it), or remove the extra folders to save a profile." : { "extractionState" : "manual", "localizations" : { @@ -2041,6 +2175,23 @@ } } }, + "An External Drive" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ein externes Laufwerk" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "An External Drive" + } + } + } + }, "An import was interrupted." : { "extractionState" : "manual", "localizations" : { @@ -2300,6 +2451,23 @@ } } }, + "Back" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Zurück" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Back" + } + } + } + }, "Before you start" : { "extractionState" : "manual", "localizations" : { @@ -2520,6 +2688,23 @@ } } }, + "Choose a Folder…" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ordner wählen…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose a Folder…" + } + } + } + }, "Choose Another Month" : { "extractionState" : "manual", "localizations" : { @@ -2657,6 +2842,23 @@ } } }, + "Choose Photos to Copy" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Fotos zum Kopieren auswählen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Choose Photos to Copy" + } + } + } + }, "Choose the folders or the destination again so macOS refreshes access." : { "extractionState" : "manual", "localizations" : { @@ -2841,6 +3043,40 @@ } } }, + "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe erstellt dort eine neue, organisierte Kopie. Deine Originale bleiben genau dort, wo sie sind." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." + } + } + } + }, + "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe kopiert deine Fotos aus Apple Fotos in diesen Ordner. Deine Fotos-Mediathek wird nie verändert." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." + } + } + } + }, "Chronoframe could not finish. Your original files were left untouched." : { "extractionState" : "manual", "localizations" : { @@ -2875,6 +3111,23 @@ } } }, + "Chronoframe could not measure this folder. Space is checked again before copying." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe konnte die Größe dieses Ordners nicht ermitteln. Der Speicherplatz wird vor dem Kopieren erneut geprüft." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe could not measure this folder. Space is checked again before copying." + } + } + } + }, "Chronoframe couldn't save that choice. Your library and the assessment weren't changed. Try again." : { "extractionState" : "manual", "localizations" : { @@ -3001,6 +3254,23 @@ } } }, + "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe liest nur. Es wird noch nichts kopiert, und du kannst deinen Mac weiterverwenden." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac." + } + } + } + }, "Chronoframe moved the files in your organized library into the new folder layout." : { "extractionState" : "manual", "localizations" : { @@ -3985,6 +4255,23 @@ } } }, + "Desktop" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Schreibtisch" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Desktop" + } + } + } + }, "Destination Folder" : { "extractionState" : "manual", "localizations" : { @@ -4291,6 +4578,23 @@ } } }, + "Downloads" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Downloads" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Downloads" + } + } + } + }, "Drag folders onto the window or click Add Folders. Chronoframe only reads them — nothing is moved." : { "extractionState" : "manual", "localizations" : { @@ -5063,6 +5367,23 @@ } } }, + "Free space on this drive is unknown." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Der freie Speicherplatz auf diesem Laufwerk ist unbekannt." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Free space on this drive is unknown." + } + } + } + }, "From" : { "extractionState" : "manual", "localizations" : { @@ -5449,6 +5770,23 @@ } } }, + "How your library will be arranged" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "So wird deine Mediathek angeordnet" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "How your library will be arranged" + } + } + } + }, "Identical copies" : { "extractionState" : "manual", "localizations" : { @@ -5764,6 +6102,23 @@ } } }, + "Layout: %@. Change it in Settings." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Struktur: %@. Ändere sie in den Einstellungen." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Layout: %@. Change it in Settings." + } + } + } + }, "Library" : { "extractionState" : "manual", "localizations" : { @@ -5885,6 +6240,23 @@ } } }, + "Look at My Photos" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Meine Fotos ansehen" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Look at My Photos" + } + } + } + }, "Look-alikes" : { "extractionState" : "manual", "localizations" : { @@ -5931,6 +6303,23 @@ } } }, + "Measuring your folder…" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Die Größe deines Ordners wird ermittelt…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Measuring your folder…" + } + } + } + }, "More worker threads can improve throughput on faster storage. Parallel copies let several files copy at once and only affect future copies." : { "extractionState" : "manual", "localizations" : { @@ -6093,6 +6482,23 @@ } } }, + "My photos are in the Apple Photos app" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Meine Fotos sind in Apple Fotos" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "My photos are in the Apple Photos app" + } + } + } + }, "Needs attention" : { "extractionState" : "manual", "localizations" : { @@ -6558,6 +6964,23 @@ } } }, + "Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "In diesem Schritt wird nichts kopiert. Das Einlesen einer sehr großen Sammlung kann 5 bis 15 Minuten dauern." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read." + } + } + } + }, "Nothing is removed until you approve it." : { "extractionState" : "manual", "localizations" : { @@ -6741,6 +7164,40 @@ } } }, + "One folder for each day" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ein Ordner für jeden Tag" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "One folder for each day" + } + } + } + }, + "one folder per day" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "ein Ordner pro Tag" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "one folder per day" + } + } + } + }, "One more step" : { "extractionState" : "manual", "localizations" : { @@ -7304,6 +7761,23 @@ } } }, + "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Wähle einen Ort für den Anfang. Weitere kannst du später hinzufügen. Chronoframe liest diesen Ort nur: Nichts darin wird verschoben, umbenannt oder gelöscht." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." + } + } + } + }, "Pick up where you left off" : { "extractionState" : "manual", "localizations" : { @@ -7321,6 +7795,23 @@ } } }, + "Pictures Folder" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ordner „Bilder“" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Pictures Folder" + } + } + } + }, "Preferences" : { "extractionState" : "manual", "localizations" : { @@ -9282,6 +9773,23 @@ } } }, + "Somewhere Else…" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Woanders…" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Somewhere Else…" + } + } + } + }, "Source Folder" : { "extractionState" : "manual", "localizations" : { @@ -10475,6 +10983,23 @@ } } }, + "Use the full setup screen" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Vollständige Einrichtung verwenden" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Use the full setup screen" + } + } + } + }, "Verification re-checks each copied file after it is copied. It adds work, but it provides stronger confidence that destination files match the originals." : { "extractionState" : "manual", "localizations" : { @@ -10854,6 +11379,40 @@ } } }, + "Where are most of your photos?" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Wo liegen die meisten deiner Fotos?" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Where are most of your photos?" + } + } + } + }, + "Where should the organized copy go?" : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Wohin soll die organisierte Kopie kommen?" + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Where should the organized copy go?" + } + } + } + }, "Where the organized copies go." : { "extractionState" : "manual", "localizations" : { @@ -10978,6 +11537,23 @@ } } }, + "You can change this later with Reorganize, which needs the unlock." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Du kannst das später mit „Neu strukturieren“ ändern. Dafür ist die Freischaltung nötig." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "You can change this later with Reorganize, which needs the unlock." + } + } + } + }, "You can copy %1$@ free. This plan has %2$@." : { "extractionState" : "manual", "localizations" : { @@ -11165,6 +11741,40 @@ } } }, + "Your folder holds about %@ in %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dein Ordner enthält etwa %1$@ in %2$@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your folder holds about %@ in %@." + } + } + } + }, + "Your folder holds at least %@." : { + "extractionState" : "manual", + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Dein Ordner enthält mindestens %@." + } + }, + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Your folder holds at least %@." + } + } + } + }, "Your folders will appear here once you choose them." : { "extractionState" : "manual", "localizations" : { diff --git a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift index 936a829d..845e3c7d 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/CurrentRunView.swift @@ -69,6 +69,10 @@ struct CurrentRunView: View { } else { RunTimelineView(model: model) + if model.context.status == .dryRunFinished { + RunLayoutPictureSection(model: model, appState: appState) + } + if showsNowCopying { NowCopyingCard(model: model) } diff --git a/ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift b/ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift new file mode 100644 index 00000000..d82604c4 --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Run/LayoutPictureModel.swift @@ -0,0 +1,113 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// One selectable picture of how the new files would be arranged (C-25). +struct LayoutPictureCard: Equatable, Identifiable { + var id: FolderStructure { structure } + let structure: FolderStructure + let title: String // FolderLayoutPresentation.title(structure) + let lines: [String] // real folders, newest first, at most 6 lines, e.g. "2026/", " 10/ · 212", " 09/ · 148" + let footer: String // .yyyy "{years} folders"; .yyyyMM "{months} folders"; .yyyyMMDD "One folder for each day" + let isSelected: Bool +} + +/// Builds the folder pictures from `RunMetrics.newFilesByMonth`: new files that +/// land in each month folder, sidecars included. The histogram is not used +/// because its counts include exact copies, which go to the Duplicate folder. +enum LayoutPictureModel { + static let offered: [FolderStructure] = [.yyyyMM, .yyyyMMDD, .yyyy] + + private static let maxLines = 6 + + static func cards(newFilesByMonth: [String: Int], selected: FolderStructure) -> [LayoutPictureCard] { + let months = datedMonths(newFilesByMonth) + guard !months.isEmpty else { return [] } + + return offered.map { structure in + LayoutPictureCard( + structure: structure, + title: FolderLayoutPresentation.title(structure), + lines: lines(for: structure, months: months), + footer: footer(for: structure, months: months), + isSelected: structure == selected + ) + } + } + + // MARK: - Private + + private struct Month { + let year: String + let month: String + let count: Int + } + + /// Dated months, newest first. Undated keys ("Unknown") and empty months are left out. + private static func datedMonths(_ newFilesByMonth: [String: Int]) -> [Month] { + newFilesByMonth.compactMap { key, count -> Month? in + let parts = key.split(separator: "-", omittingEmptySubsequences: false) + guard count > 0, + parts.count == 2, + parts[0].count == 4, parts[0].allSatisfy(\.isNumber), + parts[1].count == 2, let monthNumber = Int(parts[1]), (1...12).contains(monthNumber) + else { return nil } + return Month(year: String(parts[0]), month: String(parts[1]), count: count) + } + .sorted { ($0.year, $0.month) > ($1.year, $1.month) } + } + + private static func lines(for structure: FolderStructure, months: [Month]) -> [String] { + var result: [String] = [] + switch structure { + case .yyyy: + var yearTotals: [(year: String, count: Int)] = [] + for month in months { + if let last = yearTotals.last, last.year == month.year { + yearTotals[yearTotals.count - 1].count += month.count + } else { + yearTotals.append((month.year, month.count)) + } + } + result = yearTotals.map { "\($0.year)/ · \($0.count.formatted())" } + case .yyyyMM, .yyyyMMDD: + var currentYear: String? + var addedDayLine = false + for month in months { + if month.year != currentYear { + result.append("\(month.year)/") + currentYear = month.year + } + result.append(" \(month.month)/ · \(month.count.formatted())") + // One third-level line under the newest month is enough to show the shape. + if structure == .yyyyMMDD, !addedDayLine { + result.append(" " + AppLocalization.string("one folder per day")) + addedDayLine = true + } + } + case .yyyyMonEvent, .flat: + break + } + return Array(result.prefix(maxLines)) + } + + private static func footer(for structure: FolderStructure, months: [Month]) -> String { + switch structure { + case .yyyyMMDD: + return AppLocalization.string("One folder for each day") + case .yyyyMM: + return folderCount(months.count) + case .yyyy: + return folderCount(Set(months.map(\.year)).count) + case .yyyyMonEvent, .flat: + return "" + } + } + + private static func folderCount(_ count: Int) -> String { + count == 1 + ? AppLocalization.string("1 folder") + : AppLocalization.format("%@ folders", count.formatted()) + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift b/ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift new file mode 100644 index 00000000..2e4bcf15 --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Run/RunLayoutPictureSection.swift @@ -0,0 +1,171 @@ +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import SwiftUI + +/// The folder picture on a ready preview (C-25): how the new files will be +/// arranged, with real counts, in three layouts the person can pick between. +/// +/// Choosing a card only changes the folder-layout preference and re-runs the +/// preview (D-FRX-18). Nothing is copied, and the source is never written. +struct RunLayoutPictureSection: View { + let model: RunWorkspaceModel + let appState: AppState + @ObservedObject private var preferencesStore: PreferencesStore + @ObservedObject private var runSessionStore: RunSessionStore + @ObservedObject private var deduplicateSessionStore: DeduplicateSessionStore + + init(model: RunWorkspaceModel, appState: AppState) { + self.model = model + self.appState = appState + self._preferencesStore = ObservedObject(wrappedValue: appState.preferencesStore) + self._runSessionStore = ObservedObject(wrappedValue: appState.runSessionStore) + self._deduplicateSessionStore = ObservedObject(wrappedValue: appState.deduplicateSessionStore) + } + + private var metrics: RunMetrics { model.context.metrics } + + /// A watched-source or Apple Photos import preview. Rebuilding the preview + /// from Setup would discard that import, so no card is offered for it. + private var hasActiveImport: Bool { + appState.hasActiveWatchedImport || appState.hasActivePhotosImport + } + + private var canChooseLayout: Bool { + !runSessionStore.isRunning && !deduplicateSessionStore.isWorking + } + + var body: some View { + let cards = LayoutPictureModel.cards( + newFilesByMonth: metrics.newFilesByMonth, + selected: preferencesStore.folderStructure + ) + if !metrics.newFilesByMonth.isEmpty { + DarkroomPanel(variant: .panel) { + VStack(alignment: .leading, spacing: DesignTokens.Spacing.md) { + Text("How your library will be arranged") + .scaledFont(.cardTitle) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + + if let line = Self.layoutLine( + for: preferencesStore.folderStructure, + hasActiveImport: hasActiveImport + ) { + Text(line) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + } else { + HStack(alignment: .top, spacing: DesignTokens.Spacing.md) { + ForEach(cards) { card in + cardButton(card) + } + } + } + + VStack(alignment: .leading, spacing: 4) { + Text("You can change this later with Reorganize, which needs the unlock.") + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) + .fixedSize(horizontal: false, vertical: true) + + if metrics.duplicateCount > 0 { + Text(Self.duplicateCaption(count: metrics.duplicateCount)) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) + .fixedSize(horizontal: false, vertical: true) + } + } + } + } + } + } + + private func cardButton(_ card: LayoutPictureCard) -> some View { + Button { + let chosen = card.structure + guard Self.shouldRestartPreview( + current: preferencesStore.folderStructure, + chosen: chosen, + isRunning: runSessionStore.isRunning, + isDedupeWorking: deduplicateSessionStore.isWorking, + hasActiveImport: hasActiveImport, + canStartPreview: appState.canStartRun + ) else { return } + preferencesStore.folderStructure = chosen + Task { await appState.startPreview() } + } label: { + VStack(alignment: .leading, spacing: 6) { + Text(card.title) + .scaledFont(.subtitle, weight: .bold) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + + VStack(alignment: .leading, spacing: 2) { + ForEach(Array(card.lines.enumerated()), id: \.offset) { _, line in + Text(line) + .scaledFont(.mono) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .lineLimit(1) + } + } + + Text(card.footer) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(DesignTokens.Spacing.md) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(DesignTokens.ColorSystem.imageStage.opacity(0.4)) + ) + .overlay { + RoundedRectangle(cornerRadius: 8, style: .continuous) + .strokeBorder( + card.isSelected ? DesignTokens.ColorSystem.accentWaypoint : DesignTokens.ColorSystem.hairline, + lineWidth: card.isSelected ? 2 : 1 + ) + } + .contentShape(RoundedRectangle(cornerRadius: 8, style: .continuous)) + } + .buttonStyle(.plain) + .disabled(!canChooseLayout) + .accessibilityIdentifier(AccessibilityIdentifiers.layoutPicture(card.structure.rawValue)) + .accessibilityAddTraits(card.isSelected ? .isSelected : []) + } + + // MARK: - Pure helpers + + /// True only when choosing `chosen` will really rebuild the preview, so the + /// preference is never changed under a preview that stays as it was: a + /// different layout, no run or duplicate cleanup in progress, no import + /// preview (which a Setup preview would discard), and the same readiness + /// `AppState.startPreview()` itself requires (`canStartPreview`). + static func shouldRestartPreview( + current: FolderStructure, + chosen: FolderStructure, + isRunning: Bool, + isDedupeWorking: Bool, + hasActiveImport: Bool, + canStartPreview: Bool + ) -> Bool { + chosen != current && !isRunning && !isDedupeWorking && !hasActiveImport && canStartPreview + } + + /// `Layout: {title}. Change it in Settings.` for the layouts the picture does + /// not offer, and for any layout while an import preview is shown; `nil` + /// when the cards are offered. + static func layoutLine(for structure: FolderStructure, hasActiveImport: Bool = false) -> String? { + guard hasActiveImport || !LayoutPictureModel.offered.contains(structure) else { return nil } + return AppLocalization.format("Layout: %@. Change it in Settings.", FolderLayoutPresentation.title(structure)) + } + + /// `{duplicateCount} exact copies go to a separate Duplicate folder.` + static func duplicateCaption(count: Int) -> String { + count == 1 + ? AppLocalization.string("1 exact copy goes to a separate Duplicate folder.") + : AppLocalization.format("%@ exact copies go to a separate Duplicate folder.", count.formatted()) + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift index 07a9b4e5..98503f5b 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunSectionViews.swift @@ -447,6 +447,7 @@ struct RunWorkspaceShell: View { @Binding var workspaceTab: RunWorkspaceTab let appState: AppState @ObservedObject var previewReviewStore: PreviewReviewStore + @State private var showsOverviewDetails = false var body: some View { MeridianSurfaceCard(style: .section) { @@ -479,21 +480,44 @@ struct RunWorkspaceShell: View { } } + private var overviewPanels: some View { + ViewThatFits(in: .horizontal) { + HStack(alignment: .top, spacing: 16) { + RunSnapshotPanel(model: model) + RunArtifactsPanel(model: model, appState: appState) + } + + VStack(alignment: .leading, spacing: 16) { + RunSnapshotPanel(model: model) + RunArtifactsPanel(model: model, appState: appState) + } + } + } + @ViewBuilder private var workspaceContent: some View { switch workspaceTab { case .overview: VStack(alignment: .leading, spacing: 16) { - ViewThatFits(in: .horizontal) { - HStack(alignment: .top, spacing: 16) { - RunSnapshotPanel(model: model) - RunArtifactsPanel(model: model, appState: appState) - } - - VStack(alignment: .leading, spacing: 16) { - RunSnapshotPanel(model: model) - RunArtifactsPanel(model: model, appState: appState) + if model.context.status == .dryRunFinished { + // A ready preview leads with the photos and the folder + // picture; the technical panels stay one click away. + DisclosureGroup(isExpanded: $showsOverviewDetails) { + overviewPanels + .padding(.top, DesignTokens.Spacing.sm) + } label: { + // The whole row opens it, not only the small triangle. + Text("Details") + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + .onTapGesture { showsOverviewDetails.toggle() } } + // `.contain` first: an identifier on a bare container + // replaces the identifiers of everything inside it. + .accessibilityElement(children: .contain) + .accessibilityIdentifier(AccessibilityIdentifiers.runDetailsDisclosure) + } else { + overviewPanels } } case .review: diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift b/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift index d8abe5ce..ae353778 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunTimelineView.swift @@ -18,6 +18,9 @@ struct RunTimelineView: View { @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var selectedBucketKey: String? = nil @State private var isScrubbing = false + /// Set once the ready preview has been given its starting selection, so a + /// later deselection or choice by the person is never overridden. + @State private var didApplyDefaultSelection = false private let chartHeight: CGFloat = 136 private let minBarHeight: CGFloat = 3 @@ -62,6 +65,44 @@ struct RunTimelineView: View { .fixedSize(horizontal: false, vertical: true) } } + .onAppear { applyDefaultSelectionIfNeeded() } + .onChange(of: model.context.status) { _, _ in applyDefaultSelectionIfNeeded() } + .onChange(of: buckets) { _, _ in applyDefaultSelectionIfNeeded() } + } + + // MARK: - Default selection + + /// The newest dated bucket, chosen once when the preview is ready and nothing + /// is selected, so its photos are visible on arrival. Never `Unknown`. + static func defaultSelectionKey( + buckets: [DateHistogramBucket], + status: RunStatus, + selectedKey: String? + ) -> String? { + guard status == .dryRunFinished, selectedKey == nil else { return nil } + return buckets.map(\.key).filter { $0 != "Unknown" }.max() + } + + private func applyDefaultSelectionIfNeeded() { + guard !didApplyDefaultSelection, model.context.status == .dryRunFinished, !buckets.isEmpty else { return } + didApplyDefaultSelection = true + selectedBucketKey = Self.defaultSelectionKey( + buckets: buckets, + status: model.context.status, + selectedKey: selectedBucketKey + ) ?? selectedBucketKey + } + + /// `{Month Year}: {count} photos and videos`. The template is looked up first + /// and filled in afterwards. + static func selectedBucketTitle(key: String, count: Int) -> String { + let monthYear = formatMonthYear(key) + return count == 1 + ? AppLocalization.format("%@: 1 photo or video", monthYear) + : String( + format: AppLocalization.string("%@: %@ photos and videos"), + monthYear, count.formatted() + ) } // MARK: - Header @@ -88,12 +129,9 @@ struct RunTimelineView: View { VStack(alignment: .leading, spacing: DesignTokens.Spacing.sm) { HStack { VStack(alignment: .leading, spacing: 2) { - Text(formatMonthYear(bucket.key)) + Text(Self.selectedBucketTitle(key: bucket.key, count: bucket.plannedCount)) .scaledFont(.subtitle, weight: .bold) .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) - Text(TimelinePlurals.filesToCopy(bucket.plannedCount)) - .scaledFont(.label) - .foregroundStyle(DesignTokens.ColorSystem.captionText) } Spacer() @@ -121,13 +159,17 @@ struct RunTimelineView: View { } } .frame(height: 56) + + Text(AppLocalization.string("A sample from this month.")) + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.captionText) } } .padding(DesignTokens.Spacing.md) .background(DesignTokens.ColorSystem.imageStage.opacity(0.4), in: RoundedRectangle(cornerRadius: 8, style: .continuous)) } - private func formatMonthYear(_ key: String) -> String { + private static func formatMonthYear(_ key: String) -> String { guard key != "Unknown", key.count >= 7 else { return key == "Unknown" ? "Unknown Date" : key } diff --git a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift index 626d2dbf..4292f3a9 100644 --- a/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift +++ b/ui/Sources/ChronoframeApp/Views/Run/RunWorkspaceModel.swift @@ -360,7 +360,7 @@ struct RunWorkspaceModel { return RunHeroState( title: mode == .preview ? String(localized: "Building the preview", bundle: .module) : String(localized: "Copying your photos", bundle: .module), message: mode == .preview - ? String(localized: "You can keep using your Mac. Nothing is being copied.", bundle: .module) + ? String(localized: "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", bundle: .module) : String(localized: "You can keep using your Mac. Originals are only read, never changed.", bundle: .module), badgeTitle: mode == .preview ? String(localized: "Previewing", bundle: .module) : String(localized: "Copying", bundle: .module), badgeSymbol: "arrow.triangle.2.circlepath", diff --git a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift new file mode 100644 index 00000000..7cddf68c --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupModel.swift @@ -0,0 +1,203 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// The two questions of the first-run guided setup. +enum GuidedSetupStep: Equatable { case source, destination } + +/// The places the first question offers. The raw value is part of each button's +/// accessibility identifier, so it is never renamed. +enum GuidedSourcePlace: String, CaseIterable { case pictures, desktop, downloads, externalDrive, other } + +enum GuidedSourceKind: Equatable { case folder, applePhotos } + +/// What `GuidedSetupGate` reads. Everything but `isEligible` describes whether +/// the person has already set anything up. +struct GuidedSetupGateInputs: Equatable { + var isEligible: Bool + var didOnboard: Bool + var sourcePath: String + var sourceItemCount: Int + var destinationPath: String + var hasHistory: Bool + var hasProfiles: Bool +} + +enum GuidedSetupGate { + /// True only for an eligible person who has not been through onboarding and + /// has no folders, history or saved setups. + static func shouldShow(_ inputs: GuidedSetupGateInputs) -> Bool { + inputs.isEligible + && !inputs.didOnboard + && inputs.sourcePath.isEmpty + && inputs.sourceItemCount == 0 + && inputs.destinationPath.isEmpty + && !inputs.hasHistory + && !inputs.hasProfiles + } +} + +/// Copy and decisions for the guided setup screen. Holds no state of its own +/// beyond what the view gives it, so every sentence is testable. +struct GuidedSetupModel: Equatable { + var step: GuidedSetupStep + var sourceKind: GuidedSourceKind + var sourcePath: String + var destinationPath: String + var isMeasuring: Bool + var estimate: FolderSizeEstimate? + var destinationFreeBytes: Int64? + + init( + step: GuidedSetupStep = .source, + sourceKind: GuidedSourceKind = .folder, + sourcePath: String = "", + destinationPath: String = "", + isMeasuring: Bool = false, + estimate: FolderSizeEstimate? = nil, + destinationFreeBytes: Int64? = nil + ) { + self.step = step + self.sourceKind = sourceKind + self.sourcePath = sourcePath + self.destinationPath = destinationPath + self.isMeasuring = isMeasuring + self.estimate = estimate + self.destinationFreeBytes = destinationFreeBytes + } + + var title: String { + switch step { + case .source: + return AppLocalization.string("Where are most of your photos?") + case .destination: + return AppLocalization.string("Where should the organized copy go?") + } + } + + var body: String { + switch step { + case .source: + return AppLocalization.string( + "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." + ) + case .destination: + switch sourceKind { + case .folder: + return AppLocalization.string( + "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." + ) + case .applePhotos: + return AppLocalization.string( + "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." + ) + } + } + } + + /// The line about the size of the chosen folder; nil for Apple Photos and on the first step. + var measureLine: String? { + guard step == .destination, sourceKind == .folder else { return nil } + if isMeasuring { + return AppLocalization.string("Measuring your folder…") + } + guard let estimate else { + return AppLocalization.string( + "Chronoframe could not measure this folder. Space is checked again before copying." + ) + } + let size = Self.sizeText(estimate.totalBytes) + if estimate.isComplete { + return Self.format( + "Your folder holds about %@ in %@.", + size, + PluralPhrases.files(estimate.fileCount) + ) + } + return AppLocalization.format("Your folder holds at least %@.", size) + } + + /// The line about room on the destination drive, once a destination is chosen. + var spaceLine: String? { + guard step == .destination, !destinationPath.isEmpty else { return nil } + guard let free = destinationFreeBytes else { + return AppLocalization.string("Free space on this drive is unknown.") + } + let freeText = Self.sizeText(free) + guard let estimate = settledEstimate else { + return AppLocalization.format("%@ free here.", freeText) + } + if free < estimate.totalBytes { + return Self.format( + "%@ free here, and your folder holds about %@. It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out.", + freeText, + Self.sizeText(estimate.totalBytes) + ) + } + // An incomplete estimate is only a lower bound, so it cannot promise the folder fits. + guard estimate.isComplete else { + return AppLocalization.format("%@ free here.", freeText) + } + return Self.format( + "%@ free here. That is enough for about %@ (estimate, checked again when the copy starts).", + freeText, + Self.sizeText(estimate.totalBytes) + ) + } + + /// True when the folder is bigger than the free space. A warning only: it never stops the person. + var spaceIsWarning: Bool { + guard step == .destination, + !destinationPath.isEmpty, + let free = destinationFreeBytes, + let estimate = settledEstimate + else { return false } + return free < estimate.totalBytes + } + + var primaryTitle: String { + guard step == .destination else { return "" } + switch sourceKind { + case .folder: + return AppLocalization.string("Look at My Photos") + case .applePhotos: + return AppLocalization.string("Choose Photos to Copy") + } + } + + var canContinue: Bool { + step == .destination && !destinationPath.isEmpty + } + + /// Where the folder picker opens for each place. `home` is the person's real home folder. + static func startingDirectory(for place: GuidedSourcePlace, home: URL) -> URL? { + switch place { + case .pictures: + return home.appendingPathComponent("Pictures", isDirectory: true) + case .desktop: + return home.appendingPathComponent("Desktop", isDirectory: true) + case .downloads: + return home.appendingPathComponent("Downloads", isDirectory: true) + case .externalDrive: + return URL(fileURLWithPath: "/Volumes", isDirectory: true) + case .other: + return nil + } + } + + /// The estimate for a folder, once measuring has finished and only for a folder source. + private var settledEstimate: FolderSizeEstimate? { + guard sourceKind == .folder, !isMeasuring else { return nil } + return estimate + } + + private static func sizeText(_ bytes: Int64) -> String { + ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) + } + + /// Looks the template up first and fills both values in afterwards. + private static func format(_ key: String, _ first: String, _ second: String) -> String { + String(format: AppLocalization.string(key), first, second) + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift new file mode 100644 index 00000000..2edbff6d --- /dev/null +++ b/ui/Sources/ChronoframeApp/Views/Setup/GuidedSetupView.swift @@ -0,0 +1,314 @@ +#if canImport(ChronoframeAppCore) +import ChronoframeAppCore +#endif +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import SwiftUI + +/// The two questions a person with nothing set up answers before the normal +/// screens: where the photos are, and where the organized copy should go. It +/// only chooses folders through the existing coordinator paths and measures the +/// chosen folder read-only; nothing is copied here. +struct GuidedSetupView: View { + let appState: AppState + @Binding var didOnboard: Bool + @ObservedObject private var setupStore: SetupStore + @State private var model: GuidedSetupModel + @State private var isChoosingSource = false + @State private var isStarting = false + /// A fixed starting state for renders. While it is set nothing is measured, so the screen shows + /// exactly the estimate and free space it was given. + private let fixedModel: GuidedSetupModel? + + init(appState: AppState, didOnboard: Binding, fixedModel: GuidedSetupModel? = nil) { + self.appState = appState + self._didOnboard = didOnboard + self._setupStore = ObservedObject(wrappedValue: appState.setupStore) + self._model = State(initialValue: fixedModel ?? GuidedSetupModel()) + self.fixedModel = fixedModel + } + + /// The state the copy is built from: the view's own step and measurements, with the folders the + /// store actually holds. + private var current: GuidedSetupModel { + var value = model + value.sourcePath = setupStore.sourcePath + value.destinationPath = setupStore.destinationPath + return value + } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: DesignTokens.Layout.sectionSpacing) { + switch model.step { + case .source: + sourceStep + case .destination: + destinationStep + } + + Button("Use the full setup screen") { + didOnboard = true + } + .buttonStyle(.link) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.useFullSetup) + } + .padding(DesignTokens.Layout.contentPadding) + .frame(maxWidth: 560, alignment: .leading) + .frame(maxWidth: .infinity, alignment: .center) + } + .task(id: measurementRoot) { await measureFolder() } + .task(id: freeSpaceKey) { await refreshFreeSpace() } + } + + // MARK: Source step + + private var sourceStep: some View { + let copy = current + return VStack(alignment: .leading, spacing: DesignTokens.Layout.sectionSpacing) { + heading(copy) + + VStack(alignment: .leading, spacing: 8) { + ForEach(GuidedSourcePlace.allCases, id: \.self) { place in + Button { + chooseSource(place) + } label: { + placeLabel(place) + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(.bordered) + .controlSize(.large) + .disabled(isChoosingSource) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.source(place)) + } + } + + Button("My photos are in the Apple Photos app") { + chooseApplePhotos() + } + .buttonStyle(.link) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.sourceApplePhotos) + } + } + + @ViewBuilder + private func placeLabel(_ place: GuidedSourcePlace) -> some View { + switch place { + case .pictures: Text("Pictures Folder") + case .desktop: Text("Desktop") + case .downloads: Text("Downloads") + case .externalDrive: Text("An External Drive") + case .other: Text("Somewhere Else…") + } + } + + // MARK: Destination step + + private var destinationStep: some View { + let copy = current + return VStack(alignment: .leading, spacing: DesignTokens.Layout.sectionSpacing) { + heading(copy) + + if let measureLine = copy.measureLine { + HStack(alignment: .firstTextBaseline, spacing: 8) { + if copy.isMeasuring { + ProgressView() + .controlSize(.small) + .accessibilityHidden(true) + } + Text(verbatim: measureLine) + .scaledFont(.body) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + VStack(alignment: .leading, spacing: 8) { + Button("Choose a Folder…") { + Task { await appState.chooseDestinationFolder() } + } + .buttonStyle(.bordered) + .controlSize(.large) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.destinationChoose) + + if !copy.destinationPath.isEmpty { + Text(verbatim: copy.destinationPath) + .scaledFont(.mono) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .lineLimit(2) + .truncationMode(.middle) + .textSelection(.enabled) + } + + if let spaceLine = copy.spaceLine { + HStack(alignment: .firstTextBaseline, spacing: 6) { + if copy.spaceIsWarning { + Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(DesignTokens.ColorSystem.statusWarning) + .accessibilityHidden(true) + } + Text(verbatim: spaceLine) + .scaledFont(.body) + .foregroundStyle( + copy.spaceIsWarning + ? DesignTokens.ColorSystem.inkPrimary + : DesignTokens.ColorSystem.inkSecondary + ) + .fixedSize(horizontal: false, vertical: true) + } + } + } + + VStack(alignment: .leading, spacing: 8) { + Button { + start() + } label: { + Text(verbatim: copy.primaryTitle) + .frame(maxWidth: .infinity) + } + .buttonStyle(.borderedProminent) + .controlSize(.large) + .disabled(!copy.canContinue || isStarting) + .accessibilityIdentifier(AccessibilityIdentifiers.Guided.start) + + if copy.sourceKind == .folder { + Text("Nothing is copied in this step. A very large collection can take 5 to 15 minutes to read.") + .scaledFont(.label) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + Button("Back") { + goBack() + } + .buttonStyle(.link) + } + } + + private func heading(_ copy: GuidedSetupModel) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(verbatim: copy.title) + .scaledFont(.title) + .foregroundStyle(DesignTokens.ColorSystem.inkPrimary) + .accessibilityAddTraits(.isHeader) + Text(verbatim: copy.body) + .scaledFont(.subtitle) + .foregroundStyle(DesignTokens.ColorSystem.inkSecondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + // MARK: Actions + + private func chooseSource(_ place: GuidedSourcePlace) { + guard !isChoosingSource else { return } + isChoosingSource = true + Task { + let directory = GuidedSetupModel.startingDirectory( + for: place, + home: FolderAccessService.realHomeDirectoryURL() + ) + let chosen = await appState.chooseSourceFolder(openingAt: directory) + isChoosingSource = false + if chosen { + enterDestinationStep(sourceKind: .folder) + } + } + } + + private func chooseApplePhotos() { + enterDestinationStep(sourceKind: .applePhotos) + } + + private func enterDestinationStep(sourceKind: GuidedSourceKind) { + model.sourceKind = sourceKind + model.estimate = nil + model.destinationFreeBytes = nil + model.isMeasuring = sourceKind == .folder + model.step = .destination + } + + /// Leaving the step ends the measurement: its task id becomes nil, which cancels it. + private func goBack() { + model.step = .source + model.isMeasuring = false + model.estimate = nil + model.destinationFreeBytes = nil + } + + private func start() { + guard !isStarting else { return } + isStarting = true + let sourceKind = model.sourceKind + didOnboard = true + switch sourceKind { + case .folder: + Task { + await appState.startPreview() + isStarting = false + } + case .applePhotos: + appState.navigate(to: .photos) + isStarting = false + } + } + + // MARK: Measuring + + /// The folder to measure: only the one the person chose, and only on the destination step. + private var measurementRoot: String? { + guard fixedModel == nil, + model.step == .destination, + model.sourceKind == .folder, + !setupStore.sourcePath.isEmpty + else { return nil } + return setupStore.sourcePath + } + + /// Never measure a drive's root or the list of every mounted volume. + private static func isMeasurable(_ path: String) -> Bool { + let standardized = URL(fileURLWithPath: path).standardizedFileURL.path + return standardized != "/" && standardized != "/Volumes" + } + + /// Runs the read-only estimate off the main actor. Cancelling this task (the step is left, or the + /// view goes away) cancels the walk, which stops within a few hundred entries. + private func measureFolder() async { + guard let path = measurementRoot else { return } + model.estimate = nil + guard Self.isMeasurable(path) else { + model.isMeasuring = false + return + } + model.isMeasuring = true + let root = URL(fileURLWithPath: path, isDirectory: true) + let work = Task.detached(priority: .utility) { + FolderSizeEstimator.estimate(root: root, isCancelled: { Task.isCancelled }) + } + let result = await withTaskCancellationHandler { + await work.value + } onCancel: { + work.cancel() + } + guard !Task.isCancelled else { return } + model.estimate = result + model.isMeasuring = false + } + + private var freeSpaceKey: String { + guard fixedModel == nil, model.step == .destination else { return "" } + return setupStore.destinationPath + } + + private func refreshFreeSpace() async { + let path = freeSpaceKey + guard !path.isEmpty else { return } + let free = await Task.detached(priority: .utility) { + PhotosExportExecutor.liveFreeSpace(at: URL(fileURLWithPath: path, isDirectory: true)) + }.value + guard !Task.isCancelled else { return } + model.destinationFreeBytes = free + } +} diff --git a/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift b/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift index 21782262..d7bcbd9d 100644 --- a/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift +++ b/ui/Sources/ChronoframeApp/Views/Setup/SetupView.swift @@ -9,12 +9,20 @@ struct SetupView: View { @ObservedObject private var setupStore: SetupStore @ObservedObject private var preferencesStore: PreferencesStore @ObservedObject private var runSessionStore: RunSessionStore + @ObservedObject private var historyStore: HistoryStore @State private var isDropTargeted = false - @AppStorage("didOnboard") private var didOnboard = false + /// Once the guided setup has shown, it stays up while the person answers its questions, even + /// though choosing a folder fills the paths the gate checks. + @State private var guidedSetupLatched = false + @AppStorage("didOnboard") private var storedDidOnboard = false + /// Renders and tests supply the flag here so they never read or write `UserDefaults.standard`. + private let didOnboardOverride: Binding? @Environment(\.accessibilityReduceMotion) private var reduceMotion - init(appState: AppState) { + init(appState: AppState, didOnboard: Binding? = nil) { self.appState = appState + self.didOnboardOverride = didOnboard + self._historyStore = ObservedObject(wrappedValue: appState.historyStore) self._setupStore = ObservedObject(wrappedValue: appState.setupStore) self._preferencesStore = ObservedObject(wrappedValue: appState.preferencesStore) self._runSessionStore = ObservedObject(wrappedValue: appState.runSessionStore) @@ -28,7 +36,43 @@ struct SetupView: View { ) } - var body: some View { + private var didOnboard: Bool { + get { didOnboardOverride?.wrappedValue ?? storedDidOnboard } + nonmutating set { + if let didOnboardOverride { + didOnboardOverride.wrappedValue = newValue + } else { + storedDidOnboard = newValue + } + } + } + + private var didOnboardBinding: Binding { + didOnboardOverride ?? $storedDidOnboard + } + + private var guidedGateShows: Bool { + GuidedSetupGate.shouldShow(GuidedSetupGateInputs( + isEligible: appState.guidedSetupEligible, + didOnboard: didOnboard, + sourcePath: setupStore.sourcePath, + sourceItemCount: setupStore.sourceItems.count, + destinationPath: setupStore.destinationPath, + hasHistory: !historyStore.entries.isEmpty, + hasProfiles: !setupStore.profiles.isEmpty + )) + } + + private var showsGuidedSetup: Bool { + guidedGateShows + || (guidedSetupLatched + && appState.guidedSetupEligible + && !didOnboard + && historyStore.entries.isEmpty + && setupStore.profiles.isEmpty) + } + + private var fullSetupContent: some View { GeometryReader { geometry in let isWide = geometry.size.width >= 1024 ScrollViewReader { proxy in @@ -177,6 +221,19 @@ struct SetupView: View { } } } + } + + var body: some View { + Group { + if showsGuidedSetup { + GuidedSetupView(appState: appState, didOnboard: didOnboardBinding) + } else { + fullSetupContent + } + } + .onChange(of: guidedGateShows, initial: true) { _, shows in + if shows { guidedSetupLatched = true } + } .darkroom() .navigationTitle("Choose Folders") .onDrop(of: [UTType.fileURL], isTargeted: $isDropTargeted) { providers in diff --git a/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift b/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift index 98e81ec1..15fb6927 100644 --- a/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift +++ b/ui/Sources/ChronoframeAppCore/Services/FolderAccessService.swift @@ -98,6 +98,9 @@ public protocol FolderAccessServicing: AnyObject, Sendable { @MainActor func chooseFolder(startingAt path: String?, prompt: String, allowNetworkStart: Bool) -> URL? /// One panel, several folders. Returns an empty array when the user cancels. @MainActor func chooseFolders(startingAt path: String?, prompt: String) -> [URL] + /// Opens the panel inside `directory` itself (not at its parent). Falls back to the usual + /// start place when `directory` does not exist on a local volume. + @MainActor func chooseFolder(openingAt directory: URL, prompt: String) -> URL? func makeBookmark(for url: URL, key: String) throws -> FolderBookmark @MainActor func resolveBookmark(_ bookmark: FolderBookmark) -> ResolvedFolderBookmark? @MainActor func scopedAccess(for bookmarks: [FolderBookmark]) -> SecurityScopedFolderAccess @@ -113,6 +116,10 @@ public extension FolderAccessServicing { @MainActor func chooseFolder(startingAt path: String?, prompt: String, allowNetworkStart: Bool) -> URL? { chooseFolder(startingAt: path, prompt: prompt) } + + @MainActor func chooseFolder(openingAt directory: URL, prompt: String) -> URL? { + chooseFolder(startingAt: directory.path, prompt: prompt) + } } @MainActor @@ -134,6 +141,40 @@ public final class FolderAccessService: FolderAccessServicing { return panel.runModal() == .OK ? panel.url : nil } + public func chooseFolder(openingAt directory: URL, prompt: String) -> URL? { + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.allowsMultipleSelection = false + panel.prompt = CoreL10n.text(String.LocalizationValue(prompt)) + panel.directoryURL = Self.panelDirectoryURL(openingAt: directory) + + return panel.runModal() == .OK ? panel.url : nil + } + + /// `directory` itself when it is an existing folder on a local volume, otherwise the place + /// `initialPanelDirectoryURL` uses when it is given no path. + static func panelDirectoryURL(openingAt directory: URL) -> URL { + var isDirectory: ObjCBool = false + if FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory), + isDirectory.boolValue, + let values = try? directory.resourceValues(forKeys: [.volumeIsLocalKey]), + values.volumeIsLocal == true { + return directory + } + return initialPanelDirectoryURL(startingAt: nil) + } + + /// The person's real home folder from the password database. In a sandboxed build + /// `FileManager.homeDirectoryForCurrentUser` is the app's container, which is never + /// where the person keeps Pictures, Desktop or Downloads. + public nonisolated static func realHomeDirectoryURL() -> URL { + if let entry = getpwuid(getuid()), let directory = entry.pointee.pw_dir { + return URL(fileURLWithPath: String(cString: directory), isDirectory: true) + } + return FileManager.default.homeDirectoryForCurrentUser + } + public func chooseFolders(startingAt path: String?, prompt: String) -> [URL] { let panel = NSOpenPanel() panel.canChooseFiles = false diff --git a/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift b/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift index e9dd6a33..c61ad55b 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/PreferencesStore.swift @@ -194,7 +194,24 @@ public final class PreferencesStore: ObservableObject { self.lastDeduplicateDestinationPath = defaults.string(forKey: "lastDeduplicateDestinationPath") ?? "" self.lastSelectedProfileName = defaults.string(forKey: "lastSelectedProfileName") ?? "" let storedStructure = defaults.string(forKey: "folderStructure").flatMap(FolderStructure.init(rawValue:)) - self.folderStructure = storedStructure ?? .yyyyMMDD + if let storedStructure { + self.folderStructure = storedStructure + } else if defaults.object(forKey: "folderStructure") != nil { + // A value is stored but is not a layout this build knows: keep the old default, write nothing. + self.folderStructure = .yyyyMMDD + } else { + // Prior use: a saved folder path, or any folder bookmark (`bookmark.` prefix) or + // archive-destination bookmark (`history.destination.` prefix). + let hasSavedPath = !(defaults.string(forKey: "lastManualDestinationPath") ?? "").isEmpty + || !(defaults.string(forKey: "lastManualSourcePath") ?? "").isEmpty + || !(defaults.stringArray(forKey: "manualSourceItemPaths") ?? []).isEmpty + let hasBookmark = defaults.dictionaryRepresentation().keys.contains { + $0.hasPrefix("bookmark.") || $0.hasPrefix("history.destination.") + } + let resolved: FolderStructure = hasSavedPath || hasBookmark ? .yyyyMMDD : .yyyyMM + defaults.set(resolved.rawValue, forKey: "folderStructure") + self.folderStructure = resolved + } self.smartEventSuggestionsEnabled = defaults.object(forKey: "smartEventSuggestionsEnabled") as? Bool ?? false self.dedupeTimeWindowSeconds = defaults.object(forKey: "dedupeTimeWindowSeconds") as? Int ?? 30 self.dedupeBurstModeEnabled = defaults.object(forKey: "dedupeBurstModeEnabled") as? Bool ?? true diff --git a/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift b/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift index af07694c..c69b3aa5 100644 --- a/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift +++ b/ui/Sources/ChronoframeCore/CopyPlanBuilder.swift @@ -271,17 +271,24 @@ public enum CopyPlanBuilder { from transfers: [PlannedTransfer], namingRules: PlannerNamingRules ) -> [DateHistogramBucket] { - // Cap on how many source paths each bucket carries forward. Four - // is enough for the UI's hover peek (a small grid) without bloating - // the receipt/snapshot — even a 50K-file run with 200 buckets only - // adds ~800 path strings to the histogram. - let samplePathLimit = 4 + // Cap on how many source paths each bucket carries forward. Twelve + // fills the timeline's sample grid without bloating the + // receipt/snapshot — even a 50K-file run with 200 buckets only + // adds ~2,400 path strings to the histogram. + let samplePathLimit = 12 var countsByBucket: [String: Int] = [:] var samplesByBucket: [String: [String]] = [:] + // Exact copies are kept apart so they only top up a bucket that has + // fewer than `samplePathLimit` new files. + var duplicateSamplesByBucket: [String: [String]] = [:] for transfer in transfers { let key = histogramKey(for: transfer.dateBucket, namingRules: namingRules) countsByBucket[key, default: 0] += 1 - if (samplesByBucket[key]?.count ?? 0) < samplePathLimit { + if transfer.isDuplicate { + if (duplicateSamplesByBucket[key]?.count ?? 0) < samplePathLimit { + duplicateSamplesByBucket[key, default: []].append(transfer.sourcePath) + } + } else if (samplesByBucket[key]?.count ?? 0) < samplePathLimit { samplesByBucket[key, default: []].append(transfer.sourcePath) } } @@ -290,7 +297,11 @@ public enum CopyPlanBuilder { DateHistogramBucket( key: key, plannedCount: countsByBucket[key] ?? 0, - samplePaths: samplesByBucket[key] ?? [] + samplePaths: { + let newFiles = samplesByBucket[key] ?? [] + let exactCopies = duplicateSamplesByBucket[key] ?? [] + return newFiles + exactCopies.prefix(max(0, samplePathLimit - newFiles.count)) + }() ) } } diff --git a/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift b/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift new file mode 100644 index 00000000..0c4812c8 --- /dev/null +++ b/ui/Sources/ChronoframeCore/FolderSizeEstimator.swift @@ -0,0 +1,94 @@ +import Foundation + +public struct FolderSizeEstimate: Equatable, Sendable { + public let fileCount: Int + public let totalBytes: Int64 + /// False when cancelled or any entry could not be read. + public let isComplete: Bool + + public init(fileCount: Int, totalBytes: Int64, isComplete: Bool) { + self.fileCount = fileCount + self.totalBytes = totalBytes + self.isComplete = isComplete + } +} + +/// A read-only count of the regular files under a folder and their size. It lists directories +/// and reads file attributes; it never opens, creates, modifies or follows anything. It counts +/// every regular file, so callers say "files", never "photos". +public enum FolderSizeEstimator { + private static let cancellationCheckInterval = 500 + + /// Returns nil when the root cannot be enumerated at all. Hidden entries and package + /// contents are skipped, and symbolic links are never followed (INV-15), including a + /// root that is itself a symbolic link. + public static func estimate(root: URL, isCancelled: @Sendable () -> Bool = { false }) -> FolderSizeEstimate? { + let fileManager = FileManager.default + let keys: [URLResourceKey] = [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey] + + guard let rootValues = try? root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]), + rootValues.isDirectory == true, + rootValues.isSymbolicLink != true + else { + return nil + } + + var rootFailed = false + var sawUnreadableEntry = false + let rootPath = root.standardizedFileURL.path + guard let enumerator = fileManager.enumerator( + at: root, + includingPropertiesForKeys: keys, + options: [.skipsHiddenFiles, .skipsPackageDescendants], + errorHandler: { url, _ in + if url.standardizedFileURL.path == rootPath { + rootFailed = true + } else { + sawUnreadableEntry = true + } + return true + } + ) else { + return nil + } + + var fileCount = 0 + var totalBytes: Int64 = 0 + var entriesSeen = 0 + var cancelled = false + + while let next = enumerator.nextObject() { + if entriesSeen.isMultiple(of: cancellationCheckInterval), isCancelled() { + cancelled = true + break + } + entriesSeen += 1 + + guard let url = next as? URL else { + sawUnreadableEntry = true + continue + } + guard let values = try? url.resourceValues(forKeys: Set(keys)) else { + sawUnreadableEntry = true + continue + } + if values.isSymbolicLink == true { + continue + } + guard values.isRegularFile == true else { + continue + } + fileCount += 1 + totalBytes += Int64(values.fileSize ?? 0) + } + + if rootFailed { + return nil + } + return FolderSizeEstimate( + fileCount: fileCount, + totalBytes: totalBytes, + isComplete: !cancelled && !sawUnreadableEntry + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift index 1896e8de..8efbd20a 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreCopyPlanTests.swift @@ -277,6 +277,66 @@ final class ChronoframeCoreCopyPlanTests: XCTestCase { XCTAssertEqual(result.sequenceState.duplicatesByDate, ["2024-03-01": 1]) } + func testHistogramSamplesPreferNewFilesUpToTwelve() { + // Exact copies come first in plan order, but a bucket's samples must be + // new files first; exact copies only top up when fewer than 12 new files exist. + var transfers: [PlannedTransfer] = [] + for index in 0..<10 { + transfers.append(transfer("/source/dup\(index).jpg", bucket: "2026-03-05", isDuplicate: true)) + } + for index in 0..<5 { + transfers.append(transfer("/source/few\(index).jpg", bucket: "2026-03-05", isDuplicate: false)) + } + for index in 0..<20 { + transfers.append(transfer("/source/dup-april\(index).jpg", bucket: "2026-04-01", isDuplicate: true)) + } + for index in 0..<15 { + transfers.append(transfer("/source/new-april\(index).jpg", bucket: "2026-04-01", isDuplicate: false)) + } + for index in 0..<3 { + transfers.append(transfer("/source/only-dup\(index).jpg", bucket: "2026-05-01", isDuplicate: true)) + } + + let buckets = CopyPlanBuilder.dateHistogram(from: transfers, namingRules: .chronoframeDefault) + let byKey = Dictionary(uniqueKeysWithValues: buckets.map { ($0.key, $0) }) + + // Fewer than 12 new files: all of them, then exact copies to fill up to 12. + XCTAssertEqual( + byKey["2026-03"]?.samplePaths, + (0..<5).map { "/source/few\($0).jpg" } + (0..<7).map { "/source/dup\($0).jpg" } + ) + // 12 or more new files: only new files, first 12 in plan order. + XCTAssertEqual(byKey["2026-04"]?.samplePaths, (0..<12).map { "/source/new-april\($0).jpg" }) + // Only exact copies: they are used. + XCTAssertEqual(byKey["2026-05"]?.samplePaths, (0..<3).map { "/source/only-dup\($0).jpg" }) + } + + func testHistogramCountsUnchangedBySampleRule() { + var transfers: [PlannedTransfer] = [] + for index in 0..<30 { + transfers.append(transfer("/source/a\(index).jpg", bucket: "2026-03-05", isDuplicate: index % 3 == 0)) + } + for index in 0..<2 { + transfers.append(transfer("/source/u\(index).jpg", bucket: "Unknown_Date", isDuplicate: false)) + } + + let buckets = CopyPlanBuilder.dateHistogram(from: transfers, namingRules: .chronoframeDefault) + + XCTAssertEqual(buckets.map(\.key), ["2026-03", "Unknown"]) + XCTAssertEqual(buckets.map(\.plannedCount), [30, 2]) + XCTAssertEqual(buckets.map { $0.samplePaths.count }, [12, 2]) + } + + private func transfer(_ path: String, bucket: String, isDuplicate: Bool) -> PlannedTransfer { + PlannedTransfer( + sourcePath: path, + destinationPath: "/dest/" + (path as NSString).lastPathComponent, + identity: FileIdentity(size: 1, digest: path), + dateBucket: bucket, + isDuplicate: isDuplicate + ) + } + private func candidate(_ path: String, identity: String, date: String?) -> PlanningFileCandidate { PlanningFileCandidate( sourcePath: path, diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift new file mode 100644 index 00000000..eb379e48 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFolderSizeEstimatorTests.swift @@ -0,0 +1,168 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +final class ChronoframeCoreFolderSizeEstimatorTests: XCTestCase { + private var root: URL! + private let fileManager = FileManager.default + + override func setUpWithError() throws { + try super.setUpWithError() + root = fileManager.temporaryDirectory + .appendingPathComponent("FolderSizeEstimator-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + // Restore any permission a test removed before deleting what the test created. + if let root, fileManager.fileExists(atPath: root.path) { + try? fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: root.path) + try fileManager.removeItem(at: root) + } + root = nil + try super.tearDownWithError() + } + + func testCountsRegularFilesAndBytes() throws { + try write(Data(repeating: 1, count: 100), to: "a.jpg") + try write(Data(repeating: 2, count: 250), to: "2024/06/b.heic") + try write(Data(), to: "2024/06/empty.txt") + try fileManager.createDirectory(at: root.appendingPathComponent("empty-dir"), withIntermediateDirectories: true) + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + XCTAssertEqual(estimate.fileCount, 3) + XCTAssertEqual(estimate.totalBytes, 350) + XCTAssertTrue(estimate.isComplete) + } + + // AGENTS-INVARIANT: 15 + func testSkipsSymlinksWithoutFollowing() throws { + let outside = fileManager.temporaryDirectory + .appendingPathComponent("FolderSizeEstimatorOutside-\(UUID().uuidString)", isDirectory: true) + try fileManager.createDirectory(at: outside, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: outside) } + try Data(repeating: 9, count: 5_000).write(to: outside.appendingPathComponent("big.bin")) + try Data(repeating: 9, count: 777).write(to: outside.appendingPathComponent("target.jpg")) + + try write(Data(repeating: 1, count: 10), to: "real.jpg") + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("linked-folder"), + withDestinationURL: outside + ) + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("linked-file.jpg"), + withDestinationURL: outside.appendingPathComponent("target.jpg") + ) + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + XCTAssertEqual(estimate.fileCount, 1) + XCTAssertEqual(estimate.totalBytes, 10) + } + + func testSkipsHiddenFilesAndPackages() throws { + try write(Data(repeating: 1, count: 10), to: "visible.jpg") + try write(Data(repeating: 1, count: 20), to: ".hidden.jpg") + try write(Data(repeating: 1, count: 30), to: ".hidden-dir/inside.jpg") + try write(Data(repeating: 1, count: 40), to: "Thing.app/Contents/Info.plist") + try write(Data(repeating: 1, count: 50), to: "Photos.photoslibrary/original.jpg") + + let estimate = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + + XCTAssertEqual(estimate.fileCount, 1) + XCTAssertEqual(estimate.totalBytes, 10) + } + + func testNilForUnreadableRoot() throws { + let missing = root.appendingPathComponent("does-not-exist", isDirectory: true) + XCTAssertNil(FolderSizeEstimator.estimate(root: missing)) + + let locked = root.appendingPathComponent("locked", isDirectory: true) + try fileManager.createDirectory(at: locked, withIntermediateDirectories: true) + try write(Data(repeating: 1, count: 10), to: "locked/x.jpg") + try fileManager.setAttributes([.posixPermissions: 0o000], ofItemAtPath: locked.path) + defer { try? fileManager.setAttributes([.posixPermissions: 0o755], ofItemAtPath: locked.path) } + + XCTAssertNil(FolderSizeEstimator.estimate(root: locked)) + } + + func testIncompleteWhenCancelled() throws { + for index in 0..<1_200 { + try write(Data(repeating: 1, count: 1), to: "bulk/\(index).jpg") + } + + let alwaysCancelled = try XCTUnwrap(FolderSizeEstimator.estimate(root: root, isCancelled: { true })) + XCTAssertFalse(alwaysCancelled.isComplete) + XCTAssertLessThan(alwaysCancelled.fileCount, 1_200) + + let cancelAfterFirstCheck = CallCounter() + let partial = try XCTUnwrap( + FolderSizeEstimator.estimate(root: root, isCancelled: { cancelAfterFirstCheck.next() > 1 }) + ) + XCTAssertFalse(partial.isComplete) + XCTAssertGreaterThan(partial.fileCount, 0) + XCTAssertLessThan(partial.fileCount, 1_200) + + let finished = try XCTUnwrap(FolderSizeEstimator.estimate(root: root)) + XCTAssertTrue(finished.isComplete) + XCTAssertEqual(finished.fileCount, 1_200) + } + + // AGENTS-INVARIANT: 1 + func testCreatesAndModifiesNothing() throws { + try write(Data(repeating: 1, count: 100), to: "a.jpg") + try write(Data(repeating: 2, count: 200), to: "sub/b.jpg") + try write(Data(repeating: 3, count: 300), to: ".hidden/c.jpg") + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("link.jpg"), + withDestinationURL: root.appendingPathComponent("a.jpg") + ) + + let before = try snapshot() + _ = FolderSizeEstimator.estimate(root: root) + let after = try snapshot() + + XCTAssertEqual(before, after) + } + + // MARK: - Helpers + + private func write(_ data: Data, to relativePath: String) throws { + let url = root.appendingPathComponent(relativePath) + try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try data.write(to: url) + } + + /// Every path under the root (hidden entries included) with its size and modification date. + private func snapshot() throws -> [String] { + let keys: [URLResourceKey] = [.fileSizeKey, .contentModificationDateKey, .isDirectoryKey] + var lines: [String] = [] + guard let enumerator = fileManager.enumerator( + at: root, + includingPropertiesForKeys: keys, + options: [], + errorHandler: nil + ) else { + return lines + } + for case let url as URL in enumerator { + let values = try url.resourceValues(forKeys: Set(keys)) + lines.append( + "\(url.path)|\(values.fileSize ?? -1)|\(values.contentModificationDate?.timeIntervalSince1970 ?? -1)|\(values.isDirectory ?? false)" + ) + } + return lines.sorted() + } +} + +private final class CallCounter: @unchecked Sendable { + private let lock = NSLock() + private var count = 0 + func next() -> Int { + lock.lock() + defer { lock.unlock() } + count += 1 + return count + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift b/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift index 58fb9098..2e9ad0f6 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ModelAndServiceTests.swift @@ -136,6 +136,59 @@ final class ModelAndServiceTests: XCTestCase { ) } + @MainActor + func testOpeningAtExistingLocalFolderStartsThere() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderAccessOpeningAt-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + + // Unlike `initialPanelDirectoryURL`, which opens at the parent, this opens in the folder itself. + XCTAssertEqual( + FolderAccessService.panelDirectoryURL(openingAt: root).standardizedFileURL.path, + root.standardizedFileURL.path + ) + } + + @MainActor + func testOpeningAtMissingFolderFallsBack() throws { + let missing = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderAccessMissing-\(UUID().uuidString)", isDirectory: true) + let fallback = FolderAccessService.initialPanelDirectoryURL(startingAt: nil).path + + XCTAssertEqual(FolderAccessService.panelDirectoryURL(openingAt: missing).path, fallback) + + // A regular file is not a folder to open in. + let file = FileManager.default.temporaryDirectory + .appendingPathComponent("FolderAccessFile-\(UUID().uuidString)") + try Data([1]).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + XCTAssertEqual(FolderAccessService.panelDirectoryURL(openingAt: file).path, fallback) + } + + @MainActor + func testProtocolDefaultForwardsToStartingAt() { + let recorder = StartingAtRecordingFolderAccess() + recorder.chosen = URL(fileURLWithPath: "/tmp/chosen") + let directory = URL(fileURLWithPath: "/Users/example/Pictures", isDirectory: true) + + let result = (recorder as any FolderAccessServicing).chooseFolder(openingAt: directory, prompt: "Choose Source") + + XCTAssertEqual(result?.path, "/tmp/chosen") + XCTAssertEqual(recorder.requests.count, 1) + XCTAssertEqual(recorder.requests.first?.startingAt, "/Users/example/Pictures") + XCTAssertEqual(recorder.requests.first?.prompt, "Choose Source") + } + + func testRealHomeDirectoryIsNotInsideAContainer() throws { + let home = FolderAccessService.realHomeDirectoryURL() + + XCTAssertFalse(home.path.contains("/Library/Containers/")) + XCTAssertTrue(home.path.hasPrefix("/")) + let entry = try XCTUnwrap(getpwuid(getuid())) + XCTAssertEqual(home.path, URL(fileURLWithPath: String(cString: entry.pointee.pw_dir)).path) + } + @MainActor func testFolderAccessServiceValidatesDirectoryCapabilities() throws { let service = FolderAccessService() @@ -165,3 +218,28 @@ final class ModelAndServiceTests: XCTestCase { } } } + +/// Conforms with only the requirements a protocol-extension default cannot supply, so the +/// `chooseFolder(openingAt:prompt:)` default is the code under test. +private final class StartingAtRecordingFolderAccess: FolderAccessServicing, @unchecked Sendable { + var chosen: URL? + private(set) var requests: [(startingAt: String?, prompt: String)] = [] + + @MainActor func chooseFolder(startingAt path: String?, prompt: String) -> URL? { + requests.append((path, prompt)) + return chosen + } + + @MainActor func chooseFolders(startingAt path: String?, prompt: String) -> [URL] { [] } + + func makeBookmark(for url: URL, key: String) throws -> FolderBookmark { + FolderBookmark(key: key, path: url.path, data: Data()) + } + + @MainActor func resolveBookmark(_ bookmark: FolderBookmark) -> ResolvedFolderBookmark? { nil } + @MainActor func scopedAccess(for bookmarks: [FolderBookmark]) -> SecurityScopedFolderAccess { SecurityScopedFolderAccess() } + @MainActor func verifiedScopedAccess(for bookmarks: [FolderBookmark]) -> ScopedAccessOutcome { + ScopedAccessOutcome(access: SecurityScopedFolderAccess(), startedKeys: []) + } + func validateFolder(_ url: URL, role: FolderRole) throws {} +} diff --git a/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift index 7e537397..23475011 100644 --- a/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/PreferencesStoreTests.swift @@ -29,6 +29,80 @@ final class PreferencesStoreTests: XCTestCase { try await super.tearDown() } + @MainActor + func testFreshDefaultsUseYearMonth() { + let store = PreferencesStore(defaults: defaults) + XCTAssertEqual(store.folderStructure, .yyyyMM) + } + + @MainActor + func testPriorUseWithoutStoredLayoutKeepsYearMonthDay() { + let priorUseSetups: [(String, (UserDefaults) -> Void)] = [ + ("destination path", { $0.set("/Volumes/Archive", forKey: "lastManualDestinationPath") }), + ("source path", { $0.set("/Users/example/Unsorted", forKey: "lastManualSourcePath") }), + ("source items", { $0.set(["/Users/example/Unsorted"], forKey: "manualSourceItemPaths") }), + ("bookmark", { $0.set(Data([1]), forKey: "bookmark.manual.destination.data") }), + ("history destination", { $0.set(Data([1]), forKey: "history.destination.QUJD") }), + ] + + for (label, setup) in priorUseSetups { + let suite = "PreferencesStoreTests-prior-\(UUID().uuidString)" + let scoped = UserDefaults(suiteName: suite)! + defer { scoped.removePersistentDomain(forName: suite) } + setup(scoped) + + let store = PreferencesStore(defaults: scoped) + + XCTAssertEqual(store.folderStructure, .yyyyMMDD, label) + } + + // Empty values are not prior use. + defaults.set("", forKey: "lastManualDestinationPath") + defaults.set("", forKey: "lastManualSourcePath") + defaults.set([String](), forKey: "manualSourceItemPaths") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMM) + } + + @MainActor + func testStoredLayoutIsNeverChanged() { + defaults.set(FolderStructure.yyyy.rawValue, forKey: "folderStructure") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyy) + XCTAssertEqual(defaults.string(forKey: "folderStructure"), FolderStructure.yyyy.rawValue) + + // A stored Year/Month/Day stays even with no sign of prior use. + defaults.set(FolderStructure.yyyyMMDD.rawValue, forKey: "folderStructure") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMMDD) + + // A stored Year/Month stays even when prior use is present. + defaults.set(FolderStructure.yyyyMM.rawValue, forKey: "folderStructure") + defaults.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMM) + XCTAssertEqual(defaults.string(forKey: "folderStructure"), FolderStructure.yyyyMM.rawValue) + } + + @MainActor + func testResolvedLayoutIsWrittenOnce() { + XCTAssertNil(defaults.string(forKey: "folderStructure")) + let first = PreferencesStore(defaults: defaults) + XCTAssertEqual(first.folderStructure, .yyyyMM) + XCTAssertEqual(defaults.string(forKey: "folderStructure"), FolderStructure.yyyyMM.rawValue) + + // Later use does not flip a person who started fresh to Year/Month/Day. + defaults.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + defaults.set(Data([1]), forKey: "bookmark.manual.destination.data") + XCTAssertEqual(PreferencesStore(defaults: defaults).folderStructure, .yyyyMM) + + // And prior use is written as Year/Month/Day once, then stays. + let suite = "PreferencesStoreTests-once-\(UUID().uuidString)" + let scoped = UserDefaults(suiteName: suite)! + defer { scoped.removePersistentDomain(forName: suite) } + scoped.set("/Volumes/Archive", forKey: "lastManualDestinationPath") + XCTAssertEqual(PreferencesStore(defaults: scoped).folderStructure, .yyyyMMDD) + XCTAssertEqual(scoped.string(forKey: "folderStructure"), FolderStructure.yyyyMMDD.rawValue) + scoped.set("", forKey: "lastManualDestinationPath") + XCTAssertEqual(PreferencesStore(defaults: scoped).folderStructure, .yyyyMMDD) + } + @MainActor func testGuardianPreferenceDefaults() { let store = PreferencesStore(defaults: defaults) diff --git a/ui/Tests/ChronoframeAppTests/AppStateTests.swift b/ui/Tests/ChronoframeAppTests/AppStateTests.swift index 8079f421..1094d497 100644 --- a/ui/Tests/ChronoframeAppTests/AppStateTests.swift +++ b/ui/Tests/ChronoframeAppTests/AppStateTests.swift @@ -84,6 +84,33 @@ final class AppStateTests: XCTestCase { XCTAssertEqual(appState.selection, .organize) } + @MainActor + func testGuidedSetupEligibleDefaultsTrue() { + let harness = AppStateHarness() + let appState = harness.makeAppState(performInitialBootstrap: false) + XCTAssertTrue(appState.guidedSetupEligible) + } + + @MainActor + func testEveryExistingScenarioDisablesGuidedSetup() { + for scenario in UITestScenario.allCases where scenario != .guidedFirstRun { + XCTAssertFalse( + UITestAppStateFactory.make(scenario: scenario).guidedSetupEligible, + "\(scenario.rawValue) must keep its existing screen" + ) + } + + let guided = UITestAppStateFactory.make(scenario: .guidedFirstRun) + XCTAssertTrue(guided.guidedSetupEligible) + XCTAssertEqual(guided.selection, .organize) + XCTAssertEqual(guided.organizeSubSelection, .setup) + XCTAssertTrue(guided.setupStore.sourcePath.isEmpty) + XCTAssertTrue(guided.setupStore.destinationPath.isEmpty) + XCTAssertTrue(guided.setupStore.sourceItems.isEmpty) + XCTAssertTrue(guided.setupStore.profiles.isEmpty) + XCTAssertTrue(guided.historyStore.entries.isEmpty) + } + @MainActor func testUITestAppStateFactorySeedsHistoryAndProfilesScenarios() { let historyState = UITestAppStateFactory.make(scenario: .historyPopulated) diff --git a/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift b/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift new file mode 100644 index 00000000..f26610d0 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/GuidedSetupModelTests.swift @@ -0,0 +1,205 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation +import XCTest +@testable import ChronoframeApp + +@MainActor +final class GuidedSetupModelTests: XCTestCase { + private func size(_ bytes: Int64) -> String { + ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) + } + + private func untouched() -> GuidedSetupGateInputs { + GuidedSetupGateInputs( + isEligible: true, + didOnboard: false, + sourcePath: "", + sourceItemCount: 0, + destinationPath: "", + hasHistory: false, + hasProfiles: false + ) + } + + private func destinationModel( + kind: GuidedSourceKind = .folder, + destinationPath: String = "", + isMeasuring: Bool = false, + estimate: FolderSizeEstimate? = nil, + free: Int64? = nil + ) -> GuidedSetupModel { + GuidedSetupModel( + step: .destination, + sourceKind: kind, + sourcePath: kind == .folder ? "/Photos" : "", + destinationPath: destinationPath, + isMeasuring: isMeasuring, + estimate: estimate, + destinationFreeBytes: free + ) + } + + // MARK: Gate + + func testGateShowsOnlyForUntouchedEligibleState() { + XCTAssertTrue(GuidedSetupGate.shouldShow(untouched())) + + var ineligible = untouched() + ineligible.isEligible = false + XCTAssertFalse(GuidedSetupGate.shouldShow(ineligible)) + } + + func testGateHiddenAfterOnboardOrAnyConfiguredPath() { + var onboarded = untouched() + onboarded.didOnboard = true + XCTAssertFalse(GuidedSetupGate.shouldShow(onboarded)) + + var withSource = untouched() + withSource.sourcePath = "/Photos" + XCTAssertFalse(GuidedSetupGate.shouldShow(withSource)) + + var withItems = untouched() + withItems.sourceItemCount = 2 + XCTAssertFalse(GuidedSetupGate.shouldShow(withItems)) + + var withDestination = untouched() + withDestination.destinationPath = "/Archive" + XCTAssertFalse(GuidedSetupGate.shouldShow(withDestination)) + } + + func testGateHiddenWithHistoryOrProfiles() { + var history = untouched() + history.hasHistory = true + XCTAssertFalse(GuidedSetupGate.shouldShow(history)) + + var profiles = untouched() + profiles.hasProfiles = true + XCTAssertFalse(GuidedSetupGate.shouldShow(profiles)) + } + + // MARK: Copy + + func testSourceStepCopy() { + let model = GuidedSetupModel(step: .source) + XCTAssertEqual(model.title, "Where are most of your photos?") + XCTAssertEqual( + model.body, + "Pick one place to start. You can add more later. Chronoframe only reads this place: nothing in it is moved, renamed or deleted." + ) + XCTAssertNil(model.measureLine) + XCTAssertNil(model.spaceLine) + XCTAssertFalse(model.spaceIsWarning) + XCTAssertFalse(model.canContinue) + } + + func testDestinationStepCopyForFolderAndApplePhotos() { + let folder = destinationModel(kind: .folder) + XCTAssertEqual(folder.title, "Where should the organized copy go?") + XCTAssertEqual( + folder.body, + "Chronoframe builds a new, organized copy there. Your originals stay exactly where they are." + ) + XCTAssertEqual(folder.primaryTitle, "Look at My Photos") + + let photos = destinationModel(kind: .applePhotos) + XCTAssertEqual(photos.title, "Where should the organized copy go?") + XCTAssertEqual( + photos.body, + "Chronoframe copies your photos out of Apple Photos into this folder. Your Photos library is never changed." + ) + XCTAssertEqual(photos.primaryTitle, "Choose Photos to Copy") + XCTAssertNil(photos.measureLine) + } + + func testMeasureLineStates() { + XCTAssertEqual(destinationModel(isMeasuring: true).measureLine, "Measuring your folder…") + + let complete = FolderSizeEstimate(fileCount: 12_345, totalBytes: 48_000_000_000, isComplete: true) + XCTAssertEqual( + destinationModel(estimate: complete).measureLine, + "Your folder holds about \(size(48_000_000_000)) in \(12_345.formatted()) files." + ) + + let single = FolderSizeEstimate(fileCount: 1, totalBytes: 2_000_000, isComplete: true) + XCTAssertEqual( + destinationModel(estimate: single).measureLine, + "Your folder holds about \(size(2_000_000)) in 1 file." + ) + + let partial = FolderSizeEstimate(fileCount: 40, totalBytes: 5_000_000_000, isComplete: false) + XCTAssertEqual( + destinationModel(estimate: partial).measureLine, + "Your folder holds at least \(size(5_000_000_000))." + ) + + XCTAssertEqual( + destinationModel(estimate: nil).measureLine, + "Chronoframe could not measure this folder. Space is checked again before copying." + ) + + // Measuring wins over a stale estimate. + XCTAssertEqual(destinationModel(isMeasuring: true, estimate: complete).measureLine, "Measuring your folder…") + } + + func testSpaceLineWarnsButNeverBlocks() { + let estimate = FolderSizeEstimate(fileCount: 900, totalBytes: 80_000_000_000, isComplete: true) + let tight = destinationModel(destinationPath: "/Archive", estimate: estimate, free: 20_000_000_000) + XCTAssertEqual( + tight.spaceLine, + "\(size(20_000_000_000)) free here, and your folder holds about \(size(80_000_000_000)). It may not all fit. Pick a bigger drive, or continue: the copy pauses safely if space runs out." + ) + XCTAssertTrue(tight.spaceIsWarning) + // A shortfall warns; it never stops the person continuing. + XCTAssertTrue(tight.canContinue) + + let unknown = destinationModel(destinationPath: "/Archive", estimate: estimate, free: nil) + XCTAssertEqual(unknown.spaceLine, "Free space on this drive is unknown.") + XCTAssertFalse(unknown.spaceIsWarning) + XCTAssertTrue(unknown.canContinue) + + XCTAssertNil(destinationModel(destinationPath: "", estimate: estimate, free: 1).spaceLine) + } + + func testSpaceLineSaysEstimate() { + let estimate = FolderSizeEstimate(fileCount: 900, totalBytes: 10_000_000_000, isComplete: true) + let roomy = destinationModel(destinationPath: "/Archive", estimate: estimate, free: 500_000_000_000) + XCTAssertEqual( + roomy.spaceLine, + "\(size(500_000_000_000)) free here. That is enough for about \(size(10_000_000_000)) (estimate, checked again when the copy starts)." + ) + XCTAssertFalse(roomy.spaceIsWarning) + + // No estimate, or Apple Photos: free space only. + let unmeasured = destinationModel(destinationPath: "/Archive", estimate: nil, free: 500_000_000_000) + XCTAssertEqual(unmeasured.spaceLine, "\(size(500_000_000_000)) free here.") + let photos = destinationModel(kind: .applePhotos, destinationPath: "/Archive", estimate: estimate, free: 500_000_000_000) + XCTAssertEqual(photos.spaceLine, "\(size(500_000_000_000)) free here.") + XCTAssertFalse(photos.spaceIsWarning) + + // While measuring, a stale estimate is not used. + let measuring = destinationModel(destinationPath: "/Archive", isMeasuring: true, estimate: estimate, free: 1) + XCTAssertEqual(measuring.spaceLine, "\(size(1)) free here.") + XCTAssertFalse(measuring.spaceIsWarning) + } + + // MARK: Places and continuing + + func testStartingDirectoryForEachPlace() { + let home = URL(fileURLWithPath: "/Users/someone", isDirectory: true) + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .pictures, home: home)?.path, "/Users/someone/Pictures") + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .desktop, home: home)?.path, "/Users/someone/Desktop") + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .downloads, home: home)?.path, "/Users/someone/Downloads") + XCTAssertEqual(GuidedSetupModel.startingDirectory(for: .externalDrive, home: home)?.path, "/Volumes") + XCTAssertNil(GuidedSetupModel.startingDirectory(for: .other, home: home)) + XCTAssertEqual(GuidedSourcePlace.allCases.map(\.rawValue), ["pictures", "desktop", "downloads", "externalDrive", "other"]) + } + + func testCanContinueNeedsDestination() { + XCTAssertFalse(destinationModel(destinationPath: "").canContinue) + XCTAssertTrue(destinationModel(destinationPath: "/Archive").canContinue) + XCTAssertTrue(destinationModel(kind: .applePhotos, destinationPath: "/Archive").canContinue) + XCTAssertFalse(GuidedSetupModel(step: .source, destinationPath: "/Archive").canContinue) + } +} diff --git a/ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift b/ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift new file mode 100644 index 00000000..9ca5cce2 --- /dev/null +++ b/ui/Tests/ChronoframeAppTests/LayoutPictureModelTests.swift @@ -0,0 +1,159 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import XCTest +@testable import ChronoframeApp + +/// C-25: the folder picture on the preview. Counts come from `newFilesByMonth`, +/// never from the histogram, and undated files are left out. +@MainActor +final class LayoutPictureModelTests: XCTestCase { + private let months: [String: Int] = [ + "2026-10": 212, + "2026-09": 148, + "2025-12": 40, + ] + + func testCardsForThreeDateLayouts() { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: .yyyyMM) + + XCTAssertEqual(LayoutPictureModel.offered, [.yyyyMM, .yyyyMMDD, .yyyy]) + XCTAssertEqual(cards.map(\.structure), [.yyyyMM, .yyyyMMDD, .yyyy]) + XCTAssertEqual(cards.map(\.id), [.yyyyMM, .yyyyMMDD, .yyyy]) + XCTAssertEqual(cards.map(\.title), LayoutPictureModel.offered.map(FolderLayoutPresentation.title)) + } + + func testLinesUseNewFilesByMonthNewestFirst() { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: .yyyyMM) + + let monthCard = cards[0] + XCTAssertEqual(monthCard.lines, [ + "2026/", " 10/ · 212", " 09/ · 148", + "2025/", " 12/ · 40", + ]) + + let dayCard = cards[1] + XCTAssertEqual(dayCard.lines, [ + "2026/", " 10/ · 212", " one folder per day", " 09/ · 148", + "2025/", " 12/ · 40", + ]) + + let yearCard = cards[2] + XCTAssertEqual(yearCard.lines, ["2026/ · 360", "2025/ · 40"]) + + // Undated files are left out, not folded into a month. + let withUnknown = LayoutPictureModel.cards(newFilesByMonth: months.merging(["Unknown": 99]) { $1 }, selected: .yyyyMM) + XCTAssertEqual(withUnknown[0].lines, monthCard.lines) + XCTAssertEqual(withUnknown[2].lines, yearCard.lines) + } + + func testNoCardsWithoutMonthCounts() { + XCTAssertTrue(LayoutPictureModel.cards(newFilesByMonth: [:], selected: .yyyyMM).isEmpty) + XCTAssertTrue(LayoutPictureModel.cards(newFilesByMonth: ["Unknown": 12], selected: .yyyyMM).isEmpty) + } + + func testFooterCounts() { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: .yyyyMM) + XCTAssertEqual(cards[0].footer, "3 folders") + XCTAssertEqual(cards[1].footer, "One folder for each day") + XCTAssertEqual(cards[2].footer, "2 folders") + + let single = LayoutPictureModel.cards(newFilesByMonth: ["2026-10": 5], selected: .yyyyMM) + XCTAssertEqual(single[0].footer, "1 folder") + XCTAssertEqual(single[2].footer, "1 folder") + } + + func testSelectedCardMatchesPreference() { + for selected in LayoutPictureModel.offered { + let cards = LayoutPictureModel.cards(newFilesByMonth: months, selected: selected) + XCTAssertEqual(cards.filter(\.isSelected).map(\.structure), [selected]) + } + + // A layout that is not offered selects no card. + let none = LayoutPictureModel.cards(newFilesByMonth: months, selected: .flat) + XCTAssertTrue(none.allSatisfy { !$0.isSelected }) + } + + func testAtMostSixLines() { + var many: [String: Int] = [:] + for year in 2020...2026 { + for month in 1...12 { + many[String(format: "%04d-%02d", year, month)] = 10 + } + } + let cards = LayoutPictureModel.cards(newFilesByMonth: many, selected: .yyyyMM) + + for card in cards { + XCTAssertLessThanOrEqual(card.lines.count, 6, card.title) + } + XCTAssertEqual(cards[0].lines, ["2026/", " 12/ · 10", " 11/ · 10", " 10/ · 10", " 09/ · 10", " 08/ · 10"]) + XCTAssertEqual(cards[1].lines, ["2026/", " 12/ · 10", " one folder per day", " 11/ · 10", " 10/ · 10", " 09/ · 10"]) + XCTAssertEqual(cards[2].lines.count, 6) + XCTAssertEqual(cards[2].footer, "7 folders") + XCTAssertEqual(cards[0].footer, "84 folders") + } + + // MARK: - Section behavior + + private func restart( + current: FolderStructure = .yyyyMM, + chosen: FolderStructure = .yyyy, + isRunning: Bool = false, + isDedupeWorking: Bool = false, + hasActiveImport: Bool = false, + canStartPreview: Bool = true + ) -> Bool { + RunLayoutPictureSection.shouldRestartPreview( + current: current, + chosen: chosen, + isRunning: isRunning, + isDedupeWorking: isDedupeWorking, + hasActiveImport: hasActiveImport, + canStartPreview: canStartPreview + ) + } + + func testSectionStartsAPreviewOnlyForADifferentIdleChoice() { + // A normal ready preview restarts. + XCTAssertTrue(restart()) + // The same card is a no-op. + XCTAssertFalse(restart(chosen: .yyyyMM)) + // A run in progress blocks it. + XCTAssertFalse(restart(isRunning: true)) + } + + func testSectionDoesNotChangeLayoutWhenThePreviewCannotBeRebuilt() { + // Duplicate cleanup in flight: startPreview() would return early. + XCTAssertFalse(restart(isDedupeWorking: true)) + // Setup paths not ready: startPreview() would return early. + XCTAssertFalse(restart(canStartPreview: false)) + // An import preview would be discarded and replaced by a Setup preview. + XCTAssertFalse(restart(hasActiveImport: true)) + } + + func testSectionShowsTheOneLineInsteadOfCardsForAnImportPreview() { + XCTAssertNil(RunLayoutPictureSection.layoutLine(for: .yyyyMM, hasActiveImport: false)) + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .yyyyMM, hasActiveImport: true), + "Layout: Year / Month. Change it in Settings." + ) + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .flat, hasActiveImport: true), + "Layout: One folder. Change it in Settings." + ) + } + + func testSectionShowsOneLineForLayoutsThatAreNotOffered() { + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .flat), + "Layout: One folder. Change it in Settings." + ) + XCTAssertEqual( + RunLayoutPictureSection.layoutLine(for: .yyyyMonEvent), + "Layout: Year / Month / Event. Change it in Settings." + ) + XCTAssertNil(RunLayoutPictureSection.layoutLine(for: .yyyyMM)) + XCTAssertEqual(RunLayoutPictureSection.duplicateCaption(count: 1_204), "\((1_204).formatted()) exact copies go to a separate Duplicate folder.") + XCTAssertEqual(RunLayoutPictureSection.duplicateCaption(count: 1), "1 exact copy goes to a separate Duplicate folder.") + } +} diff --git a/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift b/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift index 8d9eeb4a..6e08159a 100644 --- a/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunTimelinePresentationTests.swift @@ -160,4 +160,42 @@ final class RunTimelinePresentationTests: XCTestCase { XCTAssertEqual(TimelinePlurals.acrossMonths(3, bundle: german), "in 3 Monaten") XCTAssertEqual(TimelinePlurals.filesToCopy(1, bundle: german), "1 Datei zu kopieren") } + + // MARK: - Photos on arrival (C-25) + + func testDefaultSelectionIsNewestDatedBucket() { + let buckets = [ + DateHistogramBucket(key: "2021-04", plannedCount: 40), + DateHistogramBucket(key: "2022-01", plannedCount: 30), + DateHistogramBucket(key: "2021-05", plannedCount: 30), + DateHistogramBucket(key: "Unknown", plannedCount: 9), + ] + XCTAssertEqual( + RunTimelineView.defaultSelectionKey(buckets: buckets, status: .dryRunFinished, selectedKey: nil), + "2022-01" + ) + // Only a ready preview selects anything, and never over a choice already made. + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: buckets, status: .running, selectedKey: nil)) + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: buckets, status: .finished, selectedKey: nil)) + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: buckets, status: .dryRunFinished, selectedKey: "2021-04")) + } + + func testNoDefaultSelectionWithoutDatedBuckets() { + XCTAssertNil(RunTimelineView.defaultSelectionKey(buckets: [], status: .dryRunFinished, selectedKey: nil)) + XCTAssertNil(RunTimelineView.defaultSelectionKey( + buckets: [DateHistogramBucket(key: "Unknown", plannedCount: 9)], + status: .dryRunFinished, + selectedKey: nil + )) + } + + func testSelectedBucketTitle() { + XCTAssertEqual(RunTimelineView.selectedBucketTitle(key: "2026-10", count: 212), "October 2026: 212 photos and videos") + XCTAssertEqual(RunTimelineView.selectedBucketTitle(key: "2026-10", count: 1), "October 2026: 1 photo or video") + XCTAssertEqual( + RunTimelineView.selectedBucketTitle(key: "2026-10", count: 1_204), + "October 2026: \((1_204).formatted()) photos and videos" + ) + XCTAssertEqual(RunTimelineView.selectedBucketTitle(key: "Unknown", count: 9), "Unknown Date: 9 photos and videos") + } } diff --git a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift index 68da8a25..2c0618bb 100644 --- a/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift +++ b/ui/Tests/ChronoframeAppTests/RunWorkspaceModelTests.swift @@ -206,7 +206,7 @@ final class RunWorkspaceModelTests: XCTestCase { badge: "Preparing"), HeroRow(label: "running preview", status: .running, mode: .preview, canStart: true, title: "Building the preview", - message: "You can keep using your Mac. Nothing is being copied.", + message: "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.", badge: "Previewing"), HeroRow(label: "running transfer", status: .running, mode: .transfer, canStart: true, title: "Copying your photos", @@ -272,6 +272,17 @@ final class RunWorkspaceModelTests: XCTestCase { ) } + func testRunningPreviewMessageSaysOnlyReading() { + let message = heroModel(status: .running, mode: .preview).heroState.message + XCTAssertEqual(message, "Chronoframe is only reading. Nothing is copied yet, and you can keep using your Mac.") + + // The running transfer message is unchanged. + XCTAssertEqual( + heroModel(status: .running, mode: .transfer).heroState.message, + "You can keep using your Mac. Originals are only read, never changed." + ) + } + func testHeroCopyNeverSaysTransferOrRun() { let statuses: [RunStatus] = [ .idle, .preflighting, .running, .dryRunFinished, .finished, .nothingToCopy, diff --git a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift index 48ba4096..5a0817bb 100644 --- a/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift +++ b/ui/Tests/ChronoframeAppTests/ScreenRenderEvidenceTests.swift @@ -57,6 +57,19 @@ final class ScreenRenderEvidenceTests: XCTestCase { assertWritten("m1-preview-over-allowance") } + func testRenderPreviewWithPhotosAndLayout() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .runPreviewOverAllowance) + // Tall frame: the preview is a scroll view, and the selected month, the folder + // picture and the Details disclosure sit below the first screen. + try await render( + RootSplitView(appState: appState), + name: "m3-preview-photos-layout", + size: NSSize(width: 1360, height: 2400) + ) + assertWritten("m3-preview-photos-layout") + } + func testRenderCopyComplete() async throws { try requireEvidenceMarker() let appState = UITestAppStateFactory.make(scenario: .runCopyComplete) @@ -101,6 +114,49 @@ final class ScreenRenderEvidenceTests: XCTestCase { assertWritten("m2-deduplicate-lanes") } + func testRenderGuidedSource() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .guidedFirstRun) + // A constant binding: the render must never read or write the real `didOnboard` default. + try await render( + SetupView(appState: appState, didOnboard: .constant(false)), + name: "m3-guided-source", + size: NSSize(width: 1180, height: 820) + ) + assertWritten("m3-guided-source") + } + + func testRenderGuidedDestination() async throws { + try requireEvidenceMarker() + let appState = UITestAppStateFactory.make(scenario: .guidedFirstRun) + // Temporary folders stand in for the person's: no panel opens and no real folder is read. + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("guided-render-\(UUID().uuidString)", isDirectory: true) + let source = root.appendingPathComponent("Pictures", isDirectory: true) + let destination = root.appendingPathComponent("Organized", isDirectory: true) + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + appState.setupStore.sourcePath = source.path + appState.setupStore.destinationPath = destination.path + + let model = GuidedSetupModel( + step: .destination, + sourceKind: .folder, + sourcePath: source.path, + destinationPath: destination.path, + isMeasuring: false, + estimate: FolderSizeEstimate(fileCount: 18_452, totalBytes: 96_400_000_000, isComplete: true), + destinationFreeBytes: 412_000_000_000 + ) + try await render( + GuidedSetupView(appState: appState, didOnboard: .constant(false), fixedModel: model).darkroom(), + name: "m3-guided-destination", + size: NSSize(width: 1180, height: 820) + ) + assertWritten("m3-guided-destination") + } + private func makeEntitlementStore() async -> EntitlementStore { let store = EntitlementStore( storeKit: EvidenceStore(), diff --git a/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift b/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift index 25ebbb06..1480e4fa 100644 --- a/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift +++ b/ui/Tests/ChronoframeAppTests/SetupCoordinatorTests.swift @@ -36,6 +36,60 @@ final class SetupCoordinatorTests: XCTestCase { XCTAssertEqual(harness.historyStore.destinationRoot, destinationURL.path) } + @MainActor + func testChooseSourceFolderOpeningAtSelectsThatFolder() async throws { + let fixture = try SetupCoordinatorFixture() + defer { fixture.tearDown() } + let chosen = try fixture.makeFolder("Pictures Pick") + let startingPlace = URL(fileURLWithPath: "/Users/someone/Pictures", isDirectory: true) + let harness = fixture.harness + + harness.folderAccessService.nextChosenFolder = chosen + let didChoose = await fixture.coordinator.chooseSourceFolder(openingAt: startingPlace) + + XCTAssertTrue(didChoose) + XCTAssertNil(fixture.errors.last) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.count, 1) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.first?.directory, startingPlace) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.first?.prompt, "Choose This Folder") + XCTAssertEqual(harness.setupStore.sourcePath, chosen.path) + XCTAssertEqual(harness.setupStore.sourceItems, [chosen]) + XCTAssertEqual(harness.preferencesStore.lastManualSourcePath, chosen.path) + XCTAssertEqual(harness.preferencesStore.bookmark(for: "manual.source")?.path, chosen.path) + + // No starting place: the default start, through the single-folder picker. + let other = try fixture.makeFolder("Somewhere Else") + harness.folderAccessService.nextChosenFolder = other + let didChooseOther = await fixture.coordinator.chooseSourceFolder(openingAt: nil) + + XCTAssertTrue(didChooseOther) + XCTAssertEqual(harness.folderAccessService.openingAtCalls.count, 1) + XCTAssertNil(harness.folderAccessService.chooseFolderCalls.last?.startingAt) + XCTAssertEqual(harness.folderAccessService.chooseFolderCalls.last?.prompt, "Choose This Folder") + XCTAssertEqual(harness.setupStore.sourceItems, [other]) + } + + @MainActor + func testChooseSourceFolderCancelledChangesNothing() async throws { + let fixture = try SetupCoordinatorFixture() + defer { fixture.tearDown() } + let harness = fixture.harness + harness.folderAccessService.nextChosenFolder = nil + + let cancelledAtPlace = await fixture.coordinator.chooseSourceFolder( + openingAt: URL(fileURLWithPath: "/Users/someone/Desktop", isDirectory: true) + ) + let cancelledAtDefault = await fixture.coordinator.chooseSourceFolder(openingAt: nil) + + XCTAssertFalse(cancelledAtPlace) + XCTAssertFalse(cancelledAtDefault) + XCTAssertNil(fixture.errors.last) + XCTAssertEqual(harness.setupStore.sourcePath, "") + XCTAssertTrue(harness.setupStore.sourceItems.isEmpty) + XCTAssertEqual(harness.preferencesStore.lastManualSourcePath, "") + XCTAssertNil(harness.preferencesStore.bookmark(for: "manual.source")) + } + @MainActor func testChooseFolderValidationFailureSurfacesErrorWithoutChangingState() async { let sourceURL = URL(fileURLWithPath: "/Volumes/Locked") diff --git a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift index ec1a7b35..30e3d5ff 100644 --- a/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift +++ b/ui/Tests/ChronoframeAppTests/UITestWindowFitTests.swift @@ -69,6 +69,23 @@ final class UITestWindowFitTests: XCTestCase { XCTAssertGreaterThanOrEqual(size.height, minimum.height) } + func testGuidedFirstRunScenarioIsSizedLikeTheWideReviewAndFitsASmallDisplay() { + let scenario = UITestScenario.guidedFirstRun + XCTAssertEqual(UITestScenario(rawValue: "guidedFirstRun"), scenario) + XCTAssertFalse(scenario.usesMeteredTrialUI) + XCTAssertFalse(scenario.opensSettingsOnLaunch) + XCTAssertEqual(scenario.preferredMainWindowSize, NSSize(width: 1180, height: 820)) + + // On a small runner display it shrinks to fit like every other main-window scenario. + let size = UITestScenario.fittedContentSize( + preferred: scenario.preferredMainWindowSize, chrome: chrome, + visible: NSSize(width: 1024, height: 690), minimum: minimum + ) + XCTAssertLessThanOrEqual(size.width, 1024 - chrome.width) + XCTAssertLessThanOrEqual(size.height, 690 - chrome.height) + XCTAssertGreaterThanOrEqual(size.height, minimum.height) + } + func testOverAllowancePreviewScenarioIsMeteredAndSizedLikeThePreviewScenario() { let scenario = UITestScenario.runPreviewOverAllowance XCTAssertEqual(UITestScenario(rawValue: "runPreviewOverAllowance"), scenario) diff --git a/ui/Xcode/UITests/ChronoframeUITests.swift b/ui/Xcode/UITests/ChronoframeUITests.swift index 2015962f..8c5fc139 100644 --- a/ui/Xcode/UITests/ChronoframeUITests.swift +++ b/ui/Xcode/UITests/ChronoframeUITests.swift @@ -936,6 +936,13 @@ final class ChronoframeUITests: XCTestCase { XCTAssertFalse(app.buttons["transferButton"].exists) XCTAssertFalse(app.toolbars.buttons["Transfer"].exists) XCTAssertFalse(app.toolbars.buttons["Preview"].exists) + // FRX C-25: on a ready preview the report and log panels sit behind a collapsed Details disclosure. + let details = Self.element(identifier: "runDetailsDisclosure", in: app) + XCTAssertTrue(details.waitForExistence(timeout: 5)) + let detailsTriangle = details.disclosureTriangles.firstMatch + XCTAssertTrue(detailsTriangle.waitForExistence(timeout: 5)) + detailsTriangle.click() + XCTAssertTrue(Self.button(identifier: "openDestinationButton", in: app).waitForExistence(timeout: 5)) XCTAssertTrue(app.buttons["openDestinationButton"].exists) XCTAssertTrue(app.descendants(matching: .any)["runWorkspaceTabs"].exists) XCTAssertTrue(app.staticTexts["Reports and Logs"].exists)