Repository Public License
1import Foundation2import Observation3import PrismAIOrchestrator4import PrismComponentSDK5import PrismCore6import PrismDataRuntime7import PrismObjectModel8import PrismProjectStore9import PrismRenderer10import PrismSatellitePublisher1112public enum StudioMode: String, CaseIterable, Sendable, Identifiable {13 case create, preview, design, evolve, publish14 public var id: String { rawValue }15 public var title: String { rawValue.capitalized }16 public var symbol: String {17 switch self {18 case .create: "sparkles"19 case .preview: "play.rectangle"20 case .design: "paintbrush"21 case .evolve: "arrow.triangle.branch"22 case .publish: "shippingbox"23 }24 }25}2627public struct ChatItem: Identifiable, Sendable, Equatable {28 public enum Role: String, Sendable { case user, assistant, status }29 public let id: Int30 public var role: Role31 public var text: String32 public var date: Date33}3435public struct BuildStep: Identifiable, Sendable, Equatable {36 public let id: Int37 public var tool: String38 public var summary: String39 public var ok: Bool40}4142/// A finished change waiting for the user's decision (Evolve).43public struct Proposal: Sendable, Equatable {44 public var blueprint: AppBlueprint45 public var diff: BlueprintDiff46 public var message: String47 public var migration: AppDataStore.MigrationReport48 public var issues: [ValidationIssue]49 public var checksRun = false50 public var checksPassed = false51 public var checkLines: [String] = []52}5354@MainActor55@Observable56public final class ProjectSession {57 @ObservationIgnored unowned let model: StudioModel58 public private(set) var record: ProjectRecord59 public private(set) var history: EditHistory?60 public private(set) var runtime: AppRuntime?61 public var mode: StudioMode = .create { didSet { if mode != oldValue { persistSession() } } }62 public private(set) var conversation: [ChatItem] = []63 public private(set) var snapshots: [SnapshotRecord] = []64 public var designSelection: String?65 /// What is typed in this project's composer.66 public var composerDraft = ""6768 // Build state69 public private(set) var isBuilding = false70 public private(set) var steps: [BuildStep] = []71 public private(set) var milestones: [Milestone] = []72 public private(set) var streamingText = ""73 public private(set) var usage = TokenUsage()74 public private(set) var estimatedCost: Double?75 public private(set) var draftRuntime: AppRuntime?76 public private(set) var draftComponents: [String] = []77 public private(set) var lastOutcome: BuildOutcome?78 public private(set) var proposal: Proposal?79 /// A first build that finished with problems: kept so the user can ask for a fix instead of losing it.80 public private(set) var unfinishedDraft: AppBlueprint?81 public private(set) var notice: String?8283 // Publish state84 public private(set) var installed: InstalledSatellite?85 public private(set) var publishPlan: PublishPlan?86 public private(set) var publishResult: PublishResult?87 public private(set) var launchReport: LaunchReport?88 public private(set) var publishError: String?89 public private(set) var isPublishing = false9091 @ObservationIgnored private var buildTask: Task<Void, Never>?92 @ObservationIgnored private var counter = 093 @ObservationIgnored private var workspace: BuildWorkspace?9495 init(model: StudioModel, record: ProjectRecord) {96 self.model = model97 self.record = record98 }99100 public var blueprint: AppBlueprint? { history?.current }101 public var id: String { record.id }102 public var isDraft: Bool { history == nil }103 public var canUndo: Bool { history?.canUndo ?? false }104 public var canRedo: Bool { history?.canRedo ?? false }105106 // MARK: Opening and closing107108 func open() {109 restoreSession()110 do {111 if let loaded = try model.store.loadBlueprint(id) {112 history = EditHistory(loaded.blueprint)113 if let from = loaded.recoveredFrom {114 notice = "The app's definition was damaged on disk. PRISM restored the version saved \(from.createdAt.formatted(date: .abbreviated, time: .shortened))."115 }116 try startRuntime(loaded.blueprint)117 if mode == .create { mode = .preview }118 }119 } catch {120 notice = "This app could not be opened: \(error.localizedDescription)"121 }122 refreshSnapshots()123 installed = model.publisher?.installed(for: id)124 }125126 func close() {127 buildTask?.cancel()128 runtime?.persistStateNow()129 runtime?.store.close()130 runtime = nil131 persistSession()132 }133134 private func startRuntime(_ blueprint: AppBlueprint) throws {135 if let runtime {136 try runtime.reload(blueprint)137 } else {138 let rt = try AppRuntime(blueprint: blueprint, store: AppDataStore(url: model.store.dataURL(id)), registry: model.registry)139 rt.dialogs = model.dialogs140 runtime = rt141 }142 }143144 private func refreshSnapshots() { snapshots = (try? model.store.snapshots(id)) ?? [] }145146 private func say(_ role: ChatItem.Role, _ text: String) {147 counter += 1148 conversation.append(ChatItem(id: counter, role: role, text: text, date: Date()))149 persistSession()150 }151152 // MARK: Session persistence (conversation, mode, selection)153154 func persistSession() {155 let items: [JSONValue] = conversation.suffix(200).map { ["role": .string($0.role.rawValue), "text": .string($0.text), "date": .double($0.date.timeIntervalSince1970)] }156 model.store.saveSession(id, ["mode": .string(mode.rawValue), "conversation": .array(items), "selection": designSelection.map(JSONValue.string) ?? .null])157 }158159 private func restoreSession() {160 guard let saved = model.store.session(id) else { return }161 if let m = saved["mode"]?.stringValue.flatMap(StudioMode.init(rawValue:)) { mode = m }162 designSelection = saved["selection"]?.stringValue163 for item in saved["conversation"]?.arrayValue ?? [] {164 counter += 1165 conversation.append(ChatItem(id: counter, role: ChatItem.Role(rawValue: item["role"]?.stringValue ?? "") ?? .status,166 text: item["text"]?.stringValue ?? "", date: Date(timeIntervalSince1970: item["date"]?.doubleValue ?? 0)))167 }168 }169170 // MARK: Prompts → builds171172 /// The composer's action in every mode: build the app, or propose a change to it.173 public func submit(_ prompt: String) {174 let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)175 guard !text.isEmpty, !isBuilding else { return }176 say(.user, text)177 guard model.keyStatus.canBuild else {178 say(.status, "Claude is not connected, so this request was saved but not built. Add an Anthropic API key in Settings, then choose Build again. Catalog apps and templates work without Claude.")179 return180 }181 start(prompt: text)182 }183184 /// Runs the last saved request again (after adding a key, or after a failure).185 public func retryLastRequest() {186 guard let last = conversation.last(where: { $0.role == .user })?.text, !isBuilding, model.keyStatus.canBuild else { return }187 start(prompt: last)188 }189190 public var contextPreview: String {191 let ws = BuildWorkspace(registry: model.registry, baseline: blueprint ?? unfinishedDraft)192 ws.allowSampleRows = model.allowSampleRows193 return BuilderAgent.requestPreview(prompt: "(your next request)", workspace: ws)194 }195196 private func start(prompt: String) {197 let baseline = blueprint ?? unfinishedDraft198 let evolving = blueprint != nil199 let ws = BuildWorkspace(registry: model.registry, baseline: baseline)200 ws.allowSampleRows = model.allowSampleRows201 ws.existingDataURL = evolving ? model.store.dataURL(id) : nil202 let store = model.store, projectID = id203 ws.audit = { kind, summary, detail in store.audit(projectID, kind, summary, detail) }204 workspace = ws205 isBuilding = true206 steps = []; milestones = []; streamingText = ""; usage = TokenUsage(); estimatedCost = nil207 draftRuntime = nil; draftComponents = []; lastOutcome = nil; proposal = nil208 if !evolving { mode = .create } else { mode = .evolve }209 let buildID = try? store.startBuild(projectID, kind: evolving ? "evolve" : "create", manifest: ["model": .string(model.settings.model)])210 store.audit(projectID, "build.start", evolving ? "Evolve: \(prompt)" : "Create: \(prompt)", ["model": .string(model.settings.model)])211 let agent = BuilderAgent(client: model.client, settings: model.settings)212 buildTask = Task { [weak self] in213 let outcome = await agent.run(prompt: prompt, workspace: ws) { event in self?.handle(event) }214 guard let self else { return }215 if let buildID { store.finishBuild(buildID, status: outcome.status.rawValue, manifest: outcome.manifest) }216 store.recordUsage(projectID, model: outcome.model, input: outcome.usage.inputTokens, output: outcome.usage.outputTokens,217 cacheRead: outcome.usage.cacheReadTokens, cacheWrite: outcome.usage.cacheWriteTokens, cost: outcome.estimatedCostUSD ?? 0)218 store.audit(projectID, "build.finish", "Build \(outcome.status.rawValue)", outcome.manifest)219 self.finish(outcome, evolving: evolving, prompt: prompt)220 }221 }222223 public func cancelBuild() { buildTask?.cancel() }224225 /// Self-test support: drives the build UI state from scripted tool calls instead of a model.226 func debugReplay(_ calls: [(String, JSONValue)], interval: Double) async {227 let ws = BuildWorkspace(registry: model.registry, baseline: nil)228 workspace = ws229 isBuilding = true230 steps = []; milestones = []; draftRuntime = nil; draftComponents = []; lastOutcome = nil231 mode = .create232 for (name, input) in calls {233 handle(.toolStarted(name: name))234 let result = await ws.execute(name, input)235 handle(.toolFinished(name: name, ok: result.ok, summary: result.summary))236 streamingText = "Working on \(name)…"237 try? await Task.sleep(for: .seconds(interval))238 }239 isBuilding = false240 streamingText = ""241 }242243 /// Waits for the running build; used by tests and by the command-line driver.244 public func waitForBuild() async { await buildTask?.value }245246 private func handle(_ event: AgentEvent) {247 switch event {248 case .started: break249 case .text(let t): streamingText += t250 case .toolStarted: streamingText = ""251 case .toolFinished(let name, let ok, let summary):252 counter += 1253 steps.append(BuildStep(id: counter, tool: name, summary: summary, ok: ok))254 if ok, name.hasPrefix("ui.") || name.hasPrefix("data.") || name.hasPrefix("logic.") || name == "project.patch" { refreshDraftPreview() }255 case .milestone(let m): milestones.append(m)256 case .usage(let u, let cost): usage = u; estimatedCost = cost257 case .repair(let round, let problems):258 counter += 1259 steps.append(BuildStep(id: counter, tool: "checks", summary: "Checks found \(problems) problem(s); repair round \(round)", ok: false))260 case .finished: break261 }262 }263264 /// The live preview during a build: the draft, run on a throwaway in-memory database, as soon as it is valid.265 private func refreshDraftPreview() {266 guard let draft = workspace?.blueprint else { return }267 draftComponents = draft.components.map { "\($0.type)|\($0.name.isEmpty ? $0.id : $0.name)" }268 guard !BlueprintValidator.validate(draft, registry: model.registry).hasErrors else { return }269 if let draftRuntime { try? draftRuntime.reload(draft) }270 else { draftRuntime = try? AppRuntime(blueprint: draft, store: AppDataStore(url: nil), registry: model.registry) }271 }272273 private func finish(_ outcome: BuildOutcome, evolving: Bool, prompt: String) {274 isBuilding = false275 lastOutcome = outcome276 streamingText = ""277 draftRuntime = nil278 workspace = nil279 defer { model.refreshProjects() }280 guard let built = outcome.blueprint, outcome.status == .succeeded || outcome.status == .incomplete || outcome.status == .budgetExceeded else {281 say(.status, outcome.status == .cancelled ? "Build cancelled. Nothing was changed." : "The build did not finish: \(outcome.message)")282 return283 }284 if !outcome.message.isEmpty { say(.assistant, outcome.message) }285 if evolving, let current = blueprint {286 var next = built287 next.version = current.version + 1288 let diff = BlueprintDiff(from: current, to: next)289 guard !diff.isEmpty else { say(.status, "No change to the app was needed."); return }290 let plan = runtime.flatMap { try? $0.store.plan(for: next) } ?? AppDataStore.MigrationReport()291 proposal = Proposal(blueprint: next, diff: diff, message: outcome.message, migration: plan,292 issues: BlueprintValidator.validate(next, registry: model.registry))293 say(.status, "Proposed \(diff.summaryLines.count) change(s). Review them, run the checks, then approve or discard.")294 return295 }296 // First build.297 if outcome.issues.hasErrors {298 unfinishedDraft = built299 say(.status, "The app was built but \(outcome.issues.errors.count) check(s) still fail, so it was not saved as a working app. Ask for a fix, or start again.")300 return301 }302 do {303 var first = built304 first.id = "app_" + PrismID.slug(id)305 try model.store.save(first, for: id, label: "First build")306 record = try model.store.project(id)307 history = EditHistory(first)308 unfinishedDraft = nil309 try startRuntime(first)310 refreshSnapshots()311 mode = .preview312 } catch { say(.status, "The app was built but could not be saved: \(error.localizedDescription)") }313 }314315 // MARK: Evolve: checks, approve, discard316317 /// Runs the real checks on the proposed version: validation, then a preview run of every expression and query.318 public func runProposalChecks() async {319 guard var p = proposal else { return }320 let ws = BuildWorkspace(registry: model.registry, baseline: p.blueprint)321 let result = await ws.execute("ui.preview", .emptyObject)322 var lines: [String] = []323 let errors = result.content["errors"]?.arrayValue ?? [], runtime = result.content["runtimeProblems"]?.arrayValue ?? []324 lines.append(errors.isEmpty ? "✓ Structure, types, bindings and permissions are valid" : "✗ \(errors.count) validation error(s): \(errors.first?["message"]?.stringValue ?? "")")325 if errors.isEmpty { lines.append(runtime.isEmpty ? "✓ Every expression and query ran in a preview" : "✗ \(runtime.count) runtime problem(s): \(runtime.first?.stringValue ?? "")") }326 lines.append(p.migration.retained.isEmpty && p.migration.addedColumns.isEmpty && p.migration.createdTables.isEmpty327 ? "✓ No change to stored data" : "✓ Data migration is additive: +\(p.migration.createdTables.count) table(s), +\(p.migration.addedColumns.count) column(s), nothing removed")328 p.checksRun = true329 p.checksPassed = result.ok330 p.checkLines = lines331 proposal = p332 model.store.audit(id, "proposal.checks", result.ok ? "Checks passed" : "Checks failed", result.content)333 }334335 @discardableResult336 public func approveProposal() -> Bool {337 guard let p = proposal, p.checksPassed, let current = blueprint else { return false }338 do {339 // The version before the change is already a snapshot; make sure of it, then apply.340 if !snapshots.contains(where: { $0.hash == current.contentHash }) { try model.store.save(current, for: id, label: "Before change") }341 try model.store.save(p.blueprint, for: id, label: "Change: " + (conversation.last(where: { $0.role == .user })?.text.prefix(80) ?? "approved"))342 try startRuntime(p.blueprint)343 history?.reset(to: p.blueprint)344 record = try model.store.project(id)345 model.store.audit(id, "proposal.approve", "Approved \(p.diff.summaryLines.count) change(s)", ["permissionsAdded": .array(p.diff.addedPermissions.map(JSONValue.string))])346 proposal = nil347 refreshSnapshots()348 model.refreshProjects()349 say(.status, "Changes applied as version \(p.blueprint.version). You can roll back from the version list at any time.")350 mode = .preview351 return true352 } catch {353 say(.status, "The change could not be applied: \(error.localizedDescription)")354 return false355 }356 }357358 public func discardProposal() {359 guard proposal != nil else { return }360 proposal = nil361 model.store.audit(id, "proposal.discard", "Discarded the proposed change")362 say(.status, "Proposed changes discarded. The app is unchanged.")363 }364365 // MARK: Deterministic edits (Design mode): no model call366367 @discardableResult368 public func edit(_ patches: [BlueprintPatch], label: String) -> Bool {369 guard var h = history else { return false }370 do {371 try h.apply(patches, label: label)372 // An edit that breaks the app is kept in the editor but the running app only reloads when it is valid.373 history = h374 try commit(label: "Design edits")375 return true376 } catch {377 notice = "That edit could not be applied: \(error.localizedDescription)"378 return false379 }380 }381382 private func commit(label: String) throws {383 guard let current = history?.current else { return }384 try model.store.save(current, for: id, label: label, coalesce: true)385 if !BlueprintValidator.validate(current, registry: model.registry).hasErrors { try startRuntime(current) }386 refreshSnapshots()387 }388389 public func undo() {390 guard history?.undo() == true else { return }391 try? commit(label: "Design edits")392 }393394 public func redo() {395 guard history?.redo() == true else { return }396 try? commit(label: "Design edits")397 }398399 public var currentIssues: [ValidationIssue] { blueprint.map { BlueprintValidator.validate($0, registry: model.registry) } ?? [] }400401 /// Adds a catalog component with its example props under the selected container (or the page root).402 @discardableResult403 public func addComponent(_ type: String, to parentID: String? = nil) -> String? {404 guard let bp = blueprint, let manifest = self.manifest(type) else { return nil }405 func accepts(_ id: String?) -> String? {406 guard let id, let o = bp.object(id) else { return nil }407 if o.isPage { return o.children.first.flatMap { accepts($0) } ?? (o.children.isEmpty ? o.id : nil) }408 return self.manifest(o.type)?.acceptsChildren == true ? o.id : bp.parent(of: o.id).flatMap { accepts($0.id) }409 }410 guard let parent = accepts(parentID ?? designSelection) ?? accepts(runtime?.currentPage ?? bp.entrypoint) else {411 notice = "Select a container (stack, card, grid…) to add the component to."412 return nil413 }414 let newID = bp.uniqueID(manifest.name)415 var object = PrismObject(id: newID, type: type, name: manifest.name, provenance: ["source": "design"])416 // Start from the fixture's props when they stand alone; data components need a table that exists in this app.417 let fixtureProps = manifest.fixture["objects"]?[0]?["props"]?.objectValue ?? [:]418 var patches: [BlueprintPatch] = []419 var state = bp.state420 for (k, v) in fixtureProps {421 if let path = (v["$bind"]?.stringValue) {422 let key = bp.state[path] == nil ? path : "\(newID)_\(path)"423 if state[key] == nil { state[key] = manifest.fixture["state"]?[path] ?? "" }424 object.props[k] = ["$bind": .string(key)]425 } else if k == "table" || k == "query" || k == "optionsFrom" {426 guard let table = bp.tables.first?.id else { continue }427 if k == "table" { object.props[k] = .string(table) }428 if k == "query", manifest.category == "data" || manifest.category == "charts" {429 object.props[k] = Self.retarget(v, to: table, schema: runtime?.schema(table))430 }431 } else if !["x", "y", "label", "value", "valueColumn", "columns", "selection", "recordId"].contains(k) || !["data", "charts"].contains(manifest.category) {432 object.props[k] = v433 }434 }435 if manifest.category == "charts", let table = bp.tables.first.flatMap({ runtime?.schema($0.id) }) {436 let numeric = table.columns.first { $0.type.isNumeric }?.name, group = table.columns.first { $0.type == .text }?.name ?? table.columns.first?.name437 if let numeric, let group {438 object.props["query"] = ["table": .string(table.name), "groupBy": ["column": .string(group), "as": "group"], "aggregates": [["fn": "sum", "column": .string(numeric), "as": "total"]]]439 object.props[type == "prism.chart.pie" ? "label" : "x"] = "group"440 object.props[type == "prism.chart.pie" ? "value" : "y"] = "total"441 }442 }443 if state != bp.state { patches.append(.setBlueprintField(field: "state", value: .object(state))) }444 let needed = manifest.permissions.filter { !bp.permissions.contains($0) }445 if !needed.isEmpty { patches.append(.setBlueprintField(field: "permissions", value: .array((bp.permissions + needed).map(JSONValue.string)))) }446 patches.append(.addObject(object, parent: parent, index: nil))447 guard edit(patches, label: "Add \(manifest.name)") else { return nil }448 designSelection = newID449 return newID450 }451452 private static func retarget(_ query: JSONValue, to table: String, schema: TableSchema?) -> JSONValue {453 guard query["aggregates"] != nil, let schema, let numeric = schema.columns.first(where: { $0.type.isNumeric })?.name else { return ["table": .string(table)] }454 return ["table": .string(table), "aggregates": [["fn": "sum", "column": .string(numeric), "as": "total"]]]455 }456457 // MARK: Versions458459 @discardableResult460 public func rollback(to snapshot: SnapshotRecord) -> Bool {461 do {462 let bp = try model.store.rollback(id, to: snapshot.id)463 try startRuntime(bp)464 history?.reset(to: bp)465 proposal = nil466 refreshSnapshots()467 say(.status, "Rolled back to “\(snapshot.label)”. Your data was not changed.")468 return true469 } catch {470 notice = "Rollback failed: \(error.localizedDescription)"471 return false472 }473 }474475 public func dismissNotice() { notice = nil }476477 // MARK: Publishing478479 public var defaultPublishDirectory: URL {480 FileManager.default.urls(for: .applicationDirectory, in: .userDomainMask).first ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Applications")481 }482483 public func nextVersion() -> String {484 guard let current = installed?.version else { return "1.0.0" }485 let parts = current.split(separator: ".").map { Int($0) ?? 0 } + [0, 0, 0]486 return "\(parts[0]).\(parts[1] + 1).0"487 }488489 @discardableResult490 public func preparePublish(directory: URL, version: String, signingIdentity: String?) -> PublishPlan? {491 publishError = nil; publishResult = nil; launchReport = nil492 guard let publisher = model.publisher else { publishError = "The satellite runtime is missing from this copy of PRISM."; return nil }493 guard let bp = blueprint else { publishError = "There is no app to publish yet."; return nil }494 do {495 try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)496 publishPlan = try publisher.plan(blueprint: bp, projectID: id, version: version, directory: directory, signingIdentity: signingIdentity)497 } catch { publishPlan = nil; publishError = error.localizedDescription }498 return publishPlan499 }500501 /// Publishes the approved plan, then launches the result to verify it. `verify: false` skips the launch (tests of the file work only).502 @discardableResult503 public func publish(verify: Bool = true) async -> Bool {504 guard let publisher = model.publisher, let plan = publishPlan, let bp = blueprint, !isPublishing else { return false }505 isPublishing = true506 defer { isPublishing = false }507 let buildID = try? model.store.startBuild(id, kind: "publish", manifest: plan.manifest.json)508 do {509 runtime?.persistStateNow()510 let result = try publisher.publish(plan, blueprint: bp)511 publishResult = result512 installed = result.installed513 publishPlan = nil514 model.store.audit(id, "publish", "Published \(plan.manifest.displayName) \(plan.manifest.version) to \(plan.destination.path)",515 ["bundleId": .string(plan.manifest.appId), "signing": .string(result.installed.signing), "permissions": .array(plan.manifest.permissions.map(JSONValue.string))])516 if verify {517 launchReport = await SatelliteVerifier.verify(app: plan.destination, bundleID: plan.manifest.appId, dataBase: model.satelliteDataBase)518 }519 if let buildID { model.store.finishBuild(buildID, status: launchReport?.passed == false ? "failed" : "succeeded", manifest: plan.manifest.json) }520 return launchReport?.passed ?? true521 } catch {522 publishError = error.localizedDescription523 if let buildID { model.store.finishBuild(buildID, status: "failed", manifest: ["error": .string(error.localizedDescription)]) }524 return false525 }526 }527528 @discardableResult529 public func rollbackSatellite() -> Bool {530 guard let publisher = model.publisher else { return false }531 do {532 installed = try publisher.rollback(projectID: id)533 model.store.audit(id, "publish.rollback", "Restored the previously published version")534 publishResult = nil; launchReport = nil; publishError = nil535 return true536 } catch { publishError = error.localizedDescription; return false }537 }538539 @discardableResult540 public func uninstallSatellite(removeData: Bool) -> Bool {541 guard let publisher = model.publisher else { return false }542 do {543 try publisher.uninstall(projectID: id, removeData: removeData, dataBase: model.satelliteDataBase)544 model.store.audit(id, "publish.uninstall", removeData ? "Uninstalled the app and deleted its data" : "Uninstalled the app; its data was kept")545 installed = nil; publishResult = nil; launchReport = nil; publishError = nil; publishPlan = nil546 return true547 } catch { publishError = error.localizedDescription; return false }548 }549550 /// The contract of a component type: from the catalog, or an on-demand component of this app.551 func manifest(_ type: String) -> ComponentManifest? {552 blueprint.flatMap { model.registry.manifest(type, in: $0) } ?? model.registry.manifest(type)553 }554}555