asterism branch T-2346/bugfix-export-cleanup-before-share-finishes commits 4 files 12 touched lines +566 / -76 round 2 of 2

Pre-push review: T-2346/bugfix-export-cleanup-before-share-finishes

Second round. Reviews what PR #87 adds to origin/main (merge base c314419d, four commits). Round 1 returned Needs fixes (docs only); this round checks those items and re-reviews the code.

At a glance

  • Round-1 status: 7 of 9 items resolved; open are the idempotence test (minor) and two unqualified Decision 6 citations in SettingsBackupModel.swift (nit). The same-subject staging race is recorded in the report's follow-up section as agreed, but no Transit ticket exists for it yet.
  • Correctness: both models now keep the staged file until documentExporter's onCompletion (activity report, or the 3 s grace expiry) instead of the sheet's dismissal. The two hooks are order-independent, which the Mac (outcome-first) needs.
  • Re-entrancy: startExport() and ContentView.startCommandExport refuse while isAwaitingShareOutcome; the ⇧⌘E guard (round-1 item) landed in 3f2f9ed4. Cost, accepted in the report: an enabled Export button whose tap is silently swallowed for up to 3 s.
  • Tests: 1,824 passed / 0 failed on the simulator (JUnit derived from the xcresult, coverage not collected). Six lifecycle tests added, four replaced; five of the backup suite's tests carry dead temp-file I/O that a shared helper would remove.
  • New this round: specs/empty-library/design.md §Pattern extension audit and implementation.md line 94 still state the pre-fix wiring; Q46 of ipad-and-mac-layouts is contradicted by the report but not annotated.
  • Optional refinement: isAwaitingShareOutcome equals state == .idle && exportedFileURL != nil at every reachable point, so it could be computed rather than stored; and an isOccupied predicate on the model would let ContentView stop reading the flag directly.

Verdict

Ready to push

The lifecycle split is correct on both platforms: every ordering of dismissal and outcome (dismiss→outcome, outcome→dismiss, double dismiss, double outcome, failure paths, model replacement) was traced and lands in .idle with the file removed exactly once and the flag never stuck. make test-quick passes: Mac build clean, 1,824 simulator unit tests, 0 failures, including both parameterised outcome tests. Of round 1's findings, the three majors (stale testing.md, the documentExporter doc comment, the report gaps), the ⇧⌘E guard, the Q47 annotation and the stale view/model comments are all resolved. Still open and minor: no test calls handleShareOutcome twice for one presentation although both doc comments claim idempotence, and two passages in specs/empty-library/design.md and implementation.md still describe the pre-fix wiring and should get the same done by T-2346 annotation Q47 got. Neither blocks the push; both are five-minute follow-ups that can ride along in a last commit or a ticket.

Review findings

10 raised · 0 fixed · 10 skipped

Jump to findings →

Tests

Pass rate: 100% (1824 of 1824)

New tests: 6

Diff coverage: n/a

Jump to tests →

Commits

Three-level explanation

What changed

When you export a backup or a Markdown file, the app first writes the file to a temporary spot and then shows the share sheet so you can save or send it. Afterwards it deletes that temporary file. Before this fix, the app deleted the file the moment the share sheet slid away. But on the iPhone, when you pick Save to Files, the sheet slides away before the Files app has finished copying. So the app could delete the file while Files was still reading it.

Now the app waits for the share sheet to report back ("done" or "cancelled") before deleting. If the sheet never reports, a three-second timer deletes the file anyway. The Empty Library row in Settings already worked this way; the other two export rows now match it.

Why it matters

Nobody had lost a file yet, but every export was one slow copy away from a missing or truncated backup. A backup that silently comes out empty is the worst kind of bug for a library app, so it was fixed before it happened.

Key concepts

  • Staged file: the temporary copy handed to the share sheet. Think of it as leaving a parcel on the porch for the courier: you should not take it back inside until the courier confirms pickup.
  • Dismissal vs outcome: "the sheet closed" and "the activity finished" are two different events, and on iOS they can arrive in that order; on the Mac they can arrive in the opposite order. The fix treats them as separate signals.
  • Re-entrancy guard: while the app is waiting for the report, a second tap on Export is ignored, so a new file can never be created while the old one's deletion is still pending.

Changes overview

Two @Observable view models, SettingsBackupModel and MarkdownExportModel, replace their single handleShareCompletion()/handleShareCancellation() (both calling cleanupAndReset()) with a two-hook lifecycle: shareDismissed() is wired to the presentation binding's set(false) and only leaves .sharing; handleShareOutcome(_:) is wired to documentExporter's onCompletion and performs the cleanup. A private isAwaitingShareOutcome flag bridges the two and is read by startExport(), and, for the Markdown model, by ContentView.startCommandExport (⇧⌘E), so a second export cannot replace the tracked staged file during the wait. The documentExporter doc comment, docs/agent-notes/testing.md, and empty-library Q47 are updated to describe the new contract, and a bugfix report records the decision.

Implementation approach

Order-independence is done with state guards rather than sequencing: shareDismissed requires state == .sharing; handleShareOutcome requires state == .sharing || isAwaitingShareOutcome. Whichever arrives first acts, the second is a no-op. On the Mac, fileExporter can deliver the outcome before SwiftUI writes isPresented back to false; on iOS the binding's set fires first and completionWithItemsHandler may follow seconds later, or never (hence the exporter's 3 s grace expiry). The view wiring becomes identical to the Empty Library row's, so the three documentExporter callers share one shape.

Trade-offs

  • Flag vs state case. EmptyLibraryModel models the wait as a .shareDismissed State case because it has something to show during it. Here the State enums are public and switched exhaustively in four views; a new case would touch all of them to render nothing. The report accepts the visible cost: for up to 3 s the Export button is enabled but a tap is swallowed.
  • Deferral widens an existing race. The detail screen's @State Markdown model and ⇧⌘E's model stage the same subject to the same path; the first model's now-deferred delete can unlink the second's file if both are used within 3 s. Recorded as a follow-up, not fixed.
  • Ignored outcome parameter. Both models ignore the DocumentExportOutcome, but keeping the parameter matches the third caller and the modifier's signature; the parameterised tests pin that the outcome is irrelevant.

Technical deep dive

The invariant that makes the guards sufficient is flag-true ⇒ state == .idle, since the flag is set and cleared only alongside state = .idle. From that, every interleaving of the two hooks terminates in (.idle, flag false, file removed once): the Mac ordering passes the outcome guard via .sharing and makes the trailing dismissal a no-op; the iOS ordering passes it via the flag. Double delivery of the outcome is closed twice on iOS (the model guard and ExportOutcomeLedger's per-presentation answer) and once on the Mac (the two fileExporter callbacks are exclusive). .failed is unreachable from .sharing, and the binding's get is state == .sharing, so no failure path can interact with the wait.

The lifetime argument for the deferred cleanup: the grace Task in DocumentExporter.startGraceWait captures the modifier struct by value, and with it the onCompletion closure that retains the model, so a replaced or torn-down owner still gets its cleanup delivered within 3 s. The single path that cancels the grace wait is beginPresentation() on the same surface, which is precisely the ⇧⌘E re-entry that startCommandExport now refuses on isAwaitingShareOutcome; the detail screens' models are per-view @State and cannot be re-presented while waiting.

Architecture impact

documentExporter's contract is now stated on the modifier itself: the binding's set leaves the caller's sharing state, onCompletion is the cleanup point. All three callers conform. MarkdownExportModel.isAwaitingShareOutcome becomes public private(set) for one reader; a computed isOccupied (or a derived flag from state == .idle && exportedFileURL != nil) would remove the stored bit and keep the busy predicate in one place. The stored flag is derivable at every reachable point today; keeping it stored is a documentation choice, not a correctness one.

Potential issues

  • Same-subject, two-model staging race (report §Follow-up): both MarkdownExportModels write stagingDirectory/<title>.md atomically; deferral extends the exposure from "before the first sheet closes" to "up to 3 s after". Per-export subdirectories with a recursive scavenge would close it. Needs a ticket; none exists.
  • Swallowed tap window: up to lateReportGrace (3 s) after dismissal when nothing reports, on both rows. Six comments now quote the literal "three seconds" that lives in a private constant.
  • Idempotence is asserted in prose only: no test delivers two outcomes for one presentation, so the guard that makes the claim true has no regression pin.
  • The real-phone Save to Files ordering is the one arm the simulator cannot exercise; the report says manual verification was not performed. A Development install and a category:DocumentExport notice line would confirm it end to end.

Completeness assessment

Fully implemented: the split lifecycle in both models, view wiring, order-independence, the export re-entrancy guard, the ⇧⌘E guard, docs (testing.md, modifier contract, Q47), the bugfix report with the flag-vs-case rationale and the follow-up. Partially: spec hygiene, since empty-library's design.md audit table and implementation.md:94 still describe the pre-fix wiring. Missing: an outcome-twice test; a ticket for the staging-path race; on-device confirmation of the iOS Save to Files arm.

Important changes — detailed

SettingsBackupModel: dismissal and outcome become two order-independent hooks

Asterism/Asterism/ViewModels/SettingsBackupModel.swift

Why it matters. This is the bug fix: the staged archive is no longer unlinked at the sheet's dismissal while a Save to Files activity may still be reading it. The two guards are what make the Mac's outcome-first ordering and iOS's dismissal-first ordering both terminate correctly.

What to look at. SettingsBackupModel.swift:297 (flag), :314 (startExport guard), :347-370 (shareDismissed / handleShareOutcome)

Takeaway. Two callbacks that can arrive in either order need no sequencing if each acts only on the state it expects and both converge on the same terminal state; the invariant 'flag-true implies .idle' is what makes the pair of guards sufficient.
Rationale. Mirrors the Empty Library row (empty-library Q28, Q34) so all three documentExporter callers share one shape; the outcome is ignored because cleanup is the same either way.

MarkdownExportModel: the same split, with the flag readable for ⇧⌘E

Asterism/Asterism/ViewModels/MarkdownExportModel.swift

Why it matters. Same correctness fix for the Markdown export; the file removal moves from the dismissal to the delivered outcome. isAwaitingShareOutcome is public private(set) here because ContentView's command export must also refuse during the wait.

What to look at. MarkdownExportModel.swift:57, :93, :155-183

Takeaway. Expose the narrowest thing a second reader needs (a read-only Bool) rather than a new state case that four exhaustive switches would have to render as nothing.
Rationale. The report records why a private flag was chosen over EmptyLibraryModel's .shareDismissed case: these rows have nothing to show during the wait, and the State enums are public and switched exhaustively in four views. The accepted cost is a swallowed tap for up to 3 s.

ContentView: ⇧⌘E refuses while the previous share's outcome is pending

Asterism/Asterism/ContentView.swift

Why it matters. Round-1 finding. A second ⇧⌘E during the grace window would replace commandExportModel; the new presentation calls beginPresentation(), which cancels the grace wait, so the old model's cleanup would never be delivered and its file would sit until the 24 h scavenge.

What to look at. ContentView.swift:846-849

Takeaway. When cleanup is deferred to a callback, every path that can cancel that callback (here: re-presenting the same surface) must be guarded too, not only the paths that create new work.
Rationale. Commit 3f2f9ed4, in response to the first pre-push review; verified that beginPresentation() → cancelGraceWait() is the cancelling path.

documentExporter doc comment states the contract for every caller

Asterism/Asterism/Support/PlatformModifiers.swift

Why it matters. The seam's own doc previously recommended the pattern this fix removes ('takes the presentation binding's set as its dismissal'). The next caller reads this, not the bugfix report.

What to look at. PlatformModifiers.swift:846-856

Takeaway. Put a lifecycle contract on the API that owns it; per-caller comments drift, the modifier's doc is what autocomplete shows.
Rationale. Round-1 major finding; resolved in 3f2f9ed4.

Lifecycle tests: six added, four replaced, both suites

Asterism/AsterismTests/SettingsBackupModelTests.swift

Why it matters. The regression pins: dismissal leaves the file; the outcome (completed or cancelled) removes it; outcome-before-dismissal cleans up and the trailing dismissal is a no-op; a second dismissal is a no-op; a second export is suppressed during the wait and allowed after.

What to look at. SettingsBackupModelTests.swift:121-266; MarkdownExportModelTests.swift:167-290

Takeaway. Parameterising the outcome test over .completed and .cancelled is the cheapest way to pin 'the argument is ignored' as a behaviour rather than an accident.
Open question. Rationale not stated by the author and not inferable from the diff.

Bugfix report and doc updates

specs/bugfixes/export-cleanup-before-share-finishes/report.md

Why it matters. Records the root cause (conflating 'sheet gone' with 'activity done'), the flag-vs-state-case decision with its visible cost, the re-entrancy rationale, and the same-subject staging race as a named follow-up. testing.md and empty-library Q47 now say the change is done.

What to look at. report.md (new); testing.md:1705-1711; empty-library decision_log.md:53

Takeaway. When a fix deliberately does not mirror the sibling it cites, write down which part differs and why; 'all three callers now agree' was true of the wiring and not of the state shape until the report said so.
Rationale. Round-1 findings on the report's gaps; resolved in 3f2f9ed4.

Key decisions

Delete on the delivered outcome, not the dismissal.

The binding's set(false) is the sheet closing; documentExporter's onCompletion is the activity reporting (or the 3 s grace expiring). On iOS, Save to Files reports after the close (empty-library Decision 6). Alternatives in the report: a fixed delay in each model (rejected: duplicates the exporter's fallback) and leaving deletion on the binding (the bug).

Order-independent guards rather than sequencing.

The Mac save panel can deliver its result before SwiftUI writes isPresented back; a fix that assumed dismissal-first left the model stuck awaiting forever (report §Investigation). Each hook acts only while its expected state is current.

A private flag, not a <code>.shareDismissed</code> state case.

EmptyLibraryModel uses a case because it has a progress sentence and an outcome-dependent branch. These rows have nothing to show; their public State enums are switched exhaustively in four views. Accepted cost: an enabled Export button whose tap is swallowed for up to 3 s; the report names promotion to a case as the remedy if that ever reads as broken.

Refuse a new export while the outcome is pending.

BackupExportStage tracks one staged result, so a fresh export in the window would be deleted by the old share's cleanup. Extended to ⇧⌘E in 3f2f9ed4 because re-presenting the surface cancels the exporter's grace wait.

<code>handleShareOutcome</code> keeps its ignored parameter and stays internal.

Matches EmptyLibraryModel.handleShareOutcome(_:) so the three callers have one shape; DocumentExportOutcome is internal to the module, like the modifier.

The same-subject staging race is recorded, not fixed.

Two MarkdownExportModels over one subject write one path; deferral widens an existing race to 3 s. Out of scope for a two-row lifecycle bugfix; per-export subdirectories or lifting the detail models (Q46) would close it. No ticket exists yet.

Verified at the model level only.

The real-phone Save to Files ordering cannot run on the simulator. The report states manual verification was not performed; a Development install would need no approval under CLAUDE.md.

Review findings

SeverityAreaFindingResolution
minorRound 1 (h): idempotence untestedBoth handleShareOutcome doc comments claim a second delivery removes nothing, but no test in either suite calls it twice for one presentation. The guard makes it true today; nothing pins it.One test per suite: export → shareDismissed() → handleShareOutcome(.completed) → handleShareOutcome(.cancelled); backup asserts cleanupCallCount == 1, markdown asserts exportedFileURL == nil and a following startExport() runs. Also covers the 'outcome with nothing pending' guard. Not applied: branch not to be modified.
minorspecs/empty-library/design.md:73-74The 'Pattern extension audit: documentExporter callers' table still says the backup row and MarkdownExportShare keep onCompletion: { _ in } with the binding's set as the dismissal — the pre-fix wiring, in the design that introduced the contract.Annotate both rows as Q47 was: 'since T-2346: set → shareDismissed(), onCompletion → handleShareOutcome(_:)'. Not applied.
minorspecs/empty-library/implementation.md:94'The backup and Markdown export rows ignore the outcome and still clean up on the binding's set, which Decision 6 shows is too early (T-2346).' — stale in the same way the round-1 testing.md sentence was.Append 'Done by T-2346 (PR #87)' or reword to past tense. Not applied.
minorSettingsBackupModelTests.swift:121-266Five lifecycle tests repeat a nine-line setup (temp dir, fake file written to disk, mock, model, startExport). MockBackupExporting.cleanup never touches disk and no assertion checks the file, so the I/O is dead; the file's older tests share the pattern and private helpers already exist in three sibling suites (BackupExportStageTests.TemporaryStaging, EmptyLibraryModelTests.Harness.stageAFile, MarkdownExportModelTests.makeStagingDirectory).A private makeStagedBackup() helper returning (model, mock, fakeURL) with no filesystem calls, or un-private TemporaryStaging and reuse it. Consistent with the file as it stands; not blocking. Not applied.
minorisAwaitingShareOutcome storage (both models)At every reachable point the flag equals state == .idle && exportedFileURL != nil (startExport nils the URL before awaiting; .sharing implies non-nil; the outcome clears it). A stored bit that two methods must keep in step could be a computed property, and the outcome guard would simplify to 'there is a staged file to remove', which also refuses a model-level startExport() during .sharing.Optional. A stored flag is more self-documenting; either answer is acceptable. If kept stored, an isOccupied predicate (isExporting || state == .sharing || isAwaitingShareOutcome) used by both startExport() and ContentView would let the flag return to private. Not applied.
nitRound 1 (f): SettingsBackupModel.swift:337, :355'(T-2118, Decision 6)' and '(Decision 6)' remain unqualified; the sibling MarkdownExportModel.swift:145 writes `empty-library` Decision 6, and this file already cites decisions from two other specs. Inferable from the Q34 citation two lines up, but the spellings should match.Qualify both as `empty-library` Decision 6. Not applied.
nitSame-subject staging race: no ticketRound 1 agreed the race could be named in the report's follow-up section, which it is. No Transit ticket exists, so it lives only in a bugfix report.Create a ticket referencing report §Follow-up candidates, and annotate ipad-and-mac-layouts Q46 ('each stages its own file') with a pointer to it. Not applied.
nit'three seconds' literal in six new commentsMarkdownExportModel.swift:47, SettingsBackupModel.swift:291, SettingsView.swift:298, MarkdownExportShare.swift:32 and both handleShareOutcome docs quote a figure that lives in the private DocumentExporter.lateReportGrace; they go stale together if it moves. testing.md already says 'at the grace expiry'.Say 'the dismissal's grace period (DocumentExporter.lateReportGrace)' and let the modifier's doc own the number. Not applied.
nitTest titles: 'leaves .sharing''Dismissing the share leaves .sharing without deleting the staged file' (both suites) asserts state == .idle; 'leaves' reads equally as 'remains in'.'exits .sharing' or 'returns the row to idle'. Not applied.
nitDuplicated prose and handleShareOutcome no-op reassignmentThe order-independence paragraph appears in full in four model doc comments plus the modifier doc; and in the iOS ordering handleShareOutcome assigns state = .idle when already .idle, one redundant @Observable invalidation per share.Keep the full text on documentExporter and one model, one-line pointers elsewhere; guard the reassignment if touching the file anyway. Cosmetic. Not applied.

Tests

Source: local run at 2026-09-22T16:42:04+10:00 · snapshot 3f2f9ed49dbbc248de50b885902968b89169d216

Baseline: none

Execution: passed · JUnit: 1 file · Coverage: none · Baseline: absent

Coverage scope: as the project configures it

Totals: 1824 passed · 0 failed · 0 skipped · 0 errored · 0 flaky

New and removed tests

Derived by declaration name, from the diff (no baseline run).

Blast radius

Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base c314419df2181896509ff9615f7e2309aac67e3c.

addedmodifieddeletedrenamedunchangedcollapsed package group or +N more⚑N test files with an edge to the node

Per-file diffs

Click to expand.

Asterism/Asterism/ContentView.swift Modified +9 / -5
diff --git a/Asterism/Asterism/ContentView.swift b/Asterism/Asterism/ContentView.swiftindex 1ef2ec9b..9fb49898 100644--- a/Asterism/Asterism/ContentView.swift+++ b/Asterism/Asterism/ContentView.swift@@ -836,12 +836,16 @@ struct ContentView: View {     /// value the moment any of the ids behind it moves.     private func startCommandExport(_ subject: MarkdownExportModel.Subject?) {         // One command export at a time. A second ⇧⌘E while the first is still-        // staging or sharing would replace the model this view's share surface-        // is bound to and strand its staged file. (The *detail screen's* own-        // export is another matter: its model is `@State` inside that screen and-        // this view cannot see it — Q46 records what that costs.)+        // staging or sharing — or, since T-2346, still waiting for its share's+        // outcome after the dismissal — would replace the model this view's+        // share surface is bound to and strand its staged file: the next+        // presentation cancels the exporter's grace wait, so the old model's+        // cleanup would never be delivered. (The *detail screen's* own export+        // is another matter: its model is `@State` inside that screen and this+        // view cannot see it — Q46 records what that costs.)         if let commandExportModel,-           commandExportModel.state == .exporting || commandExportModel.state == .sharing {+           commandExportModel.state == .exporting || commandExportModel.state == .sharing+               || commandExportModel.isAwaitingShareOutcome {             return         }         let exportModel: MarkdownExportModel?
Asterism/Asterism/Support/PlatformModifiers.swift Modified +11 / -5
diff --git a/Asterism/Asterism/Support/PlatformModifiers.swift b/Asterism/Asterism/Support/PlatformModifiers.swiftindex 7b5c4ff9..c3b1fe15 100644--- a/Asterism/Asterism/Support/PlatformModifiers.swift+++ b/Asterism/Asterism/Support/PlatformModifiers.swift@@ -846,11 +846,17 @@ extension View {     /// sheet on iOS, the save panel on the Mac (Req 4.5).     ///     /// `onCompletion` runs once per presentation, on the main actor, and is-    /// told which way it ended: a caller with the same cleanup for both ignores-    /// the argument and takes the presentation binding's `set` as its-    /// dismissal. On iOS it runs when the surface reports, which for Save to-    /// Files is after the sheet has closed, or when the dismissal's grace-    /// period runs out with nothing reported (T-2118).+    /// told which way it ended. On iOS it runs when the surface reports, which+    /// for Save to Files is after the sheet has closed, or when the dismissal's+    /// grace period runs out with nothing reported (T-2118).+    ///+    /// The two hooks split the share's lifecycle (T-2346). The presentation+    /// binding's `set` is the dismissal: it should only leave the caller's+    /// sharing state, so SwiftUI does not re-present the surface, and delete+    /// nothing — with Save to Files an activity can still be reading the staged+    /// file after the sheet has closed. `onCompletion` is the cleanup point. A+    /// caller with the same cleanup for both outcomes ignores the argument, but+    /// still does that cleanup here and never in the binding.     func documentExporter(         isPresented: Binding<Bool>,         file: URL?,
Asterism/Asterism/ViewModels/MarkdownExportModel.swift Modified +57 / -9
diff --git a/Asterism/Asterism/ViewModels/MarkdownExportModel.swift b/Asterism/Asterism/ViewModels/MarkdownExportModel.swiftindex 307d4e61..697d2eb4 100644--- a/Asterism/Asterism/ViewModels/MarkdownExportModel.swift+++ b/Asterism/Asterism/ViewModels/MarkdownExportModel.swift@@ -8,8 +8,9 @@ import OSLog /// `MarkdownExport` renders it, and this model stages the result as a `.md` file /// and drives the share sheet. Sibling of `SettingsBackupModel` and deliberately /// the same shape — same `.idle/.exporting/.sharing/.failed` machine, same-/// privacy-safe message discipline, same cleanup-on-dismiss — because the reader-/// meets both through the identical `ShareSheet`.+/// privacy-safe message discipline, same split share lifecycle (the dismissal+/// leaves `.sharing`; the delivered outcome cleans up, T-2346) — because the+/// reader meets both through the identical `ShareSheet`. @MainActor @Observable public final class MarkdownExportModel {     private static let logger = Logger(@@ -39,6 +40,22 @@ public final class MarkdownExportModel {     private let locale: Locale     private var isExporting = false +    /// True from the sharing surface's dismissal until its outcome is+    /// delivered (T-2346, mirrors `SettingsBackupModel`).+    ///+    /// `documentExporter`'s `onCompletion` runs on the activity's report or,+    /// failing that, three seconds after the dismissal — until it does, the+    /// staged file may still be in an activity's hands, so a fresh export+    /// started in that window is suppressed exactly like one already+    /// exporting rather than being allowed to replace it out from under the+    /// pending cleanup.+    ///+    /// Readable so `ContentView.startCommandExport` can refuse a second ⇧⌘E in+    /// that window too: the next presentation cancels the exporter's grace+    /// wait, so a replaced model's file would otherwise never be cleaned up+    /// until the 24-hour scavenge.+    public private(set) var isAwaitingShareOutcome = false+     /// Creates the model.     ///     /// **Nothing here touches the file system.** The scavenge used to run from@@ -73,7 +90,7 @@ public final class MarkdownExportModel {     /// Reads the input, renders it, stages the file, and hands it to the share     /// sheet. Suppresses a second submission while one is in flight.     public func startExport() async {-        guard !isExporting else { return }+        guard !isExporting, !isAwaitingShareOutcome else { return }         isExporting = true         state = .exporting         errorMessage = nil@@ -120,18 +137,49 @@ public final class MarkdownExportModel {         return fileURL     } -    // MARK: - Share lifecycle+    // MARK: - Share lifecycle (T-2346) -    public func handleShareCompletion() { cleanupAndReset() }--    public func handleShareCancellation() { cleanupAndReset() }+    /// The sharing surface closed. Leaves `.sharing` so SwiftUI does not+    /// re-present the sheet, but deletes nothing yet: with Save to Files the+    /// activity's report can still be on its way (T-2118, `empty-library`+    /// Decision 6). `documentExporter`'s `onCompletion` is where the staged+    /// file is actually removed.+    ///+    /// **Order-independent with `handleShareOutcome` (`empty-library` Q34).**+    /// iOS writes the binding's `set` first and the activity's report may+    /// follow seconds later; the Mac save panel can deliver its result+    /// first, before `isPresented` is written back to `false`. Either call+    /// can therefore run first, and each only acts while the state it+    /// expects is still current — this one requires `.sharing`, so it is a+    /// no-op once `handleShareOutcome` has already moved the row on.+    public func shareDismissed() {+        guard state == .sharing else { return }+        isAwaitingShareOutcome = true+        state = .idle+    } -    private func cleanupAndReset() {+    /// What the sharing surface reported, delivered by `documentExporter`'s+    /// `onCompletion` — on the activity's report or, failing that, three+    /// seconds after the dismissal. The outcome is ignored: a markdown+    /// export stages a file either way, and cleanup is the same whether the+    /// reader sent it or not.+    ///+    /// Accepted from `.sharing` (the Mac ordering, where this can arrive+    /// before `shareDismissed`) as well as while `isAwaitingShareOutcome` is+    /// set (the iOS ordering, where `shareDismissed` has already left+    /// `.sharing`) — see that method's note. Idempotent, so a call that+    /// lands after the model has already reset removes nothing.+    ///+    /// Not `public`: `DocumentExportOutcome` is internal to this module, like+    /// `documentExporter` itself, which is the only production caller.+    func handleShareOutcome(_ outcome: DocumentExportOutcome) {+        guard state == .sharing || isAwaitingShareOutcome else { return }+        isAwaitingShareOutcome = false+        state = .idle         if let exportedFileURL {             try? FileManager.default.removeItem(at: exportedFileURL)         }         exportedFileURL = nil-        state = .idle     }      /// Removes abandoned exports older than 24 hours.
Asterism/Asterism/ViewModels/SettingsBackupModel.swift Modified +51 / -15
diff --git a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift b/Asterism/Asterism/ViewModels/SettingsBackupModel.swiftindex d9826ac9..44ddb7e6 100644--- a/Asterism/Asterism/ViewModels/SettingsBackupModel.swift+++ b/Asterism/Asterism/ViewModels/SettingsBackupModel.swift@@ -284,6 +284,18 @@ public final class SettingsBackupModel {     private let stage: BackupExportStage     private var isExporting = false +    /// True from the sharing surface's dismissal until its outcome is+    /// delivered (T-2346).+    ///+    /// `documentExporter`'s `onCompletion` runs on the activity's report or,+    /// failing that, three seconds after the dismissal — until it does, the+    /// staged file may still be in an activity's hands. `BackupExportStage`+    /// tracks one staged result at a time, so a fresh export started in that+    /// window would replace it out from under the still-pending cleanup,+    /// which would then remove the *new* file instead of the old one. A tap+    /// here in that window is suppressed exactly like one already exporting.+    private var isAwaitingShareOutcome = false+     // MARK: - Init      /// Creates the model over a stage, which scavenges any stale backup files@@ -294,11 +306,12 @@ public final class SettingsBackupModel {      // MARK: - Export -    /// Starts a backup export. Suppresses duplicate submissions while already in flight.+    /// Starts a backup export. Suppresses duplicate submissions while already in flight,+    /// or while a previous share's outcome is still pending (see `isAwaitingShareOutcome`).     /// On success, transitions to `.sharing` with the file URL ready for system share.     /// On failure, transitions to `.failed` with a privacy-safe diagnostic message.     public func startExport() async {-        guard !isExporting else { return }+        guard !isExporting, !isAwaitingShareOutcome else { return }         isExporting = true         state = .exporting         errorMessage = nil@@ -316,22 +329,45 @@ public final class SettingsBackupModel {         isExporting = false     } -    // MARK: - Share Lifecycle--    /// Called when the user completes sharing (dismiss/send). Cleans up the staged file.-    public func handleShareCompletion() {-        cleanupAndReset()-    }+    // MARK: - Share Lifecycle (T-2346) -    /// Called when the user cancels the share sheet. Cleans up the staged file.-    public func handleShareCancellation() {-        cleanupAndReset()+    /// The sharing surface closed. Leaves `.sharing` so SwiftUI does not+    /// re-present the sheet (`empty-library` Q34), but deletes nothing yet:+    /// with Save to Files the activity's report can still be on its way+    /// (T-2118, Decision 6). `documentExporter`'s `onCompletion` is where the+    /// staged file is actually removed.+    ///+    /// **Order-independent with `handleShareOutcome` (`empty-library` Q34).**+    /// iOS writes the binding's `set` first and the activity's report may+    /// follow seconds later; the Mac save panel can deliver its result+    /// first, before `isPresented` is written back to `false`. Either call+    /// can therefore run first, and each only acts while the state it+    /// expects is still current — this one requires `.sharing`, so it is a+    /// no-op once `handleShareOutcome` has already moved the row on.+    public func shareDismissed() {+        guard state == .sharing else { return }+        isAwaitingShareOutcome = true+        state = .idle     } -    // MARK: - Private--    private func cleanupAndReset() {-        stage.cleanup()+    /// What the sharing surface reported, delivered by `documentExporter`'s+    /// `onCompletion` — on the activity's report or, failing that, three+    /// seconds after the dismissal (Decision 6). The outcome is ignored: this+    /// row's cleanup is the same whether the archive was sent or the sheet+    /// was cancelled.+    ///+    /// Accepted from `.sharing` (the Mac ordering, where this can arrive+    /// before `shareDismissed`) as well as while `isAwaitingShareOutcome` is+    /// set (the iOS ordering, where `shareDismissed` has already left+    /// `.sharing`) — see that method's note. `cleanup()` is idempotent, so a+    /// call that lands after the row has already reset removes nothing.+    ///+    /// Not `public`: `DocumentExportOutcome` is internal to this module, like+    /// `documentExporter` itself, which is the only production caller.+    func handleShareOutcome(_ outcome: DocumentExportOutcome) {+        guard state == .sharing || isAwaitingShareOutcome else { return }+        isAwaitingShareOutcome = false         state = .idle+        stage.cleanup()     } }
Asterism/Asterism/Views/MarkdownExportShare.swift Modified +13 / -10
diff --git a/Asterism/Asterism/Views/MarkdownExportShare.swift b/Asterism/Asterism/Views/MarkdownExportShare.swiftindex 4468a9b1..b5b6188c 100644--- a/Asterism/Asterism/Views/MarkdownExportShare.swift+++ b/Asterism/Asterism/Views/MarkdownExportShare.swift@@ -7,9 +7,9 @@ import SwiftUI /// whether the surface is up is `model.state == .sharing`; a second copy of that /// kept in step by `onChange` is a copy that can disagree with it. The derived /// binding is the presented-value shape both screens already use for their-/// deletion dialogs, and its `set` is the dismissal — which covers send, save-/// and cancel alike, because neither the share sheet nor the save panel reports-/// which of them happened.+/// deletion dialogs, and its `set` is the dismissal, which only leaves+/// `.sharing`. Which way the share ended, and the staged file's removal, come+/// through `onCompletion` instead (T-2346). /// /// Lifted out of `ShareSheet.swift` by `ipad-and-mac-layouts`: that file became /// iOS-only, and this modifier drives both platforms through `documentExporter`.@@ -21,15 +21,18 @@ private struct MarkdownExportShare: ViewModifier {         content.documentExporter(             isPresented: Binding(                 get: { model?.state == .sharing },-                set: { if !$0 { model?.handleShareCompletion() } }),+                set: { if !$0 { model?.shareDismissed() } }),             file: model?.exportedFileURL,             identifier: sheetIdentifier,-            // The binding's `set` above already is the dismissal handler:-            // both surfaces write `false` back when they close, so cleanup has-            // one home rather than two that can disagree. The outcome is-            // ignored here — a markdown export stages a file either way, and-            // cleanup is the same whether the reader sent it or not.-            onCompletion: { _ in }+            // The binding's `set` above only leaves `.sharing`, so SwiftUI does+            // not re-present the sheet; it does not delete the staged file+            // (T-2346). With Save to Files the activity can still be working+            // with it after the sheet has closed (empty-library Decision 6), so+            // the removal happens here instead, on the activity's report or,+            // failing that, three seconds after the dismissal. The outcome is+            // ignored — a markdown export stages a file either way, and cleanup+            // is the same whether the reader sent it or not.+            onCompletion: { outcome in model?.handleShareOutcome(outcome) }         )     } }
Asterism/Asterism/Views/SettingsView.swift Modified +11 / -8
diff --git a/Asterism/Asterism/Views/SettingsView.swift b/Asterism/Asterism/Views/SettingsView.swiftindex 9ff26e75..febbed28 100644--- a/Asterism/Asterism/Views/SettingsView.swift+++ b/Asterism/Asterism/Views/SettingsView.swift@@ -289,19 +289,22 @@ struct SettingsView: View {         // in step by `onChange` — the pattern `MarkdownExportShare` states and         // the shape the deletion dialogs above already use. What decides whether         // the surface is up is `model.state == .sharing`; a second copy of that-        // is a copy that can disagree with it, and the `set` is the dismissal,-        // which covers send, save and cancel alike because neither the share-        // sheet nor the save panel reports which of them happened.+        // is a copy that can disagree with it, and the `set` is the dismissal.+        //+        // The `set` only leaves `.sharing`; it does not delete (T-2346). With+        // Save to Files the activity can still be working with the staged file+        // after the sheet has closed (empty-library Decision 6), so the actual+        // removal happens in `onCompletion`, which fires on the activity's+        // report or, failing that, three seconds after the dismissal. The+        // outcome is ignored there too: this row's cleanup is the same whether+        // the archive was sent or the sheet was cancelled.         .documentExporter(             isPresented: Binding(                 get: { model.state == .sharing },-                set: { if !$0 { model.handleShareCompletion() } }),+                set: { if !$0 { model.shareDismissed() } }),             file: model.exportedFileURL,             identifier: "settings-backup-share-sheet",-            // The binding's `set` above already is the dismissal handler, and-            // the outcome is ignored: this row's cleanup is the same whether-            // the archive was sent or the sheet was cancelled.-            onCompletion: { _ in }+            onCompletion: { outcome in model.handleShareOutcome(outcome) }         )         // Req 6.10's delete asks first, like every other destructive action in the         // app. `presenting:` hands the destructive button the row the dialog was
Asterism/AsterismTests/IntegrationSafetyNetTests.swift Modified +2 / -1
diff --git a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift b/Asterism/AsterismTests/IntegrationSafetyNetTests.swiftindex b3191332..8953b00b 100644--- a/Asterism/AsterismTests/IntegrationSafetyNetTests.swift+++ b/Asterism/AsterismTests/IntegrationSafetyNetTests.swift@@ -249,7 +249,8 @@ struct IntegrationSafetyNetTests {                 // one.                 let document = try BackupV15Codec.decode(Data(contentsOf: backupURL))                 #expect(document.capabilityGate == AsterismCapabilities.current.gate.rawValue)-                backup.handleShareCancellation()+                backup.shareDismissed()+                backup.handleShareOutcome(.cancelled)             }         }     }
Asterism/AsterismTests/MarkdownExportModelTests.swift Modified +109 / -9
diff --git a/Asterism/AsterismTests/MarkdownExportModelTests.swift b/Asterism/AsterismTests/MarkdownExportModelTests.swiftindex c58406f2..3d27dc39 100644--- a/Asterism/AsterismTests/MarkdownExportModelTests.swift+++ b/Asterism/AsterismTests/MarkdownExportModelTests.swift@@ -4,8 +4,9 @@ import Testing @testable import Asterism  // The markdown export presentation layer (Reqs 1.5, 2.4). Mirrors-// `SettingsBackupModelTests`: the state machine, the staged file, the cleanup on-// dismissal, the stale-file scavenging, and the privacy-safe messages.+// `SettingsBackupModelTests`: the state machine, the staged file, the split share+// lifecycle (dismissal leaves `.sharing`, the delivered outcome cleans up —+// T-2346), the stale-file scavenging, and the privacy-safe messages.  @Suite("Markdown export view model") struct MarkdownExportModelTests {@@ -154,10 +155,39 @@ struct MarkdownExportModelTests {         #expect(mock.entryExportInputCallCount == 1)     } -    // MARK: - Cleanup+    // MARK: - Share Lifecycle (T-2346)+    //+    // The staged file must outlive the sharing surface's dismissal: with Save+    // to Files, `UIActivityViewController.completionWithItemsHandler` runs+    // *after* the sheet closes, so deleting on dismissal could unlink a file+    // an activity is still using. `shareDismissed()` only leaves `.sharing`;+    // `handleShareOutcome(_:)`, wired to `documentExporter`'s `onCompletion`,+    // is what actually removes the file.++    @Test("Dismissing the share leaves .sharing without deleting the staged file")+    @MainActor func shareDismissalLeavesTheFileStaged() async {+        let dir = makeStagingDirectory()+        defer { try? FileManager.default.removeItem(at: dir) }+        let (model, _) = makeSUT(subject: .entry(UUID()), stagingDirectory: dir) { mock in+            mock.entryExportInputResult = .success(entryInput())+        }+        await model.startExport()+        let staged = model.exportedFileURL++        model.shareDismissed()++        #expect(model.state == .idle)+        // The dismissal alone must not have deleted anything — the activity+        // may still be working with the file (T-2346).+        #expect(model.exportedFileURL == staged)+        #expect(FileManager.default.fileExists(atPath: staged?.path ?? ""))+    } -    @Test("Completing the share removes the staged file and returns to idle")-    @MainActor func shareCompletionCleansUp() async {+    @Test(+        "The delivered outcome removes the staged file, whether completed or cancelled",+        arguments: [DocumentExportOutcome.completed, .cancelled]+    )+    @MainActor func shareOutcomeRemovesTheStagedFile(outcome: DocumentExportOutcome) async {         let dir = makeStagingDirectory()         defer { try? FileManager.default.removeItem(at: dir) }         let (model, _) = makeSUT(subject: .entry(UUID()), stagingDirectory: dir) { mock in@@ -165,16 +195,51 @@ struct MarkdownExportModelTests {         }         await model.startExport()         let staged = model.exportedFileURL+        model.shareDismissed() -        model.handleShareCompletion()+        model.handleShareOutcome(outcome)++        #expect(model.exportedFileURL == nil)+        #expect(!FileManager.default.fileExists(atPath: staged?.path ?? ""))+    }++    /// The Mac save panel can deliver `onCompletion` before SwiftUI writes+    /// `isPresented` back to `false`, so `handleShareOutcome` can arrive+    /// while the model is still `.sharing`, ahead of `shareDismissed` (Q34+    /// of `empty-library`). It must still clean up — and the later,+    /// now-stale `shareDismissed` call must not leave the row stuck.+    @Test("The outcome arriving before the dismissal still cleans up, and the dismissal is a no-op")+    @MainActor func shareOutcomeBeforeDismissalStillCleansUp() async {+        let dir = makeStagingDirectory()+        defer { try? FileManager.default.removeItem(at: dir) }+        let (model, mock) = makeSUT(subject: .entry(UUID()), stagingDirectory: dir) { mock in+            mock.entryExportInputResult = .success(entryInput())+        }+        await model.startExport()+        #expect(model.state == .sharing)+        let staged = model.exportedFileURL +        // Mac ordering: the outcome arrives first, while still `.sharing`.+        model.handleShareOutcome(.completed)         #expect(model.state == .idle)         #expect(model.exportedFileURL == nil)         #expect(!FileManager.default.fileExists(atPath: staged?.path ?? ""))++        // The binding's `set` still fires afterwards; it must be a no-op —+        // not a stuck `isAwaitingShareOutcome` that blocks every future+        // export.+        model.shareDismissed()+        #expect(!model.isAwaitingShareOutcome)+        await model.startExport()+        #expect(mock.entryExportInputCallCount == 2)     } -    @Test("Cancelling the share removes the staged file and returns to idle")-    @MainActor func shareCancellationCleansUp() async {+    /// The symmetric stale call: a second `shareDismissed` after the first+    /// has already left `.sharing`. It must neither delete the staged file+    /// nor disturb the pending cleanup — the outcome that follows still+    /// removes the file.+    @Test("A second dismissal is a no-op and the outcome still cleans up")+    @MainActor func secondDismissalIsANoOp() async {         let dir = makeStagingDirectory()         defer { try? FileManager.default.removeItem(at: dir) }         let (model, _) = makeSUT(subject: .entry(UUID()), stagingDirectory: dir) { mock in@@ -182,13 +247,48 @@ struct MarkdownExportModelTests {         }         await model.startExport()         let staged = model.exportedFileURL+        model.shareDismissed() -        model.handleShareCancellation()+        model.shareDismissed()          #expect(model.state == .idle)+        #expect(model.exportedFileURL == staged)+        #expect(FileManager.default.fileExists(atPath: staged?.path ?? ""))++        model.handleShareOutcome(.completed)+        #expect(model.exportedFileURL == nil)         #expect(!FileManager.default.fileExists(atPath: staged?.path ?? ""))     } +    @Test("A second export is suppressed while the previous share's outcome is pending")+    @MainActor func exportSuppressedWhileShareOutcomePending() async {+        let dir = makeStagingDirectory()+        defer { try? FileManager.default.removeItem(at: dir) }+        let (model, mock) = makeSUT(subject: .entry(UUID()), stagingDirectory: dir) { mock in+            mock.entryExportInputResult = .success(entryInput())+        }+        await model.startExport()+        model.shareDismissed()+        #expect(model.state == .idle)+        // What `ContentView.startCommandExport` reads to refuse a second ⇧⌘E+        // in this window.+        #expect(model.isAwaitingShareOutcome)++        // The reader is back at the idle-looking row, but the previous+        // share's outcome has not arrived yet — a fresh export here must not+        // replace the tracked staged file out from under the pending cleanup+        // (T-2346).+        await model.startExport()+        #expect(mock.entryExportInputCallCount == 1)++        model.handleShareOutcome(.completed)+        #expect(!model.isAwaitingShareOutcome)++        // Once the outcome has landed, exporting again works normally.+        await model.startExport()+        #expect(mock.entryExportInputCallCount == 2)+    }+     // MARK: - Scavenging      /// Backup export scavenges by filename prefix; markdown filenames come from
Asterism/AsterismTests/SettingsBackupModelTests.swift Modified +116 / -10
diff --git a/Asterism/AsterismTests/SettingsBackupModelTests.swift b/Asterism/AsterismTests/SettingsBackupModelTests.swiftindex 502001ce..60e88409 100644--- a/Asterism/AsterismTests/SettingsBackupModelTests.swift+++ b/Asterism/AsterismTests/SettingsBackupModelTests.swift@@ -109,10 +109,17 @@ struct SettingsBackupModelTests {         #expect(mock.exportCallCount == 1)     } -    // MARK: - Share Completion Cleanup--    @Test("Completing share cleans up the staged file and returns to idle")-    @MainActor func shareCompletionCleanup() async {+    // MARK: - Share Lifecycle (T-2346)+    //+    // The staged file must outlive the sharing surface's dismissal: with Save+    // to Files, `UIActivityViewController.completionWithItemsHandler` runs+    // *after* the sheet closes, so deleting on dismissal could unlink a file+    // an activity is still using. `shareDismissed()` only leaves `.sharing`;+    // `handleShareOutcome(_:)`, wired to `documentExporter`'s `onCompletion`,+    // is what actually removes the file.++    @Test("Dismissing the share leaves .sharing without deleting the staged file")+    @MainActor func shareDismissalLeavesTheFileStaged() async {         let tempDir = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)         try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)         defer { try? FileManager.default.removeItem(at: tempDir) }@@ -127,18 +134,48 @@ struct SettingsBackupModelTests {         await model.startExport()         #expect(model.state == .sharing) -        model.handleShareCompletion()+        model.shareDismissed()          #expect(model.state == .idle)+        // The dismissal alone must not have deleted anything — the activity+        // may still be working with the file (T-2346).+        #expect(model.exportedFileURL == fakeURL)+        #expect(mock.cleanupCallCount == 0)+    }++    @Test(+        "The delivered outcome cleans up the staged file, whether completed or cancelled",+        arguments: [DocumentExportOutcome.completed, .cancelled]+    )+    @MainActor func shareOutcomeCleansUpTheStagedFile(outcome: DocumentExportOutcome) async {+        let tempDir = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+        try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)+        defer { try? FileManager.default.removeItem(at: tempDir) }++        let fakeURL = tempDir.appending(path: "Asterism-backup-test.json")+        try? Data("test".utf8).write(to: fakeURL)++        let mock = MockBackupExporting()+        mock.exportResult = .success(BackupExportResult(fileURL: fakeURL))++        let model = SettingsBackupModel(exporter: mock)+        await model.startExport()+        model.shareDismissed()++        model.handleShareOutcome(outcome)+         #expect(model.exportedFileURL == nil)         #expect(mock.cleanupCallCount == 1)         #expect(mock.lastCleanupURL == fakeURL)     } -    // MARK: - Cancellation Cleanup--    @Test("Cancelling share cleans up the staged file and returns to idle")-    @MainActor func shareCancellationCleanup() async {+    /// The Mac save panel can deliver `onCompletion` before SwiftUI writes+    /// `isPresented` back to `false`, so `handleShareOutcome` can arrive+    /// while the model is still `.sharing`, ahead of `shareDismissed` (Q34+    /// of `empty-library`). It must still clean up — and the later,+    /// now-stale `shareDismissed` call must not leave the row stuck.+    @Test("The outcome arriving before the dismissal still cleans up, and the dismissal is a no-op")+    @MainActor func shareOutcomeBeforeDismissalStillCleansUp() async {         let tempDir = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)         try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)         defer { try? FileManager.default.removeItem(at: tempDir) }@@ -153,13 +190,82 @@ struct SettingsBackupModelTests {         await model.startExport()         #expect(model.state == .sharing) -        model.handleShareCancellation()+        // Mac ordering: the outcome arrives first, while still `.sharing`.+        model.handleShareOutcome(.completed)+        #expect(model.state == .idle)+        #expect(model.exportedFileURL == nil)+        #expect(mock.cleanupCallCount == 1)++        // The binding's `set` still fires afterwards; it must be a no-op —+        // not a stuck `isAwaitingShareOutcome` that blocks every future+        // export.+        model.shareDismissed()+        await model.startExport()+        #expect(mock.exportCallCount == 2)+    }++    /// The symmetric stale call: a second `shareDismissed` after the first+    /// has already left `.sharing`. It must neither delete the staged file+    /// nor disturb the pending cleanup — the outcome that follows still+    /// removes the file exactly once.+    @Test("A second dismissal is a no-op and the outcome still cleans up once")+    @MainActor func secondDismissalIsANoOp() async {+        let tempDir = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+        try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)+        defer { try? FileManager.default.removeItem(at: tempDir) }++        let fakeURL = tempDir.appending(path: "Asterism-backup-test.json")+        try? Data("test".utf8).write(to: fakeURL)++        let mock = MockBackupExporting()+        mock.exportResult = .success(BackupExportResult(fileURL: fakeURL))++        let model = SettingsBackupModel(exporter: mock)+        await model.startExport()+        model.shareDismissed()++        model.shareDismissed()          #expect(model.state == .idle)+        #expect(model.exportedFileURL == fakeURL)+        #expect(mock.cleanupCallCount == 0)++        model.handleShareOutcome(.completed)         #expect(model.exportedFileURL == nil)         #expect(mock.cleanupCallCount == 1)     } +    @Test("A second export is suppressed while the previous share's outcome is pending")+    @MainActor func exportSuppressedWhileShareOutcomePending() async {+        let tempDir = FileManager.default.temporaryDirectory.appending(path: UUID().uuidString)+        try? FileManager.default.createDirectory(at: tempDir, withIntermediateDirectories: true)+        defer { try? FileManager.default.removeItem(at: tempDir) }++        let fakeURL = tempDir.appending(path: "Asterism-backup-test.json")+        try? Data("test".utf8).write(to: fakeURL)++        let mock = MockBackupExporting()+        mock.exportResult = .success(BackupExportResult(fileURL: fakeURL))++        let model = SettingsBackupModel(exporter: mock)+        await model.startExport()+        model.shareDismissed()+        #expect(model.state == .idle)++        // The reader is back at the idle-looking row, but the previous+        // share's outcome has not arrived yet — a fresh export here must not+        // replace the stage's tracked result out from under the pending+        // cleanup (T-2346).+        await model.startExport()+        #expect(mock.exportCallCount == 1)++        model.handleShareOutcome(.completed)++        // Once the outcome has landed, exporting again works normally.+        await model.startExport()+        #expect(mock.exportCallCount == 2)+    }+     // MARK: - Retry After Failure      @Test("Can retry after a failure")
docs/agent-notes/testing.md Modified +7 / -3
diff --git a/docs/agent-notes/testing.md b/docs/agent-notes/testing.mdindex 241c982c..5a92aade 100644--- a/docs/agent-notes/testing.md+++ b/docs/agent-notes/testing.md@@ -1702,9 +1702,13 @@ Three facts from `EmptyLibrarySettingsUITests` and the device bug behind - **`completionWithItemsHandler` runs after a SwiftUI sheet's `onDismiss`** when   the activity is Save to Files. Code that treats the dismissal as the end of the   share sees the completion late or not at all. `documentExporter` numbers its-  presentations and delivers the report when it arrives for that reason. The-  Export Backup and Markdown export rows still delete their staged file at the-  dismissal (T-2346).+  presentations and delivers the report when it arrives for that reason. Since+  T-2346 the Export Backup and Markdown export rows follow the same split as+  the Empty Library row: the binding's `set` (`shareDismissed()`) only leaves+  `.sharing`, and the staged file is deleted in `documentExporter`'s+  `onCompletion` (`handleShareOutcome(_:)`) — on the activity's report or, with+  nothing reported, at the grace expiry. A model test that wants the file gone+  must deliver the outcome, not just the dismissal.  ## Misc 
specs/bugfixes/export-cleanup-before-share-finishes/report.md Added +179 / -0
diff --git a/specs/bugfixes/export-cleanup-before-share-finishes/report.md b/specs/bugfixes/export-cleanup-before-share-finishes/report.mdnew file mode 100644index 00000000..ab41fe16--- /dev/null+++ b/specs/bugfixes/export-cleanup-before-share-finishes/report.md@@ -0,0 +1,179 @@+# Bugfix Report: Export Cleanup Before the Share Finishes++**Date:** 2026-09-22+**Status:** Fixed+**Ticket:** T-2346++## Description of the Issue++The Export Backup row in Settings and the Markdown export share both deleted+their staged file the moment the share sheet's presentation binding went+`false`. On iOS, `UIActivityViewController.completionWithItemsHandler` runs+*after* the SwiftUI sheet's dismissal for Save to Files (`empty-library`+Decision 6), so the file could be unlinked while the activity was still+reading it.++**Reproduction steps:**+1. Export a backup (or a Markdown export) on a phone and choose Save to Files.+2. The sheet dismisses; the binding's `set(false)` runs `handleShareCompletion`.+3. `BackupExportStage.cleanup()` removes the staged file before the activity's+   completion handler has reported.++**Impact:** An ordering defect, not a reproduced loss: no truncated or missing+export was ever observed. Both export rows were one slow activity away from a+missing file.++## Investigation Summary++- **Symptoms examined:** both `documentExporter` callers used the binding's+  `set` as the end of the share and passed a no-op `onCompletion`.+- **Code inspected:** `SettingsView.swift`, `MarkdownExportShare.swift`,+  `SettingsBackupModel.swift`, `MarkdownExportModel.swift`, and the Empty+  Library row, which already handles the same sheet correctly.+- **Hypotheses tested:** moving deletion alone to `onCompletion` was not enough.+  On the Mac the save panel can deliver the outcome *before* SwiftUI writes the+  binding back to `false`, the reverse of the iOS order; a fix that assumed+  dismissal-first left the model stuck awaiting an outcome forever.++## Discovered Root Cause++The two models conflated "the sheet is gone" with "the activity is done". The+first is the binding's `set`; the second is `documentExporter`'s+`onCompletion`, which fires on the activity's report or three seconds after+the dismissal.++**Defect type:** Lifecycle ordering error.++**Why it occurred:** the two rows predate `documentExporter` gaining a real+completion signal (`empty-library` Decision 6); they kept the older one-step+shape.++**Contributing factors:** `onCompletion` was wired to `{ _ in }`, so the grace+task the exporter spawned for it did nothing.++## Resolution for the Issue++**Changes made:**+- `Asterism/Asterism/ViewModels/SettingsBackupModel.swift` — `shareDismissed()`+  only leaves `.sharing`; `handleShareOutcome(_:)` deletes the staged file. The+  two are order-independent, and `isAwaitingShareOutcome` suppresses a new+  export until the previous share's outcome has landed.+- `Asterism/Asterism/ViewModels/MarkdownExportModel.swift` — the same split.+- `Asterism/Asterism/Views/SettingsView.swift`,+  `Asterism/Asterism/Views/MarkdownExportShare.swift` — the binding's `set`+  calls `shareDismissed()`; `onCompletion` calls `handleShareOutcome`.+- `Asterism/Asterism/ContentView.swift` — `startCommandExport` also refuses+  a second ⇧⌘E while the previous command export's+  `isAwaitingShareOutcome` is set (pre-push review, round 2). The next+  presentation cancels `documentExporter`'s grace wait, so a model replaced+  in that window would never have its cleanup delivered and its file would+  sit until the 24-hour scavenge. `MarkdownExportModel.isAwaitingShareOutcome`+  is `public private(set)` for that one reader.++**Approach rationale:** it is the shape the Empty Library row already uses for+the same sheet (`empty-library` Q28, Q34), so all three callers now agree.++**Alternatives considered:**+- Delete on dismissal after a fixed delay — the exporter already owns that+  fallback; duplicating it in each model would drift.+- Keep deletion on the binding and ignore the activity — the ordering the+  ticket describes.++The re-entrancy guard was added because the deferred cleanup opens a window of+up to three seconds in which a fresh export could replace the single tracked+stage result, and the old share's cleanup would then delete the new file.++**Why a private flag rather than a `.shareDismissed` state case.**+`EmptyLibraryModel` models the same wait as a `State` case, and that was+considered here. It was not copied because that row has something to show+and to branch on during the wait — a progress sentence, and an outcome that+decides whether the pass runs — while these two rows ignore the outcome and+have nothing to tell the reader. `SettingsBackupModel.State` and+`MarkdownExportModel.State` are public and switched exhaustively in+`SettingsView`, `EntryDetailView`, `WorkDetailView` and `ContentView`; a new+case would touch all four views and their tests to represent a wait that+draws nothing. So the dismissal returns the row to `.idle` and the wait is a+private `isAwaitingShareOutcome` flag that `startExport()` reads.++The visible consequence: for up to three seconds after the sheet closes the+Export button is enabled and a tap on it is silently swallowed. On iOS the+activity usually reports well inside that window, and on the Mac the panel's+result normally lands before the dismissal does, so the window is the grace+fallback's length only when nothing reported at all. If that ever reads as+"the button is broken", the flag should be promoted to a state case with a+progress arm, as `EmptyLibraryModel` has.++## Regression Test++**Test files:** `Asterism/AsterismTests/SettingsBackupModelTests.swift`,+`Asterism/AsterismTests/MarkdownExportModelTests.swift`++**Tests:**+- "Dismissing the share leaves .sharing without deleting the staged file"+- "The outcome arriving before the dismissal still cleans up, and the+  dismissal is a no-op"+- "A second dismissal is a no-op and the outcome still cleans up" (`secondDismissalIsANoOp`+  in both suites; the backup one also asserts cleanup runs exactly once)+- "A second export is suppressed while the previous share's outcome is+  pending" — the markdown one also pins `isAwaitingShareOutcome` true in the+  window and false after the outcome, which is what `ContentView` reads+- the parameterised outcome test over `.completed` and `.cancelled`++**Run command:** `make test-only TEST=AsterismTests/SettingsBackupModelTests`+and `make test-only TEST=AsterismTests/MarkdownExportModelTests`++## Affected Files++| File | Change |+|------|--------|+| `Asterism/Asterism/ViewModels/SettingsBackupModel.swift` | split lifecycle, order-independence, re-entrancy guard |+| `Asterism/Asterism/ViewModels/MarkdownExportModel.swift` | same |+| `Asterism/Asterism/Views/SettingsView.swift` | rewired `documentExporter` |+| `Asterism/Asterism/Views/MarkdownExportShare.swift` | rewired `documentExporter` |+| `Asterism/Asterism/ContentView.swift` | ⇧⌘E guard covers the pending-outcome window |+| `Asterism/Asterism/Support/PlatformModifiers.swift` | `documentExporter` doc comment names `onCompletion` as the cleanup point |+| `Asterism/AsterismTests/SettingsBackupModelTests.swift` | new lifecycle tests |+| `Asterism/AsterismTests/MarkdownExportModelTests.swift` | new lifecycle tests |+| `Asterism/AsterismTests/IntegrationSafetyNetTests.swift` | follows the renamed API |++## Verification++**Automated:**+- [x] Regression tests pass+- [x] `make test-quick` passes (includes `build-mac`)+- [x] No linter is configured; no new compiler warnings++**Manual verification:**+- Not performed. The real-phone Save to Files ordering cannot be exercised on+  the simulator; the fix is verified at the model level.++## Prevention++- Any new `documentExporter` caller must treat the binding's `set` as leaving+  the sharing state only, and do its cleanup in `onCompletion`. The modifier's+  doc comment now says so.+- Anything that can start a *second* export against a surface must also refuse+  while the previous share's outcome is pending, not only while `.exporting`+  or `.sharing`: the next presentation cancels the exporter's grace wait.++## Follow-up candidates (not fixed here)++- **Two `MarkdownExportModel`s over one subject stage to one path.** The+  detail screen's `@State` model and ⇧⌘E's `commandExportModel` (Q46 of+  `ipad-and-mac-layouts`) both write `<title>.md` into the same staging+  directory, so the file is the same path, not "its own file" as Q46 says. The+  first model's now-deferred delete can unlink the second's file if the reader+  exports the same subject from the other surface within the grace window+  (iPad with a keyboard, same subject, within 3 s). The race predates this fix+  — cleanup on dismissal could hit it too — but the deferral widens it from+  "before the first sheet closes" to "up to 3 s after". A per-model staging+  subdirectory (keeping the filename the sheet shows) with a recursive+  scavenge, or lifting the detail models out of their screens as Q46 already+  names, would close it. Out of scope for a bugfix that touches two shipped+  rows' lifecycle only.++## Related++- `specs/empty-library/decision_log.md` Decision 6, Q28, Q34, Q47 (annotated done)+- `specs/ipad-and-mac-layouts/decision_log.md` Q46+- PR #87
specs/empty-library/decision_log.md Modified +1 / -1
diff --git a/specs/empty-library/decision_log.md b/specs/empty-library/decision_log.mdindex f2318d3c..1bb7a0b1 100644--- a/specs/empty-library/decision_log.md+++ b/specs/empty-library/decision_log.md@@ -50,7 +50,7 @@ | Q44 | 2026-09-19 | A failure the pass does not report itself reaches the row as an error category, not a description | Review: the pass reduces a save error to its domain and code because a description can name a record; the inventory failure and a throw from the pass went to the row as `String(describing:)` and now share the export stage's content-free category | | Q45 | 2026-09-19 | The sharing seam logs under its own category, `DocumentExport`, and says so when it drops a report | Pre-push review: `documentExporter` serves the backup and Markdown exports too, so its lines under `EmptyLibrary` put unrelated shares inside an emptying's trace. A dropped report was silent, and a silently dropped genuine report is how Decision 6's bug would come back | | Q46 | 2026-09-19 | A run that cannot take the lock clears its sidecar; a run refuses while another bulk operation holds the flag; a chunk that saves without removing its rows is an interruption | Pre-push review. The sidecar is written before the lock and nothing can have been saved when the locked call throws, so keeping it told the reader "some records remain" beside "nothing was deleted", across launches. The flag's `defer` cleared it unconditionally, which would have lowered an import's fence. The chunk loop ended only because deleted rows stop being fetched, and it runs holding the exclusive cross-process lock |-| Q47 | 2026-09-19 | The Export Backup and Markdown export rows still remove their staged file at the sheet's dismissal; that is T-2346, not this branch | Pre-push review: Decision 6 established that the activity can outlive the dismissal, and Q28 keeps this row's file until the pass is terminal, but moving the other two rows' cleanup changes two shipped features and their tests. No lost export has been observed |+| Q47 | 2026-09-19 | The Export Backup and Markdown export rows still remove their staged file at the sheet's dismissal; that is T-2346, not this branch. **Done by T-2346** (PR #87): both rows now delete in `onCompletion` | Pre-push review: Decision 6 established that the activity can outlive the dismissal, and Q28 keeps this row's file until the pass is terminal, but moving the other two rows' cleanup changes two shipped features and their tests. No lost export has been observed | | Q48 | 2026-09-20 | `AppLibraryModel` owns the row's model, one per open library, and hands it to `SettingsView` as `EmptyLibraryRowModel`; a `libraryBusy` refusal has its own sentence | PR review, major: Q39 kept the model in `SettingsView`'s `@State`, but Settings can be closed mid-run (a sheet with a Done button on the iPad, a window on the Mac). A reopened Settings built a fresh idle model while the first run went on, the reader could export and share again, and the refused second run said "Nothing was deleted" while the first deleted everything. Blocking dismissal was the alternative and was rejected: it traps the reader in Settings for the length of a pass and does nothing for the Mac's window. The model is dropped at `teardownRepository()`, since its stage and its counts belong to the library being released |  ## Decision 1: Empty Means Every Device, Through Mirrored Row Deletion

Things to double-check

The iOS Save to Files arm on a real phone.

The one ordering the simulator cannot produce is the one the ticket is about. A Development install (no approval needed, but say what it does), Export Backup → Save to Files, then a subsystem:me.nore.ig.Asterism category:DocumentExport line reading delivered by the activity's report and the staging file gone would confirm the fix end to end. Owner's call; the report states it was not done.

Swallowed-tap window on the Mac.

On the Mac the panel's result normally lands before the dismissal, so the window is effectively zero. If fileExporter ever reports neither callback (a dismissed panel with no cancellation), the row sits in the flag for 3 s and the Export button swallows a tap. Worth a glance on the Mac build if you have one open; not a code issue.

Test data provenance.

make test-quick emits no JUnit; the results on this page were derived from the run's xcresult bundle via xcresulttool (1,824 tests, 128 suites). Coverage was not collected. The Makefile target is the project's configured unit-test command, so the scope is project-configured.