Repository Public License
1import AppKit2import PrismAIOrchestrator3import PrismCore4import PrismObjectModel5import PrismSecurity6import SwiftUI78/// `PRISM --selftest-ui`: opens the real main window on a throwaway library, without activating the app, and walks9/// through every screen and a simulated build (no Claude call). It exists because layout feedback loops in a live10/// window (the 0.1.0 crash of 2026-11-22) cannot be seen by off-screen rendering. Exit code 0 means the walk finished.11@MainActor12public enum StudioSelfTest {13 public static var isRequested: Bool { CommandLine.arguments.contains("--selftest-ui") }1415 static func makeModel() throws -> StudioModel {16 let root = FileManager.default.temporaryDirectory.appendingPathComponent("prism-selftest-\(UUID().uuidString)")17 return try StudioModel(root: root, secrets: InMemorySecretStore(), hostTemplate: StudioResources.locate("SatelliteHost.app"),18 templatesDirectory: StudioResources.locate("templates"), dialogs: nil)19 }2021 /// The tool calls that rebuild a blueprint, in the order a builder would make them.22 static func calls(for bp: AppBlueprint) -> [(String, JSONValue)] {23 var calls: [(String, JSONValue)] = [("project.create", ["name": .string(bp.name), "summary": .string(bp.summary), "acceptanceCriteria": ["self-test"]]), ("catalog.search", ["query": ""])]24 for t in bp.tables { calls.append(("data.createSchema", ["id": .string(t.id), "name": .string(t.name), "columns": t.props["columns"] ?? [], "seed": [25 ["date": "2026-10-03", "description": "Groceries", "category": "Food", "amount": 91.2], ["date": "2026-11-05", "description": "Monthly rent", "category": "Housing", "amount": 1450],26 ]])) }27 calls.append(("logic.bind", ["state": .object(bp.state)]))28 for p in bp.permissions where p != "storage.local" { calls.append(("security.requestPermission", ["permission": .string(p), "reason": "self-test"])) }29 for q in bp.queries { calls.append(("logic.createWorkflow", ["id": .string(q.id), "name": .string(q.name), "query": q.props["query"] ?? .null])) }30 func add(_ id: String, parent: String) {31 guard let o = bp.object(id) else { return }32 var input: [String: JSONValue] = ["parent": .string(parent), "id": .string(o.id), "type": .string(o.type), "name": .string(o.name), "props": .object(o.props)]33 if !o.events.isEmpty { input["events"] = .object(o.events.mapValues(JSONValue.array)) }34 calls.append(("ui.addComponent", .object(input)))35 o.children.forEach { add($0, parent: o.id) }36 }37 for page in bp.pages {38 calls.append(("ui.createPage", ["id": .string(page.id), "name": .string(page.name)]))39 page.children.forEach { add($0, parent: page.id) }40 }41 calls.append(("ui.preview", [:]))42 return calls43 }4445 public static func run(model: StudioModel) async {46 func step(_ name: String, _ seconds: Double = 0.7) async {47 FileHandle.standardError.write(Data("selftest: \(name)\n".utf8))48 try? await Task.sleep(for: .seconds(seconds))49 }50 // Order the window in behind everything else: real layout and drawing, no focus change.51 try? await Task.sleep(for: .seconds(1))52 for w in NSApp.windows where w.contentView != nil { w.orderBack(nil) }53 await step("welcome", 1)54 // Type into the composers the way a person does: character by character, long lines and newlines included.55 let typed = "Build a local expense tracker with CSV import, category filters, a monthly chart and persistent storage. It should also show totals per category, warn me when I go over budget, and let me export everything.\nSecond paragraph after a newline.\n\nThird one, to grow the editor past its maximum height and make it scroll."56 func type(_ set: (String) -> Void, label: String) async {57 var text = ""58 for ch in typed { text.append(ch); set(text); try? await Task.sleep(for: .milliseconds(6)) }59 await step("typed in \(label)", 0.6)60 for _ in 0..<typed.count / 3 { text.removeLast(3); set(text); try? await Task.sleep(for: .milliseconds(4)) }61 set("")62 await step("cleared \(label)", 0.3)63 }64 await type({ model.welcomeDraft = $0 }, label: "welcome composer")6566 // A draft that is "being built": the same state changes a live build produces, replayed from the recipe.67 if let draft = model.createProject(prompt: "Build a local expense tracker with CSV import, category filters, monthly chart and persistent storage."),68 let data = model.templatesDirectory.flatMap({ FileManager.default.contents(atPath: $0.appendingPathComponent("expense-tracker/blueprint.json").path) }),69 let template = try? AppBlueprint.load(data) {70 await step("draft without a key")71 await draft.replayBuild(calls(for: template), interval: 0.12)72 await step("simulated build finished", 1)73 }74 // Real model-built apps (from live runs), replayed as drafts and opened as finished apps at several window sizes.75 if let i = CommandLine.arguments.firstIndex(of: "--selftest-blueprints"), i + 1 < CommandLine.arguments.count {76 let dir = URL(fileURLWithPath: CommandLine.arguments[i + 1])77 let files = ((try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []).filter { $0.hasSuffix(".blueprint.json") }.sorted()78 let window = NSApp.windows.first(where: { $0.contentView != nil && $0.isVisible })79 for file in files {80 guard let data = FileManager.default.contents(atPath: dir.appendingPathComponent(file).path), let bp = try? AppBlueprint.load(data) else { continue }81 if let draft = model.createProject(prompt: "Replay \(file)") {82 await draft.replayBuild(calls(for: bp), interval: 0.05)83 await step("replayed draft \(file)", 0.3)84 model.deleteProject(draft.id)85 }86 guard let record = try? model.store.createProject(name: bp.name, prompt: file), (try? model.store.save(bp, for: record.id, label: "Replay")) != nil else { continue }87 model.refreshProjects()88 model.selection = .project(record.id)89 guard let opened = model.session(for: record.id) else { continue }90 for page in bp.pages { opened.runtime?.currentPage = page.id; await step("opened \(file) page \(page.id)", 0.5) }91 for (w, h) in [(1000, 640), (1500, 900), (1280, 800)] { window?.setContentSize(NSSize(width: w, height: h)); try? await Task.sleep(for: .milliseconds(350)) }92 for mode in [StudioMode.design, .evolve, .preview] { opened.mode = mode; try? await Task.sleep(for: .milliseconds(450)) }93 await step("walked \(file)", 0.2)94 }95 }96 // Every catalog component's preview fixture, opened as an app in the real window.97 for manifest in model.registry.all {98 guard let bp = try? manifest.fixtureBlueprint(), let record = try? model.store.createProject(name: manifest.name, prompt: manifest.type),99 (try? model.store.save(bp, for: record.id, label: "Fixture")) != nil else { continue }100 model.refreshProjects()101 model.selection = .project(record.id)102 if let opened = model.session(for: record.id) {103 opened.mode = .preview104 try? await Task.sleep(for: .milliseconds(140))105 opened.mode = .design106 try? await Task.sleep(for: .milliseconds(140))107 }108 model.deleteProject(record.id)109 }110 await step("walked \(model.registry.count) component fixtures", 0.3)111 guard let session = model.createFromTemplate("expense-tracker") else { exit(3) }112 for mode in StudioMode.allCases + [.preview] {113 session.mode = mode114 await step("mode \(mode.rawValue)", 1)115 if mode != .create { await type({ session.composerDraft = $0 }, label: "composer in \(mode.rawValue)") }116 }117 session.mode = .design118 for id in ["monthly_chart", "transactions_table", "bar", "root"] {119 session.designSelection = id120 await step("design select \(id)", 0.4)121 }122 _ = session.addComponent("prism.chart.pie", to: "root")123 await step("design add chart")124 _ = session.edit([.setBlueprintField(field: "theme", value: ["accent": "#FF9F0A", "density": "compact"])], label: "theme")125 await step("design theme")126 session.undo(); session.undo()127 await step("design undo")128 if let table = session.blueprint?.tables.first?.id {129 for i in 0..<40 { _ = session.runtime?.run([["type": "createRecord", "table": .string(table), "values": ["date": .string("2026-11-\(String(format: "%02d", i % 28 + 1))"), "description": .string("Row \(i)"), "amount": .double(Double(i) * 3.5)]]]) }130 }131 session.mode = .preview132 await step("preview with data", 1)133 session.runtime?.setState("showEditor", true)134 await step("sheet open", 1)135 session.runtime?.setState("showEditor", false)136 await step("sheet closed")137 for item in [SidebarItem.library, .monitor, .welcome, .project(session.id)] {138 model.selection = item139 await step("sidebar \(item)", 1)140 }141 // Resize the window through a range of sizes: split panes recompute their limits at each one.142 if let window = NSApp.windows.first(where: { $0.contentView != nil && $0.isVisible }) {143 for (w, h) in [(1000, 640), (1500, 900), (980, 620), (1280, 800)] {144 window.setContentSize(NSSize(width: w, height: h))145 await step("resize \(w)x\(h)", 0.5)146 }147 for mode in StudioMode.allCases { session.mode = mode; await step("mode \(mode.rawValue) after resize", 0.5) }148 }149 FileHandle.standardError.write(Data("selftest: PASSED\n".utf8))150 model.shutdown()151 try? FileManager.default.removeItem(at: model.store.root)152 exit(0)153 }154}155156extension ProjectSession {157 /// Replays tool calls into a build workspace with the same UI state updates as a live build (self-test only; no network).158 func replayBuild(_ calls: [(String, JSONValue)], interval: Double) async {159 await debugReplay(calls, interval: interval)160 }161}162