// // PostsModel.swift // Museion // // #18 (S1.1): the Posts pane's write side — FSEvents watcher on the piece // roots (projects/ + archive/, #107) with a ~0.5 s debounced rescan (#61), // selection, and the New Post draft lifecycle (#62). Own ops route through // the same rescan: one path. // #108: project targeting + the move/archive/restore ops behind the // variant-B library and the Archive pane. // import CoreServices import Foundation import Observation /// The New Post draft: body text only, no folder until first save (#62). /// #107: remembers the project the piece will land in when first saved. struct PostDraft { var text = "# Untitled\n\n" let project: String } /// Recursive FSEvents stream on one or more directories (#61): file-level /// events, so nested `projects///post.md` edits from Finder fire /// too — a plain dir-FD dispatch source only sees direct children and misses /// them. final nonisolated class PostsWatcher: @unchecked Sendable { /// Fired on the main actor when anything under a watched path changes. var onEvent: (@MainActor @Sendable () -> Void)? private var stream: FSEventStreamRef? func start(urls: [URL]) { stop() var context = FSEventStreamContext( version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: nil, release: nil, copyDescription: nil, ) // C function pointer — no captures; `self` rides the info pointer. let callback: FSEventStreamCallback = { _, info, _, _, _, _ in let watcher = Unmanaged.fromOpaque(info!).takeUnretainedValue() Task { @MainActor in watcher.onEvent?() } } guard let stream = FSEventStreamCreate( kCFAllocatorDefault, callback, &context, urls.map(\.path) as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0.5, // seconds; FSEvents coalesces within this latency (the #61 window) FSEventStreamCreateFlags(kFSEventStreamCreateFlagFileEvents), ) else { return } FSEventStreamScheduleWithRunLoop(stream, CFRunLoopGetMain(), CFRunLoopMode.defaultMode.rawValue) FSEventStreamStart(stream) self.stream = stream } func stop() { guard let stream else { return } FSEventStreamStop(stream) FSEventStreamInvalidate(stream) FSEventStreamRelease(stream) self.stream = nil } deinit { stop() } } /// App-scoped Posts state (@MainActor @Observable, the AppGateState pattern). /// The watcher runs while the workspace is open (app-scoped, #61). @MainActor @Observable final class PostsModel { /// The scanned, title-sorted list — mirrors `projects/` + `archive/` at /// all times (#107). private(set) var posts: [Post] = [] /// The selected Post's id; nil = nothing selected (empty editor). private(set) var selectedPostID: String? /// The in-memory draft for New Post (#62): no folder until first save. private(set) var draft: PostDraft? /// #19: the open post's editing session; nil while a draft is open or /// nothing is selected. private(set) var session: EditorSession? /// #92: the external buffer's guest slot — one at a time, transient per /// launch. Takes the editor column; opening a Post or draft dismisses it /// (flush first). private(set) var externalSession: EditorSession? /// #94: a multi-file import waiting on its ONE Origin ask; the sheet /// answers, then the batch runs. private(set) var pendingImportURLs: [URL]? /// #108: the explicit target for the NEXT new piece — set by New Project /// once the folder exists; outranks selection. Cleared when the draft /// lands (saveDraft) or the ask is canceled. private(set) var pendingProject: String? /// #108: File ▸ New Project… stages its ask here — commands can't /// present sheets, so the model holds the flag and WorkspaceView /// presents (the pendingImportURLs pattern, #94). private(set) var askNewProject = false /// Last failed-op message surfaced in the editor (nil = clean). private(set) var lastError: String? /// Home the watcher is bound to; also the rescan target. private var watchedHome: URL? private var watcher = PostsWatcher() /// #93: per-file watcher on the open external file — the #67 conflict /// check reused verbatim for foreign files. private var externalWatcher = PostsWatcher() /// Bind a Home: ensure both container roots exist (FSEvents on a missing /// path is unreliable; archive/ is a watcher root now, #107), initial /// scan + start (or restart) the watcher. Called from /// `.task(id: home)` — re-fires on Home repoint. func bind(home: URL) { startWatching(home: home) Task { await rescan() } } // MARK: Watcher (#61) private func startWatching(home: URL) { guard watchedHome != home else { return } watchedHome = home let roots = Post.containerRoots.map { home.appendingPathComponent($0, isDirectory: true) } for root in roots { try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) } watcher.onEvent = { [weak self] in Task { await self?.rescan() } } watcher.start(urls: roots) } /// Off-main scan; keeps selection valid across the fresh refresh. /// FSEvents already coalesces bursts within its 0.5 s latency window — /// no second debounce on top. private func rescan() async { guard let home = watchedHome else { return } // Scan + the #67 disk read both run off-main (a synced large post.md // must never stall the UI on a watcher burst). let openPostID = session?.postID let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { let posts = Post.scan(home: home) let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } return (posts, disk) }.value guard !Task.isCancelled else { return } posts = scanned if let id = selectedPostID, !posts.contains(where: { $0.id == id }) { selectedPostID = nil // the post vanished (deleted in Finder or here) if let open = session, open.postID == id { open.teardown(flushFirst: false) // post is gone; cancel the debounce session = nil } } // #67: watcher echo check on the open post — equality against the // session's lastFlushedText suppresses our own writes exactly. if let session, let openDiskText { session.diskDidChange(diskText: openDiskText) } } // MARK: Own ops (route through the same rescan, #61) // ponytail: the PostStore calls here run on MainActor — small single-file // writes and same-volume moves; if a big Home ever stalls the UI, wrap // them in Task.detached like rescan. /// #107: the project a NEW piece lands in — #108: an explicit pending /// target first, else the selected non-archived post's project, else the /// default. One home; newPost/importFiles must not drift. private var targetProject: String { pendingProject ?? posts.first(where: { $0.id == selectedPostID && !$0.isArchived })?.project ?? Post.defaultProject } /// Tear the watcher down on the main actor (its scheduling thread) — /// deinit of a @MainActor-held object may run elsewhere. #64: app quit /// flushes the open session first (sidecar rides along). #96: quit also /// flushes the external buffer — same posture, same moment. func shutdown() { session?.flush() externalSession?.flush() watcher.stop() externalWatcher.stop() } /// New Post (#62): fresh in-memory draft, no folder, editor takes it. /// #107: the draft targets the selected post's project (archived posts /// 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 draft = PostDraft(project: target) selectedPostID = nil } /// #92: dismiss the external guest slot, flushing pending edits (the /// guest is always leaving for somewhere — same posture as post /// selection change). private func dismissExternal() { externalSession?.teardown(flushFirst: true) externalSession = nil externalWatcher.stop() } /// First save of the draft (#62): lazy folder, slug, #59 stamp all fire /// here. The saved post opens straight into an editing session — the /// writer keeps typing where they were. Rescans immediately (the watcher /// would too, after its window). func saveDraft(home: URL) { guard let draft else { return } do { let post = try PostStore.writeNew(body: draft.text, project: draft.project, home: home) self.draft = nil pendingProject = nil // #108: the explicit target landed with the draft selectedPostID = post.id session = EditorSession(postID: post.id, home: home) wireSession() lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } /// Select a Post; selecting anything abandons an unsaved draft (the /// draft otherwise hijacks the editor — its only exits are save or /// selecting away). #19: opening a post ends the previous session /// (flush-on-selection-change, #64) and starts a new one. #92: it also /// dismisses the external guest (flush first). func select(_ id: String, home: URL) { dismissExternal() if let session, session.postID != id { session.teardown(flushFirst: true) } session = id == session?.postID ? session : EditorSession(postID: id, home: home) draft = nil // #108: abandoning the draft kills its explicit project target too — // a later New Post must not silently land in the abandoned project. pendingProject = nil selectedPostID = id wireSession() } /// Draft typing from the editor (private(set) barrier). func updateDraft(_ text: String) { draft?.text = text } /// Explicit Rename = retitle + move (#60). Renaming the open post flushes /// first (rename reads the file from disk — unflushed edits must land /// before the move), then reopens a session at the new id. Sets lastError /// on failure. func rename(_ post: Post, to title: String, home: URL) { // #108 audit 2: rename reads the file from disk — a failed write // aborts (moving the folder would strand unflushed edits), and the // session stays up, dirty and honest. guard flushOrAbort(post.id) else { return } do { let moved = try PostStore.rename(post, to: title, home: home) if selectedPostID == post.id { selectedPostID = moved.id if session?.postID == post.id { session = EditorSession(postID: moved.id, home: home) wireSession() } } lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } /// Delete a Post (Trash, recoverable — #18 AC). Clears selection if it /// was the post; the session is torn down (cancel only — the folder is /// leaving, a flush would resurrect nothing but churn the watcher). func trash(_ post: Post, home: URL) { do { try PostStore.trash(post, home: home) if selectedPostID == post.id { selectedPostID = nil if let open = session, open.postID == post.id { open.teardown(flushFirst: false) session = nil } } lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } // MARK: Projects (#108) /// #108: New Project's confirmed sheet — the folder exists, the next /// draft targets it, and opens now. func newProjectPending(named name: String) { pendingProject = name newPost() } /// #108: raw create — the sheet composes on it. The failure reason on /// false (shown inline in the sheet; never routed into lastError — the /// strip behind the sheet must not double-message one error). func createProject(named name: String, home: URL) -> String? { do { try PostStore.createProject(named: name, home: home) return nil // success } catch { return error.localizedDescription } } /// #108: File ▸ New Project… — stage the ask (WorkspaceView presents). func stageNewProject() { askNewProject = true } /// #108: the ask's Cancel. func cancelNewProject() { askNewProject = false } /// #108 audit 2: the Move-to-Project list — every project on disk under /// projects/ plus the default (bind creates the roots, not posts/ — an /// empty Home must still offer it), localized-sorted to match the /// library's section order. func moveTargets(home: URL) -> [String] { let root = home.appendingPathComponent("projects", isDirectory: true) let onDisk = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] var names = Set(onDisk.filter { !$0.hasPrefix(".") }) names.insert(Post.defaultProject) return names.sorted { $0.localizedStandardCompare($1) == .orderedAscending } } /// #108 audit: flush the open piece, aborting when the write failed — a /// folder move must never carry away text that didn't land (the move /// itself succeeds exactly when a file write fails). Returns false with /// lastError set; the session stays up, dirty and honest. private func flushOrAbort(_ postID: String) -> Bool { guard let session, session.postID == postID else { return true } if !session.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 moved." return false } 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. func moveToProject(_ post: Post, project: String, home: URL) { guard flushOrAbort(post.id) else { return } do { try PostStore.move(post, to: project, home: home) if session?.postID == post.id { session = EditorSession(postID: post.id, home: home) wireSession() } lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } /// #108: Move to Archive. Archiving the open piece clears it — the /// editor is empty until the next selection (archived pieces open from /// the Archive pane, where they're listed). func archivePost(_ post: Post, home: URL) { guard flushOrAbort(post.id) else { return } do { try PostStore.archive(post, home: home) if selectedPostID == post.id { selectedPostID = nil } if let open = session, open.postID == post.id { open.teardown(flushFirst: false) // already flushed above session = nil } lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } /// #108: Move Back — the restored piece lands in its project and opens; /// the writer stays in the piece they just revived. A session already /// open on the piece survives `select` — reopen it so folderURL points /// at projects/, not the archive path it was born with. func restorePost(_ post: Post, home: URL) { guard flushOrAbort(post.id) else { return } do { try PostStore.restore(post, home: home) if let open = session, open.postID == post.id { session = EditorSession(postID: post.id, home: home) wireSession() } else { select(post.id, home: home) } lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } /// #108: whole-project unarchive from the Archive pane's section header. /// Flush-first like every folder move (a dirty open piece inside the /// project would otherwise race the move), and its session is reopened so /// folderURL re-resolves off archive/ (same reason as restorePost). func unarchiveProject(_ name: String, home: URL) { /// #108 audit 2: disk-derived membership — the posts snapshot is stale /// the moment a Finder move lands. Captured BEFORE the move: after it /// the piece resolves under projects/ and its archive membership is /// invisible. dir − 1 = project dir (…/archive/), − 2 = root. func openPieceInArchivedProject() -> String? { guard let id = session?.postID, let projectDir = PostStore.folder(of: id, home: home)?.deletingLastPathComponent(), projectDir.lastPathComponent == name, projectDir.deletingLastPathComponent().lastPathComponent == "archive" else { return nil } return id } let openID = openPieceInArchivedProject() if let openID { // #108 audit 2: the only #108 folder move that skipped the gate. guard flushOrAbort(openID) else { return } } do { try PostStore.unarchiveProject(name, home: home) if let openID { session = EditorSession(postID: openID, home: home) wireSession() } lastError = nil Task { await rescan() } } catch { lastError = error.localizedDescription } } // MARK: External buffer (#91–#93) + Import (#94/#95) /// #91/#92: open an external markdown file in the guest slot — one at a /// time; opening anything else (file, Post, draft) flushed and replaced /// it first. A Post session/draft stands down while the guest is up /// (the editor column is the guest's; the selection stays for return). /// Local files only (a dragged web link is not a document) and symlinks /// resolve to their real target so the in-place write never severs the /// link (rename over a symlink replaces it). 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 draft = nil pendingProject = nil // #108 audit: the draft died here too — its target dies with it externalSession = EditorSession(target: .externalFile(target)) if externalSession?.loadFailed == true { lastError = "Couldn't read \(target.lastPathComponent) — not UTF-8 text or unreadable. Nothing was changed." externalSession = nil return } wireSession() startExternalWatch(url: target) } /// #93: watch the open external file — its rescan is the #67 disk-change /// check, reused verbatim for foreign files. PostsWatcher fires on the /// main actor already; no re-hop needed. private func startExternalWatch(url: URL) { externalWatcher.onEvent = { [weak self] in guard let self, let session = externalSession else { return } guard let disk = try? String(contentsOf: url, encoding: .utf8) else { return } session.diskDidChange(diskText: disk) } externalWatcher.start(urls: [url.deletingLastPathComponent()]) } /// #94: stage a multi-file import — the ONE Origin ask presents; the /// sheet's answer runs the batch. func stageImport(_ urls: [URL]) { guard !urls.isEmpty else { return } pendingImportURLs = urls } /// #94: dismiss the ask without an answer — the batch drops. func cancelImport() { pendingImportURLs = nil } /// #94/#95: run the batch after the Origin answer — copy each file in as /// a Post; a per-file failure continues the batch into lastError (stated /// default, reversible; never an alert, never an abort). The last /// imported post opens; a failure anywhere keeps its message up even /// when other files landed. #107: the batch lands in the selected /// post's project (newPost's target rule). func importFiles(origin: Post.Origin, home: URL) { guard let urls = pendingImportURLs else { return } pendingImportURLs = nil let project = targetProject var last: Post? var failures = 0 for url in urls { do { last = try PostStore.importFile(at: url, origin: origin, project: project, home: home) } catch { failures += 1 lastError = "Import failed — \(url.lastPathComponent): \(error.localizedDescription)" } } if let last { select(last.id, home: home) } if failures == 0 { lastError = nil } Task { await rescan() } } private func wireSession() { let route: (@MainActor @Sendable (String?) -> Void)? = { [weak self] message in self?.lastError = message } session?.onError = route externalSession?.onError = route } }