SPB Git

Repository Public License

LibraryMonitorSettingsViews.swift 15.5 KB 279 lines swift

1import PrismAIOrchestrator2import PrismComponentSDK3import PrismDataRuntime4import PrismProjectStore5import PrismRenderer6import SwiftUI78struct LibraryView: View {9    @Bindable var model: StudioModel10    @State private var query = ""11    @State private var category = ""12    @State private var selected: String?1314    private var results: [ComponentManifest] { model.registry.search(query, category: category.isEmpty ? nil : category, limit: 100).map(\.manifest) }1516    var body: some View {17        ResizableSplit(initial: .first(320), minFirst: 260, minSecond: 420) {18            VStack(spacing: 0) {19                HStack {20                    TextField("Search \(model.registry.count) components", text: $query).textFieldStyle(.roundedBorder)21                    Picker("Category", selection: $category) {22                        Text("All").tag("")23                        ForEach(ComponentManifest.categories, id: \.self) { Text($0.capitalized).tag($0) }24                    }.labelsHidden().fixedSize()25                }26                .padding(10)27                List(results, selection: $selected) { m in28                    VStack(alignment: .leading, spacing: 1) {29                        Text(m.name)30                        Text(m.type).font(.caption.monospaced()).foregroundStyle(.secondary)31                    }32                    .tag(m.type)33                }34                .listStyle(.inset)35                if !model.registry.rejections.isEmpty {36                    Label("\(model.registry.rejections.count) component(s) were rejected at load (hash mismatch).", systemImage: "exclamationmark.shield").font(.caption).foregroundStyle(.red).padding(8)37                }38            }39        } second: {40            Group {41                if let type = selected ?? results.first?.type, let m = model.registry.manifest(type) { ComponentDetail(manifest: m, registry: model.registry).id(type) }42                else { ContentUnavailableView("No component matches", systemImage: "magnifyingglass") }43            }44            .frame(maxWidth: .infinity, maxHeight: .infinity)45        }46        .navigationTitle("Library")47        .navigationSubtitle("\(model.registry.count) verified components")48    }49}5051struct ComponentDetail: View {52    let manifest: ComponentManifest53    let registry: ComponentRegistry54    @State private var runtime: AppRuntime?5556    var body: some View {57        ScrollView {58            VStack(alignment: .leading, spacing: 14) {59                HStack(alignment: .firstTextBaseline) {60                    Text(manifest.name).font(.title2.bold())61                    Text("v\(manifest.version)").foregroundStyle(.secondary)62                    Spacer()63                    Label("Hash verified", systemImage: "checkmark.shield").font(.caption).foregroundStyle(.green).help(manifest.contentHash)64                }65                Text(manifest.summary).foregroundStyle(.secondary)66                GroupBox("Live preview") {67                    Group {68                        if let runtime { AppView(runtime: runtime) } else { Text("Preview unavailable").foregroundStyle(.secondary) }69                    }70                    .frame(maxWidth: .infinity, minHeight: 220, maxHeight: 320)71                }72                if !manifest.permissions.isEmpty { Label("Needs: \(manifest.permissions.joined(separator: ", "))", systemImage: "lock").font(.callout) }73                Text("Properties").font(.headline)74                Grid(alignment: .leading, horizontalSpacing: 14, verticalSpacing: 5) {75                    ForEach(manifest.props, id: \.name) { p in76                        GridRow {77                            Text(p.name + (p.required ? " *" : "")).font(.callout.monospaced())78                            Text(p.kind.rawValue + (p.binding == .required ? " · bound" : p.dynamic ? " · fx" : "")).font(.caption).foregroundStyle(.secondary)79                            Text(p.summary).font(.callout)80                        }81                    }82                }83                if !manifest.events.isEmpty { Text("Events: \(manifest.events.joined(separator: ", "))").font(.callout) }84                Text("Accessibility: \(manifest.accessibilityRole)" + (manifest.accessibilityLabelProp.map { ", labelled by `\($0)`" } ?? "")).font(.callout).foregroundStyle(.secondary)85                Text("Example").font(.headline)86                Text(manifest.examples.first?.prettyString() ?? "").font(.caption.monospaced()).textSelection(.enabled)87                    .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 8))88            }89            .padding(20)90        }91        .task {92            guard let bp = try? manifest.fixtureBlueprint() else { return }93            runtime = try? AppRuntime(blueprint: bp, store: AppDataStore(url: nil), registry: registry)94        }95    }96}9798struct MonitorView: View {99    @Bindable var model: StudioModel100    @State private var tab = "jobs"101    @State private var refresh = 0102103    var body: some View {104        VStack(alignment: .leading, spacing: 0) {105            Picker("Section", selection: $tab) {106                Text("Jobs").tag("jobs"); Text("Usage & cost").tag("usage"); Text("Audit log").tag("audit"); Text("API requests").tag("api")107            }108            .pickerStyle(.segmented).labelsHidden().fixedSize().padding(12)109            Divider()110            Group {111                switch tab {112                case "usage": usage113                case "audit": audit114                case "api": api115                default: jobs116                }117            }118            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)119        }120        .navigationTitle("Monitor")121        .toolbar { Button { refresh += 1 } label: { Label("Refresh", systemImage: "arrow.clockwise") } }122    }123124    private func name(_ projectID: String) -> String { model.projects.first { $0.id == projectID }?.name ?? "Deleted app" }125126    private var jobs: some View {127        let builds = model.store.builds(limit: 200 + refresh * 0)128        return List(builds) { b in129            HStack {130                Image(systemName: b.status == "succeeded" ? "checkmark.circle.fill" : b.status == "running" ? "clock" : "exclamationmark.triangle.fill")131                    .foregroundStyle(b.status == "succeeded" ? .green : b.status == "running" ? .blue : .orange)132                VStack(alignment: .leading, spacing: 1) {133                    Text("\(b.kind.capitalized) · \(name(b.projectID))")134                    Text("\(b.status) · \(b.startedAt.formatted(date: .abbreviated, time: .standard))" + (b.manifest["toolCalls"]?.intValue.map { " · \($0) tool calls" } ?? "")).font(.caption).foregroundStyle(.secondary)135                }136                Spacer()137                if let cost = b.manifest["estimatedCostUSD"]?.doubleValue { Text(cost.formatted(.currency(code: "USD").precision(.fractionLength(2...4)))).monospacedDigit().foregroundStyle(.secondary) }138            }139        }140        .overlay { if builds.isEmpty { ContentUnavailableView("No jobs yet", systemImage: "tray", description: Text("Builds and publishes appear here.")) } }141    }142143    private var usage: some View {144        let rows = model.store.usage()145        return VStack(alignment: .leading, spacing: 10) {146            Text("Token counts are the ones the API reported. Costs are estimates from PRISM's price snapshot of \(model.settings.prices.asOf); your Anthropic invoice is the actual cost.")147                .font(.callout).foregroundStyle(.secondary).padding([.horizontal, .top], 14)148            Table(rows) {149                TableColumn("Model", value: \.model)150                TableColumn("Requests") { Text("\($0.requests)").monospacedDigit() }151                TableColumn("Input") { Text($0.inputTokens.formatted()).monospacedDigit() }152                TableColumn("Output") { Text($0.outputTokens.formatted()).monospacedDigit() }153                TableColumn("Cache read") { Text($0.cacheReadTokens.formatted()).monospacedDigit() }154                TableColumn("Cache write") { Text($0.cacheWriteTokens.formatted()).monospacedDigit() }155                TableColumn("Est. cost") { Text($0.estimatedCostUSD.formatted(.currency(code: "USD").precision(.fractionLength(2...4)))).monospacedDigit() }156            }157            .overlay { if rows.isEmpty { ContentUnavailableView("No usage yet", systemImage: "chart.bar") } }158        }159    }160161    private var audit: some View {162        let entries = model.store.auditLog(limit: 400 + refresh * 0)163        return List(entries) { e in164            VStack(alignment: .leading, spacing: 1) {165                HStack {166                    Text(e.kind).font(.caption.monospaced()).foregroundStyle(.tint)167                    Text(e.projectID.map(name) ?? "PRISM").font(.caption).foregroundStyle(.secondary)168                    Spacer()169                    Text(e.date.formatted(date: .numeric, time: .standard)).font(.caption).foregroundStyle(.secondary)170                }171                Text(e.summary).font(.callout).lineLimit(2)172            }173        }174        .overlay { if entries.isEmpty { ContentUnavailableView("Nothing logged yet", systemImage: "list.bullet.clipboard") } }175    }176177    private var api: some View {178        List(Array(model.apiLog.reversed().enumerated()), id: \.offset) { _, line in179            Text(line).font(.caption.monospaced()).textSelection(.enabled)180        }181        .overlay { if model.apiLog.isEmpty { ContentUnavailableView("No requests this session", systemImage: "network", description: Text("Each request to Anthropic is listed with its status and request id. Keys are never logged.")) } }182    }183}184185extension UsageRecord: Identifiable { public var id: String { model } }186187struct SettingsView: View {188    @Bindable var model: StudioModel189    @State private var candidate = ""190    @State private var confirmRemove = false191192    var body: some View {193        TabView {194            claude.tabItem { Label("Claude", systemImage: "sparkles") }195            limits.tabItem { Label("Limits", systemImage: "gauge.with.needle") }196            privacy.tabItem { Label("Privacy", systemImage: "hand.raised") }197        }198        .frame(width: 560, height: 430)199    }200201    private var claude: some View {202        Form {203            Section("Anthropic API key") {204                statusLine205                SecureField("sk-ant-…", text: $candidate).textContentType(.password).accessibilityLabel("Anthropic API key")206                HStack {207                    Button("Verify and Save") { Task { if await model.saveKey(candidate) { candidate = "" } } }208                        .disabled(candidate.trimmingCharacters(in: .whitespaces).isEmpty || model.isCheckingKey)209                    Button("Test Connection") { Task { await model.testConnection() } }.disabled(model.keyStatus == .missing || model.isCheckingKey)210                    Button("Remove Key…", role: .destructive) { confirmRemove = true }.disabled(model.keyStatus == .missing)211                    if model.isCheckingKey { ProgressView().controlSize(.small) }212                }213                Text("The key is kept only in your macOS Keychain. It is sent to api.anthropic.com in a request header and nowhere else.").font(.caption).foregroundStyle(.secondary)214            }215            Section("Model") {216                if model.models.isEmpty {217                    LabeledContent("Model", value: model.settings.model)218                    Text("The list comes from your account. Test the connection to load it. Until then PRISM uses the model above.").font(.caption).foregroundStyle(.secondary)219                } else {220                    Picker("Model", selection: $model.settings.model) {221                        ForEach(model.models) { Text("\($0.displayName) (\($0.id))").tag($0.id) }222                    }223                    if model.settings.prices.estimate(model: model.settings.model, usage: TokenUsage()) == nil {224                        Text("PRISM has no price for this model, so cost estimates and the cost budget are unavailable for it; the tool-call limit still applies.").font(.caption).foregroundStyle(.orange)225                    }226                }227                Picker("Effort", selection: $model.settings.effort) { ForEach(StudioModel.effortLevels, id: \.self) { Text($0).tag($0) } }228                Text("One model plans and builds. Higher effort is slower and uses more tokens.").font(.caption).foregroundStyle(.secondary)229            }230        }231        .formStyle(.grouped)232        .confirmationDialog("Remove the API key from the Keychain?", isPresented: $confirmRemove) { Button("Remove Key", role: .destructive) { model.removeKey() } }233    }234235    @ViewBuilder236    private var statusLine: some View {237        switch model.keyStatus {238        case .missing: Label("No key stored. Claude features are unavailable; catalog apps and recipes still work.", systemImage: "key.slash").foregroundStyle(.orange)239        case .stored(let f): Label("Key \(f) is stored but has not been checked this session.", systemImage: "key")240        case .verified(let f, let n): Label("Connected with key \(f). \(n) models available to this account.", systemImage: "checkmark.seal.fill").foregroundStyle(.green)241        case .invalid(let m): Label(m, systemImage: "xmark.seal.fill").foregroundStyle(.red)242        case .unreachable(let m): Label(m, systemImage: "wifi.slash").foregroundStyle(.orange)243        }244    }245246    private var limits: some View {247        Form {248            Section("Per build") {249                Stepper("At most \(model.settings.budget.maxToolCalls) tool calls", value: $model.settings.budget.maxToolCalls, in: 10...400, step: 10)250                Toggle("Stop at a cost budget", isOn: Binding(get: { model.settings.budget.maxCostUSD != nil }, set: { model.settings.budget.maxCostUSD = $0 ? 3 : nil }))251                if model.settings.budget.maxCostUSD != nil {252                    LabeledContent("Budget (estimated USD)") {253                        TextField("", value: Binding(get: { model.settings.budget.maxCostUSD ?? 3 }, set: { model.settings.budget.maxCostUSD = max(0.05, $0) }), format: .number.precision(.fractionLength(2)))254                            .frame(width: 80).multilineTextAlignment(.trailing).accessibilityLabel("Cost budget in dollars")255                    }256                }257                Text("A build stops as soon as a limit is reached and tells you which one. You can also stop it at any time with ⌘. (period).").font(.caption).foregroundStyle(.secondary)258            }259        }260        .formStyle(.grouped)261    }262263    private var privacy: some View {264        Form {265            Section("What PRISM sends to Anthropic") {266                Text("Only when you press Build or Propose: your request, PRISM's instructions and component catalog, the structure of the app being changed, and the results of PRISM's own tools (validation messages, table schemas, row counts).")267                Text("Never: your API key in a message, your files, other apps, or the rows stored in your apps, unless you turn on the option below.").foregroundStyle(.secondary)268                Toggle("Let the builder see up to 5 sample rows per query", isOn: $model.allowSampleRows)269                Text("Off by default. The eye button next to the composer shows exactly what the next request will send.").font(.caption).foregroundStyle(.secondary)270            }271            Section("On this Mac") {272                LabeledContent("Library", value: model.store.root.path)273                Text("Apps, versions, data and the audit log stay in this folder. Nothing is uploaded to a PRISM service; there is none.").font(.caption).foregroundStyle(.secondary)274            }275        }276        .formStyle(.grouped)277    }278}279
Files main
Menu

Theme