fix(editor): guard document departure on failed flushes

teardown(flushFirst:) discarded flush()'s result, so document
navigation (newPost, newOutline, select, openExternal, dismissExternal,
openUnguarded) dropped the outgoing dirty session after a failed write
and replaced the only retained copy of the unsaved prose.

One shared departure gate now covers every site, placed before any
document-specific state clears:

- sessionMayDepart(_:): flushOrAbort's two gates (unanswered #67
  conflict holds; failed flush holds) lifted to document departure —
  flushOrAbort routes through it unchanged.
- dismissExternal() -> Bool: the guest departs only when its flush
  lands; on failure the guest, its buffer, and its watcher stay live.
- departOpenDocuments(): the full-switch composition (guest + post
  session) behind newPost/newOutline/openExternal.
- select/openUnguarded gate their same-id-conditional session teardowns
  through sessionMayDepart directly.

Departure now aborts with the strip error set and the dirty session
retained; retrying after writability returns lands the edits and
completes the switch. All six PostsModelDepartureTests pins RED at
11b196d, GREEN with this change.

brief-25 [failed-flush-discarded-on-document-switch]
This commit is contained in:
AlexKucera committed 2026-11-16 20:17:58 +01:00
1 parent ecd14d1714
commit 250a662f3e
3 files changed
+70 -34

No files matched your search

+54 -20
View File
@@ -267,9 +267,7 @@ final class PostsModel {
/// target the default — new pieces are never born archived).
func newPost() {
let target = targetProject
dismissExternal() // #92: opening a draft dismisses the guest
session?.teardown(flushFirst: true) // #64: selection change flushes
session = nil
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(project: target)
lastDraftWasOutline = false // #109: the afterglow died with the draft
proseOverridePostID = nil // #111: same death, same clearing
@@ -283,9 +281,7 @@ final class PostsModel {
/// Title keeps prose semantics (raw first line).
func newOutline() {
let target = targetProject
dismissExternal()
session?.teardown(flushFirst: true)
session = nil
guard departOpenDocuments() else { return } // brief-25: edits land or the switch aborts
draft = PostDraft(text: "- ", project: target, type: .outline)
lastDraftWasOutline = false // #109: a new draft resets the afterglow
proseOverridePostID = nil // #111: same death, same clearing
@@ -296,12 +292,23 @@ final class PostsModel {
/// #92: dismiss the external guest slot, flushing pending edits (the
/// guest is always leaving for somewhere — same posture as post
/// selection change).
/// selection change). brief-25: the dismissal is GUARDED — a guest
/// whose flush fails (or whose #67 conflict is unanswered) STAYS,
/// buffer and watcher live: teardown would drop the only retained
/// copy of the unsaved edits. Callers abort their navigation on
/// false, before clearing anything.
/// #146: internal — the split-out domain extensions dismiss too.
func dismissExternal() {
externalSession?.teardown(flushFirst: true)
@discardableResult
func dismissExternal() -> Bool {
guard let guest = externalSession else {
externalWatcher.stop()
return true
}
guard sessionMayDepart(guest) else { return false }
guest.teardown(flushFirst: false) // the gate already flushed
externalSession = nil
externalWatcher.stop()
return true
}
/// First save of the draft (#62): lazy folder, slug, #59 stamp all fire
@@ -347,7 +354,7 @@ final class PostsModel {
/// its flush is prose-mode, so it can't drop anything.
func select(_ id: String) {
guard watchedHome != nil else { return } // #179: no library, no open
dismissExternal()
guard dismissExternal() else { return } // brief-25: the guest's edits land or the switch aborts
// A reselect of the already-open piece is a no-op — INCLUDING a
// guarded one: the piece is open under a prior answer, and firing
// the ask again would nil its session without teardown (the armed
@@ -356,7 +363,10 @@ final class PostsModel {
return
}
if let session {
session.teardown(flushFirst: true)
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
}
if isGuardedOutline(id) {
outlineGuardPieceID = id
@@ -503,15 +513,25 @@ final class PostsModel {
/// through the same rail.
func flushOrAbort(_ postID: String) -> Bool {
guard let session, session.postID == postID else { return true }
// #114 audit: an unanswered #67 conflict means disk holds foreign
// text with the session's version unwritten — proceeding would act
// on the foreign body and discard the editor's. Abort; the alert
// stays up for the writer to answer, then the op retries.
if session.conflictAlert {
return sessionMayDepart(session)
}
/// brief-25 (failed-flush-discarded-on-document-switch): the departure
/// gate for ONE outgoing session — flushOrAbort's two gates lifted to
/// document departure. An unanswered #67 conflict means disk holds
/// foreign text with the session's version unwritten (#114 audit); a
/// failed flush means the edits never landed. Either way the document
/// may not leave: the caller aborts its navigation BEFORE clearing
/// document-specific state, so the dirty session stays retained and
/// honest while lastError says why (the structural rail's #108
/// posture — now the navigation sites' too).
/// #146: internal — PostsModelOutline's openUnguarded gates too.
func sessionMayDepart(_ outgoing: EditorSession) -> Bool {
if outgoing.conflictAlert {
lastError = "This piece changed on disk underneath you — answer the reload question first."
return false
}
if !session.flush() {
if !outgoing.flush() {
// Append, don't replace — the flush already routed the write's
// localizedDescription into lastError; only say what was skipped.
lastError = (lastError.map { "\($0) " } ?? "") + "— nothing was changed."
@@ -520,6 +540,22 @@ final class PostsModel {
return true
}
/// brief-25: the shared departure run for a full document switch —
/// the external guest and the post session both leave (newPost,
/// newOutline, openExternal). Each flushes through the departure gate
/// first; a failure retains BOTH exactly as they are and the
/// navigation aborts with nothing cleared.
@discardableResult
func departOpenDocuments() -> Bool {
guard dismissExternal() else { return false }
if let open = session {
guard sessionMayDepart(open) else { return false }
open.teardown(flushFirst: false) // the gate already flushed
session = nil
}
return true
}
/// #108: Move to Project — flush first (move reads disk), then the
/// folder moves under projects/. Id stays the same; the session is
/// reopened anyway so folderURL re-resolves to the new parent.
@@ -616,9 +652,7 @@ final class PostsModel {
func openExternal(_ url: URL) {
guard url.isFileURL else { return }
let target = url.resolvingSymlinksInPath()
dismissExternal()
session?.teardown(flushFirst: true) // #92: the guest takes the column
session = nil
guard departOpenDocuments() else { return } // #92 + brief-25: the column's edits land or the drop aborts
draft = nil
pendingProject = nil // #108 audit: the draft died here too — its target dies with it
lastDraftWasOutline = false // #109: same death, same clearing
+5 -3
View File
@@ -66,10 +66,12 @@ extension PostsModel {
/// #146: internal — `select` (PostsModel.swift) routes its tail through
/// this one open body.
func openUnguarded(_ id: String) {
guard let home = watchedHome else { return }
dismissExternal()
guard let home = watchedHome, dismissExternal() else { return } // brief-25: the guest's edits land or the open aborts
if let session, session.postID != id {
session.teardown(flushFirst: true)
// brief-25: a failed flush (or an unanswered #67 conflict)
// aborts here — the dirty session stays up and honest.
guard sessionMayDepart(session) else { return }
session.teardown(flushFirst: false) // the gate already flushed
}
session = id == session?.postID ? session : EditorSession(postID: id, home: home)
draft = nil
+11 -11
View File
@@ -80,28 +80,28 @@ struct PostsModelDepartureTests {
@Test func `switching pieces aborts when the outgoing session flush fails`() throws {
let (model, home) = try makeModelHome()
let a = try PostStore.writeNew(body: "# A\n", home: home)
let b = try PostStore.writeNew(body: "# B\n", home: home)
model.select(a.id)
let postA = try PostStore.writeNew(body: "# A\n", home: home)
let postB = try PostStore.writeNew(body: "# B\n", home: home)
model.select(postA.id)
model.session?.edit("# A\n\noutgoing paragraph")
let dirA = try #require(PostStore.folder(of: a.id, home: home))
let dirA = try #require(PostStore.folder(of: postA.id, home: home))
try denyWrites(to: dirA)
defer { try? allowWrites(to: dirA) }
model.select(b.id)
model.select(postB.id)
// The switch aborted before replacing the session (select's own
// teardown AND the second one through openUnguarded both gated).
#expect(model.session?.postID == a.id)
#expect(model.session?.postID == postA.id)
#expect(model.session?.text == "# A\n\noutgoing paragraph")
#expect(model.selectedPostID == a.id)
#expect(model.selectedPostID == postA.id)
#expect(model.lastError != nil)
#expect(PostStore.readBody(id: a.id, home: home) == "# A\n")
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n")
try allowWrites(to: dirA)
model.select(b.id)
#expect(model.session?.postID == b.id)
#expect(PostStore.readBody(id: a.id, home: home) == "# A\n\noutgoing paragraph")
model.select(postB.id)
#expect(model.session?.postID == postB.id)
#expect(PostStore.readBody(id: postA.id, home: home) == "# A\n\noutgoing paragraph")
}
@Test func `open external aborts when the dirty session flush fails`() throws {