Tests/OrgAppTests/AppTests.swift

cba778d55e19c2c7a8dce862eb5d5f46d3d8c792
orgstar/Tests/OrgAppTests/AppTests.swift history · blame · raw

1084 lines · 53033 bytes

   1import Foundation
   2import OrgCore
   3import OrgDocument
   4import OrgIndex
   5import Testing
   6@testable import OrgApp
   7
   8/// A temporary folder that removes itself.
   9final class Folder {
  10    let url: URL
  11
  12    init() throws {
  13        url = FileManager.default.temporaryDirectory.appendingPathComponent("orgstar-\(UUID().uuidString)").standardizedFileURL
  14        try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)
  15    }
  16
  17    deinit {
  18        try? FileManager.default.removeItem(at: url)
  19    }
  20
  21    @discardableResult
  22    func write(_ path: String, _ text: String) throws -> URL {
  23        let file = url.appendingPathComponent(path)
  24        try FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true)
  25        try Data(text.utf8).write(to: file)
  26        return file.standardizedFileURL
  27    }
  28}
  29
  30struct FileTreeTests {
  31    @Test func foldersFirstThenFiles() {
  32        let files = ["b.org", "a/z.org", "a/y.org", "c.sync-conflict-1.org", "a2.org"].map {
  33            FileEntry(path: "/r/" + $0, root: "/r", kind: $0.contains("conflict") ? .conflict : .org)
  34        }
  35        let tree = FileTreeNode.build(root: "/r", files: files)
  36        #expect(tree.children?.map(\.name) == ["a", "a2.org", "b.org", "c.sync-conflict-1.org"])
  37        #expect(tree.children?[0].children?.map(\.name) == ["y.org", "z.org"])
  38        #expect(tree.children?[1].children == nil)
  39    }
  40
  41    @Test func fuzzyMatching() {
  42        #expect(FuzzyMatch.score("wn", "work/notes.org") != nil)
  43        #expect(FuzzyMatch.score("xyz", "work/notes.org") == nil)
  44        let files = ["work/notes.org", "notes.org", "personal/wine.org"].map { FileEntry(path: "/r/" + $0, root: "/r", kind: .org) }
  45        #expect(FuzzyMatch.rank("notes", files).map(\.relativePath) == ["notes.org", "work/notes.org"])
  46        #expect(FuzzyMatch.rank("", files).count == 3)
  47    }
  48}
  49
  50@MainActor
  51struct WorkspaceModelTests {
  52    @Test func addSearchRemoveAndPersist() async throws {
  53        let notes = try Folder()
  54        let support = try Folder()
  55        try notes.write("a.org", "* Groceries\nbuy apples\n")
  56        try notes.write("sub/b.org", "* Taxes\n")
  57        try notes.write("c.sync-conflict-1.org", "* Taxes copy\n")
  58
  59        let model = try WorkspaceModel(directory: support.url)
  60        try await model.addRoot(notes.url)
  61        #expect(model.files.count == 3)
  62        #expect(model.search("apples").map(\.title) == ["Groceries"])
  63        #expect(model.quickOpen("bo").map(\.name) == ["b.org"])
  64        let root = try #require(model.rootPaths.first)
  65        #expect(model.tree(forRoot: root).children?.map(\.name) == ["sub", "a.org", "c.sync-conflict-1.org"])
  66
  67        let reopened = try WorkspaceModel(directory: support.url)
  68        #expect(reopened.roots.count == 1)
  69        #expect(reopened.files.count == 3)
  70
  71        try reopened.removeRoot(path: root)
  72        #expect(reopened.roots.isEmpty)
  73        #expect(reopened.files.isEmpty)
  74        #expect(reopened.search("apples").isEmpty)
  75    }
  76
  77    @Test func aMovedFolderLeavesNoOldRows() async throws {
  78        let parent = try Folder()
  79        let original = parent.url.appendingPathComponent("notes")
  80        try FileManager.default.createDirectory(at: original, withIntermediateDirectories: true)
  81        try "* Plumber\n".write(to: original.appendingPathComponent("a.org"), atomically: true, encoding: .utf8)
  82        let data = parent.url.appendingPathComponent("data")
  83        let model = try WorkspaceModel(directory: data)
  84        try await model.addRoot(original)
  85        #expect(model.search("plumber").count == 1)
  86
  87        let moved = parent.url.appendingPathComponent("moved")
  88        try FileManager.default.moveItem(at: original, to: moved)
  89        let reopened = try WorkspaceModel(directory: data)
  90        await reopened.refresh()
  91        let found = reopened.search("plumber").map(\.path)
  92        #expect(found.count == 1 && found[0].hasSuffix("/moved/a.org"), "\(found)")
  93        // Adding it again, under its new path, adds nothing.
  94        try await reopened.addRoot(moved)
  95        #expect(reopened.roots.count == 1)
  96    }
  97
  98    @Test func listsDownloadsInTheTree() {
  99        let files = [FileEntry(path: "/r/a.org", root: "/r", kind: .org)]
 100        let tree = FileTreeNode.build(root: "/r", files: files, downloading: ["/r/b.org", "/r/sub/c.org"])
 101        #expect(tree.children?.map(\.name) == ["sub", "a.org", "b.org"])
 102        #expect(tree.children?[2].isDownloading == true && tree.children?[2].file == nil)
 103        #expect(tree.children?[0].children?.map(\.name) == ["c.org"])
 104    }
 105
 106    @Test func findsBacklinks() async throws {
 107        let notes = try Folder()
 108        try notes.write("a.org", "* Sink\n:PROPERTIES:\n:ID: s-1\n:CUSTOM_ID: sink\n:END:\nsee [[*Taps]]\n* Taps\n")
 109        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")
 110        // Links before the first heading come from the file itself.
 111        try notes.write("c.org", "#+TITLE: C\nAbout [[file:a.org::*Sink]] and [[file:a.org]].\n* Later\n")
 112        let model = try WorkspaceModel(directory: nil)
 113        try await model.addRoot(notes.url)
 114        let a = try #require(model.files.first { $0.path.hasSuffix("/a.org") }).path
 115        let c = try #require(model.files.first { $0.path.hasSuffix("/c.org") }).path
 116        let sink = Backlinks.Target(path: a, title: "Sink", id: "s-1", customID: "sink")
 117        #expect(model.backlinks(to: sink).map(\.title) == ["Plumbing", "Other", "c.org"])
 118        #expect(model.backlinks(to: Backlinks.Target(path: a)).map(\.title) == ["Plumbing", "c.org"])
 119        #expect(model.backlinks(to: Backlinks.Target(path: a, title: "Taps")).map(\.title) == ["Sink"])
 120        #expect(model.backlinks(to: sink, excluding: 0).map(\.title) == ["Plumbing", "Other", "c.org"])
 121        let fromC = try #require(model.backlinks(to: sink).last)
 122        #expect(fromC == .file(c, contentHash: fromC.contentHash))
 123        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 124        session.show(fromC)
 125        #expect(session.path == c && session.revealRequest?.offset == 0)
 126    }
 127
 128    @Test func createRenameAndTrashFiles() async throws {
 129        let notes = try Folder()
 130        try notes.write("a.org", "* Alpha\n")
 131        let model = try WorkspaceModel(directory: nil)
 132        model.trasher = { try FileManager.default.removeItem(at: $0) }
 133        try await model.addRoot(notes.url)
 134        let root = try #require(model.rootPaths.first)
 135
 136        let created = try await model.createFile(named: "projects/plan", in: root)
 137        #expect(created == root + "/projects/plan.org")
 138        #expect(model.files.map(\.path).contains(created))
 139        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "projects/plan.org", in: root) }
 140        await #expect(throws: WorkspaceModel.FileError.self) { try await model.createFile(named: "../escape", in: root) }
 141
 142        let renamed = try await model.rename(created, to: "roadmap.org")
 143        #expect(model.files.map(\.path).contains(renamed) && !model.files.map(\.path).contains(created))
 144        let folder = try await model.rename(root + "/projects", to: "work")
 145        #expect(model.files.map(\.path).contains(folder + "/roadmap.org"))
 146
 147        try await model.trash(folder + "/roadmap.org")
 148        #expect(!FileManager.default.fileExists(atPath: folder + "/roadmap.org"))
 149        #expect(!model.files.map(\.path).contains(folder + "/roadmap.org"))
 150        #expect(model.search("alpha").count == 1)
 151    }
 152
 153    /// Watching starts with no folders (a first launch); a folder added afterwards is
 154    /// watched.
 155    @Test func foldersAddedLaterAreWatched() async throws {
 156        let notes = try Folder()
 157        let model = try WorkspaceModel(directory: nil)
 158        model.startWatching()
 159        try await model.addRoot(notes.url)
 160        let file = try notes.write("new.org", "* Fresh heading\n")
 161        var found = false
 162        for _ in 0..<40 where !found {
 163            try await Task.sleep(for: .milliseconds(100))
 164            found = model.files.contains { URL(fileURLWithPath: $0.path).resolvingSymlinksInPath() == file.resolvingSymlinksInPath() }
 165        }
 166        #expect(found)
 167    }
 168
 169    @Test func changedFilesAreReindexed() async throws {
 170        let notes = try Folder()
 171        let file = try notes.write("a.org", "* Old\n")
 172        let model = try WorkspaceModel(directory: nil)
 173        try await model.addRoot(notes.url)
 174        try notes.write("a.org", "* New\n")
 175        await model.filesChanged([file], rescan: [])
 176        #expect(model.search("new").count == 1)
 177        #expect(model.changedFile?.path == file.path)
 178    }
 179}
 180
 181@MainActor
 182struct DocumentSessionTests {
 183    @Test func openShowAndReload() throws {
 184        let notes = try Folder()
 185        let file = try notes.write("a.org", "* One\n* Two\n")
 186        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 187        session.open(file.path)
 188        #expect(session.outline.map(\.title) == ["One", "Two"])
 189
 190        let location = HeadingLocation(path: file.path, ordinal: 1, title: "Two", start: 6, contentHash: "stale")
 191        session.show(location)
 192        #expect(session.revealRequest?.offset == 6)
 193
 194        try notes.write("a.org", "intro\n* One\n* Two\n")
 195        session.fileChanged(file.path)
 196        #expect(session.outline.map(\.start) == [6, 12])
 197        session.show(location)
 198        #expect(session.revealRequest?.offset == 12)
 199    }
 200
 201    @Test func sameFileByAnotherPathSharesItsBuffer() throws {
 202        let notes = try Folder()
 203        let file = try notes.write("a.org", "* One\n")
 204        let link = notes.url.appendingPathComponent("link")
 205        try FileManager.default.createSymbolicLink(at: link, withDestinationURL: notes.url)
 206        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 207        session.open(file.path)
 208        session.open(link.appendingPathComponent("a.org").path)
 209        #expect(session.openPaths == [file.path])
 210        #expect(session.path == file.path)
 211    }
 212
 213    @Test func buffersOfTheSameNameShowTheirFolders() throws {
 214        let notes = try Folder()
 215        let a = try notes.write("x/blog/index.org", "a\n")
 216        let b = try notes.write("y/blog/index.org", "b\n")
 217        let c = try notes.write("y/other.org", "c\n")
 218        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 219        session.open(a.path)
 220        #expect(session.bufferName(a.path) == "index.org")
 221        session.open(b.path)
 222        session.open(c.path)
 223        #expect(session.bufferName(a.path) == "index.org<x/blog>")
 224        #expect(session.bufferName(b.path) == "index.org<y/blog>")
 225        #expect(session.bufferName(c.path) == "other.org")
 226    }
 227
 228    @Test func openReadsSetupFiles() throws {
 229        let notes = try Folder()
 230        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 231        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
 232        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 233        session.open(file.path)
 234        #expect(session.document?.tree.settings.todoKeywordNames.contains("NEXT") == true)
 235    }
 236
 237
 238    @Test func keywordCtrlCCtrlCRereadsSetupFiles() throws {
 239        let notes = try Folder()
 240        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 241        let file = try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
 242        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 243        session.open(file.path)
 244        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == false)
 245        try notes.write("setup.org", "#+TODO: NEXT WAIT | DONE\n")
 246        let text = session.document!.text
 247        let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
 248        guard case .commit(let result) = CtrlCCtrlC().run(in: context) else { Issue.record("no commit"); return }
 249        #expect(result.effects.contains(.refreshSetup))
 250        session.refreshSetup()
 251        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
 252        #expect(session.document?.isDirty == false)
 253    }
 254
 255    @Test func reloadingFromDiskReadsSetupFilesAgain() throws {
 256        let notes = try Folder()
 257        try notes.write("setup.org", "#+TODO: NEXT | DONE\n")
 258        let file = try notes.write("a.org", "* WAIT One\n")
 259        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 260        session.open(file.path)
 261        try notes.write("a.org", "#+SETUPFILE: setup.org\n* WAIT One\n")
 262        try notes.write("setup.org", "#+TODO: WAIT | DONE\n")
 263        session.fileChanged(file.path)
 264        #expect(session.document?.tree.settings.todoKeywordNames.contains("WAIT") == true)
 265    }
 266
 267    @Test func missingFileReportsAnError() {
 268        let session = DocumentSession()
 269        session.open("/nonexistent/a.org")
 270        #expect(session.lastError != nil)
 271        #expect(session.document == nil)
 272    }
 273}
 274
 275@MainActor
 276struct SessionSavingTests {
 277    let notes: Folder
 278    let file: URL
 279    let recovery: FileRecoveryStore
 280    let session: DocumentSession
 281
 282    init() throws {
 283        notes = try Folder()
 284        file = try notes.write("a.org", "a\nb\nc\n")
 285        recovery = FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery"))
 286        session = DocumentSession(recovery: recovery)
 287        session.saveMode = .explicit
 288        session.open(file.path)
 289    }
 290
 291    /// Types `text` at `offset`, as the editor would.
 292    func type(_ text: String, at offset: Int) throws {
 293        let buffer = StateBuffer(session.document!)
 294        session.attach(buffer)
 295        try buffer.update { try $0.apply([TextEdit(range: offset..<offset, replacement: text)], baseRevision: $0.revision) }
 296        session.bufferChanged()
 297    }
 298
 299    var disk: String { (try? String(contentsOf: file, encoding: .utf8)) ?? "" }
 300
 301    @Test func saveWritesAndClearsDirty() throws {
 302        try type("x", at: 0)
 303        #expect(session.isDirty)
 304        #expect(session.save())
 305        #expect(!session.isDirty)
 306        #expect(disk == "xa\nb\nc\n")
 307    }
 308
 309    @Test func automaticModeSavesAfterTheDelay() async throws {
 310        session.saveMode = .automatic
 311        session.autosaveDelay = .milliseconds(10)
 312        try type("x", at: 0)
 313        #expect(disk == "a\nb\nc\n")
 314        await session.autosave?.value
 315        #expect(disk == "xa\nb\nc\n")
 316        #expect(!session.isDirty)
 317    }
 318
 319    @Test func explicitModeWaitsForSave() throws {
 320        try type("x", at: 0)
 321        #expect(session.autosave == nil)
 322    }
 323
 324    @Test func externalChangeMergesIntoEdits() throws {
 325        try type("x", at: 0)
 326        try notes.write("a.org", "a\nb\nC\n")
 327        session.fileChanged(file.path)
 328        #expect(session.document?.text == "xa\nb\nC\n")
 329        #expect(session.conflict == nil)
 330        #expect(session.save())
 331        #expect(disk == "xa\nb\nC\n")
 332    }
 333
 334    @Test func conflictKeepMine() throws {
 335        try type("x", at: 0)
 336        try notes.write("a.org", "z\nb\nc\n")
 337        session.fileChanged(file.path)
 338        #expect(session.conflict != nil)
 339        #expect(!session.save())
 340        #expect(disk == "z\nb\nc\n")
 341        session.keepMine()
 342        #expect(session.conflict == nil)
 343        #expect(disk == "xa\nb\nc\n")
 344        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
 345        #expect(kept.contains("z\nb\nc\n"))
 346    }
 347
 348    @Test func conflictUseDiskVersion() throws {
 349        try type("x", at: 0)
 350        try notes.write("a.org", "z\nb\nc\n")
 351        #expect(!session.save())
 352        #expect(session.conflict != nil)
 353        session.useDiskVersion()
 354        #expect(session.conflict == nil)
 355        #expect(!session.isDirty)
 356        #expect(session.document?.text == "z\nb\nc\n")
 357        let kept = try recovery.versions(for: file).map { try String(contentsOf: $0, encoding: .utf8) }
 358        #expect(kept.contains("xa\nb\nc\n"))
 359    }
 360
 361    @Test func searchSeesUnsavedHeadings() async throws {
 362        let workspace = try WorkspaceModel(directory: nil)
 363        try await workspace.addRoot(notes.url)
 364        try type("* Unsaved heading\n", at: 0)
 365        let overlay = workspace.overlay(path: session.path, document: session.document)
 366        #expect(workspace.search("unsaved").isEmpty)
 367        #expect(workspace.search("unsaved", overlay: overlay).map(\.title) == ["Unsaved heading"])
 368    }
 369}
 370
 371@MainActor
 372struct KeymapLoaderTests {
 373    @Test func layersTheUserFile() throws {
 374        let folder = try Folder()
 375        let missing = KeymapLoader.load(.emacs, userFile: folder.url.appendingPathComponent("none.toml"))
 376        #expect(missing.keymap == KeymapPreset.emacs.keymap && missing.problems.isEmpty)
 377
 378        let file = try folder.write("keymap.toml", "[[bind]]\nkeys = \"C-c a\"\ncommand = \"app.palette\"\n[[bind]]\nkeys = \"Q-q\"\ncommand = \"x\"\n")
 379        let loaded = KeymapLoader.load(.emacs, userFile: file)
 380        #expect(loaded.keymap.candidates(for: KeySequence.parse("C-c a")!).first?.command == "app.palette")
 381        #expect(loaded.problems == ["line 4: bad or missing keys"])
 382
 383        let broken = try folder.write("broken.toml", "keys = \"x")
 384        #expect(KeymapLoader.load(.mac, userFile: broken).problems == ["line 1: unclosed string"])
 385    }
 386}
 387
 388@MainActor
 389struct MoveSubtreeTests {
 390    @Test func refileWithinAndAcrossFiles() async throws {
 391        let notes = try Folder()
 392        let file = try notes.write("a.org", "* one\nbody\n* two\n")
 393        let other = try notes.write("b.org", "* inbox\n")
 394        let workspace = try WorkspaceModel(directory: nil)
 395        try await workspace.addRoot(notes.url)
 396        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 397        session.saveMode = .explicit
 398        session.open(file.path)
 399        let targets = workspace.refileTargets(openPath: session.path, document: session.document)
 400        #expect(targets.map(\.label) == ["a.org", "a.org/one", "a.org/two", "b.org", "b.org/inbox"])
 401
 402        #expect(session.refile(to: targets[2]) == "Refiled to a.org/two")
 403        #expect(session.document?.text == "* two\n** one\nbody\n")
 404
 405        let inbox = try #require(workspace.refileTargets(openPath: session.path, document: session.document).first { $0.label == "b.org/inbox" })
 406        StateBufferCaret.set(session, 6)
 407        #expect(session.refile(to: inbox) == "Refiled to b.org/inbox")
 408        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 409        #expect(session.document?.text == "* two\n")
 410    }
 411
 412    @Test func archiveToTheArchiveFile() throws {
 413        let notes = try Folder()
 414        let file = try notes.write("a.org", "* done\n* keep\n")
 415        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 416        session.saveMode = .explicit
 417        session.open(file.path)
 418        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 419        #expect(session.document?.text == "* keep\n")
 420        let archived = try String(contentsOf: notes.url.appendingPathComponent("a.org_archive"), encoding: .utf8)
 421        #expect(archived.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
 422    }
 423}
 424
 425@MainActor
 426struct AgendaActionTests {
 427    /// From the agenda: entries in files that aren't open move and archive on disk, and the
 428    /// current buffer stays as it was.
 429    @Test func refileAndArchiveFromAnEntry() async throws {
 430        let notes = try Folder()
 431        let file = try notes.write("a.org", "* one\nbody\n* two\n* three\n")
 432        let other = try notes.write("b.org", "* inbox\n")
 433        let shown = try notes.write("c.org", "* shown\n")
 434        let workspace = try WorkspaceModel(directory: nil)
 435        try await workspace.addRoot(notes.url)
 436        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 437        session.saveMode = .explicit
 438        session.open(shown.path)
 439
 440        let inbox = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/inbox" })
 441        #expect(session.refile(to: inbox, from: (file.path, 0)) == "Refiled to b.org/inbox")
 442        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n** one\nbody\n")
 443        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n* three\n")
 444
 445        let text = try String(contentsOf: file, encoding: .utf8)
 446        let two = try #require(workspace.refileTargets(openPath: file.path, document: DocumentState(bytes: [UInt8](text.utf8))).first { $0.label == "a.org/two" })
 447        #expect(session.refile(to: two, from: (file.path, 6)) == "Refiled to a.org/two")
 448        #expect(try String(contentsOf: file, encoding: .utf8) == "* two\n** three\n")
 449
 450        #expect(session.archive(from: (file.path, 0), now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 451        #expect(try String(contentsOf: file, encoding: .utf8) == "")
 452        #expect(session.path == shown.path && session.document?.text == "* shown\n")
 453    }
 454
 455    @Test func locatesMovedHeadings() throws {
 456        let notes = try Folder()
 457        let file = try notes.write("a.org", "* new\n* task\n* other\n* task\n")
 458        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 459        #expect(session.locateHeading(path: file.path, line: "* task", near: 0) == 6)
 460        #expect(session.locateHeading(path: file.path, line: "* task", near: 20) == 21)
 461        #expect(session.locateHeading(path: file.path, line: "* other", near: 14) == 13)
 462        #expect(session.locateHeading(path: file.path, line: "* gone", near: 0) == nil)
 463    }
 464}
 465
 466@MainActor
 467struct MoveIntoOpenBufferTests {
 468    /// A target open with unsaved edits above its heading takes the subtree in its buffer,
 469    /// under the right heading, and the disk keeps the saved text.
 470    @Test func refileIntoAnOpenBuffer() async throws {
 471        let notes = try Folder()
 472        let file = try notes.write("a.org", "* task\nbody\n")
 473        let other = try notes.write("b.org", "* inbox\n* projects\n")
 474        let workspace = try WorkspaceModel(directory: nil)
 475        try await workspace.addRoot(notes.url)
 476        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 477        session.saveMode = .explicit
 478        session.open(other.path)
 479        let projects = try #require(workspace.refileTargets(openPath: nil, document: nil).first { $0.label == "b.org/projects" })
 480        _ = session.perform(InsertText(text: "* new\n"), path: other.path, at: 0, expect: nil)
 481        session.open(file.path)
 482        #expect(session.refile(to: projects) == "Refiled to b.org/projects")
 483        #expect(session.document?.text == "")
 484        #expect(session.openDocuments.first { $0.path == other.path }?.document.text == "* new\n* inbox\n* projects\n** task\nbody\n")
 485        #expect(try String(contentsOf: other, encoding: .utf8) == "* inbox\n* projects\n")
 486    }
 487
 488    @Test func archiveIntoAnOpenBuffer() throws {
 489        let notes = try Folder()
 490        let file = try notes.write("a.org", "* done\n* keep\n")
 491        let archive = try notes.write("a.org_archive", "* old\n")
 492        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 493        session.saveMode = .explicit
 494        session.open(archive.path)
 495        session.open(file.path)
 496        #expect(session.archive(now: Date(timeIntervalSince1970: 0)) == "Archived to a.org_archive")
 497        #expect(session.document?.text == "* keep\n")
 498        let text = try #require(session.openDocuments.first { $0.path == archive.path }?.document.text)
 499        #expect(text.hasPrefix("* old\n") && text.contains("* done\n:PROPERTIES:\n:ARCHIVE_TIME:"))
 500        #expect(try String(contentsOf: archive, encoding: .utf8) == "* old\n")
 501    }
 502}
 503
 504/// Inserts text at the caret, for tests.
 505struct InsertText: OrgCommand {
 506    let text: String
 507    var id: String { "test.insert" }
 508    var title: String { "Insert" }
 509    func applies(in context: EditContext) -> Bool { true }
 510    func run(in context: EditContext) -> CommandStep {
 511        .commit(EditResult(baseRevision: context.revision, edits: [TextEdit(range: context.caret..<context.caret, replacement: text)]))
 512    }
 513}
 514
 515/// Moves the caret of a session's `StateBuffer`, as clicking in the editor would.
 516@MainActor
 517enum StateBufferCaret {
 518    static func set(_ session: DocumentSession, _ offset: Int) {
 519        let buffer = StateBuffer(session.document!)
 520        buffer.selection = [offset..<offset]
 521        session.attach(buffer)
 522    }
 523}
 524
 525@MainActor
 526struct AgendaModelTests {
 527    @Test func openBuffersFollowTheirText() async throws {
 528        let notes = try Folder()
 529        let file = try notes.write("a.org", "* TODO One\n")
 530        let model = try WorkspaceModel(directory: nil)
 531        try await model.addRoot(notes.url)
 532        let agenda = AgendaModel(workspace: model)
 533        agenda.mode = .todo(keywords: nil)
 534        for text in ["* TODO One\n", "* TODO Two\n", "* TODO One\n", "* TODO Two\n"] {
 535            await agenda.refresh(open: [file.path: text])
 536            #expect(agenda.list.map(\.text) == [String(text.dropFirst(2).dropLast())])
 537        }
 538        await agenda.refresh(open: [:])
 539        #expect(agenda.list.map(\.text) == ["TODO One"])
 540    }
 541
 542    @Test func entriesKnowTheirDoneKeyword() async throws {
 543        let notes = try Folder()
 544        try notes.write("setup.org", "#+TODO: NEXT | FINISHED\n")
 545        try notes.write("a.org", "#+SETUPFILE: setup.org\n* NEXT One\n")
 546        let plain = try notes.write("b.org", "* WAIT Two\n")
 547        let model = try WorkspaceModel(directory: nil)
 548        model.settings = .with(todoKeywords: try #require(OrgSettings.default.withTodoKeywords("WAIT | OK")))
 549        try await model.addRoot(notes.url)
 550        let agenda = AgendaModel(workspace: model)
 551        agenda.mode = .todo(keywords: nil)
 552        await agenda.refresh(open: [:])
 553        #expect(Dictionary(uniqueKeysWithValues: agenda.list.map { ($0.todo ?? "", $0.doneKeyword) }) == ["NEXT": "FINISHED", "WAIT": "OK"])
 554        await agenda.refresh(open: [plain.path: "#+TODO: WAIT | GONE\n* WAIT Two\n"])
 555        #expect(agenda.list.first { $0.todo == "WAIT" }?.doneKeyword == "GONE")
 556    }
 557
 558    @Test func topLevelFilesAndTheOpenBuffer() async throws {
 559        let notes = try Folder()
 560        try notes.write("a.org", "* TODO Pay rent\nSCHEDULED: <2026-10-05 Mon>\n")
 561        try notes.write("sub/b.org", "* Hidden <2026-10-05 Mon>\n")
 562        try notes.write("old.org_archive", "* Archived <2026-10-05 Mon>\n")
 563        let model = try WorkspaceModel(directory: nil)
 564        try await model.addRoot(notes.url)
 565        let agenda = AgendaModel(workspace: model)
 566        agenda.startOffset = -3
 567        var utc = Calendar(identifier: .gregorian)
 568        utc.timeZone = TimeZone(identifier: "UTC")!
 569        let now = try #require(utc.date(from: DateComponents(year: 2026, month: 10, day: 5, hour: 9)))
 570
 571        await agenda.refresh(open: [:], now: now, calendar: utc)
 572        #expect(agenda.days.count == 10)
 573        #expect(agenda.days[3].isToday)
 574        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent"])
 575
 576        agenda.includeSubfolders = true
 577        await agenda.refresh(open: [:], now: now, calendar: utc)
 578        #expect(agenda.days[3].items.map(\.text) == ["TODO Pay rent", "Hidden "])
 579
 580        let path = try #require(agenda.files.first { $0.hasSuffix("/a.org") })
 581        await agenda.refresh(open: [path: "* DONE Pay rent\nSCHEDULED: <2026-10-05 Mon>\n"], now: now, calendar: utc)
 582        #expect(agenda.days[3].items.first?.text == "DONE Pay rent")
 583
 584        agenda.shift(forward: true, now: now, calendar: utc)
 585        await agenda.refresh(open: [:], now: now, calendar: utc)
 586        #expect(agenda.days.first?.day == Days.absolute(year: 2026, month: 10, day: 12))
 587    }
 588}
 589
 590@MainActor
 591struct AgendaCommandTests {
 592    @Test func loadsViews() throws {
 593        let folder = try Folder()
 594        let file = try folder.write("views.toml", """
 595        [[view]]
 596        name = "Work"
 597        type = "match"
 598        match = "+work"
 599        [[view]]
 600        name = "Week"
 601        span = 7
 602        start = -1
 603        [[view]]
 604        name = "Waiting"
 605        type = "todo"
 606        keywords = "WAIT|HOLD"
 607        [[view]]
 608        name = "Broken"
 609        type = "match"
 610        """)
 611        let loaded = AgendaViewLoader.load(userFile: file)
 612        #expect(loaded.views.map(\.name) == ["Agenda", "TODO List", "Work", "Week", "Waiting"])
 613        #expect(loaded.views[2].mode == .match("+work", todoOnly: false))
 614        #expect(loaded.views[3].mode == .agenda(span: 7, startOffset: -1))
 615        #expect(loaded.views[4].mode == .todo(keywords: "WAIT|HOLD"))
 616        #expect(loaded.problems == ["views.toml line 13: Broken needs a match"])
 617    }
 618
 619    @Test func todoListMode() async throws {
 620        let notes = try Folder()
 621        try notes.write("a.org", "* TODO One :work:\n* DONE Two\n* TODO Three\n")
 622        let model = try WorkspaceModel(directory: nil)
 623        try await model.addRoot(notes.url)
 624        let agenda = AgendaModel(workspace: model)
 625        agenda.mode = .todo(keywords: nil)
 626        await agenda.refresh(open: [:])
 627        #expect(agenda.list.map(\.text) == ["TODO One", "TODO Three"])
 628        agenda.mode = .match("work", todoOnly: false)
 629        await agenda.refresh(open: [:])
 630        #expect(agenda.list.map(\.text) == ["TODO One"])
 631    }
 632
 633    @Test func runsCommandsOnClosedAndOpenFiles() throws {
 634        let notes = try Folder()
 635        let a = try notes.write("a.org", "* TODO One\n* TODO Two\n")
 636        let b = try notes.write("b.org", "* TODO Three\n")
 637        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 638        session.open(a.path)
 639
 640        // A closed file is changed on disk.
 641        let closed = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
 642        guard case .commit = closed else { Issue.record("\(closed)"); return }
 643        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
 644
 645        // The open file changes in its buffer.
 646        let open = session.perform(TodoCycle(), path: a.path, at: 11, expect: (11, "* TODO Two"))
 647        guard case .commit = open else { Issue.record("\(open)"); return }
 648        #expect(session.document?.text == "* TODO One\n* DONE Two\n")
 649
 650        // A heading that moved is refused.
 651        let stale = session.perform(TodoCycle(), path: b.path, at: 0, expect: (0, "* TODO Three"))
 652        guard case .failed = stale else { Issue.record("\(stale)"); return }
 653        #expect(try String(contentsOf: b, encoding: .utf8) == "* DONE Three\n")
 654    }
 655}
 656
 657final class FakeReminderCenter: ReminderCenter, @unchecked Sendable {
 658    private let lock = NSLock()
 659    private var pending: [String] = ["someone.else"]
 660    var authorized = true
 661    private(set) var added: [String] = []
 662
 663    func authorize() async -> Bool { authorized }
 664    func pendingIDs() async -> [String] { lock.withLock { pending } }
 665    var delivered: [String] = []
 666    func deliveredIDs() async -> [String] { lock.withLock { delivered } }
 667    /// The system showing a notification: no longer pending.
 668    func fire(_ id: String, keep: Bool) {
 669        lock.withLock {
 670            pending.removeAll { $0 == id }
 671            if keep { delivered.append(id) }
 672        }
 673    }
 674    func add(_ reminder: Reminder) async throws {
 675        lock.withLock {
 676            pending.append(reminder.id)
 677            added.append(reminder.id)
 678        }
 679    }
 680    func remove(_ ids: [String]) { lock.withLock { pending.removeAll { ids.contains($0) } } }
 681    var ids: [String] { lock.withLock { pending } }
 682}
 683
 684@MainActor
 685struct ReminderSchedulerTests {
 686    func reminder(_ id: String, _ minutes: Double) -> Reminder {
 687        let date = Date(timeIntervalSince1970: 1_000_000 + minutes * 60)
 688        return Reminder(id: "orgstar.\(id)", fireDate: date, eventDate: date.addingTimeInterval(720), title: id, body: "", path: "/a.org", offset: 0)
 689    }
 690
 691    @Test func reconciles() async {
 692        let center = FakeReminderCenter()
 693        let scheduler = ReminderScheduler(center: center)
 694        await scheduler.reconcile([reminder("a", 1), reminder("b", 2)])
 695        #expect(center.ids == ["someone.else", "orgstar.a", "orgstar.b"])
 696        #expect(scheduler.scheduledThrough == reminder("b", 2).eventDate)
 697
 698        await scheduler.reconcile([reminder("b", 2), reminder("c", 3)])
 699        #expect(center.ids == ["someone.else", "orgstar.b", "orgstar.c"])
 700        #expect(center.added == ["orgstar.a", "orgstar.b", "orgstar.c"])
 701
 702        await scheduler.clear()
 703        #expect(center.ids == ["someone.else"])
 704        #expect(scheduler.scheduledThrough == nil)
 705
 706        // Fired reminders aren't set again, whether or not they're still in Notification Center.
 707        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
 708        center.fire("orgstar.e", keep: false)
 709        await scheduler.reconcile([reminder("e", 5), reminder("f", 6)])
 710        #expect(center.added.filter { $0 == "orgstar.e" }.count == 1)
 711        let relaunched = ReminderScheduler(center: center)
 712        center.fire("orgstar.f", keep: true)
 713        await relaunched.reconcile([reminder("f", 6)])
 714        #expect(center.added.filter { $0 == "orgstar.f" }.count == 1)
 715        await scheduler.clear()
 716
 717        center.authorized = false
 718        await scheduler.reconcile([reminder("d", 4)])
 719        #expect(!scheduler.isAuthorized)
 720        #expect(center.ids == ["someone.else"])
 721    }
 722}
 723
 724@MainActor
 725struct EmacsFallbackTests {
 726    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 727    func recalculatesTablesNativeCodeCannot() async throws {
 728        let notes = try Folder()
 729        let file = try notes.write("t.org", "* Prices\n| item | n | twice |\n|------+---+-------|\n| x | a | |\n| y | 2 | |\n#+TBLFM: $3=$2*2\n")
 730        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 731        session.open(file.path)
 732        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 50, expect: nil)
 733        guard case .external(.emacsTable(let table, let point, let form, let reason, let lisp)) = step else {
 734            Issue.record("\(step)")
 735            return
 736        }
 737        #expect(reason == "non-numeric field a")
 738        #expect(!lisp)
 739        let message = await session.recalculateInEmacs(table: table, point: point, form: form)
 740        #expect(message == "Recalculated in Emacs")
 741        #expect(session.document?.text == "* Prices\n| item | n | twice |\n|------+---+-------|\n| x    | a | 2 a   |\n| y    | 2 | 4     |\n#+TBLFM: $3=$2*2\n")
 742    }
 743
 744    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 745    func cancelingARecalculationLeavesTheTable() async throws {
 746        let notes = try Folder()
 747        let text = "| n | twice |\n|---+-------|\n| a |       |\n#+TBLFM: $2=$1*2\n"
 748        let file = try notes.write("t.org", text)
 749        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 750        session.open(file.path)
 751        let step = session.perform(TableRecalculate(all: true), path: file.path, at: 2, expect: nil)
 752        guard case .external(.emacsTable(let table, let point, let form, _, _)) = step else {
 753            Issue.record("\(step)")
 754            return
 755        }
 756        let task = Task { await session.recalculateInEmacs(table: table, point: point, form: form) }
 757        task.cancel()
 758        #expect(await task.value == "Recalculation canceled")
 759        #expect(session.document?.text == text)
 760    }
 761}
 762
 763@MainActor
 764struct BabelSessionTests {
 765    @Test func runsBlocksAndWritesResults() async throws {
 766        let notes = try Folder()
 767        let file = try notes.write("b.org", "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n")
 768        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 769        session.open(file.path)
 770        let step = session.perform(ExecuteSrcBlock(), path: file.path, at: 3, expect: nil)
 771        guard case .external(.babel(let job)) = step else {
 772            Issue.record("\(step)")
 773            return
 774        }
 775        #expect(await session.runBabel(job) == "Code block evaluation complete.")
 776        // A column that is half numbers is right-aligned, as org-table-align does.
 777        #expect(session.document?.text == "#+begin_src sh\necho answer\necho \"$((6 * 7))\"\n#+end_src\n\n#+RESULTS:\n| answer |\n|     42 |\n")
 778    }
 779}
 780
 781@MainActor
 782struct BabelErrorTests {
 783    func job(_ session: DocumentSession, _ path: String) throws -> BabelJob {
 784        guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: path, at: 3, expect: nil) else {
 785            throw CancellationError()
 786        }
 787        return job
 788    }
 789
 790    /// Like `org-babel-eval`: the results go in, and the error output and status are shown.
 791    @Test func reportsErrorsAndStillInsertsResults() async throws {
 792        let notes = try Folder()
 793        let file = try notes.write("e.org", "#+begin_src sh\necho out\necho oops >&2\nexit 3\n#+end_src\n")
 794        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 795        session.open(file.path)
 796        #expect(await session.runBabel(try job(session, file.path)) == "Exited with status 3: oops")
 797        #expect(session.document?.text.hasSuffix("#+RESULTS:\n: out\n") == true)
 798    }
 799
 800    @Test func cancelsARunningBlock() async throws {
 801        let notes = try Folder()
 802        let file = try notes.write("s.org", "#+begin_src sh\nsleep 20\necho late\n#+end_src\n")
 803        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 804        session.open(file.path)
 805        let start = ContinuousClock.now
 806        var message: String?
 807        session.startBabel(try job(session, file.path)) { message = $0 }
 808        #expect(session.isRunningBabel)
 809        try await Task.sleep(for: .milliseconds(200))
 810        session.cancelBabel()
 811        while message == nil, ContinuousClock.now - start < .seconds(5) { try await Task.sleep(for: .milliseconds(20)) }
 812        #expect(message == "Code block canceled.")
 813        #expect(!session.isRunningBabel)
 814        #expect(ContinuousClock.now - start < .seconds(5))
 815        #expect(session.document?.text.contains("#+RESULTS:") == false)
 816    }
 817}
 818
 819struct EmacsExportTests {
 820    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 821    func exportsBesideTheFile() async throws {
 822        let notes = try Folder()
 823        let file = try notes.write("doc.org", "#+TITLE: On disk\n")
 824        // The buffer's text is exported, not the file's.
 825        let written = try await EmacsRunner.export(text: "#+TITLE: In the buffer\n\n* Heading\nBody.\n", path: file.path, function: "org-ascii-export-to-ascii")
 826        #expect(URL(fileURLWithPath: written).lastPathComponent == "doc.txt")
 827        let text = try String(contentsOfFile: written, encoding: .utf8)
 828        #expect(text.uppercased().contains("IN THE BUFFER") && text.contains("Body."), "\(text)")
 829        #expect(try String(contentsOf: file, encoding: .utf8) == "#+TITLE: On disk\n")
 830    }
 831
 832    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 833    func exportUsesBabelPath() async throws {
 834        let notes = try Folder()
 835        let file = try notes.write("doc.org", "")
 836        let function = #"(lambda () (with-temp-file "path.txt" (insert (getenv "PATH"))) "path.txt")"#
 837        let written = try await EmacsRunner.export(text: "", path: file.path, function: function)
 838        #expect(try String(contentsOfFile: written, encoding: .utf8) == BabelRunner.environment["PATH"])
 839    }
 840
 841    @Test(.enabled(if: EmacsRunner.executable() != nil && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
 842    func cancellingStopsTheExport() async throws {
 843        let notes = try Folder()
 844        let file = try notes.write("doc.org", "")
 845        let pidFile = notes.url.appendingPathComponent("pid")
 846        let function = #"(lambda () (with-temp-file "pid" (insert (number-to-string (emacs-pid)))) (sleep-for 60) "x")"#
 847        let export = Task { try await EmacsRunner.export(text: "", path: file.path, function: function) }
 848        var pid: pid_t?
 849        for _ in 0..<200 where pid == nil {
 850            try await Task.sleep(for: .milliseconds(50))
 851            pid = (try? String(contentsOf: pidFile, encoding: .utf8)).flatMap { pid_t($0) }
 852        }
 853        let started = try #require(pid)
 854        export.cancel()
 855        await #expect(throws: CancellationError.self) { try await export.value }
 856        var alive = true
 857        for _ in 0..<100 where alive {
 858            alive = kill(started, 0) == 0
 859            if alive { try await Task.sleep(for: .milliseconds(50)) }
 860        }
 861        #expect(!alive)
 862    }
 863}
 864
 865@MainActor
 866struct CaptureAppTests {
 867    @Test func loadsTemplates() throws {
 868        let folder = try Folder()
 869        let file = try folder.write("capture.toml", """
 870        [[template]]
 871        key = "w"
 872        name = "Work"
 873        file = "work.org"
 874        olp = "Projects/Work"
 875        template = "* TODO %?\\n%a"
 876        [[template]]
 877        key = "j"
 878        type = "plain"
 879        file = "~/journal.org"
 880        template = "%U %?"
 881        prepend = true
 882        """)
 883        let loaded = CaptureTemplates.load(userFile: file)
 884        #expect(loaded.problems.isEmpty)
 885        #expect(loaded.templates.map(\.key) == ["w", "j"])
 886        #expect(loaded.templates[0].target == .outline(file: "work.org", path: ["Projects", "Work"]))
 887        #expect(loaded.templates[0].template == "* TODO %?\n%a")
 888        #expect(loaded.templates[1].kind == .plain && loaded.templates[1].prepend)
 889        try """
 890        [[template]]
 891        key = "d"
 892        file = "journal.org"
 893        datetree = true
 894        olp = "Journal"
 895        tree-type = "month"
 896        template = "* %?"
 897        empty-lines-after = 1
 898        jump-to-captured = true
 899        [[template]]
 900        key = "i"
 901        id = "abc"
 902        template = "* %?"
 903        clock-in = true
 904        clock-resume = true
 905        [[template]]
 906        key = "k"
 907        clock = true
 908        type = "item"
 909        template = "%?"
 910        immediate-finish = true
 911        """.write(to: file, atomically: true, encoding: .utf8)
 912        let targets = CaptureTemplates.load(userFile: file)
 913        #expect(targets.problems.isEmpty)
 914        #expect(targets.templates.map(\.target) == [.datetree(file: "journal.org", path: ["Journal"], tree: .month), .id("abc"), .clock])
 915        #expect(targets.templates[0].options == .init(emptyLinesAfter: 1, jumpToCaptured: true))
 916        #expect(targets.templates[1].options == .init(clockIn: true, clockResume: true))
 917        #expect(targets.templates[2].options.immediateFinish)
 918        #expect(CaptureTemplates.load(userFile: folder.url.appendingPathComponent("none.toml")).templates == CaptureTemplates.defaults)
 919    }
 920
 921    @Test func capturesIntoClosedMissingAndOpenFiles() throws {
 922        let notes = try Folder()
 923        let todo = try notes.write("todo.org", "* Inbox\n** TODO Old\n* Later\n")
 924        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 925        let template = CaptureTemplates.defaults[0]
 926        let placed = try session.capture("* TODO New\n", template: template, root: notes.url.path).get()
 927        #expect(try String(contentsOf: todo, encoding: .utf8) == "* Inbox\n** TODO Old\n** TODO New\n* Later\n")
 928        #expect(placed.path == todo.path && placed.offset == ("* Inbox\n** TODO Old\n" as NSString).length)
 929
 930        _ = try session.capture("* Note\n", template: CaptureTemplates.defaults[1], root: notes.url.path).get()
 931        #expect(try String(contentsOf: notes.url.appendingPathComponent("notes.org"), encoding: .utf8) == "* Inbox\n** Note\n")
 932
 933        session.open(todo.path)
 934        _ = try session.capture("* TODO Third\n", template: template, root: notes.url.path).get()
 935        #expect(session.document?.text == "* Inbox\n** TODO Old\n** TODO New\n** TODO Third\n* Later\n")
 936
 937        // An ID's file is resolved by the caller.
 938        let id = CaptureTemplate(key: "i", name: "", target: .id("x1"), template: "")
 939        let ided = try notes.write("ided.org", "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n")
 940        _ = try session.capture("* Child\n", template: id, root: nil, file: ided.path).get()
 941        #expect(try String(contentsOf: ided, encoding: .utf8) == "* Target\n:PROPERTIES:\n:ID: x1\n:END:\n** Child\n")
 942    }
 943}
 944
 945@MainActor
 946struct ClockModelTests {
 947    @Test func clocksInAndOutAcrossFiles() throws {
 948        let notes = try Folder()
 949        let work = try notes.write("work.org", "* Task\nBody\n")
 950        let other = try notes.write("other.org", "* Other\n")
 951        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 952        session.open(work.path)
 953        session.reveal(2)
 954        let stateFile = notes.url.appendingPathComponent("clock.json")
 955        let clock = ClockModel(file: stateFile)
 956        var utc = Calendar(identifier: .gregorian)
 957        utc.timeZone = TimeZone(identifier: "UTC")!
 958        let start = Date(timeIntervalSince1970: 1_789_000_000)
 959        _ = clock.clockIn(session, now: start)
 960        #expect(clock.running?.heading == "Task")
 961        #expect(ClockModel(file: stateFile).running == clock.running)
 962
 963        // Out from another file: the clocked file's buffer is still open behind it and takes
 964        // the change.
 965        session.open(other.path)
 966        let message = clock.clockOut(session, now: start.addingTimeInterval(95 * 60))
 967        #expect(message == "Clock stopped after 1:35")
 968        #expect(clock.running == nil)
 969        #expect(session.dirtyPaths == [work.path])
 970        #expect(session.saveAll())
 971        let text = try String(contentsOf: work, encoding: .utf8)
 972        #expect(text.hasPrefix("* Task\n:LOGBOOK:\nCLOCK: [") && text.contains("=>  1:35\n:END:\nBody\n"), "\(text)")
 973    }
 974}
 975
 976@MainActor
 977struct BufferTests {
 978    @Test func buffersKeepEditsWhileOthersShow() throws {
 979        let notes = try Folder()
 980        let a = try notes.write("a.org", "* A\n")
 981        let b = try notes.write("b.org", "* B\n")
 982        let c = try notes.write("c.org", "* C\n")
 983        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
 984        session.saveMode = .explicit
 985        session.open(a.path)
 986        _ = session.perform(SetTodo(keyword: "TODO"), path: a.path, at: 0, expect: nil)
 987        session.open(b.path)
 988        #expect(session.path == b.path)
 989        #expect(session.openPaths == [a.path, b.path])
 990        #expect(session.dirtyPaths == [a.path])
 991        // A background buffer takes commands for its file, not the disk.
 992        _ = session.perform(SetTodo(keyword: "DONE"), path: a.path, at: 0, expect: nil)
 993        #expect(try String(contentsOf: a, encoding: .utf8) == "* A\n")
 994        #expect(session.openDocuments.first { $0.path == a.path }?.document.text.hasPrefix("* DONE A") == true)
 995
 996        session.open(a.path)
 997        #expect(session.document?.text.hasPrefix("* DONE A") == true)
 998        session.open(c.path)
 999        // Opened after the current buffer.
1000        #expect(session.openPaths == [a.path, c.path, b.path])
1001        session.cycle(1)
1002        #expect(session.path == b.path)
1003        session.cycle(1)
1004        #expect(session.path == a.path)
1005        session.showPrevious()
1006        #expect(session.path == b.path)
1007        #expect(session.recentPaths == [b.path, a.path, c.path])
1008
1009        session.kill(b.path)
1010        #expect(session.path == a.path)
1011        #expect(session.openPaths == [a.path, c.path])
1012        #expect(session.saveAll())
1013        #expect(try String(contentsOf: a, encoding: .utf8).hasPrefix("* DONE A"))
1014        session.kill(a.path)
1015        session.kill(c.path)
1016        #expect(session.path == nil && session.document == nil && session.openPaths.isEmpty)
1017    }
1018
1019    @Test func backgroundBuffersFollowTheDisk() throws {
1020        let notes = try Folder()
1021        let a = try notes.write("a.org", "* A\n")
1022        let b = try notes.write("b.org", "* B\n")
1023        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1024        session.open(a.path)
1025        session.open(b.path)
1026        try notes.write("a.org", "* A changed\n")
1027        session.fileChanged(a.path)
1028        #expect(session.openDocuments.first { $0.path == a.path }?.document.text == "* A changed\n")
1029    }
1030}
1031
1032@MainActor
1033struct LinkFollowTests {
1034    @Test func followsLinksOfEachKind() async throws {
1035        let notes = try Folder()
1036        let a = try notes.write("a.org", "* Start\nSee <<here>>.\n* Second [1/2]\n:PROPERTIES:\n:CUSTOM_ID: two\n:END:\n")
1037        let b = try notes.write("sub/b.org", "* Target heading\n:PROPERTIES:\n:ID: 1234-ABCD\n:END:\nline 5\nline 6\n")
1038        _ = try notes.write("pic.png", "not really")
1039        let workspace = try WorkspaceModel(directory: nil)
1040        try await workspace.addRoot(notes.url)
1041        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1042        session.open(a.path)
1043        let text = { (path: String) in try? String(contentsOfFile: path, encoding: .utf8) }
1044        func follow(_ raw: String) -> LinkFollow { session.follow(Links.parse(bracket: raw), workspace: workspace, isText: { $0.hasSuffix(".org") }) }
1045
1046        #expect(follow("here") == .shown)
1047        #expect(session.revealRequest?.offset == (text(a.path)! as NSString).range(of: "<<here>>").location)
1048        #expect(follow("#two") == .shown)
1049        #expect(follow("Second") == .shown)
1050        #expect(follow("Nowhere") == .message("No match for fuzzy expression: Nowhere"))
1051
1052        #expect(follow("file:sub/b.org::5") == .shown)
1053        #expect(session.path == b.path)
1054        #expect(session.revealRequest?.offset == (text(b.path)! as NSString).range(of: "line 5").location)
1055        session.open(a.path)
1056        #expect(follow("file:sub/b.org::*Target heading") == .shown && session.path == b.path)
1057        session.open(a.path)
1058        #expect(follow("id:1234-ABCD") == .shown && session.path == b.path)
1059        #expect(follow("id:none") == .message("No heading has the ID none"))
1060        // Relative to the open file (now sub/b.org); files Orgstar doesn't edit go to macOS.
1061        #expect(follow("file:../pic.png") == .openExternally(URL(fileURLWithPath: (notes.url.appendingPathComponent("pic.png").path as NSString).standardizingPath)))
1062        #expect(follow("file:pic.png") == .message("No file " + (notes.url.appendingPathComponent("sub/pic.png").path as NSString).standardizingPath))
1063        #expect(follow("https://orgmode.org/a b") == .openExternally(URL(string: "https://orgmode.org/a%20b")!))
1064        #expect(follow("doi:10.1000/182") == .openExternally(URL(string: "https://doi.org/10.1000/182")!))
1065        #expect(follow("shell:rm -rf x") == .message("orgstar doesn't run shell links"))
1066    }
1067
1068    @Test func followsAttachmentAndRadioLinks() throws {
1069        let notes = try Folder()
1070        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"
1071        let a = try notes.write("a.org", text)
1072        let scan = try notes.write("data/ab/12-cd/scan.pdf", "pdf")
1073        let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".r")))
1074        session.open(a.path)
1075        let tree = try #require(session.document?.tree)
1076        func follow(_ needle: String) throws -> LinkFollow {
1077            let link = try #require(Links.link(at: (text as NSString).range(of: needle).location + 1, text: text, tree: tree)?.link)
1078            return session.follow(link, workspace: nil, isText: { $0.hasSuffix(".org") })
1079        }
1080        #expect(try follow("attachment:") == .openExternally(URL(fileURLWithPath: (scan.path as NSString).standardizingPath)))
1081        #expect(try follow("The Plan") == .shown)
1082        #expect(session.revealRequest?.offset == (text as NSString).range(of: "<<<the plan>>>").location)
1083    }
1084}