// // PostsModelWatcher.swift // Museion // // #193: the watching domain of PostsModel, moved from PostsModel.swift // (file-length ceiling) — the PostsWatcher FSEvents stream (#61), Home // binding, startWatching, and the rescan rail, code unchanged. // import CoreServices import Foundation /// 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() } } // MARK: Watcher (#61) extension PostsModel { /// 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 WorkspaceView's /// root `.task(id: museionHome)` — first frame and every Home repoint, /// pane-independent. /// brief-28: the dumb binder — it flips `watchedHome` unconditionally. /// A REPOINT reaches it only after `repoint(to:)` passed its departure /// gate (the Settings binding runs the gate before committing the /// preference; the `.task` fires after that commit). func bind(home: URL) { startWatching(home: home) Task { await rescan() } } /// brief-28 (home-repoint-retains-old-editor-target): a Home repoint is /// a DOCUMENT DEPARTURE — the gate runs FIRST, the binding commits /// after. The Settings path used to flip `watchedHome` under the open /// session: the session's immutable target kept the OLD Home, a /// same-slug piece in the new library made the ID-only reselect return /// it, and autosave/Save/quit wrote the old library while structural /// operations resolved against the new one (#198's departure gate never /// saw this seam; a no-collision piece was torn down by the vanish /// path with its dirty buffer dropped). /// True = every open document landed through `sessionMayDepart` (the /// three legs: unanswered #67, failed flush, never-loaded retype) and /// the departed piece's state is cleared — the caller may bind the new /// Home. False = `lastError` says why and NOTHING changed: the /// preference stays A, `watchedHome` stays A, the session keeps its /// (A, id) target and its buffer. No parallel gate — the same one /// `select`/`newPost`/quit ride. /// The in-memory draft survives: it has no Home until first save (#62) /// and lands in the new library — the only alternative is dropping the /// only copy. A running pass or Blind Read keeps its own completion /// guard (#179: the advance refuses once `watchedHome` moved). @discardableResult func repoint(to newHome: URL) -> Bool { guard newHome != watchedHome else { return true } // first bind / the same folder: nothing departs guard departOpenDocuments() else { return false } // The departed piece's state dies with it: a stale id under the new // library is a ghost selection (a same-slug piece would read as // open over an empty editor) and a stale ask would act on the new // library's piece. Nothing auto-reopens — the writer picks from // the new list (the reopen machinery stays where it is). selectedPostID = nil openPieceCards = [] openPieceHasSnapshot = false outlineGuardPieceID = nil proseOverridePostID = nil pendingConversion = nil lastDraftWasOutline = false pendingProject = nil return true } 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. /// #146: internal — the split-out domain extensions trigger rescans. 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). // #114 audit: identity, not id — a same-id reopen (convert/restore/ // move) must not receive the OLD session's stale disk text as a // spurious #67 conflict. let openSession = session // brief-28: the Home half of that identity — the open post's disk // text is read from the session's OWN library. A session targeting // another Home has no piece in this scan's tree; reading the // current Home's same-slug file for it raised a spurious #67 on the // old session. let openPostID = openSession?.targets(home: home) == true ? openSession?.postID : nil let scanMemo = scanCache // detached capture, not a property read // The search's content signal: a re-read post.md (a cache miss) // changed library content even when its Post compares equal. Read // the counter before the scan so the delta after it says "this // scan saw disk change" (#144's mounted half). let missesBefore = scanMemo.misses let (scanned, openDiskText) = await Task.detached(priority: .userInitiated) { let posts = Post.scan(home: home, cache: scanMemo) let disk = openPostID.flatMap { PostStore.readBody(id: $0, home: home) } return (posts, disk) }.value guard !Task.isCancelled else { return } // Stale-scan guard (#137 suite find / finish): the snapshot can // PREDATE the current selection, and a scan that outlived a Home // repoint speaks for the OLD tree — bind's initial rescan (detached // scan over the empty tree) can land its continuation after a // select its scan never saw, "vanishing" a piece that exists, and a // pre-repoint scan would land the old library's list under the new // binding. Disk is the truth for vanished; a stale snapshot must // not kill a live session (teardown cancels the debounce — // unflushed edits would die with it); the new Home's own rescan // owns everything (brief-28: hoisted — the list, the revision and // the #67 text ride the same verdict, not just the vanish check). guard watchedHome == home else { return } // #143: @Observable invalidates on assignment regardless of equality — // skip the no-op so panes don't regroup on our own autosave echoes. let listChanged = scanned != posts if listChanged { posts = scanned } // #144's mounted half: any list change OR any re-read file bumps the // content revision — the search snapshot's invalidation signal. // Archive/trash/rename arrive as list changes; a body-only edit as // a cache miss (metadata-equal — the skip above keeps the panes // still, the bump alone re-keys the mounted search). if listChanged || scanMemo.misses > missesBefore { contentRevision += 1 } if let id = selectedPostID, !posts.contains(where: { $0.id == id }), PostStore.folder(of: id, home: home) == nil { selectedPostID = nil // the post vanished (deleted in Finder or here) if let open = session, open.targets(postID: id, home: home) { 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 openSession === session, let openDiskText { openSession?.diskDidChange(diskText: openDiskText) } // #23: the open piece's stored fix cards ride the same rescan — // the watcher fires on /cards/ writes too. refreshCards() } }