Skip to content

mac: replacing the project saves or snapshots every dirty document, not just the active one (#786, #789) - #804

Merged
d-q222 merged 1 commit into
mainfrom
fix/786-unsaved-inactive
Sep 17, 2026
Merged

d-q222 merged 1 commit into
mainfrom
fix/786-unsaved-inactive

Conversation

@d-q222

@d-q222 d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor

Fixes #786. Fixes #789.

Problem

When the project was replaced (Open, New Project, fixture load, Reload from disk), the app checked only the active document for unsaved edits. Edits in inactive member files were silently discarded. Separately, ProjectDocuments.saveConflict held one conflict at a time, so two conflicted members evicted each other and autosave kept retrying both.

Change

  • One resolution for every replacement: a single project-wide unsaved-edits resolution in DocumentFiles.swift covers the entry file plus every dirty member.
    • No choice yet: refuse with .blockedByUnsavedEdits.
    • Save: write the entry, then each dirty member; abort the replacement on any failure or conflict.
    • Discard: snapshot each dirty member under its own path. The entry also goes to recoverableBuffer.
  • Paths that use it: Open (openTexPanel/openTex), New Project, fixture load (the new loadFixturesReplacingProject), and the direct Reload from disk. The preview-controller reload still checks only the active document, because it changes only the entry text. Restore Discarded Buffer refuses while anything is dirty.
  • Prompts list every dirty file.
  • Per-member conflicts (mac: member save conflicts share one slot (ProjectDocuments.saveConflict) #789): saveConflict becomes a per-member map saveConflicts: [String: DocumentConflict] with a saveConflict(for:) lookup. It is cleared on open and close, carried over on rename, and autosave skips conflicted members.

Tests

  • Six new AutosaveTests cover: open refused, discard snapshots the member, reload refused, fixture Save writes the member, fixture aborted on a member conflict, and two member conflicts both retained with neither retried.
  • All six fail against the old logic: 13 assertion failures, with the other 22 tests passing.
  • Filtered run AutosaveTests|ProjectDocumentsTests|DocumentFilesTests|DirtySnapshotsTests|ShellModelTests|WorkspaceShellTests: 84 tests, 0 failures, 10 skipped. The skipped tests need helper binaries that aren't built locally.

Independent review pending before merge.

🤖 Generated with Claude Code

…ot just the active one (#786, #789)

Open, New Project, fixture load, Reload from disk and Restore Discarded
Buffer now go through one project-wide unsaved-edits resolution in
DocumentFiles.swift. Save writes the entry and every dirty member and aborts
the replacement on any failure or conflict. Discard snapshots each dirty
member under its own path. Prompts list every dirty file.

ProjectDocuments.saveConflict becomes a per-member map (saveConflicts), so
two conflicted members no longer evict each other and autosave stops
retrying them.

Six new AutosaveTests cover these cases; all six fail against the old code.

Implementation-Agent: Claude Opus 5 (daniel-parent subagent)
Commit-Executor: daniel-parent (Claude Opus 5)
Co-authored-by: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
@d-q222

d-q222 commented Sep 17, 2026

Copy link
Copy Markdown
Contributor Author

Commander (daniel-parent): independent Opus review of 5b96697e, APPROVE. No material findings. The non-blocking follow-ups below go to a separate issue. Merging after a run of the filtered Mac tests on the merged tree.

PR #804 review — head 5b96697 (verified)

"mac: replacing the project saves or snapshots every dirty document, not just the active one (#786, #789)"

Reviewer: opus (independent, read-only). Scope: git diff origin/main...5b96697e plus the surrounding code in
DocumentFiles.swift, ShellModel.swift, ProjectDocuments.swift, DirtySnapshots.swift, ProjectScaffoldViews.swift and FlashTeXMacApp.swift.

Material findings

None. I found no path where this PR loses unsaved text or writes it to the wrong file, and no regression from main.
Every replacement entry point I could find now gates on every dirty document:

  • File > Open / palette openLaTeXFile -> openTexPanel -> openTex -> authorizeProjectReplacement.
  • New Project sheet -> createProject(dirty:) -> openTex.
  • Open Fixture / Reload Fixture (menu and palette) -> confirmLoadFixtures -> loadFixturesReplacingProject -> authorizeProjectReplacement.
  • Direct reload (reloadFromDisk, confirmReload when not routed through the controller) -> hasUnsavedDocuments, and adoptOpenedText -> keepDiscarded snapshots the members.
  • Controller reload replaces only the entry buffer. viaController implies activePath == entry (controllerRoutesFiles), so isDirty there really does mean the entry.
  • Restore Discarded Buffer -> hasUnsavedDocuments.
  • Launch seed (init defer) and the launch fixture load run before any user edit.
  • Quit / last-window close -> applicationShouldTerminate, which already used project.anyDirty plus preserveDirtyBuffers. The PR does not touch it.
  • \input navigation (openForNavigation / openDocument) only adds members and never calls replaceProject.

On a partial save-all failure with .saveFirst, the entry saves first, then each member. The first failure or conflict returns .refused before replaceProject or loadFixtures runs. Documents that already saved keep their new baselines (savedText / baselines / diskBaselines), so the state stays consistent; only the refused member stays dirty. The replacement path has no awaits, so edits cannot interleave. (During the NSAlert modal, autosave can still fire on the main queue, but it can only save, never drop.)

The discard snapshots are keyed correctly: the entry goes under documentURL, and each member under projectRoot/<path>, standardized by DirtySnapshotStore.key. One slot per file means a later snapshot can only replace an earlier snapshot of the same file, never another document's text.

saveConflicts is keyed by member path. It is cleared on a successful save (both routes), on member open, by prune and by replaceProject. retarget carries it on rename. Autosave skips exactly the conflicted member. Helper-route late replies are already guarded by projectGeneration/projectRoot, so a late conflict cannot land on a new project's same-named member.

Non-blocking notes (recommended follow-ups)

  1. Member discard relies only on a best-effort durable write, and its failure is ignored. DocumentFiles.swift keepDiscarded calls preserveDirtyText(doc.text, at: root/path, ...) for each dirty member and discards the result. DirtySnapshotStore.write returns nil when the store is unwritable. Its own doc comment says that is acceptable because "the text is still in memory", but on a project replacement it is not. Scenario: the Application Support store is unwritable (disk full, permissions). The user picks Discard with an inactive chapter.tex dirty, and the edits are gone with no warning. This is still strictly better than main, which dropped them outright. Fix: if any member snapshot returns nil, refuse the replacement with a note, or keep the text in session memory (e.g. a [URL: String] next to recoverableBuffer).

  2. The prompt copy promises the wrong recovery route for members. Three prompts (openTexPanel, confirmLoadFixtures, NewProjectSheet.create) say "Discarded text stays recoverable this session via Edit > Restore Discarded Buffer". When only a member is dirty, keepDiscarded deliberately leaves recoverableBuffer alone. That slot may still hold an older, unrelated entry buffer. Then openTex's captureNote ("previous unsaved buffer kept (Edit > Restore Discarded Buffer)") fires because recoverableBuffer != nil, and restoring brings back that stale entry, not the member. The member's text is really only reachable through File > Restore Unsaved Snapshot…, or by reopening that member under the old root. Fix: name that route for members, and clear or annotate a stale recoverableBuffer on replacement.

  3. "Reload" from the entry-conflict panel escalates to discarding members. Flow: openTexPanel Save -> the entry save conflicts -> resolveConflictPanel -> Reload -> confirmReload(review, dirty: review.bufferDirty ? .discard : .none). bufferDirty is now hasUnsavedDocuments, so a user who asked to save and then to reload main.tex has every dirty member evicted from its buffers (snapshotted, not saved) without the members being named. Main dropped them with no snapshot at all, so this is an improvement. Still, the review summary ("Your unsaved edits are replaced") should list the members, or a direct reload of the entry should keep member buffers (and ideally prefer saving them).

  4. Discard is consumed before the fixture load can fail. ShellModel.swift loadFixturesReplacingProject calls keepDiscarded before loadFixtures, which can still reject the file (decode error, layout violation) without replacing anything. The buffers stay open, but recoverableBuffer is overwritten (dropping any earlier discarded buffer from session memory) and snapshots of still-open text are written. adoptOpenedText already follows the rule "only a successful read consumes a discard". Main had the same order. Fix: validate or decode first, then keepDiscarded.

  5. New Project writes before it authorizes. ProjectScaffoldViews.swift createProject calls ProjectScaffold.create(... overwrite:) before openTex(... dirty:). When the new project overwrites the open project's own files, .saveFirst then conflicts against the template that was just written. The buffers survive and nothing is lost, but the "Save" choice does not do what it says. This behaviour predates the PR.

  6. Fixture members are never dirty. loadFixtures sets documents = req.payload.documents without baselines, so project.isDirty(member) is false. Edits in a fixture member tab are dropped silently by any replacement, and quit ignores them too. There is no file behind them, so the impact is low, and this predates the PR.

  7. retarget carries a conflict whose url still names the old file. This only matters once member-conflict UI exists (mac: member save conflicts share one slot (ProjectDocuments.saveConflict) #789's remaining item). Also, a member that was edited back to its baseline keeps its conflict, so autosave keeps skipping it after later edits until a manual save.

  8. unsavedDocumentsDescription falls back to the entry name when documentURL == nil, even when the list could be non-empty. The "have"/"has" choice counts listing separately. Cosmetic only.

  9. Test gaps.

    • privateSnapshots is a no-op. openProject -> openTex -> offerDirtySnapshot has already created the associated DirtySnapshotStore before setenv, so the tests use the per-pid XCTest temp store. That is still isolated, so it is harmless, but the helper can be dropped.
    • Nothing covers: an entry save that succeeds followed by a member failure; .discard of members on fixture load or a direct reload; clearSaveConflicts on replace; retarget of a conflict; or the helper route (saveDocument async) for .saveFirst.
    • The mac: member save conflicts share one slot (ProjectDocuments.saveConflict) #789 test does exercise the claim: on main, other.tex's conflict overwrote chapter's, autosave retried chapter.tex, and the snapshot reappeared.

Tests run

VERDICT: APPROVE

@d-q222
d-q222 merged commit 59db320 into main Sep 17, 2026
21 checks passed
ItsAkilesh pushed a commit to ItsAkilesh/flashtex that referenced this pull request Sep 18, 2026
…lash-tex#806)

Follow-ups to flash-tex#804, which made replacing a project save or snapshot every
dirty document.

- Snapshot write failure: keepDiscarded now writes each dirty member's
  snapshot first and checks the result (preserveDiscardedText). If the store
  cannot keep a member's text, nothing is replaced (open, direct reload,
  fixture load all return .saveFailed), recoverableBuffer is untouched, and
  captureNote names the file and the store error; the text stays in the
  editor.
- Recovery hints: Save/Discard prompts (Open, New Project, fixture load) and
  the open/reload notes now name the command per file:
  Edit > Restore Discarded Buffer for the entry, File > Restore Unsaved
  Snapshot… for members (discardRecoveryRoutes).
- Reload: ReloadReview carries entryDirty and discardedMembers (bufferDirty
  is now derived). A direct reload's summary, shown by the conflict panel's
  Reload and by Reload from Disk, names the dirty members it also discards.
- Fixture load records the discard only after the fixture decodes and
  validates (loadFixtures' beforeReplacing hook); a rejected fixture no
  longer overwrites the recoverable buffer or member snapshots.
- Tests: privateSnapshots now points the model's store directly (the env
  override came after the store was created). New tests cover the private
  store, entry saved then member save failing, discard via fixture and via
  reload after an entry conflict, a rejected fixture, the open hint, a
  member conflict carried across a rename, and a failed snapshot write.

Implementation-Agent: Claude Opus 5 (daniel-parent subagent)
Commit-Executor: daniel-parent (Claude Opus 5)
Co-authored-by: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012c9XLkHjePPGBuarrmE2mz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant