Tests/OrgAppTests/UserCommandRunTests.swift

4d8e517de5aef10e915fb482735feba5435a4a21
orgstar/Tests/OrgAppTests/UserCommandRunTests.swift

476 lines · 22830 bytes

22 symbols in this file
  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import Testing
  5@testable import OrgApp
  6
  7/// User commands run through the real command host against a session's buffer.
  8@MainActor
  9@Suite(.serialized)
 10struct UserCommandRunTests {
 11    static let manifest = """
 12        api = 1
 13
 14        [[command]]
 15        name = "upcase-title"
 16        title = "Upcase Heading Title"
 17        file = "headings.js"
 18        function = "upcaseTitle"
 19        when = "heading"
 20
 21        [[command]]
 22        name = "weekly-review"
 23        title = "Add Weekly Review"
 24        file = "review.js"
 25        function = "weeklyReview"
 26
 27        [[command]]
 28        name = "overlap"
 29        file = "bad.js"
 30        function = "overlap"
 31
 32        [[command]]
 33        name = "loop"
 34        file = "bad.js"
 35        function = "loop"
 36        timeout = 1
 37
 38        [[command]]
 39        name = "refuse"
 40        file = "bad.js"
 41        function = "refuse"
 42
 43        [[command]]
 44        name = "copy"
 45        file = "bad.js"
 46        function = "copy"
 47
 48        [[command]]
 49        name = "compose"
 50        file = "run.js"
 51        function = "compose"
 52
 53        [[command]]
 54        name = "schedule"
 55        file = "run.js"
 56        function = "schedule"
 57
 58        [[command]]
 59        name = "promote"
 60        title = "Promote"
 61        file = "run.js"
 62        function = "promote"
 63
 64        [[command]]
 65        name = "refused"
 66        file = "run.js"
 67        function = "refused"
 68
 69        [[command]]
 70        name = "save"
 71        file = "run.js"
 72        function = "save"
 73
 74        [[command]]
 75        name = "edit-while-running"
 76        file = "run.js"
 77        function = "editWhileRunning"
 78        """
 79    static let headings = """
 80        import { upper } from "./lib/text.js";
 81
 82        export async function upcaseTitle(org) {
 83          const heading = await org.heading();
 84          if (!heading) return org.fail("Not in an entry");
 85          const text = await org.text();
 86          const title = text.slice(heading.titleStart, heading.titleEnd);
 87          return {
 88            edits: [{ from: heading.titleStart, to: heading.titleEnd, text: upper(title) }],
 89            message: `Upcased ${title}`,
 90          };
 91        }
 92        """
 93    static let review = """
 94        export async function weeklyReview(org) {
 95          const heading = await org.heading();
 96          if (!heading) return org.fail("Not on a heading");
 97          const week = await org.prompt({ message: "Week: ", initial: "W48" });
 98          return {
 99            edits: [{ from: heading.end, to: heading.end, text: `${"*".repeat(heading.level + 1)} Review ${week}\\n` }],
100            selection: heading.end + heading.level + 2,
101          };
102        }
103        """
104    static let bad = """
105        export function overlap() { return { edits: [{ from: 0, to: 4 }, { from: 2, to: 6 }] }; }
106        export function loop() { for (;;) {} }
107        export async function refuse(org) { await org.fail("Not today"); }
108        export async function copy(org) { org.message("Copying"); return { copy: (await org.file()) ?? "none" }; }
109        """
110    static let builtIns = """
111        export async function compose(org) {
112          await org.run("org.todo.cycle");
113          await org.run("org.todo.cycle");
114          const { text, selection: [{ from }] } = await org.run("org.heading.insert");
115          if (text !== await org.text()) return org.fail("org.text() isn't the text org.run gave");
116          return { edits: [{ from, text: "New" }] };
117        }
118        export async function schedule(org) {
119          await org.run("org.schedule");
120          await org.message((await org.heading()).scheduled);
121        }
122        export async function promote(org) {
123          try {
124            await org.run("org.heading.promote");
125          } catch (error) {
126            org.message("caught " + error.message);
127          }
128          await org.run("org.heading.promote");
129        }
130        export async function refused(org) {
131          const messages = [];
132          for (const id of ["app.export.html", "user.compose", "org.cycle", "org.babel.execute"]) {
133            try {
134              await org.run(id);
135              messages.push("ran " + id);
136            } catch (error) {
137              messages.push(error.message);
138            }
139          }
140          await org.message(messages.join(" | "));
141        }
142        export async function save(org) {
143          await org.run("org.todo.cycle");
144          const { text } = await org.run("app.save");
145          await org.message(text.slice(0, 6));
146        }
147        export async function editWhileRunning(org) {
148          await org.run("org.todo.cycle");
149          await org.prompt("Go on? ");
150        }
151        """
152    static let file = "* Plan the week :work:\nbody\n* Next\n"
153
154    let config: Folder
155    let notes: Folder
156    let path: String
157    let session: DocumentSession
158    let buffer: StateBuffer
159
160    init() throws {
161        config = try Folder()
162        notes = try Folder()
163        try config.write("commands.toml", Self.manifest)
164        try config.write("commands/headings.js", Self.headings)
165        try config.write("commands/lib/text.js", "export const upper = s => s.toUpperCase();\n")
166        try config.write("commands/review.js", Self.review)
167        try config.write("commands/bad.js", Self.bad)
168        try config.write("commands/run.js", Self.builtIns)
169        path = try notes.write("a.org", Self.file).path
170        session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
171        session.saveMode = .explicit
172        session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
173        session.userCommands = UserCommands()
174        #expect(UserCommandFile.load(into: session.userCommands, folder: config.url) == [])
175        session.open(path)
176        buffer = StateBuffer(try #require(session.document))
177        session.attach(buffer)
178    }
179
180    func run(_ name: String, at caret: Int = 4, ask: @escaping @MainActor (Prompt, @escaping (String?) -> Void) -> Void = { _, reply in reply(nil) },
181             report: @escaping @MainActor (String) -> Void = { _ in }) async throws -> String? {
182        let command = try #require(session.userCommands.command("user." + name))
183        let document = buffer.document
184        let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [caret..<caret])
185        guard case .external(.userCommand(let request)) = command.run(in: context) else { throw CancellationError() }
186        return await session.runUserCommand(request, context: context, file: "a.org", ask: ask, report: report)
187    }
188
189    @Test func upcasesTheHeadingTitle() async throws {
190        #expect(try await run("upcase-title") == nil)
191        #expect(buffer.document.text == "* PLAN THE WEEK :work:\nbody\n* Next\n")
192        // Before the first heading, `org.fail`'s text.
193        _ = buffer.perform(ReplaceText(old: buffer.document.text, new: "intro\n" + Self.file), now: Date(), answers: [:])
194        #expect(try await run("upcase-title", at: 0) == "Not in an entry")
195    }
196
197    @Test func asksThroughThePrompt() async throws {
198        var asked: Prompt?
199        let message = try await run("weekly-review", ask: { prompt, reply in
200            asked = prompt
201            reply("W49")
202        })
203        #expect(message == nil)
204        #expect(asked == Prompt(key: "user", message: "Week: ", initial: "W48", requireMatch: false))
205        #expect(buffer.document.text == "* Plan the week :work:\nbody\n** Review W49\n* Next\n")
206        #expect(buffer.selection == [31..<31])
207        // A canceled prompt ends the command with nothing changed.
208        #expect(try await run("weekly-review") == "Quit")
209        #expect(buffer.document.text == "* Plan the week :work:\nbody\n** Review W49\n* Next\n")
210    }
211
212    @Test func anEditWhileItRanRefusesItsResult() async throws {
213        let message = try await run("weekly-review", ask: { [buffer] _, reply in
214            _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
215            reply("W49")
216        })
217        #expect(message == "The file changed; try again.")
218        #expect(buffer.document.text == Self.file + "typed\n")
219    }
220
221    @Test func refusesWhatCantApply() async throws {
222        #expect(try await run("overlap") == "overlap: edits overlap")
223        #expect(try await run("refuse") == "Not today")
224        let start = ContinuousClock.now
225        #expect(try await run("loop") == "loop didn't finish within 1 s and was stopped.")
226        #expect(ContinuousClock.now - start < .seconds(10))
227        #expect(buffer.document.text == Self.file)
228        var reported: [String] = []
229        #expect(try await run("copy", report: { reported.append($0) }) == nil)
230        #expect(reported == ["Copying"])
231    }
232
233    // MARK: - org.run
234
235    /// The commands a script runs and its own edits after them are one undo step, with the text
236    /// and selection that running the same commands directly gives.
237    @Test func runningBuiltInsIsOneUndoStep() async throws {
238        let direct = StateBuffer(DocumentState(bytes: Array(Self.file.utf8)))
239        direct.selection = [4..<4]
240        for id in ["org.todo.cycle", "org.todo.cycle", "org.heading.insert"] {
241            guard case .commit = direct.perform(try #require(Commands.command(id)), now: Date(), answers: [:]) else {
242                Issue.record("\(id) didn't commit")
243                return
244            }
245        }
246        let caret = direct.selection[0].lowerBound
247        #expect(try await run("compose") == nil)
248        #expect(buffer.document.text == (direct.document.text as NSString).replacingCharacters(in: NSRange(location: caret, length: 0), with: "New"))
249        #expect(buffer.document.text.hasPrefix("* DONE Pl"))
250        #expect(buffer.selection == [caret + 3..<caret + 3])
251        #expect(buffer.update { $0.undo() } != nil)
252        #expect(buffer.document.text == Self.file)
253        #expect(!buffer.document.canUndo)
254    }
255
256    /// A built-in command's prompt goes through the prompt the command's own prompts use.
257    @Test func aBuiltInsPromptGoesThroughThePrompt() async throws {
258        var asked: [Prompt] = []
259        var reported: [String] = []
260        let message = try await run("schedule", ask: { prompt, reply in
261            asked.append(prompt)
262            reply("2026-12-01")
263        }, report: { reported.append($0) })
264        #expect(message == nil)
265        #expect(asked.count == 1 && asked.first?.key == "date" && asked.first?.date != nil)
266        let scheduled = "* Plan the week :work:\nSCHEDULED: <2026-12-01 Tue>\nbody\n* Next\n"
267        #expect(buffer.document.text == scheduled)
268        #expect(reported == ["<2026-12-01 Tue>"])
269        // Canceling it ends the command with nothing changed.
270        #expect(try await run("schedule") == "Quit")
271        #expect(buffer.document.text == scheduled)
272    }
273
274    /// A failing built-in rejects with its message, which the script can catch.
275    @Test func aFailingBuiltInRejectsWithItsMessage() async throws {
276        let document = buffer.document
277        let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [4..<4])
278        guard case .failed(let failure) = PromoteHeading().run(in: context) else {
279            Issue.record("promoting a level 1 heading didn't fail")
280            return
281        }
282        var reported: [String] = []
283        #expect(try await run("promote", report: { reported.append($0) }) == "Promote: \(failure)")
284        #expect(reported == ["caught \(failure)"])
285        #expect(buffer.document.text == Self.file)
286    }
287
288    /// Commands of the app other than the safe ones, user commands, the editor's own commands
289    /// and work outside the text are refused.
290    @Test func refusesWhatIsntABuiltInCommand() async throws {
291        let block = "#+begin_src sh\necho hi\n#+end_src\n"
292        _ = buffer.perform(ReplaceText(old: buffer.document.text, new: block), now: Date(), answers: [:])
293        let document = buffer.document
294        let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [2..<2])
295        guard case .external(.babel) = ExecuteSrcBlock().run(in: context) else {
296            Issue.record("the block doesn't run through Babel")
297            return
298        }
299        var reported: [String] = []
300        #expect(try await run("refused", at: 2, report: { reported.append($0) }) == nil)
301        #expect(reported == [[
302            "app.export.html is a command of the app, which user commands can't run",
303            "A user command can't run another: user.compose",
304            "No built-in command org.cycle",
305            UserCommandAPI.external("org.babel.execute").message,
306        ].joined(separator: " | ")])
307        #expect(buffer.document.text == block)
308    }
309
310    /// `app.save` saves the file once the command's changes are applied.
311    @Test func saveRunsAfterTheChanges() async throws {
312        var reported: [String] = []
313        #expect(try await run("save", report: { reported.append($0) }) == nil)
314        #expect(reported == ["* TODO"])
315        #expect(buffer.document.text.hasPrefix("* TODO Plan"))
316        #expect(!buffer.document.isDirty)
317        #expect(try String(contentsOfFile: path, encoding: .utf8) == buffer.document.text)
318    }
319
320    @Test func anEditWhileRunningRefusesWhatItsCommandsDid() async throws {
321        let message = try await run("edit-while-running", ask: { [buffer] _, reply in
322            _ = buffer.perform(ReplaceText(old: buffer.document.text, new: buffer.document.text + "typed\n"), now: Date(), answers: [:])
323            reply("yes")
324        })
325        #expect(message == "The file changed; try again.")
326        #expect(buffer.document.text == Self.file + "typed\n")
327    }
328
329    @Test func cancelStopsTheCommand() async throws {
330        let document = buffer.document
331        let command = try #require(session.userCommands.command("user.loop"))
332        let request = UserCommandRequest(command: command, revision: document.revision, selection: [0..<0])
333        let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [0..<0])
334        var reported: [String] = []
335        session.startUserCommand(request, context: context, file: nil, ask: { _, reply in reply(nil) }) { reported.append($0) }
336        #expect(session.isRunningUserCommand)
337        try await Task.sleep(for: .milliseconds(200))
338        session.cancelUserCommand()
339        for _ in 0..<100 where reported.isEmpty { try await Task.sleep(for: .milliseconds(20)) }
340        #expect(reported == ["loop canceled."])
341        #expect(!session.isRunningUserCommand)
342    }
343
344    @Test func refusedInBuffersWithDecryptedText() async throws {
345        let gpg = notes.url.appendingPathComponent("d.org.gpg")
346        try OpenPGP.encryptedMessage(Data("* Secret\n".utf8), passphrase: "pw").write(to: gpg)
347        session.open(gpg.path)
348        #expect(session.unlock("pw", for: gpg.path) == nil)
349        #expect(session.refusesUserCommand(gpg.path) == "d.org.gpg has decrypted entries, so user commands don't run in it.")
350        let document = try #require(session.document)
351        let command = try #require(session.userCommands.command("user.upcase-title"))
352        let context = EditContext(revision: document.revision, text: document.text, tree: document.tree, selection: [3..<3])
353        let request = UserCommandRequest(command: command, revision: document.revision, selection: [3..<3])
354        #expect(await session.runUserCommand(request, context: context, file: nil, ask: { _, _ in }, report: { _ in })
355            == "d.org.gpg has decrypted entries, so user commands don't run in it.")
356        #expect(session.document?.text == "* Secret\n")
357        #expect(session.refusesUserCommand(path) == nil)
358    }
359}
360
361@MainActor
362struct UserCommandFileTests {
363    @Test func reportsProblemsByFile() throws {
364        let config = try Folder()
365        let store = UserCommands()
366        #expect(UserCommandFile.load(into: store, folder: config.url) == [])
367        try config.write("commands.toml", "api = 1\n[[command]]\nname = \"a\"\nfile = \"a.js\"\nfunction = \"a\"\n")
368        #expect(UserCommandFile.load(into: store, folder: config.url) == ["commands.toml: command a: no file commands/a.js"])
369        #expect(store.all.isEmpty && store.folder == nil)
370        try config.write("commands/a.js", "export function a() {}\n")
371        #expect(UserCommandFile.load(into: store, folder: config.url) == [])
372        #expect(store.all.map(\.id) == ["user.a"])
373        #expect(store.folder?.lastPathComponent == "commands")
374        try config.write("commands.toml", "api = 1\n[[command]\n")
375        #expect(UserCommandFile.load(into: store, folder: config.url) == ["commands.toml: line 2: unclosed table header"])
376        #expect(store.all.isEmpty)
377    }
378
379    @Test func importsResolveInsideTheFolder() {
380        let text = """
381            import { a } from "./a.js";
382            import * as b from '../b.js';
383            export { c } from "./lib/c.mjs";
384            import "./side.js";
385            const d = await import("./d.js");
386            import e from "https://example.com/e.js";
387            """
388        #expect(UserCommandFile.imports(text, from: "sub/main.js").sorted() == ["b.js", "sub/a.js", "sub/d.js", "sub/lib/c.mjs", "sub/side.js"])
389        #expect(UserCommandFile.imports("import x from '../../x.js';", from: "main.js") == [])
390    }
391
392    @Test func relativePath() {
393        #expect(UserCommandFile.relativePath("/n/notes/a/b.org", roots: ["/n", "/n/notes"]) == "a/b.org")
394        #expect(UserCommandFile.relativePath("/elsewhere/c.org", roots: ["/n"]) == "c.org")
395    }
396
397    /// Always keeps trust for the file and its imports as they are; a change to either, as one
398    /// arriving by sync, asks again.
399    @Test func aChangedScriptAsksForTrustAgain() throws {
400        let config = try Folder()
401        try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return x; }\n")
402        try config.write("commands/lib.js", "export const x = null;\n")
403        let modules = config.url.appendingPathComponent("commands")
404        let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
405        let command = UserCommand(name: "go", title: "Go", file: "main.js", function: "go")
406        var asked: [UserCommandTrust.Question] = []
407        var runs = 0
408        var refusals: [String] = []
409        func check(_ answer: UserCommandTrust.Answer?) {
410            UserCommandTrust.check(command, modules: modules, trust: trust, ask: { question, reply in
411                asked.append(question)
412                reply(answer)
413            }, run: { runs += 1 }, refuse: { refusals.append($0) })
414        }
415        check(.dontRun)
416        #expect(runs == 0 && refusals == ["Not run"])
417        #expect(asked == [UserCommandTrust.Question(file: "commands/main.js", imports: ["commands/lib.js"])])
418        check(.runOnce)
419        check(.runOnce)
420        #expect(runs == 2 && asked.count == 3)
421        check(.always)
422        check(nil)
423        #expect(runs == 4 && asked.count == 4)
424        try config.write("commands/lib.js", "export const x = 1;\n")
425        check(.always)
426        #expect(runs == 5 && asked.count == 5)
427        try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return 2; }\n")
428        check(nil)
429        #expect(runs == 5 && asked.count == 6 && refusals == ["Not run", "Not run"])
430        // Back to a version trusted before, it runs without asking.
431        try config.write("commands/main.js", "import { x } from \"./lib.js\";\nexport function go() { return x; }\n")
432        check(nil)
433        #expect(runs == 6)
434        #expect(UserCommandFile.trustedText("gone.js", modules: modules) == nil)
435        #expect(UserCommandFile.trustedText("main.js", modules: modules)
436            == "// lib.js\nexport const x = 1;\n\n// main.js\nimport { x } from \"./lib.js\";\nexport function go() { return x; }\n")
437    }
438
439    /// The question names the file and every module it imports, through other modules too;
440    /// one that can't be read isn't listed.
441    @Test func theTrustQuestionListsTheImportedModules() throws {
442        let config = try Folder()
443        try config.write("commands/tools/main.js", "import { a } from \"../lib/a.js\";\nimport \"./gone.js\";\nexport function go() {}\n")
444        try config.write("commands/lib/a.js", "export { b } from \"./b.js\";\nexport const a = 1;\n")
445        try config.write("commands/lib/b.js", "export const b = 2;\n")
446        let modules = config.url.appendingPathComponent("commands")
447        let trust = TrustStore(file: config.url.appendingPathComponent("trusted.json"))
448        var asked: [UserCommandTrust.Question] = []
449        UserCommandTrust.check(UserCommand(name: "go", title: "Go", file: "tools/main.js", function: "go"), modules: modules, trust: trust,
450                               ask: { question, _ in asked.append(question) }, run: {}, refuse: { _ in })
451        #expect(asked == [UserCommandTrust.Question(file: "commands/tools/main.js", imports: ["commands/lib/a.js", "commands/lib/b.js"])])
452        #expect(asked.first?.title == "Run commands from commands/tools/main.js?")
453
454        let question = UserCommandTrust.Question(file: "commands/review.js", imports: ["commands/lib/dates.js"])
455        #expect(question.message == """
456            It imports commands/lib/dates.js.
457            They can read and change the file you run them in, and nothing else: no other files and no network.
458            """)
459        #expect(UserCommandTrust.Question(file: "commands/review.js").message
460            == "They can read and change the file you run them in, and nothing else: no other files and no network.")
461        #expect(UserCommandTrust.Question(file: "commands/review.js", workspace: true).message
462            == "They can read and change the file you run them in, read every file in your folders and capture to them, but not use the network.")
463    }
464
465    @Test func emacsImportNotesBindingsToTheUsersFunctions() throws {
466        let folder = try Folder()
467        try folder.write("init.el", """
468            (defun my/weekly-review () (interactive) (org-insert-heading))
469            (global-set-key (kbd "C-c w") #'my/weekly-review)
470            (global-set-key (kbd "C-c q") #'some-package-command)
471            """)
472        let result = EmacsImport.scan(EmacsImport.files(in: folder.url))
473        #expect(result.unsupported.contains { $0.name == "C-c w → my/weekly-review" && $0.reason == "your own function; write it as a user command in commands.toml" })
474        #expect(result.unsupported.contains { $0.name == "C-c q → some-package-command" && $0.reason == "orgstar has no such command" })
475    }
476}
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