SPB Git

Repository Public License

main.swift 15.1 KB 253 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX OS Automation9// File             : Packages/ORIXFeatureManage/Sources/orix-preview-manage/main.swift10// Description      : Renders every screen of the management sections (Settings,11//                    Permissions, Agents, Skills, Onboarding, Watch & Learn) to12//                    PNG files on a throwaway data folder.13// Module           : orix-preview-manage14// 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 ORIXAppUI93import ORIXFeatureManage94import SwiftUI9596/// An obviously fake key, stored only in the preview Keychain service while the provider screens render, then deleted.97let previewKey = "sk-test-0000000000000000"9899@MainActor100func shot<V: View>(_ name: String, _ view: V, _ model: AppModel, to dir: URL, size: CGSize = CGSize(width: 1100, height: 760), settle: Double = 1.4) async throws {101    for dark in [true, false] {102        let url = dir.appendingPathComponent("\(name)-\(dark ? "dark" : "light").png")103        try await ShotRenderer.render(view.environment(model), size: size, dark: dark, settle: settle, to: url)104        print("SHOT \(url.path)")105    }106}107108/// Synthetic actions for the review screen. The view labels them as a sample.109func sampleRecording() -> [RecordedAction] {110    let notes = "com.apple.Notes"111    return [112        RecordedAction(sequence: 1, kind: .recordingStarted, summary: "Recording started for \(notes)"),113        RecordedAction(sequence: 2, kind: .appActivated, bundleID: notes, appName: "Notes", summary: "Switched to Notes"),114        RecordedAction(sequence: 3, kind: .menuItemSelected, bundleID: notes, appName: "Notes", role: "AXMenuItem", title: "New Note", summary: "chose menu item \"New Note\""),115        RecordedAction(sequence: 4, kind: .windowFocused, bundleID: notes, appName: "Notes", role: "AXWindow", title: "Notes", summary: "window \"Notes\" came to the front"),116        RecordedAction(sequence: 5, kind: .focusChanged, bundleID: notes, appName: "Notes", role: "AXTextField", title: "Search", summary: "focused AXTextField \"Search\""),117        RecordedAction(sequence: 6, kind: .valueChanged, bundleID: notes, appName: "Notes", role: "AXTextField", title: "Search", summary: "typed text of length 14 in field \"Search\"", coalesced: 14),118        RecordedAction(sequence: 7, kind: .valueChanged, bundleID: notes, appName: "Notes", role: "AXCheckBox", title: "Pin note", summary: "set AXCheckBox \"Pin note\" to true", value: true),119        RecordedAction(sequence: 8, kind: .valueChanged, bundleID: notes, appName: "Notes", role: "AXSecureTextField", title: "Password", summary: "edited secure field \"Password\" (content and length not recorded)"),120        RecordedAction(sequence: 9, kind: .selectionChanged, bundleID: notes, appName: "Notes", role: "AXOutline", title: "Folders", summary: "selection changed in AXOutline \"Folders\""),121        RecordedAction(sequence: 10, kind: .recordingStopped, summary: "Recording stopped"),122    ]123}124125@MainActor126func seed(_ model: AppModel) async throws {127    let s = model.services128    // A user agent with an evaluation case.129    let agent = AgentProfile(id: "sample-agent", name: "sample-report-writer", role: "specialist",130                             instructions: "Sample agent. Read the documents in the workspace and write a one-page summary in report.md. Quote figures exactly.",131                             model: ModelRef(provider: .anthropic, model: ""), toolPatterns: ["filesystem.list", "filesystem.read", "filesystem.write", "documents.*"],132                             memoryScopes: ["session", "user"])133    try await s.agents.save(agent)134    // Memory records, one of them waiting for approval.135    await s.memory.save(MemoryRecord(scope: .user, kind: "preference", text: "Sample · Write reports in Canadian French.", provenance: "run sample-1", approved: false))136    await s.memory.save(MemoryRecord(scope: .user, kind: "convention", text: "Sample · Dates are written YYYY-MM-DD.", provenance: "user", approved: true))137    await s.memory.save(MemoryRecord(scope: .workflow("system-health-report"), kind: "fix", text: "Sample · diskUsage needs the volume path, not the device name.", provenance: "run sample-4"))138    // One revoked grant so the history is visible, and one workflow-scoped acceptance.139    let extra = PermissionGrant(capability: .fileWrite(path: NSHomeDirectory() + "/Documents/Reports"), scope: .persistent, maxTier: .reversibleWrite, note: "Sample grant")140    await s.policy.add(extra)141    await s.policy.revoke(id: extra.id)142    if let wf = await s.workflows.list().first { try? await s.workflows.acceptPermissions(workflowID: wf.id) }143    // A real skill: proposed, analysed, tested and installed through the services.144    let built = try SkillFormPreview.wordCount()145    let draft = try await s.skills.propose(manifest: built.manifest, sources: built.sources, source: "user")146    if draft.installable {147        _ = try await s.skills.install(draftID: draft.id)148        await s.refreshSkillTools()149    } else {150        print("NOTE the word-count skill could not be installed here: \(draft.tests.map(\.detail)) \(draft.findings.map(\.message))")151    }152    // A draft the review blocks: it uses the network without declaring a host.153    var bad = built.manifest154    bad.id = "skill.fetchTitle"; bad.name = "Fetch title"; bad.summary = "Sample · Downloads a page and returns its title."155    _ = try await s.skills.propose(manifest: bad, sources: ["main.py": "import json, sys, urllib.request\n\nargs = json.load(sys.stdin)\npage = urllib.request.urlopen(\"https://example.com\").read()\nprint(json.dumps({\"words\": len(page.split()), \"lines\": 1}))\n"], source: "import:sample-folder")156    await model.refreshShared()157}158159/// The word-count skill used by the preview, as a manifest and sources.160enum SkillFormPreview {161    static func wordCount() throws -> (manifest: SkillManifest, sources: [String: String]) {162        let source = "import json, sys\n\nargs = json.load(sys.stdin)\nwith open(args[\"path\"], \"r\", encoding=\"utf-8\") as handle:\n    text = handle.read()\nprint(json.dumps({\"words\": len(text.split()), \"lines\": len(text.splitlines())}))\n"163        let manifest = SkillManifest(164            id: "skill.wordCount", name: "Word count", summary: "Counts the words and lines of a text file.",165            inputSchema: .object(["path": .string("Text file to count.")], required: ["path"]),166            outputSchema: .object(["words": .integer(), "lines": .integer()], required: ["words", "lines"], additional: true),167            permissions: SkillPermissions(fileRead: ["$input.path"]), author: "ORIX preview",168            tests: [SkillTestCase(name: "counts a small file", input: ["path": "$fixture/sample.txt"], files: ["sample.txt": "one two three\nfour five\n"],169                                  expectOutput: ["words": 5, "lines": 2])])170        return (manifest, ["main.py": source])171    }172}173174@MainActor175func run(_ dir: URL) async throws {176    try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)177    let model = try await PreviewEnvironment.make()178    try await seed(model)179    let tall = CGSize(width: 1100, height: 1500)180181    // Settings. The fake key exists only while the Providers pane renders.182    try await model.services.providers.setKey(previewKey, for: .anthropic)183    await model.refreshShared()184    do {185        try await shot("settings-providers", SettingsView(tab: .providers, expandCatalogFor: .anthropic), model, to: dir, size: CGSize(width: 1100, height: 2000), settle: 3.0)186        try await shot("settings-providers-compact", SettingsView(tab: .providers), model, to: dir, size: CGSize(width: 1100, height: 700), settle: 2.0)187        try await shot("onboarding-2-provider", OnboardingView(step: 1) {}, model, to: dir, size: CGSize(width: 1100, height: 900), settle: 3.0)188    } catch {189        try? await model.services.providers.removeKey(for: .anthropic)190        throw error191    }192    try await model.services.providers.removeKey(for: .anthropic)193    Redactor.shared.unregister(secret: previewKey)194    await model.refreshShared()195    print("KEY preview key removed: \(await model.services.providers.keySource(for: .anthropic) == .none)")196197    try await shot("settings-general", SettingsView(tab: .general), model, to: dir, size: CGSize(width: 1100, height: 1100))198    try await shot("settings-privacy", SettingsView(tab: .privacy), model, to: dir, size: tall)199    try await shot("settings-storage", SettingsView(tab: .storage), model, to: dir, size: tall, settle: 2.0)200    try await shot("settings-diagnostics", SettingsView(tab: .diagnostics), model, to: dir, size: CGSize(width: 1100, height: 1000), settle: 2.0)201    try await shot("settings-updates", SettingsView(tab: .updates), model, to: dir)202203    // Permissions204    try await shot("permissions-macos", PermissionsView(tab: .macOS), model, to: dir, size: CGSize(width: 1100, height: 1300), settle: 2.0)205    try await shot("permissions-grants", PermissionsView(tab: .grants), model, to: dir, size: CGSize(width: 1100, height: 1100))206    try await shot("permissions-grants-add", PermissionsView(tab: .grants, showAddForm: true), model, to: dir, size: CGSize(width: 1100, height: 900))207    try await shot("permissions-approval", PermissionsView(tab: .approval), model, to: dir, size: CGSize(width: 1100, height: 1000))208    try await shot("permissions-audit", PermissionsView(tab: .audit), model, to: dir)209210    // Agents211    try await shot("agents-list", AgentsView(tab: .profiles), model, to: dir, size: CGSize(width: 1100, height: 760))212    try await shot("agents-editor", AgentsView(tab: .profiles, selectAgentNamed: "sample-report-writer", expandedFamilies: ["filesystem"]), model, to: dir, size: CGSize(width: 1100, height: 2300))213    try await shot("agents-memory", AgentsView(tab: .memory), model, to: dir)214215    // Skills216    try await shot("skills-installed", SkillsView(tab: .installed), model, to: dir)217    try await shot("skills-drafts", SkillsView(tab: .drafts), model, to: dir, size: CGSize(width: 1100, height: 1000))218    try await shot("skills-catalog", SkillsView(tab: .catalog, selectTool: "filesystem.move"), model, to: dir, size: CGSize(width: 1100, height: 900))219    try await shot("skills-author", SkillsView(tab: .author), model, to: dir, size: CGSize(width: 1100, height: 1700))220    if let draft = await model.services.skills.allDrafts().first {221        try await shot("skills-install-confirmation", InstallConfirmationPreview(draft: draft), model, to: dir, size: CGSize(width: 560, height: 520))222    }223224    // Onboarding225    try await shot("onboarding-1-welcome", OnboardingView(step: 0) {}, model, to: dir)226    try await shot("onboarding-3-workspace", OnboardingView(step: 2) {}, model, to: dir, size: CGSize(width: 1100, height: 860))227    try await shot("onboarding-4-permissions", OnboardingView(step: 3) {}, model, to: dir, size: CGSize(width: 1100, height: 860), settle: 2.0)228    try await shot("onboarding-5-done", OnboardingView(step: 4) {}, model, to: dir)229230    // Watch & Learn231    try await shot("watch-idle", WatchAndLearnView(), model, to: dir, size: CGSize(width: 1100, height: 1000))232    try await shot("watch-review-sample", WatchAndLearnView(sampleRecording: sampleRecording()), model, to: dir, size: CGSize(width: 1100, height: 1150))233    try await shot("watch-proposal-sample", WatchAndLearnView(sampleRecording: sampleRecording(), showProposal: true), model, to: dir, size: CGSize(width: 1100, height: 1150), settle: 2.0)234235    await model.services.shutdown()236    try? FileManager.default.removeItem(at: model.services.paths.root)237}238239_ = NSApplication.shared240let arguments = CommandLine.arguments241guard let i = arguments.firstIndex(of: "--shot"), arguments.count > i + 1 else {242    print("usage: orix-preview-manage --shot <directory>")243    exit(2)244}245let directory = URL(fileURLWithPath: arguments[i + 1])246Task { @MainActor in247    do { try await run(directory); exit(0) } catch {248        print("FAILED \(error)")249        exit(1)250    }251}252RunLoop.main.run()253
Files main
Menu

Theme