Repository Public License
1import Foundation2import Testing3import PrismAIOrchestrator4import PrismCore5import PrismIconKit6import PrismObjectModel7import PrismRenderer8import PrismSecurity9import PrismTestKit10@testable import PrismStudio1112/// Live tests call the real Anthropic API and cost money. They run only when PRISM_LIVE=1 and ANTHROPIC_API_KEY are set13/// (never in `scripts/verify.sh` by default). The key stays in memory for the duration of the test.14let liveKey: String? = ProcessInfo.processInfo.environment["PRISM_LIVE"] == "1" ? ProcessInfo.processInfo.environment["ANTHROPIC_API_KEY"].flatMap { $0.isEmpty ? nil : $0 } : nil1516@MainActor17@Suite(.serialized, .enabled(if: liveKey != nil, "Set PRISM_LIVE=1 and ANTHROPIC_API_KEY to run against the real API.")) struct LiveTests {18 func liveStudio(_ root: URL) throws -> StudioModel {19 let studio = try StudioModel(root: root.appendingPathComponent("Library"), secrets: InMemorySecretStore([SecretAccount.anthropicAPIKey: liveKey ?? ""]),20 hostTemplate: studioHostTemplate, templatesDirectory: testRepoRoot.appendingPathComponent("templates"))21 if let model = ProcessInfo.processInfo.environment["PRISM_LIVE_MODEL"] { studio.settings.model = model }22 if let effort = ProcessInfo.processInfo.environment["PRISM_LIVE_EFFORT"] { studio.settings.effort = effort }23 return studio24 }2526 func report(_ name: String, _ session: ProjectSession, _ studio: StudioModel) {27 let o = session.lastOutcome28 let dir = testRepoRoot.appendingPathComponent("build/live")29 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)30 if let bp = session.proposal?.blueprint ?? session.blueprint ?? session.unfinishedDraft { try? bp.prettyData().write(to: dir.appendingPathComponent("\(name).blueprint.json")) }31 var lines = ["LIVE \(name): status=\(o?.status.rawValue ?? "-") model=\(o?.model ?? "-") toolCalls=\(o?.toolCalls ?? 0) turns=\(o?.turns ?? 0) coverage=\(o?.coverage ?? 0)"]32 lines.append("LIVE \(name): tokens in=\(o?.usage.inputTokens ?? 0) out=\(o?.usage.outputTokens ?? 0) cacheRead=\(o?.usage.cacheReadTokens ?? 0) cacheWrite=\(o?.usage.cacheWriteTokens ?? 0) estCost=\(o?.estimatedCostUSD.map { String(format: "%.4f", $0) } ?? "unknown")")33 lines.append("LIVE \(name): errors=\(o?.issues.errors.map(\.message) ?? []) message=\(o?.message.prefix(600) ?? "")")34 lines.append("LIVE \(name): steps=\(session.steps.map { ($0.ok ? "" : "!") + $0.tool }.joined(separator: " "))")35 lines.append("LIVE \(name): api=\(studio.apiLog.suffix(3))")36 for l in lines { print(l) }37 try? lines.joined(separator: "\n").write(to: dir.appendingPathComponent("\(name).report.txt"), atomically: true, encoding: .utf8)38 }3940 @Test func connectionAndModelDiscovery() async throws {41 let root = studioRoot()42 defer { try? FileManager.default.removeItem(at: root) }43 let studio = try liveStudio(root)44 #expect(await studio.testConnection())45 print("LIVE models: \(studio.models.map(\.id))")46 #expect(!studio.models.isEmpty)47 }4849 /// Golden journey steps 3, 4, 6 and 7 against the real model.50 @Test func goldenPromptThenEvolve() async throws {51 let root = studioRoot()52 defer { try? FileManager.default.removeItem(at: root) }53 let studio = try liveStudio(root)54 let session = try #require(studio.createProject(prompt: goldenPrompt))55 await session.waitForBuild()56 report("create", session, studio)57 #expect(session.lastOutcome?.status == .succeeded)58 let bp = try #require(session.blueprint)59 #expect(session.lastOutcome?.coverage == 1 && session.currentIssues.errors.isEmpty)60 let types = Set(bp.componentTypes)61 #expect(types.contains("prism.csvImport") && !types.isDisjoint(with: ["prism.chart.bar", "prism.chart.line"]) && !types.isDisjoint(with: ["prism.table", "prism.crud"]))62 #expect(!bp.tables.isEmpty && bp.permissions.contains("storage.local") && bp.permissions.contains("files.import.userSelected"))6364 session.submit("Add a budget alert and a new chart.")65 await session.waitForBuild()66 report("evolve", session, studio)67 let proposal = try #require(session.proposal)68 #expect(proposal.diff.added.contains { $0.type == "prism.alert" } && proposal.diff.added.contains { $0.type.hasPrefix("prism.chart") })69 #expect(proposal.diff.removed.filter(\.isTable).isEmpty)70 await session.runProposalChecks()71 #expect(session.proposal?.checksPassed == true)72 #expect(session.approveProposal())73 }7475 /// A request the catalog cannot express: the builder must design a theme and an icon and build an on-demand component.76 @Test func aGameGetsItsOwnLookIconAndCustomComponent() async throws {77 let root = studioRoot()78 defer { try? FileManager.default.removeItem(at: root) }79 let studio = try liveStudio(root)80 let prompt = "A memory card game for kids: a 4×4 board of emoji pairs you flip two at a time, a move counter, a new game button, and a list of best scores that is kept between sessions."81 let session = try #require(studio.createProject(prompt: prompt))82 await session.waitForBuild()83 report("memory-game", session, studio)84 #expect(session.lastOutcome?.status == .succeeded)85 let bp = try #require(session.blueprint)86 #expect(session.currentIssues.errors.isEmpty)87 #expect(!bp.componentDefinitions.isEmpty && bp.components.contains { $0.isCustomInstance }, "expected an on-demand component")88 #expect(!bp.theme.isEmpty, "expected a designed theme")89 let icon = try #require(bp.icon, "expected a designed icon")90 #expect(IconSpec.problems(icon).isEmpty)91 let dir = testRepoRoot.appendingPathComponent("build/live")92 try IconRenderer.png(icon, pixels: 512).write(to: dir.appendingPathComponent("memory-game.icon.png"))93 #expect(session.steps.contains { $0.tool == "design.setIcon" && $0.ok } && session.steps.contains { $0.tool == "ui.screenshot" && $0.ok })94 }9596 /// With the large catalog, things that used to be impossible come from catalog components, not custom code.97 @Test func aProjectBoardComesFromTheCatalogWithADarkLook() async throws {98 let root = studioRoot()99 defer { try? FileManager.default.removeItem(at: root) }100 let studio = try liveStudio(root)101 let prompt = "A project board for a small team: tasks in Kanban columns (To do, Doing, Done) that I can move between columns, a calendar of due dates, and a gauge of how much is done. Dark, professional look."102 let session = try #require(studio.createProject(prompt: prompt))103 await session.waitForBuild()104 report("project-board", session, studio)105 #expect(session.lastOutcome?.status == .succeeded)106 let bp = try #require(session.blueprint)107 let types = Set(bp.componentTypes)108 #expect(types.contains("prism.kanban") && types.contains("prism.calendar"), "\(types.sorted())")109 #expect(bp.componentDefinitions.isEmpty, "the catalog covers this request; no custom component was needed")110 #expect(PrismTheme(bp.theme).colorScheme == .dark)111 let icon = try #require(bp.icon, "expected a designed icon")112 try IconRenderer.png(icon, pixels: 512).write(to: testRepoRoot.appendingPathComponent("build/live/project-board.icon.png"))113 }114}115