SPB Git

Repository Public License

ProjectView.swift 13.9 KB 293 lines swift

1import PrismAIOrchestrator2import PrismObjectModel3import PrismRenderer4import SwiftUI56struct ProjectView: View {7    @Bindable var model: StudioModel8    @Bindable var session: ProjectSession9    @State private var showContext = false1011    var body: some View {12        VStack(spacing: 0) {13            if let notice = session.notice {14                HStack {15                    Image(systemName: "exclamationmark.triangle.fill").foregroundStyle(.orange)16                    Text(notice).font(.callout)17                    Spacer()18                    Button("Dismiss") { session.dismissNotice() }19                }20                .padding(10).background(.orange.opacity(0.12))21            }22            content.frame(maxWidth: .infinity, maxHeight: .infinity)23            Divider()24            composerBar25        }26        .navigationTitle(session.record.name)27        .navigationSubtitle(session.blueprint.map { "Version \($0.version) · \($0.components.count) components" } ?? "Not built yet")28        .toolbar {29            ToolbarItem(placement: .principal) {30                Picker("Mode", selection: $session.mode) {31                    ForEach(StudioMode.allCases) { mode in32                        Label(mode.title, systemImage: mode.symbol).tag(mode)33                    }34                }35                .pickerStyle(.segmented)36                .disabled(session.isDraft)37                .help(session.isDraft ? "Build the app first" : "Switch view (⌘1–⌘5)")38            }39            ToolbarItemGroup {40                Button { session.undo() } label: { Label("Undo", systemImage: "arrow.uturn.backward") }.disabled(!session.canUndo).help(session.history?.undoLabel.map { "Undo \($0)" } ?? "Nothing to undo")41                Button { session.redo() } label: { Label("Redo", systemImage: "arrow.uturn.forward") }.disabled(!session.canRedo).help(session.history?.redoLabel.map { "Redo \($0)" } ?? "Nothing to redo")42            }43        }44    }4546    @ViewBuilder47    private var content: some View {48        if session.isBuilding || session.isDraft || session.mode == .create {49            BuildView(model: model, session: session)50        } else {51            switch session.mode {52            case .preview, .create: PreviewPane(session: session)53            case .design: DesignView(model: model, session: session)54            case .evolve: EvolveView(model: model, session: session)55            case .publish: PublishView(model: model, session: session)56            }57        }58    }5960    /// The prompt composer stays reachable from every mode (spec §8).61    private var composerBar: some View {62        HStack(alignment: .bottom, spacing: 8) {63            Composer(64                text: $session.composerDraft, placeholder: session.blueprint == nil ? "Describe the app you need…" : "Ask for a change, e.g. “Add a budget alert and a new chart”",65                actionTitle: session.blueprint == nil ? "Build" : "Propose", isBusy: session.isBuilding,66                onSubmit: { let text = session.composerDraft; session.composerDraft = ""; session.submit(text) }, onStop: { session.cancelBuild() }67            )68            Button { showContext = true } label: { Image(systemName: "eye") }69                .help("See exactly what a request sends to Anthropic")70                .accessibilityLabel("Preview what will be sent to Anthropic")71                .popover(isPresented: $showContext) {72                    ScrollView {73                        Text(session.contextPreview).font(.callout.monospaced()).textSelection(.enabled).padding(14).frame(maxWidth: .infinity, alignment: .leading)74                    }75                    .frame(width: 520, height: 420)76                }77        }78        .padding(10)79        .background(.bar)80    }81}8283struct PreviewPane: View {84    let session: ProjectSession8586    var body: some View {87        if let runtime = session.runtime {88            AppView(runtime: runtime)89        } else {90            ContentUnavailableView("Nothing to run yet", systemImage: "play.slash", description: Text("Build the app to see it here."))91        }92    }93}9495/// Create mode: real progress, a live map of the components placed so far, and the draft app running beside it.96struct BuildView: View {97    @Bindable var model: StudioModel98    @Bindable var session: ProjectSession99    @Environment(\.openSettings) private var openSettings100101    var body: some View {102        ResizableSplit(initial: .first(410), minFirst: 320, minSecond: 380) {103            ScrollView {104                VStack(alignment: .leading, spacing: 16) {105                    header106                    milestones107                    if !session.draftComponents.isEmpty { componentMap }108                    if !session.steps.isEmpty { activity }109                    if let outcome = session.lastOutcome { OutcomeSummary(outcome: outcome) }110                    transcript111                }112                .padding(18)113                .frame(maxWidth: .infinity, alignment: .leading)114            }115        } second: {116            Group {117                if let draft = session.draftRuntime {118                    AppView(runtime: draft).overlay(alignment: .topTrailing) { Text("Live draft · sample data").font(.caption).padding(6).background(.thinMaterial, in: Capsule()).padding(8) }119                } else if let runtime = session.runtime {120                    AppView(runtime: runtime)121                } else {122                    ContentUnavailableView("The app appears here as it is built", systemImage: "rectangle.3.group", description: Text("PRISM runs the draft as soon as its first valid page exists."))123                }124            }125            .frame(maxWidth: .infinity, maxHeight: .infinity)126        }127    }128129    @ViewBuilder130    private var header: some View {131        if session.isBuilding {132            HStack(spacing: 10) {133                ProgressView().controlSize(.small)134                Text(session.streamingText.isEmpty ? (session.steps.last?.summary ?? "Contacting Claude…") : session.streamingText)135                    .lineLimit(3).font(.callout)136                Spacer()137                Button("Stop", role: .cancel) { session.cancelBuild() }138            }139        } else if session.isDraft {140            VStack(alignment: .leading, spacing: 10) {141                Text(session.unfinishedDraft == nil ? "This app has not been built yet" : "The first build did not pass its checks").font(.title3.bold())142                if !model.keyStatus.canBuild {143                    Text("Claude is not connected. Your request is saved. Add an Anthropic API key to build it, or start from a recipe that needs no Claude call.")144                        .foregroundStyle(.secondary)145                    HStack {146                        Button("Open Settings") { openSettings() }.buttonStyle(.borderedProminent)147                        ForEach(model.templateNames, id: \.self) { name in148                            Button("Use the \(name.replacingOccurrences(of: "-", with: " ")) recipe") { model.createFromTemplate(name, into: session.id) }149                        }150                    }151                } else {152                    Text(session.unfinishedDraft == nil ? "Run the saved request, or type a new one below." : "Ask for a fix below, or run the request again from scratch.").foregroundStyle(.secondary)153                    Button("Build “\(session.conversation.last(where: { $0.role == .user })?.text.prefix(60) ?? "request")”") { session.retryLastRequest() }154                        .buttonStyle(.borderedProminent)155                        .disabled(session.conversation.first(where: { $0.role == .user }) == nil)156                }157            }158        } else {159            Text("Build history").font(.title3.bold())160        }161    }162163    private var milestones: some View {164        VStack(alignment: .leading, spacing: 6) {165            // A change to an existing app does not re-parse intent or re-create the data model: list only the steps that apply.166            let shown = session.blueprint == nil ? Milestone.allCases : Milestone.allCases.filter { session.milestones.contains($0) || $0 == .previewRunning || $0 == .testsComplete }167            ForEach(shown, id: \.self) { m in168                let done = session.milestones.contains(m)169                HStack(spacing: 8) {170                    Image(systemName: done ? "checkmark.circle.fill" : "circle").foregroundStyle(done ? Color.green : Color.secondary)171                    Text(m.title).foregroundStyle(done ? .primary : .secondary)172                }173                .accessibilityElement(children: .combine)174                .accessibilityLabel("\(m.title): \(done ? "done" : "not yet")")175            }176            if session.usage.totalTokens > 0 {177                Text("\(session.usage.inputTokens + session.usage.cacheReadTokens + session.usage.cacheWriteTokens) tokens in · \(session.usage.outputTokens) out · est. \(session.estimatedCost.map { $0.formatted(.currency(code: "USD").precision(.fractionLength(2...4))) } ?? "cost unknown for this model")")178                    .font(.caption).foregroundStyle(.secondary).padding(.top, 2)179            }180        }181    }182183    private var componentMap: some View {184        VStack(alignment: .leading, spacing: 6) {185            Text("Components (\(session.draftComponents.count))").font(.headline)186            FlowLayout(spacing: 6) {187                ForEach(Array(session.draftComponents.enumerated()), id: \.offset) { _, entry in188                    let parts = entry.split(separator: "|", maxSplits: 1).map(String.init)189                    Text(parts.last ?? entry)190                        .font(.caption)191                        .padding(.horizontal, 8).padding(.vertical, 3)192                        .background(Color.accentColor.opacity(0.14), in: Capsule())193                        .help(parts.first ?? "")194                }195            }196        }197    }198199    private var activity: some View {200        VStack(alignment: .leading, spacing: 4) {201            Text("Activity").font(.headline)202            ForEach(session.steps.suffix(60)) { step in203                HStack(alignment: .firstTextBaseline, spacing: 6) {204                    Image(systemName: step.ok ? "checkmark" : "exclamationmark.triangle").font(.caption).foregroundStyle(step.ok ? Color.secondary : Color.orange).frame(width: 14)205                    Text(step.tool).font(.caption.monospaced()).foregroundStyle(.secondary)206                    Text(step.summary).font(.caption).lineLimit(2)207                }208            }209        }210    }211212    private var transcript: some View {213        VStack(alignment: .leading, spacing: 8) {214            ForEach(session.conversation.suffix(12)) { item in ChatBubble(item: item) }215        }216    }217}218219struct ChatBubble: View {220    let item: ChatItem221222    var body: some View {223        HStack(alignment: .top, spacing: 8) {224            Image(systemName: item.role == .user ? "person.fill" : item.role == .assistant ? "sparkles" : "info.circle")225                .foregroundStyle(item.role == .status ? Color.secondary : Color.accentColor).frame(width: 18)226                .accessibilityLabel(item.role == .user ? "You" : item.role == .assistant ? "Claude" : "PRISM")227            Text(item.text).font(.callout).foregroundStyle(item.role == .status ? .secondary : .primary).textSelection(.enabled)228            Spacer(minLength: 0)229        }230    }231}232233struct OutcomeSummary: View {234    let outcome: BuildOutcome235236    var body: some View {237        let ok = outcome.status == .succeeded238        VStack(alignment: .leading, spacing: 6) {239            Label(title, systemImage: ok ? "checkmark.seal.fill" : "exclamationmark.triangle.fill").foregroundStyle(ok ? Color.green : Color.orange).font(.headline)240            Text("\(outcome.toolCalls) tool calls · \(outcome.turns) turns · catalog coverage \(Int(outcome.coverage * 100))% · model \(outcome.model)").font(.caption).foregroundStyle(.secondary)241            if !outcome.requestedPermissions.isEmpty {242                Text("Permissions this app uses: \(outcome.requestedPermissions.joined(separator: ", "))").font(.caption).foregroundStyle(.secondary)243            }244            ForEach(Array(outcome.issues.errors.prefix(6).enumerated()), id: \.offset) { _, issue in245                Label(issue.message, systemImage: "xmark.circle").font(.caption).foregroundStyle(.red)246            }247            if let error = outcome.error { Text(error).font(.callout).foregroundStyle(.red) }248        }249        .padding(12)250        .frame(maxWidth: .infinity, alignment: .leading)251        .background(.quaternary.opacity(0.4), in: RoundedRectangle(cornerRadius: 10))252    }253254    private var title: String {255        switch outcome.status {256        case .succeeded: "Built and checked"257        case .incomplete: "Built, but some checks fail"258        case .cancelled: "Cancelled"259        case .budgetExceeded: "Stopped at the budget"260        case .refused: "Claude declined"261        case .failed: "The build failed"262        }263    }264}265266/// Wraps chips onto as many lines as needed.267struct FlowLayout: Layout {268    var spacing: CGFloat = 6269270    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {271        let width = proposal.width ?? 400272        var x: CGFloat = 0, y: CGFloat = 0, line: CGFloat = 0273        for s in subviews {274            let size = s.sizeThatFits(.unspecified)275            if x + size.width > width, x > 0 { x = 0; y += line + spacing; line = 0 }276            x += size.width + spacing277            line = max(line, size.height)278        }279        return CGSize(width: width, height: y + line)280    }281282    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {283        var x = bounds.minX, y = bounds.minY, line: CGFloat = 0284        for s in subviews {285            let size = s.sizeThatFits(.unspecified)286            if x + size.width > bounds.maxX, x > bounds.minX { x = bounds.minX; y += line + spacing; line = 0 }287            s.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))288            x += size.width + spacing289            line = max(line, size.height)290        }291    }292}293
Files main
Menu

Theme