Tests/OrgAppTests/AppTests.swift

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

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form