SPB Git

Repository Public License

main.swift 8.2 KB 149 lines swift

1// ORIX OS Automation2// File: Packages/ORIXFeatureCode/Sources/orix-preview-code/main.swift3// Description: Renders every Code Studio screen to PNG files on a throwaway data folder: `orix-preview-code --shot <dir>`. Scripts are really run through the services; approvals are answered automatically here and nowhere else.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AppKit8import ORIXAppUI9import ORIXFeatureCode10import SwiftUI1112@MainActor13enum PreviewRunner {14    static let compact = CGSize(width: 1100, height: 700)15    static let large = CGSize(width: 1600, height: 1000)1617    static func shot(_ name: String, _ studio: CodeStudioModel, _ model: AppModel, in dir: URL, size: CGSize = compact,18                     prepare: (@MainActor () -> Void)? = nil) async throws {19        for dark in [true, false] {20            if let prepare {21                Task { @MainActor in22                    try? await Task.sleep(nanoseconds: 900_000_000)23                    prepare()24                }25            }26            let url = dir.appendingPathComponent("\(name)-\(dark ? "dark" : "light").png")27            try await ShotRenderer.render(CodeStudioView(studio: studio).environment(model), size: size, dark: dark, settle: prepare == nil ? 1.4 : 2.2, to: url)28            print("SHOT \(url.path)")29        }30    }3132    static func makeStudio(_ model: AppModel, open id: String?) async -> CodeStudioModel {33        let studio = CodeStudioModel()34        await studio.workflow.reload(model.services)35        if let id {36            await studio.workflow.open(id, services: model.services)37            model.selectedWorkflowID = id38        }39        return studio40    }4142    static func run(_ dir: URL) async throws {43        let model = try await PreviewEnvironment.make()44        let services = model.services45        // Preview only: every approval request is granted once, so the script runs below are real.46        let approver = Task {47            for await pending in services.approvals.updates() {48                for request in pending { await services.approvals.resolve(id: request.id, response: .approveOnce) }49            }50        }51        defer { approver.cancel() }52        let sample = "system-health-report"5354        // 1. A stored workflow, highlighted.55        var studio = await makeStudio(model, open: sample)56        try await shot("workflow-editor", studio, model, in: dir)57        try await shot("workflow-editor-large", studio, model, in: dir, size: large)5859        // 2. The same with intentional mistakes: squiggles, gutter markers and the problems list.60        studio = await makeStudio(model, open: sample)61        var broken = studio.workflow.text62        broken = broken.replacingOccurrences(of: "tool: system.info", with: "tool: system.infoo")63        broken = broken.replacingOccurrences(of: "maxToolCalls: 15", with: "maxToolCalls: 0")64        studio.workflow.text = broken + "    - id: last\n      needs: [doesNotExist]\n      delay: 1\n"65        await studio.workflow.validateNow()66        let firstError = studio.workflow.diagnostics.first { $0.line > 0 }67        try await shot("workflow-problems", studio, model, in: dir) { [studio] in68            if let d = firstError { studio.workflow.editor.goTo(line: d.line, column: d.column) }69        }7071        // 3. Completion after `tool: `.72        studio = await makeStudio(model, open: nil)73        let typed = WorkflowSnippets.starter + "    - id: read\n      needs: [list]\n      tool: filesystem."74        studio.workflow.startNew(source: typed)75        await studio.workflow.validateNow()76        try await shot("workflow-completion", studio, model, in: dir) { [studio] in77            let end = (studio.workflow.text as NSString).length78            studio.workflow.editor.select(NSRange(location: end, length: 0))79            studio.workflow.editor.triggerCompletion(explicit: true)80            studio.workflow.editor.moveCompletion(4)81        }8283        // 4. Diff of unsaved changes against the stored version, with the semantic change list.84        studio = await makeStudio(model, open: sample)85        var edited = studio.workflow.text86        edited = edited.replacingOccurrences(of: "notifications: true", with: "notifications: true\n    network: [example.com]")87        edited = edited.replacingOccurrences(of: "tool: system.info", with: "tool: system.info\n              timeoutSeconds: 20")88        studio.workflow.text = edited89        studio.diff = studio.workflow.unsavedDiff()90        try await shot("diff", studio, model, in: dir)9192        // 5. The same workflow as JSON.93        studio = await makeStudio(model, open: sample)94        if let json = try? studio.workflow.formatted(as: .json) { studio.workflow.apply(json.text, format: .json) }95        await studio.workflow.validateNow()96        try await shot("workflow-json", studio, model, in: dir)9798        // 6. Script workbench after really running a Python and a Bash script through the tools.99        studio = await makeStudio(model, open: nil)100        studio.tab = .scripts101        studio.scripts.language = .python102        studio.scripts.text = "import platform\n\nvalues = [3, 1, 4, 1, 5, 9, 2, 6]\nprint(f\"Python {platform.python_version()}\")\nprint(\"sum =\", sum(values), \"max =\", max(values))\n"103        let python = await studio.scripts.run(source: studio.scripts.text, defaultWorkspace: model.defaultWorkspace, services: services, console: studio.console)104        print("PYTHON \(python?.status.rawValue ?? "nil") exit=\(python?.exitCode.map(String.init) ?? "nil") \(python?.message ?? "")")105        studio.scripts.language = .bash106        studio.scripts.text = "#!/bin/bash\nset -euo pipefail\n\necho \"Working in $(basename \"$(pwd)\")\"\nfor n in 1 2 3; do\n    printf 'step %s of 3\\n' \"$n\"\ndone\nprintf '\\033[32mall steps done\\033[0m\\n'\nprintf '\\033[33mwarning: nothing was written\\033[0m\\n' >&2\n"107        let bash = await studio.scripts.run(source: studio.scripts.text, defaultWorkspace: model.defaultWorkspace, services: services, console: studio.console)108        print("BASH \(bash?.status.rawValue ?? "nil") exit=\(bash?.exitCode.map(String.init) ?? "nil") \(bash?.message ?? "")")109        try await shot("script-workbench", studio, model, in: dir)110111        // 7. The assistant panel beside the editor (idle: nothing is sent by a preview).112        studio = await makeStudio(model, open: sample)113        studio.showAssistant = true114        try await shot("assistant", studio, model, in: dir)115116        // 8. Tool documentation card.117        studio = await makeStudio(model, open: sample)118        studio.toolDoc = studio.workflow.tools.first { $0.identifier == "filesystem.write" }119        try await shot("tool-docs", studio, model, in: dir)120121        // 9. Save as skill, after a real proposal (analysis + sandboxed tests).122        let form = SkillFormModel(language: .python, source: ScriptTemplates.templates(.python).first { $0.id == "python.skill" }?.body ?? "")123        form.name = "Count words"124        form.summary = "Counts the words and characters of a text."125        form.inputSchemaJSON = "{\n  \"type\": \"object\",\n  \"properties\": { \"text\": { \"type\": \"string\" } },\n  \"required\": [\"text\"],\n  \"additionalProperties\": false\n}"126        form.tests = [SkillTestDraft(name: "two words", inputJSON: "{\"text\": \"hello world\"}", expectSucceeded: true, expectOutputJSON: "{\"words\": 2}")]127        await form.submit(services)128        print("SKILL draft=\(form.draft?.id ?? "nil") installable=\(form.draft?.installable ?? false) problems=\(form.problems)")129        for dark in [true, false] {130            let url = dir.appendingPathComponent("skill-form-\(dark ? "dark" : "light").png")131            try await ShotRenderer.render(SkillFormView(form: form, onClose: {}, openSkills: {}).environment(model), size: CGSize(width: 640, height: 640), dark: dark, to: url)132            print("SHOT \(url.path)")133        }134    }135}136137_ = NSApplication.shared138let arguments = CommandLine.arguments139guard let flag = arguments.firstIndex(of: "--shot"), flag + 1 < arguments.count else {140    print("usage: orix-preview-code --shot <directory>")141    exit(2)142}143let directory = URL(fileURLWithPath: arguments[flag + 1])144Task { @MainActor in145    do { try await PreviewRunner.run(directory); exit(0) }146    catch { print("FAILED \(error)"); exit(1) }147}148RunLoop.main.run()149
Files main
Menu

Theme