Tests/OrgAppTests/AppTests.swift

design-themes-widgets
orgstar/Tests/OrgAppTests/AppTests.swift history · blame · raw

1496 lines · 77817 bytes

   1import Foundation
   2import OrgCore
   3import OrgDocument
   4@testable import OrgIndex
   5import os
   6import Testing
   7@testable import OrgApp
   8
   9/// A temporary folder that removes itself.
  10final class Folder {
  11    let url: URL
  12
  13    init() throws {
  14        url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)").standardizedFileURL
  15        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
  16    }
  17
  18    deinit {
  19        try? FileManager.default.removeItem(at: url)
  20    }
  21
  22    @discardableResult
  23    func write(_ path: String, _ text: String) throws -> URL {
  24        let file = url.appendingPathComponent(path)
  25        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
  26        try Data(text.utf8).write(to: file)
  27        return file.standardizedFileURL
  28    }
  29}
  30
  31struct FileTreeTests {
  32    @Test func foldersFirstThenFiles() {
  33        let files = ["b.org", "a/z.org", "a/y.org", "c.sync-conflict-1.org", "a2.org"].map {
  34            FileEntry(path: "/r/" + $0, root: "/r", kind: $0.contains("conflict") ? .conflict : .org)
  35        }
  36        let tree = FileTreeNode.build(root: "/r", files: files)
  37        #expect(tree.children?.map(\.name) == ["a", "a2.org", "b.org", "c.sync-conflict-1.org"])
  38        #expect(tree.children?[0].children?.map(\.name) == ["y.org", "z.org"])
  39        #expect(tree.children?[1].children == nil)
  40    }
  41
  42    @Test func fuzzyMatching() {
  43        #expect(FuzzyMatch.score("wn", "work/notes.org") != nil)
  44        #expect(FuzzyMatch.score("xyz", "work/notes.org") == nil)
  45        let files = ["work/notes.org", "notes.org", "personal/wine.org"].map { FileEntry(path: "/r/" + $0, root: "/r", kind: .org) }
  46        #expect(FuzzyMatch.rank("notes", files).map(\.relativePath) == ["notes.org", "work/notes.org"])
  47        #expect(FuzzyMatch.rank("", files).count == 3)
  48    }
  49}
  50
  51@MainActor
  52struct WorkspaceModelTests {
  53    @Test func addSearchRemoveAndPersist() async throws {
  54        let notes = try Folder()
  55        let support = try Folder()
  56        try notes.write("a.org", "* Groceries\nbuy apples\n")
  57        try notes.write("sub/b.org", "* Taxes\n")
  58        try notes.write("c.sync-conflict-1.org", "* Taxes copy\n")
  59
  60        let model = try WorkspaceModel(directory: support.url)
  61        try await model.addRoot(notes.url)
  62        #expect(model.files.count == 3)
  63        #expect(try model.search("apples").map(\.title) == ["Groceries"])
  64        #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
  65        let root = try #require(model.rootPaths.first)
  66        #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
  67
  68        let reopened = try WorkspaceModel(directory: support.url)
  69        #expect(reopened.roots.count == 1)
  70        #expect(reopened.files.count == 3)
  71
  72        try reopened.removeRoot(path: root)
  73        #expect(reopened.roots.isEmpty)
  74        #expect(reopened.files.isEmpty)
  75        #expect(try reopened.search("apples").isEmpty)
  76    }
  77
  78    @Test func aMovedFolderLeavesNoOldRows() async throws {
  79        let parent = try Folder()
  80        let original = parent.url.appendingPathComponent("notes")
  81        try FileManager.default.createDirectory(at: original, withIntermediateDirectories: true)
  82        try "* Plumber\n".write(to: original.appendingPathComponent("a.org"), atomically: true, encoding: .utf8)
  83        let data = parent.url.appendingPathComponent("data")
  84        let model = try WorkspaceModel(directory: data)
  85        try await model.addRoot(original)
  86        #expect(try model.search("plumber").count == 1)
  87
  88        let moved = parent.url.appendingPathComponent("moved")
  89        try FileManager.default.moveItem(at: original, to: moved)
  90        let reopened = try WorkspaceModel(directory: data)
  91        await reopened.refresh()
  92        let found = try reopened.search("plumber").map(\.path)
  93        #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)")
  94        // Adding it again, under its new path, adds nothing.
  95        try await reopened.addRoot(moved)
  96        #expect(reopened.roots.count == 1)
  97    }
  98
  99    @Test func aFolderThatDoesntResolveCanBeChosenAgain() async throws {
 100        let parent = try Folder()
 101        let gone = parent.url.appendingPathComponent("gone")
 102        try FileManager.default.createDirectory(at: gone, withIntermediateDirectories: true)
 103        let data = parent.url.appendingPathComponent("data")
 104        let model = try WorkspaceModel(directory: data)
 105        try await model.addRoot(gone)
 106        #expect(model.unresolvedRoots.isEmpty)
 107        try FileManager.default.removeItem(at: gone)
 108
 109        let reopened = try WorkspaceModel(directory: data)
 110        let root = try #require(reopened.unresolvedRoots.first)
 111        #expect(reopened.rootPaths.isEmpty && root.path == gone.path)
 112        let found = try parent.write("found/a.org", "* Plumber\n").deletingLastPathComponent()
 113        try await reopened.regrant(root, with: found)
 114        #expect(reopened.unresolvedRoots.isEmpty)
 115        #expect(reopened.roots.map(\.path) == [found.path])
 116        #expect(try reopened.search("plumber").count == 1)
 117        #expect(try WorkspaceModel(directory: data).roots.map(\.path) == [found.path])
 118
 119        // Chosen again as a folder already in the sidebar, the old one just goes.
 120        let other = parent.url.appendingPathComponent("other")
 121        try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true)
 122        try await reopened.addRoot(other)
 123        try FileManager.default.removeItem(at: other)
 124        let third = try WorkspaceModel(directory: data)
 125        let stale = try #require(third.unresolvedRoots.first)
 126        try await third.regrant(stale, with: found)
 127        #expect(third.roots.map(\.path) == [found.path] && third.unresolvedRoots.isEmpty)
 128    }
 129
 130    @Test func listsDownloadsInTheTree() {
 131        let files = [FileEntry(path: "/r/a.org", root: "/r", kind: .org)]
 132        let tree = FileTreeNode.build(root: "/r", files: files, downloading: ["/r/b.org", "/r/sub/c.org"])
 133        #expect(tree.children?.map(\.name) == ["sub", "a.org", "b.org"])
 134        #expect(tree.children?[2].isDownloading == true && tree.children?[2].file == nil)
 135        #expect(tree.children?[0].children?.map(\.name) == ["c.org"])
 136    }
 137
 138    @Test func findsBacklinks() async throws {
 139        let notes = try Folder()
 140        try notes.write("a.org", "* Sink\n:PROPERTIES:\n:ID: s-1\n:CUSTOM_ID: sink\n:END:\nsee [[*Taps]]\n* Taps\n")
 141        try notes.write("b.org", "* Plumbing\n[[id:s-1][the sink]] and [[file:a.org]]\n* Other\n[[file:a.org::#sink]] [[https://x.org]]\n")
 142        // Links before the first heading come from the file itself.
 143        try notes.write("c.org", "#+TITLE: C\nAbout [[file:a.org::*Sink]] and [[file:a.org]].\n* Later\n")
 144        let model = try WorkspaceModel(directory: nil)
 145        try await model.addRoot(notes.url)
 146        let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
 147        let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path
 148        let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
 149        #expect(try model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
 150        #expect(try model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
 151        #expect(try model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
 152        #expect(try model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
 153        // Off the main actor, as the panes ask.
 154        #expect(try await Task.detached { try model.backlinks(to: sink).map(\.title) }.value == ["Plumbing", "Other", "c.org"])
 155        // Each with the line its link is on, the link as it reads.
 156        #expect(try model.backlinks(to: sink).map { $0.snippet?.text } == ["the sink and file:a.org", "file:a.org::#sink https://x.org", "About file:a.org::*Sink and file:a.org."])
 157        #expect(try model.backlinks(to: sink).first?.snippet?.matches == [0..<8])
 158        let fromC = try #require(try model.backlinks(to: sink).last)
 159        #expect(fromC == .file(c, contentHash: fromC.contentHash))
 160        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 161        session.show(fromC)
 162        #expect(session.path == c && session.revealRequest?.offset == 0)
 163    }
 164
 165    @Test func createRenameAndTrashFiles() async throws {
 166        let notes = try Folder()
 167        try notes.write("a.org", "* Alpha\n")
 168        let model = try WorkspaceModel(directory: nil)
 169        model.trasher = { try FileManager.default.removeItem(at: $0) }
 170        try await model.addRoot(notes.url)
 171        let root = try #require(model.rootPaths.first)
 172
 173        let created = try await model.createFile(named: "projects/plan", in: root)
 174        #expect(created == root + "/projects/plan.org")
 175        #expect(model.files.map(\.path).contains(created))
 176        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "projects/plan.org", in: root) }
 177        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "../escape", in: root) }
 178
 179        let renamed = try await model.rename(created, to: "roadmap.org")
 180        #expect(model.files.map(\.path).contains(renamed) && !model.files.map(\.path).contains(created))
 181        let folder = try await model.rename(root + "/projects", to: "work")
 182        #expect(model.files.map(\.path).contains(folder + "/roadmap.org"))
 183
 184        try await model.trash(folder + "/roadmap.org")
 185        #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
 186        #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
 187        #expect(try model.search("alpha").count == 1)
 188    }
 189
 190    /// Watching starts with no folders (a first launch); a folder added afterwards is
 191    /// watched.
 192    @Test func foldersAddedLaterAreWatched() async throws {
 193        let notes = try Folder()
 194        let model = try WorkspaceModel(directory: nil)
 195        model.startWatching()
 196        try await model.addRoot(notes.url)
 197        let file = try notes.write("new.org", "* Fresh heading\n")
 198        var found = false
 199        for _ in 0..<40 where !found {
 200            try await Task.sleep(for: .milliseconds(100))
 201            found = model.files.contains { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() }
 202        }
 203        #expect(found)
 204    }
 205
 206    @Test func changedFilesAreReindexed() async throws {
 207        let notes = try Folder()
 208        let file = try notes.write("a.org", "* Old\n")
 209        let model = try WorkspaceModel(directory: nil)
 210        try await model.addRoot(notes.url)
 211        try notes.write("a.org", "* New\n")
 212        await model.filesChanged([file], rescan: [])
 213        #expect(try model.search("new").count == 1)
 214        #expect(model.changedFile?.path == file.path)
 215    }
 216
 217    /// A database error is reported, not shown as nothing found.
 218    @Test func reportsIndexErrors() async throws {
 219        let notes = try Folder()
 220        let file = try notes.write("a.org", "* Alpha\n:PROPERTIES:\n:ID: a-1\n:END:\n* Beta\n[[id:a-1]]\n")
 221        let model = try WorkspaceModel(directory: nil)
 222        try await model.addRoot(notes.url)
 223        let a = try #require(model.files.first).path
 224        let target = Backlinks.Target(path: a, title: "Alpha", id: "a-1")
 225        #expect(try model.nodes(denote: false).map(\.title) == ["Alpha"])
 226        #expect(try model.backlinks(to: target).map(\.title) == ["Beta"])
 227        #expect(try model.search("gamma").isEmpty)
 228        #expect(model.lastError == nil)
 229
 230        try model.index.database.close()
 231        #expect(throws: WorkspaceModel.FileError.self) { try model.search("alpha") }
 232        #expect(throws: WorkspaceModel.FileError.self) { try model.nodes(denote: false) }
 233        #expect(throws: WorkspaceModel.FileError.self) { try model.backlinks(to: target) }
 234        await model.filesChanged([file], rescan: [])
 235        #expect(model.lastError?.hasPrefix("Indexing ") == true)
 236        model.lastError = nil
 237        await model.filesChanged([], rescan: [notes.url])
 238        #expect(model.lastError?.hasPrefix("Indexing ") == true)
 239    }
 240}
 241
 242@MainActor
 243struct DocumentSessionTests {
 244    @Test func openShowAndReload() throws {
 245        let notes = try Folder()
 246        let file = try notes.write("a.org", "* One\n* Two\n")
 247        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 248        session.open(file.path)
 249        #expect(session.outline.map(\.title) == ["One", "Two"])
 250
 251        let location = HeadingLocation(path: file.path, ordinal: 1, title: "Two", start: 6, contentHash: "stale")
 252        session.show(location)
 253        #expect(session.revealRequest?.offset == 6)
 254
 255        try notes.write("a.org", "intro\n* One\n* Two\n")
 256        session.fileChanged(file.path)
 257        #expect(session.outline.map(\.start) == [6, 12])
 258        session.show(location)
 259        #expect(session.revealRequest?.offset == 12)
 260    }
 261
 262    /// A change that can't be read is reported, and the buffer keeps its text.
 263    @Test func unreadableChangeIsReported() throws {
 264        let notes = try Folder()
 265        let file = try notes.write("a.org", "* One\n")
 266        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 267        session.open(file.path)
 268        try notes.write("a.org", "* Two\n")
 269        try FileManager.default.setAttributes([.posixPermissions: 0], ofItemAtPath: file.path)
 270        session.fileChanged(file.path)
 271        #expect(session.lastError?.hasPrefix("Can't read a.org: ") == true)
 272        #expect(session.document?.text == "* One\n")
 273    }
 274
 275    @Test func sameFileByAnotherPathSharesItsBuffer() throws {
 276        let notes = try Folder()
 277        let file = try notes.write("a.org", "* One\n")
 278        let link = notes.url.appendingPathComponent("link")
 279        try FileManager.default.createSymbolicLink(at: link, withDestinationURL: notes.url)
 280        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 281        session.open(file.path)
 282        session.open(link.appendingPathComponent("a.org").path)
 283        #expect(session.openPaths == [file.path])
 284        #expect(session.path == file.path)
 285    }
 286
 287    @Test func buffersOfTheSameNameShowTheirFolders() throws {
 288        let notes = try Folder()
 289        let a = try notes.write("x/blog/index.org", "a\n")
 290        let b = try notes.write("y/blog/index.org", "b\n")
 291        let c = try notes.write("y/other.org", "c\n")
 292        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 293        session.open(a.path)
 294        #expect(session.bufferName(a.path) == "index.org")
 295        session.open(b.path)
 296        session.open(c.path)
 297        #expect(session.bufferName(a.path) == "index.org<x/blog>")
 298        #expect(session.bufferName(b.path) == "index.org<y/blog>")
 299        #expect(session.bufferName(c.path) == "other.org")
 300    }
 301
 302    @Test func openReadsSetupFiles() throws {
 303        let notes = try Folder()
 304        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 305        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
 306        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 307        session.open(file.path)
 308        #expect(session.document?.tree.settings.todoKeywordNames.contains("NEXT") == true)
 309    }
 310
 311
 312    @Test func keywordCtrlCCtrlCRereadsSetupFiles() throws {
 313        let notes = try Folder()
 314        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 315        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
 316        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 317        session.open(file.path)
 318        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == false)
 319        try notes.write("setup.org", "#+TODO: NEXT WAIT | DONE\n")
 320        let text = session.document!.text
 321        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
 322        guard case .commit(let result) = CtrlCCtrlC().run(in: context) else { Issue.record("no commit"); return }
 323        #expect(result.effects.contains(.refreshSetup))
 324        session.refreshSetup()
 325        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
 326        #expect(session.document?.isDirty == false)
 327    }
 328
 329    @Test func reloadingFromDiskReadsSetupFilesAgain() throws {
 330        let notes = try Folder()
 331        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 332        let file = try notes.write("a.org", "* WAIT One\n")
 333        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 334        session.open(file.path)
 335        try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
 336        try notes.write("setup.org", "#+TODO: WAIT | DONE\n")
 337        session.fileChanged(file.path)
 338        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
 339    }
 340
 341    @Test func missingFileReportsAnError() {
 342        let session = DocumentSession()
 343        session.open("/nonexistent/a.org")
 344        #expect(session.lastError != nil)
 345        #expect(session.document == nil)
 346    }
 347}
 348
 349@MainActor
 350struct SessionSavingTests {
 351    let notes: Folder
 352    let file: URL
 353    let recovery: FileRecoveryStore
 354    let session: DocumentSession
 355
 356    init() throws {
 357        notes = try Folder()
 358        file = try notes.write("a.org", "a\nb\nc\n")
 359        recovery = FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))
 360        session = DocumentSession(recovery: recovery)
 361        session.saveMode = .explicit
 362        session.open(file.path)
 363    }
 364
 365    /// Types `text` at `offset`, as the editor would.
 366    func type(_ text: String, at offset: Int) throws {
 367        let buffer = StateBuffer(session.document!)
 368        session.attach(buffer)
 369        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
 370        session.bufferChanged()
 371    }
 372
 373    var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
 374
 375    @Test func saveWritesAndClearsDirty() throws {
 376        try type("x", at: 0)
 377        #expect(session.isDirty)
 378        #expect(session.save())
 379        #expect(!session.isDirty)
 380        #expect(disk == "xa\nb\nc\n")
 381    }
 382
 383    @Test func automaticModeSavesAfterTheDelay() async throws {
 384        session.saveMode = .automatic
 385        session.autosaveDelay = .milliseconds(10)
 386        try type("x", at: 0)
 387        #expect(disk == "a\nb\nc\n")
 388        await session.autosave?.value
 389        #expect(disk == "xa\nb\nc\n")
 390        #expect(!session.isDirty)
 391    }
 392
 393    @Test func explicitModeWaitsForSave() throws {
 394        try type("x", at: 0)
 395        #expect(session.autosave == nil)
 396    }
 397
 398    @Test func externalChangeMergesIntoEdits() throws {
 399        try type("x", at: 0)
 400        try notes.write("a.org", "a\nb\nC\n")
 401        session.fileChanged(file.path)
 402        #expect(session.document?.text == "xa\nb\nC\n")
 403        #expect(session.conflict == nil)
 404        #expect(session.save())
 405        #expect(disk == "xa\nb\nC\n")
 406    }
 407
 408    @Test func conflictKeepMine() throws {
 409        try type("x", at: 0)
 410        try notes.write("a.org", "z\nb\nc\n")
 411        session.fileChanged(file.path)
 412        #expect(session.conflict != nil)
 413        #expect(!session.save())
 414        #expect(disk == "z\nb\nc\n")
 415        session.keepMine()
 416        #expect(session.conflict == nil)
 417        #expect(disk == "xa\nb\nc\n")
 418        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
 419        #expect(kept.contains("z\nb\nc\n"))
 420    }
 421
 422    @Test func conflictUseDiskVersion() throws {
 423        try type("x", at: 0)
 424        try notes.write("a.org", "z\nb\nc\n")
 425        #expect(!session.save())
 426        #expect(session.conflict != nil)
 427        session.useDiskVersion()
 428        #expect(session.conflict == nil)
 429        #expect(!session.isDirty)
 430        #expect(session.document?.text == "z\nb\nc\n")
 431        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
 432        #expect(kept.contains("xa\nb\nc\n"))
 433    }
 434
 435    @Test func searchSeesUnsavedHeadings() async throws {
 436        let workspace = try WorkspaceModel(directory: nil)
 437        try await workspace.addRoot(notes.url)
 438        try type("* Unsaved heading\n", at: 0)
 439        let overlay = workspace.overlay(path: session.path, document: session.document)
 440        #expect(try workspace.search("unsaved").isEmpty)
 441        #expect(try workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
 442    }
 443}
 444
 445@MainActor
 446struct KeymapLoaderTests {
 447    @Test func layersTheUserFile() throws {
 448        let folder = try Folder()
 449        let missing = KeymapLoader.load(.emacs, userFile: folder.url.appendingPathComponent("none.toml"))
 450        #expect(missing.keymap == KeymapPreset.emacs.keymap && missing.problems.isEmpty)
 451
 452        let file = try folder.write("keymap.toml", "[[bind]]\nkeys = \"C-c a\"\ncommand = \"app.palette\"\n[[bind]]\nkeys = \"Q-q\"\ncommand = \"x\"\n")
 453        let loaded = KeymapLoader.load(.emacs, userFile: file)
 454        #expect(loaded.keymap.candidates(for: KeySequence.parse("C-c a")!).first?.command == "app.palette")
 455        #expect(loaded.problems == ["line 4: bad or missing keys"])
 456
 457        let broken = try folder.write("broken.toml", "keys = \"x")
 458        #expect(KeymapLoader.load(.mac, userFile: broken).problems == ["line 1: unclosed string"])
 459    }
 460}
 461
 462@MainActor
 463struct MoveSubtreeTests {
 464    @Test func refileWithinAndAcrossFiles() async throws {
 465        let notes = try Folder()
 466        let file = try notes.write("a.org", "* one\nbody\n* two\n")
 467        let other = try notes.write("b.org", "* inbox\n")
 468        let workspace = try WorkspaceModel(directory: nil)
 469        try await workspace.addRoot(notes.url)
 470        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 471        session.saveMode = .explicit
 472        session.open(file.path)
 473        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 474        #expect(targets.map(\.label) == ["a.org", "a.org/one", "a.org/two", "b.org", "b.org/inbox"])
 475
 476        #expect(session.refile(to: targets[2]) == "Refiled to a.org/two")
 477        #expect(session.document?.text == "* two\n** one\nbody\n")
 478
 479        let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
 480        StateBufferCaret.set(session, 6)
 481        #expect(session.refile(to: inbox) == "Refiled to b.org/inbox")
 482        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 483        #expect(session.document?.text == "* two\n")
 484    }
 485
 486    @Test func copyLeavesTheSubtree() async throws {
 487        let notes = try Folder()
 488        let file = try notes.write("a.org", "* one\nbody\n* two\n")
 489        let other = try notes.write("b.org", "* inbox\n")
 490        let workspace = try WorkspaceModel(directory: nil)
 491        try await workspace.addRoot(notes.url)
 492        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 493        session.saveMode = .explicit
 494        session.open(file.path)
 495        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 496        #expect(session.refile(to: targets[2], keep: true) == "Copied to a.org/two")
 497        #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n")
 498
 499        let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
 500        StateBufferCaret.set(session, 0)
 501        #expect(session.refile(to: inbox, keep: true) == "Copied to b.org/inbox")
 502        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 503        #expect(session.document?.text == "* one\nbody\n* two\n** one\nbody\n")
 504    }
 505
 506    @Test func archiveToTheArchiveFile() throws {
 507        let notes = try Folder()
 508        let file = try notes.write("a.org", "* done\n* keep\n")
 509        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 510        session.saveMode = .explicit
 511        session.open(file.path)
 512        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 513        #expect(session.document?.text == "* keep\n")
 514        let archived = try String(contentsOf: notes.url.appendingPathComponent("a.org_archive"), encoding: .utf8)
 515        #expect(archived.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
 516    }
 517}
 518
 519@MainActor
 520struct AgendaActionTests {
 521    /// From the agenda: entries in files that aren't open move and archive on disk, and the
 522    /// current buffer stays as it was.
 523    @Test func refileAndArchiveFromAnEntry() async throws {
 524        let notes = try Folder()
 525        let file = try notes.write("a.org", "* one\nbody\n* two\n* three\n")
 526        let other = try notes.write("b.org", "* inbox\n")
 527        let shown = try notes.write("c.org", "* shown\n")
 528        let workspace = try WorkspaceModel(directory: nil)
 529        try await workspace.addRoot(notes.url)
 530        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 531        session.saveMode = .explicit
 532        session.open(shown.path)
 533
 534        let inbox = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/inbox" })
 535        #expect(session.refile(to: inbox, from: (file.path, 0)) == "Refiled to b.org/inbox")
 536        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 537        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n* three\n")
 538
 539        let text = try String(contentsOf: file, encoding: .utf8)
 540        let two = try #require(workspace.refileTargets(openPath: file.path, document: DocumentState(bytes: [UInt8](text.utf8))).first { $0.label == "a.org/two" })
 541        #expect(session.refile(to: two, from: (file.path, 6)) == "Refiled to a.org/two")
 542        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n** three\n")
 543
 544        #expect(session.archive(from: (file.path, 0), now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 545        #expect(try String(contentsOf: file, encoding: .utf8) == "")
 546        #expect(session.path == shown.path && session.document?.text == "* shown\n")
 547    }
 548
 549    @Test func locatesMovedHeadings() throws {
 550        let notes = try Folder()
 551        let file = try notes.write("a.org", "* new\n* task\n* other\n* task\n")
 552        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 553        #expect(session.locateHeading(path: file.path, line: "* task", near: 0) == 6)
 554        #expect(session.locateHeading(path: file.path, line: "* task", near: 20) == 21)
 555        #expect(session.locateHeading(path: file.path, line: "* other", near: 14) == 13)
 556        #expect(session.locateHeading(path: file.path, line: "* gone", near: 0) == nil)
 557    }
 558}
 559
 560@MainActor
 561struct MoveIntoOpenBufferTests {
 562    /// A target open with unsaved edits above its heading takes the subtree in its buffer,
 563    /// under the right heading, and the disk keeps the saved text.
 564    @Test func refileIntoAnOpenBuffer() async throws {
 565        let notes = try Folder()
 566        let file = try notes.write("a.org", "* task\nbody\n")
 567        let other = try notes.write("b.org", "* inbox\n* projects\n")
 568        let workspace = try WorkspaceModel(directory: nil)
 569        try await workspace.addRoot(notes.url)
 570        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 571        session.saveMode = .explicit
 572        session.open(other.path)
 573        let projects = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/projects" })
 574        _ = session.perform(InsertText(text: "* new\n"), path: other.path, at: 0, expect: nil)
 575        session.open(file.path)
 576        #expect(session.refile(to: projects) == "Refiled to b.org/projects")
 577        #expect(session.document?.text == "")
 578        #expect(session.openDocuments.first { $0.path == other.path }?.document.text == "* new\n* inbox\n* projects\n** task\nbody\n")
 579        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n* projects\n")
 580    }
 581
 582    @Test func archiveIntoAnOpenBuffer() throws {
 583        let notes = try Folder()
 584        let file = try notes.write("a.org", "* done\n* keep\n")
 585        let archive = try notes.write("a.org_archive", "* old\n")
 586        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 587        session.saveMode = .explicit
 588        session.open(archive.path)
 589        session.open(file.path)
 590        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 591        #expect(session.document?.text == "* keep\n")
 592        let text = try #require(session.openDocuments.first { $0.path == archive.path }?.document.text)
 593        #expect(text.hasPrefix("* old\n") && text.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
 594        #expect(try String(contentsOf: archive, encoding: .utf8) == "* old\n")
 595    }
 596}
 597
 598/// Inserts text at the caret, for tests.
 599struct InsertText: OrgCommand {
 600    let text: String
 601    var id: String { "test.insert" }
 602    var title: String { "Insert" }
 603    func applies(in context: EditContext) -> Bool { true }
 604    func run(in context: EditContext) -> CommandStep {
 605        .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: text)]))
 606    }
 607}
 608
 609/// Moves the caret of a session's `StateBuffer`, as clicking in the editor would.
 610@MainActor
 611enum StateBufferCaret {
 612    static func set(_ session: DocumentSession, _ offset: Int) {
 613        let buffer = StateBuffer(session.document!)
 614        buffer.selection = [offset..<offset]
 615        session.attach(buffer)
 616    }
 617}
 618
 619@MainActor
 620struct AgendaModelTests {
 621    @Test func openBuffersFollowTheirText() async throws {
 622        let notes = try Folder()
 623        let file = try notes.write("a.org", "* TODO One\n")
 624        let model = try WorkspaceModel(directory: nil)
 625        try await model.addRoot(notes.url)
 626        let agenda = AgendaModel(workspace: model)
 627        agenda.mode = .todo(keywords: nil)
 628        for text in ["* TODO One\n", "* TODO Two\n", "* TODO One\n", "* TODO Two\n"] {
 629            await agenda.refresh(open: [file.path: text])
 630            #expect(agenda.list.map(\.text) == [String(text.dropFirst(2).dropLast())])
 631        }
 632        await agenda.refresh(open: [:])
 633        #expect(agenda.list.map(\.text) == ["TODO One"])
 634    }
 635
 636    /// A refresh, the first and one over cached files, checks the files on disk off the main thread.
 637    @Test func checksFilesOffTheMainActor() async throws {
 638        let notes = try Folder()
 639        for file in 0..<20 { try notes.write("f\(file).org", "* TODO Item\n") }
 640        let model = try WorkspaceModel(directory: nil)
 641        try await model.addRoot(notes.url)
 642        let agenda = AgendaModel(workspace: model)
 643        agenda.mode = .todo(keywords: nil)
 644        let stats = OSAllocatedUnfairLock(initialState: (all: 0, onMain: 0))
 645        agenda.willStat = { _ in
 646            let onMain = Thread.isMainThread
 647            stats.withLock { $0 = ($0.all + 1, $0.onMain + (onMain ? 1 : 0)) }
 648        }
 649        await agenda.refresh(open: [:])
 650        await agenda.refresh(open: [:])
 651        #expect(agenda.list.count == 20)
 652        #expect(stats.withLock { $0 } == (40, 0))
 653    }
 654
 655    @Test func entriesKnowTheirDoneKeyword() async throws {
 656        let notes = try Folder()
 657        try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
 658        try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
 659        let plain = try notes.write("b.org", "* WAIT Two\n")
 660        let model = try WorkspaceModel(directory: nil)
 661        model.settings = .with(todoKeywords: try #require(OrgSettings.default.withTodoKeywords("WAIT | OK")))
 662        try await model.addRoot(notes.url)
 663        let agenda = AgendaModel(workspace: model)
 664        agenda.mode = .todo(keywords: nil)
 665        await agenda.refresh(open: [:])
 666        #expect(Dictionary(uniqueKeysWithValues: agenda.list.map { ($0.todo ?? "", $0.doneKeyword) }) == ["NEXT": "FINISHED", "WAIT": "OK"])
 667        await agenda.refresh(open: [plain.path: "#+TODO: WAIT | GONE\n* WAIT Two\n"])
 668        #expect(agenda.list.first { $0.todo == "WAIT" }?.doneKeyword == "GONE")
 669    }
 670
 671    @Test func topLevelFilesAndTheOpenBuffer() async throws {
 672        let notes = try Folder()
 673        try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")
 674        try notes.write("sub/b.org", "* Hidden <2026-10-05 Mon>\n")
 675        try notes.write("old.org_archive", "* Archived <2026-10-05 Mon>\n")
 676        let model = try WorkspaceModel(directory: nil)
 677        try await model.addRoot(notes.url)
 678        let agenda = AgendaModel(workspace: model)
 679        agenda.startOffset = -3
 680        var utc = Calendar(identifier: .gregorian)
 681        utc.timeZone = TimeZone(identifier: "UTC")!
 682        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
 683
 684        await agenda.refresh(open: [:], now: now, calendar: utc)
 685        #expect(agenda.days.count == 10)
 686        #expect(agenda.days[3].isToday)
 687        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent"])
 688
 689        agenda.includeSubfolders = true
 690        await agenda.refresh(open: [:], now: now, calendar: utc)
 691        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent", "Hidden "])
 692
 693        let path = try #require(agenda.files.first { $0.hasSuffix("/a.org") })
 694        await agenda.refresh(open: [path: "* DONE Pay rent\nSCHEDULED: <2026-10-05 Mon>\n"], now: now, calendar: utc)
 695        #expect(agenda.days[3].items.first?.text == "DONE Pay rent")
 696
 697        agenda.shift(forward: true, now: now, calendar: utc)
 698        await agenda.refresh(open: [:], now: now, calendar: utc)
 699        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 12))
 700
 701        // org-agenda-start-on-weekday: a week starts on Monday by default, from a Wednesday.
 702        let wednesday = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 7, hour: 9)))
 703        agenda.showToday()
 704        agenda.span = 7
 705        agenda.startOffset = 0
 706        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 707        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 5))
 708        agenda.startOnWeekday = 0
 709        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 710        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 4))
 711        agenda.shift(forward: true, now: wednesday, calendar: utc)
 712        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 713        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 11))
 714        agenda.showToday()
 715        agenda.startOnWeekday = nil
 716        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 717        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 7))
 718        agenda.startOnWeekday = 1
 719        agenda.span = 10
 720        await agenda.refresh(open: [:], now: wednesday, calendar: utc)
 721        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 7))
 722    }
 723
 724    @Test func leavesOutArchiveFiles() async throws {
 725        let notes = try Folder()
 726        try notes.write("todo.org", "#+ARCHIVE: todo_archive.org::* %s\n* TODO Live\nSCHEDULED: <2026-10-05 Mon>\n")
 727        try notes.write("todo_archive.org", "* DONE Old\nSCHEDULED: <2026-10-05 Mon>\n")
 728        try notes.write("work.org", "* Project\n:PROPERTIES:\n:ARCHIVE: done/work.org::\n:END:\n** TODO Task\nSCHEDULED: <2026-10-05 Mon>\n")
 729        try notes.write("self.org", "#+ARCHIVE: ::* Archived\n* TODO Mine\nSCHEDULED: <2026-10-05 Mon>\n")
 730        try notes.write("done/work.org", "* DONE Older\nSCHEDULED: <2026-10-05 Mon>\n")
 731        let model = try WorkspaceModel(directory: nil)
 732        try await model.addRoot(notes.url)
 733        let agenda = AgendaModel(workspace: model)
 734        agenda.includeSubfolders = true
 735        agenda.span = 1
 736        var utc = Calendar(identifier: .gregorian)
 737        utc.timeZone = TimeZone(identifier: "UTC")!
 738        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
 739
 740        agenda.excludeArchives = false
 741        await agenda.refresh(open: [:], now: now, calendar: utc)
 742        #expect(Set(agenda.days[0].items.map(\.text)) == ["TODO Live", "DONE Old", "TODO Task", "TODO Mine", "DONE Older"])
 743        agenda.excludeArchives = true
 744        await agenda.refresh(open: [:], now: now, calendar: utc)
 745        #expect(Set(agenda.days[0].items.map(\.text)) == ["TODO Live", "TODO Task", "TODO Mine"])
 746    }
 747
 748    @Test func leavesOutHiddenFoldersAndTagsReminders() async throws {
 749        let work = try Folder()
 750        let home = try Folder()
 751        try work.write("work.org", "* TODO Report\nSCHEDULED: <2026-10-05 Mon 14:00>\n")
 752        try home.write("home.org", "* TODO Groceries\nSCHEDULED: <2026-10-05 Mon 15:00>\n")
 753        let model = try WorkspaceModel(directory: nil)
 754        try await model.addRoot(work.url)
 755        try await model.addRoot(home.url)
 756        let workRoot = try #require(model.files.first { $0.name == "work.org" }?.root)
 757        let agenda = AgendaModel(workspace: model)
 758        agenda.span = 1
 759        var utc = Calendar(identifier: .gregorian)
 760        utc.timeZone = TimeZone(identifier: "UTC")!
 761        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
 762
 763        agenda.hiddenFolders = [workRoot]
 764        await agenda.refresh(open: [:], now: now, calendar: utc)
 765        #expect(agenda.days[0].items.filter { $0.path != nil }.map(\.title) == ["Groceries"])
 766
 767        // Reminders keep hidden folders' entries and carry their folder for Focus filters.
 768        let reminders = await AgendaModel(workspace: model).reminders(open: [:], now: now, calendar: utc)
 769        #expect(Set(reminders.map(\.title)) == ["Report", "Groceries"])
 770        #expect(reminders.first { $0.title == "Report" }?.folder == workRoot)
 771    }
 772
 773    @Test func hiddenFoldersPersistAndMatchPaths() {
 774        let defaults = TestDefaults("hidden")
 775        let folders = HiddenFolders(defaults: defaults)
 776        folders.manual = ["/a"]
 777        folders.focus = ["/b"]
 778        let reloaded = HiddenFolders(defaults: defaults)
 779        #expect(reloaded.all == ["/a", "/b"])
 780        #expect(HiddenFolders.hides(["/a"], path: "/a/x.org"))
 781        #expect(!HiddenFolders.hides(["/a"], path: "/ab/x.org"))
 782        let predicate = HiddenFolders.notificationPredicate(hiding: ["/a"])
 783        #expect(!predicate.evaluate(with: "/a"))
 784        #expect(predicate.evaluate(with: "/b"))
 785    }
 786}
 787
 788@MainActor
 789struct AgendaCommandTests {
 790    @Test func loadsViews() throws {
 791        let folder = try Folder()
 792        let file = try folder.write("views.toml", """
 793        [[view]]
 794        name = "Work"
 795        type = "match"
 796        match = "+work"
 797        [[view]]
 798        name = "Week"
 799        span = 7
 800        start = -1
 801        [[view]]
 802        name = "Waiting"
 803        type = "todo"
 804        keywords = "WAIT|HOLD"
 805        [[view]]
 806        name = "Broken"
 807        type = "match"
 808        """)
 809        let loaded = AgendaViewLoader.load(userFile: file)
 810        #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Stuck Projects", "Work", "Week", "Waiting"])
 811        #expect(loaded.views[3].mode == .match("+work", todoOnly: false))
 812        #expect(loaded.views[4].mode == .agenda(span: 7, startOffset: -1))
 813        #expect(loaded.views[5].mode == .todo(keywords: "WAIT|HOLD"))
 814        #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
 815    }
 816
 817    @Test func viewsSortAndPrefixThemselves() async throws {
 818        let notes = try Folder()
 819        try notes.write("a.org", "* TODO b\n:PROPERTIES:\n:Effort: 0:30\n:END:\n* TODO [#A] c\n* TODO a\n")
 820        let file = try notes.write("views.toml", """
 821        [[view]]
 822        name = "Alphabetical"
 823        type = "todo"
 824        sorting-strategy = "alpha-up bogus"
 825        prefix-format = "%e"
 826        """)
 827        let loaded = AgendaViewLoader.load(userFile: file)
 828        #expect(loaded.problems == ["views.toml line 1: unknown sorting key bogus"])
 829        #expect(loaded.views[3].settings == AgendaViewSettings(prefixFormat: "%e", sortingStrategy: ["alpha-up"]))
 830        let model = try WorkspaceModel(directory: nil)
 831        try await model.addRoot(notes.url)
 832        let agenda = AgendaModel(workspace: model)
 833        agenda.viewSettings = AgendaViewLoader.settings(loaded.views)
 834        agenda.mode = .todo(keywords: nil)
 835        await agenda.refresh(open: [:])
 836        // `alpha-up` keeps the priority cookie, as Org does.
 837        #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO a", "TODO b"])
 838        #expect(agenda.list.map(\.prefixDetail) == [nil, nil, "0:30"])
 839        agenda.mode = .todo(keywords: "TODO")
 840        await agenda.refresh(open: [:])
 841        #expect(agenda.list.map(\.text) == ["TODO [#A] c", "TODO b", "TODO a"])
 842    }
 843
 844    @Test func stuckProjectViews() async throws {
 845        let notes = try Folder()
 846        try notes.write("a.org", "* Projects\n** Website\n*** TODO Draft\n** Garden\n*** WAIT Seeds\n")
 847        let file = try notes.write("views.toml", """
 848        [[view]]
 849        name = "Stuck"
 850        type = "stuck"
 851        [[view]]
 852        name = "Waiting counts"
 853        type = "stuck"
 854        keywords = "TODO WAIT"
 855        """)
 856        let loaded = AgendaViewLoader.load(userFile: file)
 857        #expect(loaded.problems.isEmpty)
 858        #expect(loaded.views[3].mode == .stuck(nil))
 859        guard case .stuck(let definition?) = loaded.views[4].mode else { Issue.record("no definition"); return }
 860        #expect(definition.todo == ["TODO", "WAIT"] && definition.match == "+LEVEL=2/-DONE")
 861        let model = try WorkspaceModel(directory: nil)
 862        try await model.addRoot(notes.url)
 863        let agenda = AgendaModel(workspace: model)
 864        agenda.mode = loaded.views[3].mode
 865        await agenda.refresh(open: [:])
 866        #expect(agenda.list.map(\.text) == ["Garden"])
 867        agenda.mode = loaded.views[4].mode
 868        await agenda.refresh(open: [:])
 869        #expect(agenda.list.isEmpty)
 870    }
 871
 872    @Test func blockViews() async throws {
 873        let notes = try Folder()
 874        let today = Days.date(Days.absolute(Date(), calendar: .current))
 875        let stamp = String(format: "%04d-%02d-%02d", today.year, today.month, today.day)
 876        try notes.write("a.org", "#+TODO: TODO NEXT WAIT | DONE\n* TODO Call\nSCHEDULED: <\(stamp)>\n* NEXT Write\n* WAIT Hear back\n* TODO Later :someday:\n")
 877        let file = try notes.write("views.toml", """
 878        [[view]]
 879        name = "Daily"
 880        span = 1
 881        sorting-strategy = "alpha-up"
 882        [[view.block]]
 883        type = "agenda"
 884        header = "Today"
 885        [[view.block]]
 886        type = "todo"
 887        skip-entry-if = "'scheduled 'regexp \\"someday\\""
 888        [[view.block]]
 889        type = "match"
 890        match = "TODO=\\"WAIT\\""
 891        [[view]]
 892        name = "Broken skip"
 893        type = "todo"
 894        skip-entry-if = "'level 2"
 895        """)
 896        let loaded = AgendaViewLoader.load(userFile: file)
 897        #expect(loaded.problems == ["views.toml line 14: skip-entry-if: level isn't supported"])
 898        guard case .blocks(let blocks) = loaded.views.last!.mode else { Issue.record("no blocks"); return }
 899        #expect(blocks.map(\.mode) == [.agenda(span: 1, startOffset: nil), .todo(keywords: nil), .match("TODO=\"WAIT\"", todoOnly: false)])
 900        #expect(blocks.map(\.settings.header) == ["Today", nil, nil])
 901        #expect(blocks.allSatisfy { $0.settings.sortingStrategy == ["alpha-up"] })
 902        #expect(blocks[1].settings.skip == AgendaSkip(subtree: false, conditions: [.scheduled, .regexp("someday")]))
 903        let model = try WorkspaceModel(directory: nil)
 904        try await model.addRoot(notes.url)
 905        let agenda = AgendaModel(workspace: model)
 906        agenda.mode = loaded.views.last!.mode
 907        await agenda.refresh(open: [:])
 908        #expect(agenda.blocks.map(\.header) == ["Today", "TODO items: all", "Entries matching TODO=\"WAIT\""])
 909        #expect(agenda.blocks[0].days.count == 1 && agenda.blocks[0].days[0].items.contains { $0.text == "TODO Call" })
 910        #expect(agenda.blocks[1].list.map(\.text) == ["WAIT Hear back", "NEXT Write"])
 911        #expect(agenda.blocks[2].list.map(\.text) == ["WAIT Hear back"])
 912        #expect(agenda.list.isEmpty && agenda.days.isEmpty)
 913    }
 914
 915    @Test func agendaFilesList() async throws {
 916        let notes = try Folder()
 917        try notes.write("a.org", "* TODO A\n")
 918        try notes.write("b.org", "* TODO B\n")
 919        try notes.write(".hidden.org", "* TODO Hidden\n")
 920        try notes.write("sub/c.org", "* TODO C\n")
 921        try notes.write("sub/d.org", "* TODO D\n")
 922        try notes.write("sub/notes.txt", "x\n")
 923        try notes.write("list", "sub/d.org\n\n  b.org\nmissing.org\nsub/notes.txt\n")
 924        let root = notes.url.path
 925        #expect(AgendaFiles.resolve(["sub"], base: root) == ["\(root)/sub/c.org", "\(root)/sub/d.org"])
 926        #expect(AgendaFiles.resolve([root, "sub/c.org"], base: nil) == ["\(root)/a.org", "\(root)/b.org"])
 927        #expect(AgendaFiles.resolve(["list", "a.org"], base: root) == ["\(root)/sub/d.org", "\(root)/b.org", "\(root)/sub/notes.txt", "\(root)/a.org"])
 928        let model = try WorkspaceModel(directory: nil)
 929        try await model.addRoot(notes.url)
 930        let agenda = AgendaModel(workspace: model)
 931        agenda.agendaFiles = ["sub/c.org", "b.org"]
 932        agenda.mode = .todo(keywords: nil)
 933        await agenda.refresh(open: [:])
 934        #expect(agenda.list.map(\.text) == ["TODO C", "TODO B"])
 935    }
 936
 937    @Test func todoListMode() async throws {
 938        let notes = try Folder()
 939        try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
 940        let model = try WorkspaceModel(directory: nil)
 941        try await model.addRoot(notes.url)
 942        let agenda = AgendaModel(workspace: model)
 943        agenda.mode = .todo(keywords: nil)
 944        await agenda.refresh(open: [:])
 945        #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
 946        agenda.mode = .match("work", todoOnly: false)
 947        await agenda.refresh(open: [:])
 948        #expect(agenda.list.map(\.text) == ["TODO One"])
 949    }
 950
 951    @Test func runsCommandsOnClosedAndOpenFiles() throws {
 952        let notes = try Folder()
 953        let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
 954        let b = try notes.write("b.org", "* TODO Three\n")
 955        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 956        session.open(a.path)
 957
 958        // A closed file is changed on disk.
 959        let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
 960        guard case .commit = closed else { Issue.record("\(closed)"); return }
 961        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
 962
 963        // The open file changes in its buffer.
 964        let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
 965        guard case .commit = open else { Issue.record("\(open)"); return }
 966        #expect(session.document?.text == "* TODO One\n* DONE Two\n")
 967
 968        // A heading that moved is refused.
 969        let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
 970        guard case .failed = stale else { Issue.record("\(stale)"); return }
 971        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
 972    }
 973}
 974
 975final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
 976    private let lock = NSLock()
 977    private var pending: [String] = ["someone.else"]
 978    var authorized = true
 979    private(set) var added: [String] = []
 980
 981    func authorize() async -> Bool { authorized }
 982    func pendingIDs() async -> [String] { lock.withLock { pending } }
 983    var delivered: [String] = []
 984    func deliveredIDs() async -> [String] { lock.withLock { delivered } }
 985    /// The system showing a notification: no longer pending.
 986    func fire(_ id: String, keep: Bool) {
 987        lock.withLock {
 988            pending.removeAll { $0 == id }
 989            if keep { delivered.append(id) }
 990        }
 991    }
 992    func add(_ reminder: Reminder) async throws {
 993        lock.withLock {
 994            pending.append(reminder.id)
 995            added.append(reminder.id)
 996        }
 997    }
 998    func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
 999    var ids: [String] { lock.withLock { pending } }
1000}
1001
1002@MainActor
1003struct ReminderSchedulerTests {
1004    func reminder(_ id: String, _ minutes: Double) -> Reminder {
1005        let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
1006        return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
1007    }
1008
1009    @Test func reconciles() async {
1010        let center = FakeReminderCenter()
1011        let scheduler = ReminderScheduler(center: center)
1012        await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
1013        #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
1014        #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
1015
1016        await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
1017        #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
1018        #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
1019
1020        await scheduler.clear()
1021        #expect(center.ids == ["someone.else"])
1022        #expect(scheduler.scheduledThrough == nil)
1023
1024        // Fired reminders aren't set again, whether or not they're still in Notification Center.
1025        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
1026        center.fire("orgstar.e", keep: false)
1027        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
1028        #expect(center.added.filter { $0 == "orgstar.e" }.count == 1)
1029        let relaunched = ReminderScheduler(center: center)
1030        center.fire("orgstar.f", keep: true)
1031        await relaunched.reconcile([reminder("f", 6)])
1032        #expect(center.added.filter { $0 == "orgstar.f" }.count == 1)
1033        await scheduler.clear()
1034
1035        center.authorized = false
1036        await scheduler.reconcile([reminder("d", 4)])
1037        #expect(!scheduler.isAuthorized)
1038        #expect(center.ids == ["someone.else"])
1039    }
1040}
1041
1042/// Without `DocumentSession.programs`, only Emacs Lisp and js run, natively.
1043@MainActor
1044struct NativeProgramsTests {
1045    @Test func runsOnlyNativeBlocksWithoutARunner() async throws {
1046        #expect(DocumentSession.runner == nil)
1047        let notes = try Folder()
1048        let file = try notes.write("b.org", "#+begin_src sh\necho hi\n#+end_src\n\n#+begin_src emacs-lisp\n(+ 1 2)\n#+end_src\n\n#+begin_src js\nreturn 2 + 3\n#+end_src\n")
1049        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1050        session.open(file.path)
1051        guard case .external(.babel(let sh)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil),
1052              case .external(.babel(let lisp)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 40, expect: nil),
1053              case .external(.babel(let js)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 78, expect: nil) else {
1054            Issue.record("not planned")
1055            return
1056        }
1057        #if os(macOS)
1058        #expect(await session.runBabel(sh) == "sh blocks don't run in this version of orgstar.")
1059        #expect(await session.recalculateInEmacs(table: 0..<1, point: 0, form: "") == "Tables that need Emacs aren't recalculated in this version of orgstar.")
1060        #endif
1061        #expect(await session.runBabel(lisp) == "Code block evaluation complete.")
1062        #expect(session.document?.text.contains("#+RESULTS:\n: 3\n") == true)
1063        #expect(await session.runBabel(js) == "Code block evaluation complete.")
1064        #expect(session.document?.text.hasSuffix("#+RESULTS:\n: 5\n") == true)
1065    }
1066
1067    /// A block whose `:post` or noweb reference runs a block that needs a program runs nothing;
1068    /// with blocks that run in-process, the reference's value is the result.
1069    @Test func refusesReferencesToBlocksThatNeedARunner() async throws {
1070        #expect(DocumentSession.runner == nil)
1071        let notes = try Folder()
1072        let helpers = "#+NAME: sh\n#+begin_src sh :var x=\"\"\necho hi\n#+end_src\n\n#+NAME: double\n#+begin_src emacs-lisp :var n=0\n(* 2 n)\n#+end_src\n\n"
1073        let blocks = [
1074            "#+begin_src emacs-lisp :post sh(x=*this*)\n(error \"ran\")\n#+end_src\n",
1075            "#+begin_src emacs-lisp :noweb yes\n(concat \"<<sh()>>\")\n#+end_src\n",
1076            "#+begin_src emacs-lisp :var v=double(n=1) :post sh(x=*this*)\n(error \"ran\")\n#+end_src\n",
1077            "#+begin_src js :post double(n=*this*)\nreturn 2 + 3\n#+end_src\n",
1078            "#+begin_src emacs-lisp :noweb yes\n(+ 1 <<double(n=4)>>)\n#+end_src\n",
1079        ]
1080        var messages: [String] = []
1081        var texts: [String] = []
1082        for block in blocks {
1083            let file = try notes.write("p\(messages.count).org", helpers + block)
1084            let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1085            session.open(file.path)
1086            guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: helpers.utf16.count + 3, expect: nil) else {
1087                Issue.record("not planned: \(block)")
1088                return
1089            }
1090            messages.append(await session.runBabel(job))
1091            texts.append(String((session.document?.text ?? "").dropFirst(helpers.count + block.count)))
1092        }
1093        #if os(macOS)
1094        let refusal = "This block needs a sh block, and sh blocks don't run in this version of orgstar; nothing was run."
1095        #else
1096        let refusal = "This block needs a sh block, and sh blocks need the Mac to run; nothing was run."
1097        #endif
1098        #expect(messages == [refusal, refusal, refusal, "Code block evaluation complete.", "Code block evaluation complete."])
1099        #expect(texts == ["", "", "", "\n#+RESULTS:\n: 10\n", "\n#+RESULTS:\n: 9\n"])
1100    }
1101}
1102
1103@MainActor
1104struct CaptureAppTests {
1105    @Test func loadsTemplates() throws {
1106        let folder = try Folder()
1107        let file = try folder.write("capture.toml", """
1108        [[template]]
1109        key = "w"
1110        name = "Work"
1111        file = "work.org"
1112        olp = "Projects/Work"
1113        template = "* TODO %?\\n%a"
1114        [[template]]
1115        key = "j"
1116        type = "plain"
1117        file = "~/journal.org"
1118        template = "%U %?"
1119        prepend = true
1120        """)
1121        let loaded = CaptureTemplates.load(userFile: file)
1122        #expect(loaded.problems.isEmpty)
1123        #expect(loaded.templates.map(\.key) == ["w", "j"])
1124        #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
1125        #expect(loaded.templates[0].template == "* TODO %?\n%a")
1126        #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
1127        try """
1128        [[template]]
1129        key = "d"
1130        file = "journal.org"
1131        datetree = true
1132        olp = "Journal"
1133        tree-type = "month"
1134        template = "* %?"
1135        empty-lines-after = 1
1136        jump-to-captured = true
1137        [[template]]
1138        key = "i"
1139        id = "abc"
1140        template = "* %?"
1141        clock-in = true
1142        clock-resume = true
1143        [[template]]
1144        key = "k"
1145        clock = true
1146        type = "item"
1147        template = "%?"
1148        immediate-finish = true
1149        """.write(to: file, atomically: true, encoding: .utf8)
1150        let targets = CaptureTemplates.load(userFile: file)
1151        #expect(targets.problems.isEmpty)
1152        #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
1153        #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
1154        #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
1155        #expect(targets.templates[2].options.immediateFinish)
1156        #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
1157    }
1158
1159    @Test func loadsGroupsRegexpsAndTreeTypes() throws {
1160        let folder = try Folder()
1161        let file = try folder.write("capture.toml", """
1162        [[template]]
1163        key = "t"
1164        name = "Todo"
1165        file = "todo.org"
1166        template = "* TODO %?"
1167        [[template]]
1168        key = "w"
1169        name = "Work"
1170        [[template]]
1171        key = "wm"
1172        name = "Meeting"
1173        file = "work.org"
1174        regexp = "^\\\\* Meetings"
1175        template = "* %?"
1176        [[template]]
1177        key = "wq"
1178        name = "Quarter"
1179        file = "work.org"
1180        datetree = true
1181        tree-type = "year quarter"
1182        time-prompt = true
1183        template = "* %?"
1184        [[template]]
1185        key = "xy"
1186        name = "Ungrouped"
1187        file = "x.org"
1188        template = "* %?"
1189        """)
1190        let loaded = CaptureTemplates.load(userFile: file)
1191        #expect(loaded.problems.isEmpty, "\(loaded.problems)")
1192        #expect(loaded.groups == [CaptureGroup(key: "w", name: "Work")])
1193        #expect(loaded.templates.map(\.key) == ["t", "wm", "wq", "xy"])
1194        #expect(loaded.templates[1].target == .regexp(file: "work.org", regexp: "^\\* Meetings"))
1195        #expect(loaded.templates[2].target == .datetree(file: "work.org", path: [], tree: CaptureTemplate.TreeType(groups: [.year, .quarter])))
1196        #expect(loaded.templates[2].asksTreeDate && !loaded.templates[0].asksTreeDate)
1197        #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "").map(\.key) == ["t", "w", "xy"])
1198        #expect(CaptureTemplates.menu(loaded.templates, groups: loaded.groups, typed: "w").map(\.key) == ["wm", "wq"])
1199        #expect(CaptureTemplates.label(loaded.templates[1], groups: loaded.groups) == "Work › Meeting")
1200        try "[[template]]\nkey = \"d\"\nfile = \"j.org\"\ndatetree = true\ntree-type = \"year fortnight\"\ntemplate = \"* %?\"\n".write(to: file, atomically: true, encoding: .utf8)
1201        #expect(CaptureTemplates.load(userFile: file).problems.count == 1)
1202    }
1203
1204    @Test func treeDateFollowsOrgCapture() {
1205        var calendar = Calendar(identifier: .gregorian)
1206        calendar.timeZone = TimeZone(identifier: "UTC")!
1207        let now = calendar.date(from: DateComponents(year: 2026, month: 10, day: 11, hour: 7, minute: 6, second: 27))!
1208        func text(_ date: Date) -> String {
1209            let c = calendar.dateComponents([.year, .month, .day, .hour, .minute], from: date)
1210            return String(format: "%04d-%02d-%02d %02d:%02d", c.year!, c.month!, c.day!, c.hour!, c.minute!)
1211        }
1212        #expect(text(Capture.treeDate("", now: now, calendar: calendar)) == "2026-10-11 07:06")
1213        #expect(text(Capture.treeDate("fri", now: now, calendar: calendar)) == "2026-10-16 00:00")
1214        #expect(text(Capture.treeDate("fri 14:00", now: now, calendar: calendar)) == "2026-10-16 14:00")
1215    }
1216
1217    @Test func capturesIntoClosedMissingAndOpenFiles() throws {
1218        let notes = try Folder()
1219        let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
1220        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1221        let template = CaptureTemplates.defaults[0]
1222        let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
1223        #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
1224        #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
1225
1226        _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
1227        #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
1228
1229        session.open(todo.path)
1230        _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
1231        #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
1232
1233        // An ID's file is resolved by the caller.
1234        let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
1235        let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
1236        _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
1237        #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
1238    }
1239}
1240
1241@MainActor
1242struct ClockModelTests {
1243    /// A clock started in Emacs becomes the running one; stopped there, it ends here.
1244    @Test func followsClocksStartedElsewhere() throws {
1245        let notes = try Folder()
1246        let work = try notes.write("work.org", "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 09:00]\n:END:\n* Older\nCLOCK: [2026-10-04 Sun 09:00]\n")
1247        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1248        let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"))
1249        #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Task\" since [2026-10-05 Mon 09:00]")
1250        #expect(clock.running?.path == work.path && clock.running?.start == "2026-10-05 Mon 09:00")
1251        #expect(clock.history.first?.title == "Task")
1252        #expect(clock.sync(session, paths: [work.path]) == nil)
1253        // Emacs clocks out.
1254        try "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 09:00]--[2026-10-05 Mon 10:00] =>  1:00\n:END:\n* Older\nCLOCK: [2026-10-04 Sun 09:00]\n"
1255            .write(to: work, atomically: true, encoding: .utf8)
1256        #expect(clock.sync(session, paths: [work.path]) == "The clock in \"Task\" was stopped elsewhere")
1257        #expect(clock.running == nil)
1258        // The dangling one stays for resolution; a clock Emacs starts later runs.
1259        #expect(clock.sync(session, paths: [work.path]) == nil)
1260        try "* Task\n:LOGBOOK:\nCLOCK: [2026-10-05 Mon 11:00]\nCLOCK: [2026-10-05 Mon 09:00]--[2026-10-05 Mon 10:00] =>  1:00\n:END:\n* Older\nCLOCK: [2026-10-04 Sun 09:00]\n"
1261            .write(to: work, atomically: true, encoding: .utf8)
1262        #expect(clock.sync(session, paths: [work.path]) == "Clock running in \"Task\" since [2026-10-05 Mon 11:00]")
1263        // Another file's change says nothing about the running clock.
1264        #expect(clock.sync(session, paths: [notes.url.appendingPathComponent("other.org").path]) == nil)
1265        #expect(clock.running?.start == "2026-10-05 Mon 11:00")
1266    }
1267
1268    @Test func clocksInAndOutAcrossFiles() throws {
1269        let notes = try Folder()
1270        let work = try notes.write("work.org", "* Task\nBody\n")
1271        let other = try notes.write("other.org", "* Other\n")
1272        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1273        session.open(work.path)
1274        session.reveal(2)
1275        let stateFile = notes.url.appendingPathComponent("clock.json")
1276        let clock = ClockModel(file: stateFile)
1277        var utc = Calendar(identifier: .gregorian)
1278        utc.timeZone = TimeZone(identifier: "UTC")!
1279        let start = Date(timeIntervalSince1970: 1_789_000_000)
1280        _ = clock.clockIn(session, now: start)
1281        #expect(clock.running?.heading == "Task")
1282        #expect(ClockModel(file: stateFile).running == clock.running)
1283
1284        // Out from another file: the clocked file's buffer is still open behind it and takes
1285        // the change.
1286        session.open(other.path)
1287        let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
1288        #expect(message == "Clock stopped after 1:35")
1289        #expect(clock.running == nil)
1290        #expect(session.dirtyPaths == [work.path])
1291        #expect(session.saveAll())
1292        let text = try String(contentsOf: work, encoding: .utf8)
1293        #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=>  1:35\n:END:\nBody\n"), "\(text)")
1294    }
1295
1296    /// `org-clock-out-when-done`, through the session's text-changed hook, and the Effort
1297    /// notification.
1298    @Test func clocksOutWhenDoneAndRemindsAtEffort() async throws {
1299        let notes = try Folder()
1300        let work = try notes.write("work.org", "* TODO Task\n:PROPERTIES:\n:Effort:   1:00\n:END:\n:LOGBOOK:\nCLOCK: [2026-09-01 Tue 09:00]--[2026-09-01 Tue 09:20] =>  0:20\n:END:\n** Sub\n:LOGBOOK:\nCLOCK: [2026-09-02 Wed 09:00]--[2026-09-02 Wed 09:10] =>  0:10\n:END:\n")
1301        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1302        let defaults = TestDefaults("orgstar-clock-done")
1303        let clock = ClockModel(file: notes.url.appendingPathComponent("clock.json"), defaults: defaults)
1304        let center = FakeReminderCenter()
1305        clock.notifications = center
1306        var messages: [String] = []
1307        session.textChanged = { path in if let message = clock.textChanged(path, session) { messages.append(message) } }
1308        let start = Date(timeIntervalSince1970: 1_789_000_000)
1309        _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1310        #expect(clock.running != nil)
1311        // An hour of effort, half an hour clocked in the subtree before.
1312        #expect(clock.effort(session, now: start).map { [$0.effort, $0.clocked] } == [60, 30])
1313        for _ in 0..<200 where center.added.isEmpty { try await Task.sleep(for: .milliseconds(10)) }
1314        #expect(center.added == ["orgstar-effort"])
1315        // Marking it done from an unopened file's command clocks out.
1316        _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1317        #expect(clock.running == nil && messages.count == 1)
1318        let text = try String(contentsOf: work, encoding: .utf8)
1319        #expect(!text.contains(#/CLOCK: \[[^\]]+\]\n/#), "\(text)")
1320
1321        // nil keeps it running.
1322        UserConfig.apply("org-clock-out-when-done = \"nil\"\n", to: defaults)
1323        _ = session.perform(SetTodo(keyword: "TODO"), path: work.path, at: 2, expect: nil)
1324        _ = clock.clockIn(session, path: work.path, at: 2, now: start)
1325        _ = session.perform(SetTodo(keyword: "DONE"), path: work.path, at: 2, expect: nil)
1326        #expect(clock.running != nil)
1327    }
1328}
1329
1330@MainActor
1331struct BufferTests {
1332    @Test func buffersKeepEditsWhileOthersShow() throws {
1333        let notes = try Folder()
1334        let a = try notes.write("a.org", "* A\n")
1335        let b = try notes.write("b.org", "* B\n")
1336        let c = try notes.write("c.org", "* C\n")
1337        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1338        session.saveMode = .explicit
1339        session.open(a.path)
1340        _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
1341        session.open(b.path)
1342        #expect(session.path == b.path)
1343        #expect(session.openPaths == [a.path, b.path])
1344        #expect(session.dirtyPaths == [a.path])
1345        // A background buffer takes commands for its file, not the disk.
1346        _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
1347        #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
1348        #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
1349
1350        session.open(a.path)
1351        #expect(session.document?.text.hasPrefix("* DONE A") == true)
1352        session.open(c.path)
1353        // Opened after the current buffer.
1354        #expect(session.openPaths == [a.path, c.path, b.path])
1355        session.cycle(1)
1356        #expect(session.path == b.path)
1357        session.cycle(1)
1358        #expect(session.path == a.path)
1359        session.showPrevious()
1360        #expect(session.path == b.path)
1361        #expect(session.recentPaths == [b.path, a.path, c.path])
1362
1363        session.kill(b.path)
1364        #expect(session.path == a.path)
1365        #expect(session.openPaths == [a.path, c.path])
1366        #expect(session.saveAll())
1367        #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
1368        session.kill(a.path)
1369        session.kill(c.path)
1370        #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
1371    }
1372
1373    @Test func backgroundBuffersFollowTheDisk() throws {
1374        let notes = try Folder()
1375        let a = try notes.write("a.org", "* A\n")
1376        let b = try notes.write("b.org", "* B\n")
1377        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1378        session.open(a.path)
1379        session.open(b.path)
1380        try notes.write("a.org", "* A changed\n")
1381        session.fileChanged(a.path)
1382        #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
1383    }
1384}
1385
1386@MainActor
1387struct LinkFollowTests {
1388    @Test func followsLinksOfEachKind() async throws {
1389        let notes = try Folder()
1390        let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
1391        let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
1392        _ = try notes.write("pic.png", "not really")
1393        let workspace = try WorkspaceModel(directory: nil)
1394        try await workspace.addRoot(notes.url)
1395        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1396        session.open(a.path)
1397        let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
1398        func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1399
1400        #expect(follow("here") == .shown)
1401        #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
1402        #expect(follow("#two") == .shown)
1403        #expect(follow("Second") == .shown)
1404        #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
1405
1406        #expect(follow("file:sub/b.org::5") == .shown)
1407        #expect(session.path == b.path)
1408        #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
1409        session.open(a.path)
1410        #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
1411        session.open(a.path)
1412        #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
1413        #expect(follow("id:none") == .message("No heading has the ID none"))
1414        // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
1415        #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
1416        #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
1417        #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
1418        #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
1419        #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links"))
1420        #expect(follow("elisp:(+ 1 2)") == .elisp("(+ 1 2)"))
1421        #expect(follow("elisp:org-agenda") == .message("orgstar doesn't run Emacs commands from elisp: links"))
1422        // Without a runner, in orgstar's interpreter.
1423        #expect(await session.evaluateLink("(+ 1 2)") == "(+ 1 2) => 3")
1424    }
1425
1426    @Test func followsDenoteLinks() async throws {
1427        let notes = try Folder()
1428        let a = try notes.write("a.org", "* Start\n")
1429        let note = try notes.write("sub/20261119T120000--a-note__kw.org", "#+title: A note\n* Inside\n:PROPERTIES:\n:CUSTOM_ID: in\n:END:\n")
1430        let pdf = try notes.write("20261119T120000--a-note.pdf", "pdf")
1431        let workspace = try WorkspaceModel(directory: nil)
1432        try await workspace.addRoot(notes.url)
1433        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1434        session.open(a.path)
1435        func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1436
1437        #expect(follow("denote:20261119T120000") == .shown && session.path == note.path)
1438        session.open(a.path)
1439        #expect(follow("denote:20261119T120000::#in") == .shown && session.path == note.path)
1440        #expect(session.revealRequest?.offset == (try String(contentsOfFile: note.path, encoding: .utf8) as NSString).range(of: "* Inside").location)
1441        #expect(follow("denote:20200101T000000") == .message("No file has the Denote identifier 20200101T000000"))
1442        // Query links: the notes whose text or name the regexp matches.
1443        #expect(follow("denote:query-contents:INSIDE") == .choose(prompt: "Notes matching INSIDE: ", paths: [note.path]))
1444        #expect(follow("denote:query-filenames:a-no+te") == .choose(prompt: "Notes matching a-no+te: ", paths: [pdf.path, note.path].sorted()))
1445        #expect(follow("denote:query-contents:Start") == .message("No notes match Start"))
1446    }
1447
1448    @Test func followsAttachmentAndRadioLinks() throws {
1449        let notes = try Folder()
1450        let text = "* Task\n:PROPERTIES:\n:ID: ab12-cd\n:END:\nSee [[attachment:scan.pdf]] and <<<the plan>>>.\n* Later\nAs in The Plan.\n"
1451        let a = try notes.write("a.org", text)
1452        let scan = try notes.write("data/ab/12-cd/scan.pdf", "pdf")
1453        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1454        session.open(a.path)
1455        let tree = try #require(session.document?.tree)
1456        func follow(_ needle: String) throws -> LinkFollow {
1457            let link = try #require(Links.link(at: (text as NSString).range(of: needle).location + 1, text: text, tree: tree)?.link)
1458            return session.follow(link, workspace: nil, isText: { $0.hasSuffix(".org") })
1459        }
1460        #expect(try follow("attachment:") == .openExternally(URL(fileURLWithPath: (scan.path as NSString).standardizingPath)))
1461        #expect(try follow("The Plan") == .shown)
1462        #expect(session.revealRequest?.offset == (text as NSString).range(of: "<<<the plan>>>").location)
1463    }
1464}
1465
1466struct ICalendarFilesTests {
1467    @Test func writesBesideEachFileAndCombined() throws {
1468        let folder = try Folder()
1469        let a = try folder.write("a.org", "#+EXPORT_FILE_NAME: out/cal\n* Meeting <2026-10-12 Mon 10:00>\n")
1470        let b = try folder.write("b.org", "* TODO Task\nDEADLINE: <2026-10-20 Tue>\n")
1471        var options = ICalendarOptions()
1472        options.includeTodo = .unfinished
1473        let read = { (path: String) -> (text: String, settings: OrgSettings)? in (try? String(contentsOfFile: path, encoding: .utf8)).map { ($0, OrgSettings.default) } }
1474        let written = try ICalendarFiles.exportEach([a.path, b.path], options: options, read: read)
1475        #expect(written.map(\.lastPathComponent) == ["cal.ics", "b.ics"])
1476        #expect(written[0].deletingLastPathComponent().lastPathComponent == "out")
1477        let first = try String(contentsOf: written[0], encoding: .utf8)
1478        #expect(first.hasPrefix("BEGIN:VCALENDAR\r\n") && first.contains("SUMMARY:Meeting <2026-10-12 Mon 10:00>\r\n"))
1479        let combined = folder.url.appendingPathComponent("all/org.ics").path
1480        let url = try ICalendarFiles.combine([a.path, b.path], to: combined, options: options, read: read)
1481        let text = try String(contentsOf: url, encoding: .utf8)
1482        #expect(text.contains("X-WR-CALNAME:OrgMode\r\n") && text.contains("BEGIN:VTODO\r\n") && text.contains("DUE;VALUE=DATE:20261020\r\n"))
1483    }
1484
1485    @Test func readsSettings() {
1486        let defaults = TestDefaults("orgstar-ics")
1487        #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .none)
1488        #expect(OrgPreferences.icalendarOptions(defaults).useDeadline == ["event-if-not-todo", "todo-due"])
1489        defaults.set("NEXT WAIT", forKey: "icalendarIncludeTodo")
1490        defaults.set("event-if-todo", forKey: "icalendarUseScheduled")
1491        #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .keywords(["NEXT", "WAIT"]))
1492        #expect(OrgPreferences.icalendarOptions(defaults).useScheduled == ["event-if-todo"])
1493        defaults.set("unblocked", forKey: "icalendarIncludeTodo")
1494        #expect(OrgPreferences.icalendarOptions(defaults).includeTodo == .unblocked)
1495    }
1496}