CI / ci (push) Canceled after 0s
Fix Cards become actionable. Mechanical cards offer Apply behind a blocking ask-before sheet showing the exact edit (anchored quote -> replacement, occurrence + context; empty fix cuts); the sheet is the only path to a write, one card at a time, no apply-all. The edit lands through the editing session (pending edits flush first, the editor re-seeds via adoptText, the card closes applied); Skip and Done close the card in place, recording nothing; demonstration cards close Done/Skip only (ADR-0006). Cards arrive ranked (store-stamped, scan-ordered, open-first palette) and capped at ten per submit — the app keeps the ranked head and the wire reply discloses the drop. Stale anchors re-validate at apply: no text selected or changed, the card flags itself. Includes the finish-audit round (11 fixes, 2 flip-verified pins); 316 tests green. Closes #25
304 lines
11 KiB
Swift
304 lines
11 KiB
Swift
//
|
|
// EditorSession.swift
|
|
// Museion
|
|
//
|
|
// #19 (S1.2): the editor's write-behind machinery — debounced autosave (#64),
|
|
// save-state dot (#65), cursor-state sidecar (#66), external-change conflict
|
|
// rule (#67). One session per open post, owned by PostsModel. Drafts stay
|
|
// #62's explicit-⌘S path (PostsModel.saveDraft) — no session, no autosave.
|
|
//
|
|
|
|
import Foundation
|
|
import Observation
|
|
|
|
/// Save-state indicator (#65/#83): Saved = clean, Changed = dirty (text ≠
|
|
/// last flushed), failed = last write threw (sticky until one succeeds).
|
|
enum SaveState: Equatable {
|
|
case saved
|
|
case changed
|
|
case failed
|
|
}
|
|
|
|
/// What a session writes to (#92): a Post in the Home, or an external
|
|
/// markdown file edited as-is — the file is the document (ADR-0004).
|
|
enum SessionTarget {
|
|
case post(id: String, home: URL)
|
|
case externalFile(URL)
|
|
}
|
|
|
|
/// One open document's editing session (@MainActor @Observable, the
|
|
/// PostsModel pattern). Born from a disk read; writes go out after the #64
|
|
/// debounce. External targets save in place and never write a cursor sidecar
|
|
/// (#93) — nothing of ours lands next to a foreign file.
|
|
@MainActor
|
|
@Observable
|
|
final class EditorSession {
|
|
/// #24: the pass rails' shared piece facts — runPass and PassBarView
|
|
/// must agree on the stub path and the research probe (review: two
|
|
/// hand-copies drifting).
|
|
var passPieceURL: URL {
|
|
folderURL.appendingPathComponent("post.md")
|
|
}
|
|
|
|
var hasResearch: Bool {
|
|
FileManager.default.fileExists(atPath: folderURL.appendingPathComponent("research").path)
|
|
}
|
|
|
|
let target: SessionTarget
|
|
private let debounce: Duration
|
|
|
|
/// The Post id for post targets; nil for external.
|
|
var postID: String? {
|
|
if case let .post(id, _) = target {
|
|
return id
|
|
}
|
|
return nil
|
|
}
|
|
|
|
/// The external file's URL; nil for posts.
|
|
var fileURL: URL? {
|
|
if case let .externalFile(url) = target {
|
|
return url
|
|
}
|
|
return nil
|
|
}
|
|
|
|
/// The document's folder — the piece's resolved folder under projects/
|
|
/// or archive/ for posts (image resolution #71; resolved once at init,
|
|
/// ADR-0012 — a vanished piece still needs some path, so an unresolvable
|
|
/// id falls back to the default-project path); the external file's
|
|
/// containing folder, so relative images resolve beside the file.
|
|
private(set) var folderURL: URL
|
|
|
|
/// Current body text (live, per keystroke).
|
|
private(set) var text: String
|
|
/// The save-state indicator (#65).
|
|
private(set) var saveState: SaveState = .saved
|
|
/// #67: external change detected → the surface presents the alert.
|
|
private(set) var conflictAlert = false
|
|
|
|
/// Load plumbing for the editor surface: `loadText` changes only at open
|
|
/// and Yes-reload (a `loadGeneration` bump) — never per keystroke.
|
|
private(set) var loadGeneration = 0
|
|
private(set) var loadText: String
|
|
/// Cursor state restored from the sidecar (#66); the surface applies it
|
|
/// (clamped) on load.
|
|
private(set) var restoreCursor: PostStore.CursorState?
|
|
|
|
/// Live cursor state pushed by the surface; written to the sidecar on
|
|
/// each flush.
|
|
private(set) var cursor = PostStore.CursorState()
|
|
|
|
/// Text at last flush (or open). The watcher-echo check compares disk
|
|
/// against this — an exact, timer-free suppression of our own writes.
|
|
private var lastFlushedText: String
|
|
private var debounceTask: Task<Void, Never>?
|
|
|
|
/// True when the initial read failed (foreign file unreadable — wrong
|
|
/// encoding, permissions, vanished). A session that never loaded must
|
|
/// never write: the empty editor's first keystroke would otherwise
|
|
/// destroy the file we failed to read.
|
|
private(set) var loadFailed = false
|
|
|
|
/// Failure text for the owner's lastError strip; nil clears it (#65).
|
|
var onError: (@MainActor @Sendable (String?) -> Void)?
|
|
|
|
init(target: SessionTarget, debounce: Duration = .seconds(1)) {
|
|
self.target = target
|
|
self.debounce = debounce
|
|
switch target {
|
|
case let .post(id, home):
|
|
folderURL = PostStore.folder(of: id, home: home)
|
|
?? home.appendingPathComponent("projects", isDirectory: true)
|
|
.appendingPathComponent(Post.defaultProject, isDirectory: true)
|
|
.appendingPathComponent(id, isDirectory: true)
|
|
case let .externalFile(url):
|
|
folderURL = url.deletingLastPathComponent()
|
|
}
|
|
let read = Self.readDocument(target)
|
|
loadFailed = read == nil
|
|
let body = read ?? ""
|
|
text = body
|
|
loadText = body
|
|
lastFlushedText = body
|
|
if case let .post(id, home) = target {
|
|
restoreCursor = PostStore.readCursor(id: id, home: home)
|
|
}
|
|
}
|
|
|
|
/// Convenience: post-target session (#19 call sites).
|
|
convenience init(postID: String, home: URL, debounce: Duration = .seconds(1)) {
|
|
self.init(target: .post(id: postID, home: home), debounce: debounce)
|
|
}
|
|
|
|
/// Whole-document read per target: posts edit body-only (frontmatter
|
|
/// stamped back on write); external files round-trip the text — the file
|
|
/// is the document (#91/#93). BOM stripped and CRLF normalized to LF on
|
|
/// read (same reason as importFile: the corpus machinery splits on \n;
|
|
/// in Swift a CRLF pair is one grapheme and every split sees one line).
|
|
private static func readDocument(_ target: SessionTarget) -> String? {
|
|
switch target {
|
|
case let .post(id, home):
|
|
return PostStore.readBody(id: id, home: home)
|
|
case let .externalFile(url):
|
|
guard var text = try? String(contentsOf: url, encoding: .utf8) else { return nil }
|
|
if text.hasPrefix("\u{FEFF}") {
|
|
text.removeFirst()
|
|
}
|
|
return text.replacingOccurrences(of: "\r\n", with: "\n")
|
|
}
|
|
}
|
|
|
|
/// Target-aware write: posts → `PostStore.overwrite` (+ sidecar);
|
|
/// external → the whole text, in place, no sidecar (#93).
|
|
private func writeDocument() throws {
|
|
switch target {
|
|
case let .post(id, home):
|
|
try PostStore.overwrite(id: id, body: text, home: home)
|
|
PostStore.writeCursor(cursor, id: id, home: home)
|
|
case let .externalFile(url):
|
|
try text.write(to: url, atomically: true, encoding: .utf8)
|
|
}
|
|
}
|
|
|
|
// MARK: Edit + debounce (#64)
|
|
|
|
/// Keystroke from the editor surface; re-arms the ~1 s idle debounce.
|
|
func edit(_ newText: String) {
|
|
text = newText
|
|
syncSaveState() // #83: dirty shows while the debounce holds
|
|
debounceTask?.cancel()
|
|
debounceTask = Task { [debounce] in
|
|
try? await Task.sleep(for: debounce)
|
|
guard !Task.isCancelled else { return }
|
|
// #67: never autosave over an external change while its alert is
|
|
// unanswered — the alert promises the writer chooses. ⌘S (flush)
|
|
// stays explicit.
|
|
guard !conflictAlert else { return }
|
|
flush()
|
|
}
|
|
}
|
|
|
|
/// Live cursor state from the surface (selection + scroll).
|
|
func cursorUpdate(_ state: PostStore.CursorState) {
|
|
cursor = state
|
|
}
|
|
|
|
// MARK: Flush (#64/#65/#66)
|
|
|
|
/// Write body (+ post sidecar) now. ⌘S, debounce fire, selection change,
|
|
/// window close, and app quit all land here. No-op when clean or when the
|
|
/// document never loaded (a failed read must not become a write
|
|
/// that destroys the file). #108 audit: reports success — the flush-first
|
|
/// ops (move/archive/rename/restore) abort on false instead of moving a
|
|
/// piece whose edits failed to land.
|
|
@discardableResult
|
|
func flush() -> Bool {
|
|
debounceTask?.cancel()
|
|
guard !loadFailed, text != lastFlushedText else { return true }
|
|
do {
|
|
try writeDocument()
|
|
lastFlushedText = text
|
|
saveState = .saved
|
|
onError?(nil)
|
|
return true
|
|
} catch {
|
|
saveState = .failed
|
|
onError?(error.localizedDescription)
|
|
return false
|
|
}
|
|
}
|
|
|
|
/// #83: the indicator mirrors cleanliness — text ≠ last flushed = Changed.
|
|
private func syncSaveState() {
|
|
if text != lastFlushedText {
|
|
if saveState == .saved {
|
|
saveState = .changed
|
|
}
|
|
} else if saveState == .changed {
|
|
saveState = .saved
|
|
}
|
|
}
|
|
|
|
// MARK: External change (#67)
|
|
|
|
/// Owner teardown when the post leaves the editor (rename away, trash,
|
|
/// vanished on disk). `flushFirst` writes pending edits (rename reads the
|
|
/// file from disk, so unflushed text would be lost); otherwise the armed
|
|
/// debounce is cancelled so it can't fire at a dead path and report a
|
|
/// spurious failure.
|
|
func teardown(flushFirst: Bool) {
|
|
if flushFirst {
|
|
flush()
|
|
}
|
|
debounceTask?.cancel()
|
|
}
|
|
|
|
/// The owner's rescan calls this with the open post's current disk text.
|
|
/// Equality against `lastFlushedText` suppresses our own write's watcher
|
|
/// echo exactly — no suppression timers.
|
|
func diskDidChange(diskText: String) {
|
|
guard diskText != lastFlushedText, diskText != text else { return }
|
|
conflictAlert = true
|
|
}
|
|
|
|
/// #67 Yes: reload from disk; cursor restored from the sidecar where
|
|
/// still valid (the surface clamps). External targets reset the cursor
|
|
/// (#93 — no sidecar next to foreign files).
|
|
func reloadFromDisk() {
|
|
guard conflictAlert else { return }
|
|
conflictAlert = false
|
|
guard let disk = Self.readDocument(target) else { return }
|
|
text = disk
|
|
loadText = disk
|
|
loadGeneration += 1
|
|
lastFlushedText = disk
|
|
if case let .post(id, home) = target {
|
|
restoreCursor = PostStore.readCursor(id: id, home: home)
|
|
} else {
|
|
restoreCursor = nil
|
|
}
|
|
saveState = .saved
|
|
// #83: reload resolves a failure too — shown text now equals disk.
|
|
onError?(nil)
|
|
}
|
|
|
|
/// #25: adopt externally-computed text (Fix Card apply) — Yes-reload's
|
|
/// body with a provided text: bumps loadGeneration so both surfaces
|
|
/// (the prose coordinator seeds from session.text on a generation move,
|
|
/// PostEditorView.swift:405; OutlineEditorView re-parses on the bump)
|
|
/// re-seed, then flushes to disk now. Writer-consented explicit action
|
|
/// (like ⌘S) — the #67 conflict guard is the CALLER's job.
|
|
@discardableResult
|
|
func adoptText(_ newText: String) -> Bool {
|
|
// A session that never loaded must never write (the flush guard's
|
|
// own rule, made explicit here: flush reports success on a clean
|
|
// no-op, so a loadFailed session would close cards over a write
|
|
// that never landed).
|
|
guard !loadFailed else { return false }
|
|
// A session that never loaded must never write (the flush guard's
|
|
// own rule, made explicit here: flush reports success on a clean
|
|
// no-op, so a loadFailed session would close cards over a write
|
|
// that never landed).
|
|
debounceTask?.cancel()
|
|
text = newText
|
|
loadText = newText
|
|
loadGeneration += 1
|
|
return flush()
|
|
}
|
|
|
|
/// #67 No: keep local — the next autosave overwrites disk (the writer's
|
|
/// explicit choice). Marks the disk state as seen so the same external
|
|
/// content doesn't re-alert on every watcher tick; a new external write
|
|
/// still does. An unreadable disk (post vanished mid-alert) keeps the
|
|
/// previous flushed text — the session stays dirty, ⌘S stays armed.
|
|
func keepLocal() {
|
|
guard conflictAlert else { return }
|
|
conflictAlert = false
|
|
if let disk = Self.readDocument(target) {
|
|
lastFlushedText = disk
|
|
}
|
|
syncSaveState() // #83: local ≠ disk now — shows as pending changes
|
|
}
|
|
}
|