// // 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. func bind(home: URL) { startWatching(home: home) Task { await rescan() } } 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). let openPostID = session?.postID // #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 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 } // #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 } // Stale-scan guard (#137 suite find): the snapshot can PREDATE the // current selection — 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. 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). // #137 audit (finish): a scan that outlived a Home repoint speaks // for the OLD tree — never let it kill a session selected under // the NEW home (the id is missing from the old snapshot by // construction); the next rescan under the new home owns it. if let id = selectedPostID, !posts.contains(where: { $0.id == id }), watchedHome == home, PostStore.folder(of: id, home: home) == nil { 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 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() } }