SPB Git

Repository Public License

main.swift 14.4 KB 255 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX OS Automation9// File             : Packages/ORIXFeatureRuns/Sources/orix-preview-runs/main.swift10// Description      : Renders every screen of the Runs feature package to PNG on11//                    a throwaway data folder: `swift run orix-preview-runs12//                    --shot <dir>`.13// Module           : orix-preview-runs14// Repository       : https://git.spboucher.ai/orix-automation15// Created          : 2026-11-2116// Last Modified    : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : Proprietary, all rights reserved (see license file)83// License File     : LICENSE84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import AppKit92import CryptoKit93import ORIXAppUI94@_spi(Preview) import ORIXFeatureRuns95import SwiftUI9697/// Runs a short real bash script through the tool executor (policy, approval, confinement and all), streaming its98/// output to the live hub the console listens to. Approvals are answered automatically: this is a development harness.99@MainActor100func runRealScript(_ model: AppModel, console: ConsoleModel) async throws -> String {101    let s = model.services102    let runID = UUID().uuidString103    let artifacts = s.paths.artifacts.appendingPathComponent(runID)104    try FileManager.default.createDirectory(at: artifacts, withIntermediateDirectories: true)105    var record = RunRecord(id: runID, kind: "script", title: "Sample · Disk and folder report (real shell.script run)", trigger: "manual", mode: .guided,106                           status: .running, startedAt: Date())107    try await s.store.saveRun(record)108    await console.start(runID: runID, services: s)109110    let approver = Task {111        for await pending in s.approvals.updates() { for r in pending { await s.approvals.resolve(id: r.id, response: .approveOnce) } }112    }113    let script = """114    echo "Checking the workspace"115    for i in 1 2 3 4 5; do echo "step $i of 5: $(date +%H:%M:%S)"; sleep 0.15; done116    echo "a warning written to standard error" >&2117    ls -1 /usr/share/dict | head -5118    df -h / | tail -1119    echo "done"120    """121    let hub = s.runs.live122    hub.publish(runID, .status(.running))123    let call = ToolCall(toolID: "shell.script", arguments: ["script": .string(script)])124    hub.publish(runID, .toolStarted(call))125    let context = InvocationContext(runID: runID, mode: .guided, workingDirectory: s.paths.scratch, artifactsDirectory: artifacts,126                                    progress: { callID, p in hub.publish(runID, .toolProgress(callID: callID, p)) })127    let result = await s.executor.invoke(call, context: context)128    hub.publish(runID, .toolFinished(call, result))129    approver.cancel()130131    // A real artifact with a real checksum, and a check that is actually performed.132    let report = artifacts.appendingPathComponent("report.txt")133    try Data((result.output["stdout"]?.stringValue ?? result.summary).utf8).write(to: report)134    let data = try Data(contentsOf: report)135    let sha = SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()136    let exists = FileManager.default.fileExists(atPath: report.path)137    record.status = result.status == .succeeded ? .succeeded : .failed138    record.endedAt = Date(); record.usage.toolCalls = 1139    record.errorSummary = result.failure?.message140    try await s.store.saveRun(record)141    try await s.store.saveReceipt(RunReceipt(142        runID: runID, title: record.title, status: record.status, objective: "Run a short bash script and keep its output as a report.", model: nil,143        startedAt: record.startedAt ?? Date(), endedAt: record.endedAt ?? Date(), usage: record.usage,144        toolCalls: [ToolCallRecord(id: call.id, toolID: call.toolID, arguments: ["script": "(bash, 6 lines)"], status: result.status, summary: result.summary,145                                   durationMs: result.durationMs, tier: .consequential)],146        approvals: ["Approved once by the preview harness"], permissionsUsed: ["shell.script (bash)"],147        artifacts: [Artifact(path: report.path, kind: "report", bytes: data.count, sha256: sha),148                    Artifact(path: artifacts.appendingPathComponent("removed-later.log").path, kind: "log", bytes: 120, note: "Deleted after the run")],149        verifications: [VerificationResult(assertion: "report.txt exists in the run's artifacts folder", kind: "file_exists", passed: exists, evidence: exists ? "found, \(data.count) bytes" : "not found")],150        agentSummary: "", limitations: ["The script ran confined: it could not write outside its artifacts folder."]))151    hub.publish(runID, .finished(record.status))152    hub.finish(runID)153    try? await Task.sleep(nanoseconds: 400_000_000)154    await console.refreshPersisted()155    return runID156}157158@MainActor159func shoot<V: View>(_ name: String, _ view: V, _ model: AppModel, size: CGSize, dir: URL, settle: Double = 1.4) async {160    for dark in [true, false] {161        let url = dir.appendingPathComponent("\(name)-\(dark ? "dark" : "light").png")162        do { try await ShotRenderer.render(view.environment(model), size: size, dark: dark, settle: settle, to: url); print("SHOT \(url.path)") }163        catch { print("FAILED \(name): \(error)") }164    }165}166167@MainActor168func main() async {169    let args = CommandLine.arguments170    guard let i = args.firstIndex(of: "--shot"), args.count > i + 1 else { print("usage: orix-preview-runs --shot <dir>"); exit(2) }171    let dir = URL(fileURLWithPath: args[i + 1])172    do {173        let model = try await PreviewEnvironment.make()174        let s = model.services175        let wide = CGSize(width: 1280, height: 820)176177        // Console: real output streamed while the model listens.178        let console = ConsoleModel()179        let scriptRun = try await runRealScript(model, console: console)180        await shoot("console-live", RunsPreviewScreens.console(console).padding(16), model, size: CGSize(width: 1100, height: 560), dir: dir)181        console.query = "step"182        await shoot("console-search", RunsPreviewScreens.console(console).padding(16), model, size: CGSize(width: 1100, height: 560), dir: dir)183        console.stop()184185        // A run that needs recovery, and richer usage on one sample, so those states are visible.186        if var r = try await s.store.run(id: "sample-5") {187            r.usage.tokens = TokenUsage(inputTokens: 36_000, outputTokens: 1_500, cacheReadTokens: 12_000, cacheWriteTokens: 4_000)188            r.usage.costIsComplete = false189            try await s.store.saveRun(r)190        }191        try await s.store.saveRun(RunRecord(id: "sample-recovery", kind: "agent", title: "Sample · Rename scanned invoices", trigger: "manual", mode: .guided,192                                            status: .recoveryRequired, model: ModelRef(provider: .anthropic, model: "claude-haiku-5-5"),193                                            startedAt: Date().addingTimeInterval(-900), endedAt: Date().addingTimeInterval(-840)))194195        // A checkpoint with an action in flight, written the way the runtime stores it, so the recovery choices show.196        let task = AgentTask(objective: "Rename the scanned invoices in ~/Documents/Invoices by date", workingDirectory: s.paths.scratch.path)197        let inFlight = ToolCall(toolID: "filesystem.move", arguments: ["source": "scan-014.pdf", "destination": "2026-11-03-invoice.pdf"])198        let checkpoint: JSONValue = ["runID": "sample-recovery", "task": try JSONValue.encoding(task), "profile": try JSONValue.encoding(BuiltInAgents.all[0]),199                                     "messages": [], "usage": try JSONValue.encoding(RunUsage()), "toolCalls": [], "turn": 4,200                                     "inFlightCall": try JSONValue.encoding(inFlight), "savedAt": try JSONValue.encoding(Date()), "modelVersion": 1]201        if let cp = try? checkpoint.decode(AgentCheckpoint.self) {202            try await s.store.put(cp, collection: Collections.agentCheckpoints, id: "sample-recovery")203        } else { print("NOTE: could not build a sample checkpoint; the recovery sheet shows its no-checkpoint state") }204205        // Two real schedules, created through services.206        let workflows = await s.workflows.list()207        if workflows.count >= 2 {208            try await s.workflows.saveSchedule(Schedule(workflowID: workflows[0].id, name: workflows[0].name, trigger: .cron(expression: "0 9 * * MON", timezone: "America/Toronto"),209                                                        enabled: true, missedRunPolicy: .runOnce, concurrency: .skipIfRunning, maxRetries: 2))210            try await s.workflows.saveSchedule(Schedule(workflowID: workflows[1].id, name: workflows[1].name,211                                                        trigger: .fileChange(path: NSHomeDirectory() + "/Documents/Research", recursive: true, glob: "*.pdf", debounceSeconds: 5),212                                                        enabled: true, concurrency: .queue))213            try await s.workflows.saveSchedule(Schedule(workflowID: workflows[1].id, name: workflows[1].name, trigger: .cron(expression: "30 7,18 * * *", timezone: "Europe/Paris"), enabled: true))214        }215        await model.refreshShared()216217        await shoot("dashboard", DashboardView(), model, size: CGSize(width: 1280, height: 1560), dir: dir, settle: 2.0)218        await shoot("dashboard-compact", DashboardView(), model, size: CGSize(width: 1100, height: 700), dir: dir, settle: 2.0)219        model.selectedRunID = "sample-0"220        await shoot("runs-timeline", RunsPreviewScreens.runs(tab: "timeline"), model, size: wide, dir: dir)221        model.selectedRunID = scriptRun222        await shoot("runs-receipt", RunsPreviewScreens.runs(tab: "receipt"), model, size: CGSize(width: 1280, height: 1100), dir: dir)223        await shoot("runs-console", RunsPreviewScreens.runs(tab: "console"), model, size: wide, dir: dir)224        model.selectedRunID = "sample-5"225        await shoot("runs-usage", RunsPreviewScreens.runs(tab: "usage"), model, size: CGSize(width: 1280, height: 1000), dir: dir)226        model.selectedRunID = "sample-recovery"227        await shoot("runs-recovery", RunsPreviewScreens.runs(tab: "timeline"), model, size: wide, dir: dir)228        if let r = try await s.store.run(id: "sample-recovery") {229            await shoot("recovery-sheet", RunsPreviewScreens.recovery(r), model, size: CGSize(width: 560, height: 520), dir: dir)230        }231        await shoot("scheduler-list", RunsPreviewScreens.scheduler(tab: "schedules"), model, size: wide, dir: dir)232        await shoot("scheduler-agenda", RunsPreviewScreens.scheduler(tab: "agenda"), model, size: CGSize(width: 1280, height: 1000), dir: dir)233        await shoot("scheduler-queue", RunsPreviewScreens.scheduler(tab: "queue"), model, size: wide, dir: dir)234        let schedules = await s.workflows.schedules()235        await shoot("schedule-editor", RunsPreviewScreens.scheduleEditor(existing: schedules.first { $0.enabled }, workflows: workflows), model,236                    size: CGSize(width: 640, height: 720), dir: dir)237238        let empty = try await PreviewEnvironment.make(seed: false)239        await shoot("dashboard-empty", DashboardView(), empty, size: wide, dir: dir)240        await shoot("runs-empty", RunsView(), empty, size: wide, dir: dir)241        await shoot("scheduler-empty", SchedulerView(), empty, size: wide, dir: dir)242        try? FileManager.default.removeItem(at: s.paths.root)243        try? FileManager.default.removeItem(at: empty.services.paths.root)244    } catch {245        print("FAILED: \(error)")246        exit(1)247    }248    exit(0)249}250251setvbuf(stdout, nil, _IONBF, 0)252_ = NSApplication.shared253Task { await main() }254RunLoop.main.run()255
Files main
Menu

Theme