Tests/OrgAppTests/UserCommandWorkspaceTests.swift

main
orgstar/Tests/OrgAppTests/UserCommandWorkspaceTests.swift

284 lines · 15921 bytes

13 symbols in this file
  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import Testing
  5@testable import OrgApp
  6
  7/// `org.search`, `org.outlineOf`, `org.agenda` and `org.capture` through the real command host.
  8@MainActor
  9@Suite(.serialized)
 10struct UserCommandWorkspaceTests {
 11    static let manifest = """
 12        api = 1
 13
 14        [[command]]
 15        name = "search"
 16        file = "ws.js"
 17        function = "search"
 18        workspace = true
 19
 20        [[command]]
 21        name = "outline"
 22        file = "ws.js"
 23        function = "outline"
 24        workspace = true
 25
 26        [[command]]
 27        name = "agenda"
 28        file = "ws.js"
 29        function = "agenda"
 30        workspace = true
 31
 32        [[command]]
 33        name = "capture"
 34        file = "ws.js"
 35        function = "capture"
 36        workspace = true
 37
 38        [[command]]
 39        name = "buffer-only"
 40        file = "ws.js"
 41        function = "all"
 42        """
 43    /// Each command asks for its arguments and shows what the call gave, or its error.
 44    static let module = """
 45        async function show(org, call) {
 46          try {
 47            await org.message(JSON.stringify(await call()));
 48          } catch (error) {
 49            await org.message("error: " + error.message);
 50          }
 51        }
 52        export const search = org => show(org, async () => org.search(await org.prompt("Query: ")));
 53        export const outline = org => show(org, async () => org.outlineOf(await org.prompt("Path: ")));
 54        export const agenda = org => show(org, async () => org.agenda(JSON.parse(await org.prompt("Span: "))));
 55        export const capture = org => show(org, async () =>
 56          org.capture(await org.prompt("Template: "), await org.prompt("Text: "), JSON.parse(await org.prompt("Fields: "))));
 57        export async function all(org) {
 58          const errors = [];
 59          for (const call of [() => org.search("x"), () => org.outlineOf("todo.org"), () => org.agenda(), () => org.capture("t", "x")]) {
 60            try { await call(); } catch (error) { errors.push(error.message); }
 61          }
 62          await org.message(errors.join(" | "));
 63        }
 64        """
 65    static let todo = """
 66        * Inbox
 67        * Project
 68        ** TODO Write report about milk
 69        SCHEDULED: <2026-11-26 Thu 10:00>
 70        Milk prices for the report.
 71        * TODO Call Sam :phone:
 72
 73        """
 74    static let current = "* Current\nbody\n"
 75
 76    let config: Folder
 77    let notes: Folder
 78    let outside: Folder
 79    let path: String
 80    let workspace: WorkspaceModel
 81    let session: DocumentSession
 82    let buffer: StateBuffer
 83    var access: UserCommandWorkspace
 84
 85    init() async throws {
 86        config = try Folder()
 87        notes = try Folder()
 88        outside = try Folder()
 89        try config.write("commands.toml", Self.manifest)
 90        try config.write("commands/ws.js", Self.module)
 91        try notes.write("todo.org", Self.todo)
 92        try notes.write("sub/deep.org", "#+TITLE: Deep\n* Top\n** Inner :x:\n:PROPERTIES:\n:KIND: deep\n:END:\n")
 93        try notes.write("crypt.org", "* Bank :crypt:\n-----BEGIN PGP MESSAGE-----\n\nhQEMAciphertext\n-----END PGP MESSAGE-----\n")
 94        try OpenPGP.encryptedMessage(Data("* Vault milk\nmilk secret\n".utf8), passphrase: "pw").write(to: notes.url.appendingPathComponent("vault.org.gpg"))
 95        try notes.write("b.org", "* Plain\n")
 96        try outside.write("secret.org", "* Outside secret\n")
 97        try FileManager.default.createSymbolicLink(at: notes.url.appendingPathComponent("link.org"), withDestinationURL: outside.url.appendingPathComponent("secret.org"))
 98        try FileManager.default.createSymbolicLink(at: notes.url.appendingPathComponent("inner.org"), withDestinationURL: notes.url.appendingPathComponent("sub/deep.org"))
 99        path = try notes.write("a.org", Self.current).path
100        workspace = try WorkspaceModel(directory: nil)
101        try await workspace.addRoot(notes.url)
102        await workspace.refresh()
103        session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
104        session.saveMode = .explicit
105        session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
106        session.userCommands = UserCommands()
107        #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
108        session.open(path)
109        buffer = StateBuffer(try #require(session.document))
110        session.attach(buffer)
111        access = UserCommandWorkspace(workspace: workspace, clock: ClockModel(file: notes.url.appendingPathComponent("clock.json"), defaults: TestDefaults("user-command-workspace")))
112        access.templates = {
113            [
114                CaptureTemplate(key: "t", name: "Todo", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %i"),
115                CaptureTemplate(key: "e", name: "Errand", target: .headline(file: "todo.org", headline: "Inbox"), template: "* TODO %^{What} %^g\n%i"),
116                CaptureTemplate(key: "here", name: "Here", target: .file("a.org"), template: "* %i"),
117            ]
118        }
119        let now = try #require(ISO8601DateFormatter().date(from: "2026-11-26T09:00:00Z"))
120        access.now = { now }
121        access.calendar = Calendar(identifier: .gregorian)
122        access.calendar.timeZone = TimeZone(identifier: "UTC")!
123    }
124
125    /// Runs `name` in a.org with `answers` to its prompts, in order; what it showed.
126    func run(_ name: String, _ answers: [String] = [], workspace: Bool = true) async throws -> String {
127        let command = try #require(session.userCommands.command("user." + name))
128        let document = buffer.document
129        let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
130        guard case .external(.userCommand(let request)) = command.run(in: context) else { throw CancellationError() }
131        var answers = answers
132        var shown: [String] = []
133        let message = await session.runUserCommand(request, context: context, file: "a.org", workspace: workspace ? access : nil, ask: { _, reply in
134            reply(answers.isEmpty ? nil : answers.removeFirst())
135        }, report: { shown.append($0) })
136        #expect(message == nil)
137        return shown.joined(separator: "\n")
138    }
139
140    func json(_ text: String) throws -> Any {
141        try JSONSerialization.jsonObject(with: Data(text.utf8))
142    }
143
144    @Test func searchesTheIndex() async throws {
145        let results = try #require(try json(try await run("search", ["milk report"])) as? [[String: Any]])
146        #expect(results.count == 1)
147        let found = try #require(results.first)
148        #expect(found["file"] as? String == "todo.org")
149        #expect(found["title"] as? String == "Write report about milk")
150        #expect(found["outline"] as? [String] == ["Project"])
151        #expect(found["start"] as? Int == (Self.todo as NSString).range(of: "** TODO").location)
152        #expect(found["heading"] as? Bool == true)
153        #expect((found["snippet"] as? String)?.contains("Milk prices") == true)
154        // The text before a file's first heading.
155        let deep = try #require(try json(try await run("search", ["Deep"])) as? [[String: Any]])
156        #expect(deep.contains { $0["file"] as? String == "sub/deep.org" && $0["heading"] as? Bool == false && $0["title"] as? String == "Deep" })
157    }
158
159    @Test func readsAnotherFilesOutline() async throws {
160        let headings = try #require(try json(try await run("outline", ["sub/deep.org"])) as? [[String: Any]])
161        #expect(headings.map { $0["title"] as? String } == ["Top", "Inner"])
162        #expect(headings[1]["level"] as? Int == 2)
163        #expect(headings[1]["tags"] as? [String] == ["x"])
164        #expect(headings[1]["properties"] as? [String: String] == ["KIND": "deep"])
165        // Absolute inside a folder, and a symlink to a file inside one.
166        let absolute = notes.url.appendingPathComponent("todo.org").path
167        #expect((try json(try await run("outline", [absolute])) as? [[String: Any]])?.count == 4)
168        #expect((try json(try await run("outline", ["inner.org"])) as? [[String: Any]])?.count == 2)
169    }
170
171    @Test func refusesFilesOutsideTheFolders() async throws {
172        #expect(try await run("outline", ["link.org"]) == "error: No file link.org in orgstar's folders.")
173        #expect(try await run("outline", ["../" + outside.url.lastPathComponent + "/secret.org"])
174            == "error: No file ../\(outside.url.lastPathComponent)/secret.org in orgstar's folders.")
175        let secret = outside.url.appendingPathComponent("secret.org").path
176        #expect(try await run("outline", [secret]) == "error: No file \(secret) in orgstar's folders.")
177        #expect(try await run("outline", ["/etc/hosts"]) == "error: No file /etc/hosts in orgstar's folders.")
178        #expect(try await run("outline", ["sub"]) == "error: No file sub in orgstar's folders.")
179    }
180
181    @Test func readsTheAgendaForASpan() async throws {
182        let entries = try #require(try json(try await run("agenda", [#"{"from": "2026-11-26", "to": "2026-11-27"}"#])) as? [[String: Any]])
183        let report = try #require(entries.first { $0["title"] as? String == "Write report about milk" })
184        #expect(report["date"] as? String == "2026-11-26")
185        #expect(report["time"] as? String == "10:00")
186        #expect(report["kind"] as? String == "scheduled")
187        #expect(report["file"] as? String == "todo.org")
188        #expect(report["todo"] as? String == "TODO")
189        // A span with nothing in it.
190        #expect((try json(try await run("agenda", [#"{"from": "2026-12-10"}"#])) as? [Any])?.isEmpty == true)
191        #expect(try await run("agenda", [#"{"from": "2026-11-27", "to": "2026-11-26"}"#]) == "error: org.agenda: to is before from.")
192        #expect(try await run("agenda", [#"{"from": "2026-02-30"}"#]) == "error: org.agenda: from must be a date as YYYY-MM-DD.")
193        #expect(try await run("agenda", [#"{"from": "2026-01-01", "to": "2027-06-01"}"#]) == "error: org.agenda: a span of at most 366 days.")
194    }
195
196    @Test func capturesThroughATemplate() async throws {
197        let shown = try json(try await run("capture", ["e", "for the weekend", #"{"What": "Buy bread", "Tags": "shop"}"#])) as? [String: String]
198        #expect(shown == ["template": "e", "file": "todo.org"])
199        let todo = try String(contentsOf: notes.url.appendingPathComponent("todo.org"), encoding: .utf8)
200        #expect(todo.hasPrefix("* Inbox\n** TODO Buy bread "))
201        #expect(todo.contains(" :shop:\nfor the weekend\n* Project\n"))
202        // The buffer the command ran in is as it was, with nothing to undo.
203        #expect(buffer.document.text == Self.current)
204        #expect(!buffer.document.canUndo)
205    }
206
207    @Test func refusesCapturesItCantFill() async throws {
208        #expect(try await run("capture", ["e", "x", "{}"]) == "error: Template \"e\" asks for What, Tags; give them in fields.")
209        #expect(try await run("capture", ["e", "x", #"{"What": "Milk"}"#]) == "error: Template \"e\" asks for Tags; give it in fields.")
210        #expect(try await run("capture", ["zz", "x", "null"]) == "error: No capture template \"zz\".")
211        #expect(try await run("capture", ["e", "x", #"{"What": 1}"#]) == "error: org.capture: field What must be a string.")
212        #expect(try await run("capture", ["here", "x", "null"]) == "error: org.capture can't file to the file the command runs in; return edits instead.")
213        #expect(try String(contentsOf: notes.url.appendingPathComponent("todo.org"), encoding: .utf8) == Self.todo)
214        #expect(buffer.document.text == Self.current)
215    }
216
217    @Test func refusedWithoutWorkspace() async throws {
218        let needs = { (name: String) in "org.\(name) needs workspace = true on the command in commands.toml." }
219        #expect(try await run("buffer-only") == ["search", "outlineOf", "agenda", "capture"].map(needs).joined(separator: " | "))
220        // Where the app gives no access, a command with workspace = true is told so.
221        #expect(try await run("search", ["milk"], workspace: false) == "error: org.search isn't available here.")
222    }
223
224    /// Text encrypted on disk is never returned: not from `.gpg` files, not from buffers
225    /// holding decrypted entries, and not as a snippet of an encrypted entry.
226    @Test func encryptedTextIsNotReturned() async throws {
227        #expect(try await run("outline", ["vault.org.gpg"]) == "error: vault.org.gpg is encrypted, so user commands can't read it.")
228        let milk = try #require(try json(try await run("search", ["milk"])) as? [[String: Any]])
229        #expect(!milk.contains { ($0["file"] as? String)?.hasSuffix(".gpg") == true })
230        let cipher = try #require(try json(try await run("search", ["hQEMAciphertext"])) as? [[String: Any]])
231        #expect(cipher.count == 1 && cipher.first?["title"] as? String == "Bank" && cipher.first?["snippet"] is NSNull)
232
233        // A buffer with an entry decrypted and edited: search and outlines read the file on disk.
234        session.encryptsTaggedEntries = true
235        let other = notes.url.appendingPathComponent("b.org")
236        session.open(other.path)
237        let secret = StateBuffer(try #require(session.document))
238        session.attach(secret)
239        try secret.update { try $0.apply([TextEdit(range: 8..<8, replacement: "* Bank :crypt:\nAccount zebra12345\n")], baseRevision: $0.revision) }
240        session.bufferChanged()
241        #expect(session.openTexts[other.path] == nil)
242        session.open(path)
243        #expect(session.path == path)
244        #expect((try json(try await run("search", ["zebra12345"])) as? [Any])?.isEmpty == true)
245        let outline = try #require(try json(try await run("outline", ["b.org"])) as? [[String: Any]])
246        #expect(outline.map { $0["title"] as? String } == ["Plain"])
247    }
248
249    /// Trust for workspace access is kept apart from trust for the buffer alone.
250    @Test func workspaceAccessAsksForTrustAgain() throws {
251        let modules = config.url.appendingPathComponent("commands")
252        let file = config.url.appendingPathComponent("trusted.json")
253        let trust = TrustStore(file: file)
254        var asked: [UserCommandTrust.Question] = []
255        var runs = 0
256        func check(_ command: UserCommand, _ answer: UserCommandTrust.Answer?, in store: TrustStore) {
257            UserCommandTrust.check(command, modules: modules, trust: store, ask: { question, reply in
258                asked.append(question)
259                reply(answer)
260            }, run: { runs += 1 }, refuse: { _ in })
261        }
262        let bufferOnly = UserCommand(name: "a", title: "A", file: "ws.js", function: "all")
263        let withWorkspace = UserCommand(name: "a", title: "A", file: "ws.js", function: "all", workspace: true)
264        check(bufferOnly, .always, in: trust)
265        check(bufferOnly, nil, in: trust)
266        #expect(runs == 2 && asked == [UserCommandTrust.Question(file: "commands/ws.js")])
267        // `workspace = true` added: asked again, saying what it can read.
268        check(withWorkspace, nil, in: trust)
269        #expect(runs == 2 && asked.last == UserCommandTrust.Question(file: "commands/ws.js", workspace: true))
270        check(withWorkspace, .always, in: trust)
271        #expect(runs == 3 && asked.count == 3)
272        // Kept on the device: both kinds of command run without asking, and the workspace
273        // trust survives the buffer-only one being given again.
274        let relaunched = TrustStore(file: file)
275        check(withWorkspace, nil, in: relaunched)
276        check(bufferOnly, nil, in: relaunched)
277        #expect(runs == 5 && asked.count == 3)
278        // A file trusted only for the buffer, in a fresh store, doesn't cover workspace access.
279        let fresh = TrustStore(file: config.url.appendingPathComponent("other.json"))
280        check(bufferOnly, .always, in: fresh)
281        check(withWorkspace, nil, in: fresh)
282        #expect(runs == 6 && asked.count == 5)
283    }
284}
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