SPB Git

Repository Public License

StudioModel.swift 12.3 KB 273 lines swift

1import Foundation2import Observation3import PrismAIOrchestrator4import PrismComponentCatalog5import PrismComponentSDK6import PrismCore7import PrismDataRuntime8import PrismObjectModel9import PrismProjectStore10import PrismRenderer11import PrismSatellitePublisher12import PrismSecurity1314public enum SidebarItem: Hashable, Sendable {15    case welcome, library, monitor16    case project(String)17}1819public enum KeyStatus: Equatable, Sendable {20    case missing21    case stored(fingerprint: String)22    case verified(fingerprint: String, models: Int)23    case invalid(String)24    case unreachable(String)2526    public var canBuild: Bool {27        switch self {28        case .stored, .verified, .unreachable: true29        case .missing, .invalid: false30        }31    }32}3334/// The app-wide state of PRISM. Views are thin; behaviour lives here so it runs under `swift test`.35@MainActor36@Observable37public final class StudioModel {38    public let store: ProjectStore39    public let secrets: SecretStore40    public let registry = Catalog.registry41    public let publisher: SatellitePublisher?42    public var dialogs: FileDialogs?43    public private(set) var client: AnthropicClient4445    public private(set) var projects: [ProjectRecord] = []46    public var selection: SidebarItem? = .welcome47    public private(set) var keyStatus: KeyStatus = .missing48    public private(set) var models: [ModelInfo] = []49    public private(set) var apiLog: [String] = []50    public private(set) var isCheckingKey = false51    public var settings = AgentSettings() { didSet { if settings != oldValue { persistSettings() } } }52    /// Opt-in: lets the builder see up to five rows per query while it checks its work.53    public var allowSampleRows = false { didSet { store.setSetting("allowSampleRows", allowSampleRows ? "1" : nil) } }54    public var lastError: String?55    /// What is typed in the welcome composer; kept here so it survives switching screens.56    public var welcomeDraft = ""5758    @ObservationIgnored private var sessions: [String: ProjectSession] = [:]59    @ObservationIgnored let templatesDirectory: URL?60    /// Redirects satellites' data folders; only tests set it.61    @ObservationIgnored public var satelliteDataBase: URL?6263    public static let suggestedPrompts = [64        "Build a local expense tracker with CSV import, category filters, monthly chart and persistent storage.",65        "Create a personal finance app with charts, CSV imports, budgets and local storage.",66        "Make a reading list with status, rating, a search box and a chart of books finished per month.",67        "Track my workouts: date, exercise, minutes, and a chart of total minutes per month.",68    ]6970    public init(root: URL = ProjectStore.defaultRoot, secrets: SecretStore = KeychainSecretStore(), transport: HTTPTransport = URLSessionTransport(),71                hostTemplate: URL? = nil, templatesDirectory: URL? = nil, dialogs: FileDialogs? = nil) throws {72        self.secrets = secrets73        self.dialogs = dialogs74        self.templatesDirectory = templatesDirectory75        let secretsRef = secrets76        store = try ProjectStore(root: root) { [(try? secretsRef.secret(for: SecretAccount.anthropicAPIKey)) ?? nil].compactMap { $0 } }77        publisher = hostTemplate.map { SatellitePublisher(hostTemplate: $0, registryFile: root.appendingPathComponent("satellites.json"), registry: Catalog.registry) }78        client = AnthropicClient(transport: transport, secrets: secrets)79        client.log = { [weak self] line in Task { @MainActor in self?.appendAPILog(line) } }80        loadSettings()81        refreshProjects()82        refreshKeyStatus()83    }8485    private func appendAPILog(_ line: String) {86        apiLog.append("\(Date().formatted(date: .omitted, time: .standard))  \(line)")87        if apiLog.count > 300 { apiLog.removeFirst(apiLog.count - 300) }88    }8990    // MARK: Settings9192    private func loadSettings() {93        allowSampleRows = store.setting("allowSampleRows") == "1"94        guard let raw = store.setting("agent"), let json = try? JSONValue.parse(raw) else { return }95        var s = AgentSettings()96        if let m = json["model"]?.stringValue, !m.isEmpty { s.model = m }97        if let e = json["effort"]?.stringValue, Self.effortLevels.contains(e) { s.effort = e }98        if let v = json["maxToolCalls"]?.intValue { s.budget.maxToolCalls = max(5, min(v, 400)) }99        if let v = json["maxCostUSD"]?.doubleValue { s.budget.maxCostUSD = max(0.05, v) }100        if json["maxCostUSD"]?.isNull == true { s.budget.maxCostUSD = nil }101        settings = s102    }103104    private func persistSettings() {105        let json: JSONValue = [106            "model": .string(settings.model), "effort": .string(settings.effort), "maxToolCalls": .int(settings.budget.maxToolCalls),107            "maxCostUSD": settings.budget.maxCostUSD.map(JSONValue.double) ?? .null,108        ]109        store.setSetting("agent", json.canonicalString())110    }111112    public static let effortLevels = ["low", "medium", "high", "xhigh", "max"]113114    // MARK: API key115116    public func refreshKeyStatus() {117        if let key = (try? secrets.secret(for: SecretAccount.anthropicAPIKey)) ?? nil, !key.isEmpty {118            if case .verified = keyStatus { return }119            keyStatus = .stored(fingerprint: Redactor.fingerprint(key))120        } else {121            keyStatus = .missing122        }123    }124125    /// Checks a key against the API before storing it; a rejected key never reaches the Keychain.126    @discardableResult127    public func saveKey(_ candidate: String) async -> Bool {128        let key = candidate.trimmingCharacters(in: .whitespacesAndNewlines)129        guard !key.isEmpty else { keyStatus = .invalid("Enter a key first."); return false }130        isCheckingKey = true131        defer { isCheckingKey = false }132        do {133            let list = try await client.listModels(key: key)134            try secrets.setSecret(key, for: SecretAccount.anthropicAPIKey)135            adopt(models: list)136            keyStatus = .verified(fingerprint: Redactor.fingerprint(key), models: list.count)137            store.audit(nil, "key.add", "Stored an Anthropic API key (\(Redactor.fingerprint(key)))")138            return true139        } catch ClaudeError.invalidKey {140            keyStatus = .invalid("Anthropic rejected this key. It was not stored.")141        } catch let error as ClaudeError {142            // The key could not be checked (offline, outage). Store it and say so, rather than block the user.143            do {144                try secrets.setSecret(key, for: SecretAccount.anthropicAPIKey)145                keyStatus = .unreachable("The key was stored but could not be verified: \(error.localizedDescription)")146            } catch { keyStatus = .invalid(error.localizedDescription) }147        } catch { keyStatus = .invalid(error.localizedDescription) }148        return false149    }150151    @discardableResult152    public func testConnection() async -> Bool {153        guard let key = (try? secrets.secret(for: SecretAccount.anthropicAPIKey)) ?? nil else { keyStatus = .missing; return false }154        isCheckingKey = true155        defer { isCheckingKey = false }156        do {157            let list = try await client.listModels()158            adopt(models: list)159            keyStatus = .verified(fingerprint: Redactor.fingerprint(key), models: list.count)160            return true161        } catch ClaudeError.invalidKey {162            keyStatus = .invalid("Anthropic rejected the stored key.")163        } catch { keyStatus = .unreachable(AnthropicClient.map(error).localizedDescription) }164        return false165    }166167    public func removeKey() {168        try? secrets.removeSecret(for: SecretAccount.anthropicAPIKey)169        models = []170        keyStatus = .missing171        store.audit(nil, "key.remove", "Removed the Anthropic API key")172    }173174    /// Keeps the chosen model if the account still offers it; otherwise falls back to the configured default or the newest listed.175    private func adopt(models list: [ModelInfo]) {176        models = list177        guard !list.isEmpty, !list.contains(where: { $0.id == settings.model }) else { return }178        settings.model = list.first(where: { $0.id == AgentSettings.fallbackModel })?.id ?? list[0].id179    }180181    // MARK: Projects182183    public func refreshProjects() { projects = store.projects() }184185    public func session(for id: String) -> ProjectSession? {186        if let s = sessions[id] { return s }187        guard let record = try? store.project(id) else { return nil }188        let s = ProjectSession(model: self, record: record)189        sessions[id] = s190        s.open()191        return s192    }193194    static func name(from prompt: String) -> String {195        let words = prompt.split(whereSeparator: { $0.isWhitespace }).prefix(6).joined(separator: " ")196        return words.isEmpty ? "Untitled app" : String(words.prefix(48))197    }198199    /// Submitting a prompt always creates a persisted project. The build starts if Claude can be reached;200    /// otherwise the project says exactly why it is waiting.201    @discardableResult202    public func createProject(prompt: String) -> ProjectSession? {203        let text = prompt.trimmingCharacters(in: .whitespacesAndNewlines)204        guard !text.isEmpty else { return nil }205        do {206            let record = try store.createProject(name: Self.name(from: text), prompt: text)207            refreshProjects()208            selection = .project(record.id)209            let s = session(for: record.id)210            s?.submit(text)211            return s212        } catch { lastError = error.localizedDescription; return nil }213    }214215    public var templateNames: [String] {216        guard let templatesDirectory, let items = try? FileManager.default.contentsOfDirectory(atPath: templatesDirectory.path) else { return [] }217        return items.filter { FileManager.default.fileExists(atPath: templatesDirectory.appendingPathComponent($0).appendingPathComponent("blueprint.json").path) }.sorted()218    }219220    /// Creates an app from a bundled recipe. No Claude call is made, so this works offline.221    @discardableResult222    public func createFromTemplate(_ name: String, into existing: String? = nil) -> ProjectSession? {223        guard let url = templatesDirectory?.appendingPathComponent(name).appendingPathComponent("blueprint.json"), let data = FileManager.default.contents(atPath: url.path) else {224            lastError = "The “\(name)” template is missing from this copy of PRISM."225            return nil226        }227        do {228            var blueprint = try AppBlueprint.load(data)229            let errors = BlueprintValidator.validate(blueprint, registry: registry).errors230            guard errors.isEmpty else { throw StoreError("The template is not valid: \(errors[0].message)") }231            let record = try existing.map { try store.project($0) } ?? store.createProject(name: blueprint.name, prompt: "From the \(blueprint.name) template")232            blueprint.id = "app_" + PrismID.slug(record.id)233            try store.save(blueprint, for: record.id, label: "Created from the \(blueprint.name) template")234            refreshProjects()235            sessions[record.id] = nil236            selection = .project(record.id)237            return session(for: record.id)238        } catch { lastError = error.localizedDescription; return nil }239    }240241    public func deleteProject(_ id: String) {242        sessions[id]?.close()243        sessions[id] = nil244        do { try store.deleteProject(id) } catch { lastError = error.localizedDescription }245        refreshProjects()246        if selection == .project(id) { selection = .welcome }247    }248249    @discardableResult250    public func importProject(from url: URL) -> ProjectRecord? {251        do {252            let scoped = url.startAccessingSecurityScopedResource()253            defer { if scoped { url.stopAccessingSecurityScopedResource() } }254            let record = try store.importProject(try Data(contentsOf: url)) { BlueprintValidator.validate($0, registry: self.registry) }255            refreshProjects()256            selection = .project(record.id)257            return record258        } catch { lastError = error.localizedDescription; return nil }259    }260261    @discardableResult262    public func exportProject(_ id: String, to url: URL) -> Bool {263        sessions[id]?.runtime?.persistStateNow()264        do { try AtomicFile.write(try store.exportProject(id), to: url); return true } catch { lastError = error.localizedDescription; return false }265    }266267    /// Called when the app quits: flush every running app's state.268    public func shutdown() {269        for s in sessions.values { s.close() }270        sessions.removeAll()271    }272}273
Files main
Menu

Theme