SPB Git

Repository Public

ClaudeProposalCard.swift 21.6 KB 348 lines swift

1// ORIX DJ2// File: App/Sources/Features/ClaudeStudio/ClaudeProposalCard.swift3// Description: One turn of the Claude Studio conversation: the request, the answer and the validated proposal card4//              (script, compile and simulation results, requirements, risks, diff) with Save, Edit, Test and Run.5//              Run always asks for confirmation and names the decks the script touches.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import ORIXDJCore10import SwiftUI1112struct ClaudeTurnView: View {13    @Environment(AppModel.self) private var model14    var turn: ClaudeTurn15    var studio: ClaudeStudioModel1617    @State private var showSent = false18    @State private var showTrace = false19    @State private var runMessage: String?20    @State private var confirmMapping = false2122    var body: some View {23        VStack(alignment: .leading, spacing: 10) {24            ClaudeRequestHeader(task: turn.task, prompt: turn.prompt)25            DisclosureGroup("What was sent", isExpanded: $showSent) {26                Text(verbatim: turn.sentText).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary)27                    .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(8)28                    .background(ORIX.Palette.well.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))29            }30            .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)31            .accessibilityIdentifier("claude-turn-sent")3233            if let error = turn.error {34                Label { Text(verbatim: error).textSelection(.enabled) } icon: { Image(systemName: "exclamationmark.triangle.fill") }35                    .font(.system(size: 12.5, weight: .medium)).foregroundStyle(ORIX.Palette.danger)36                    .padding(10).frame(maxWidth: .infinity, alignment: .leading)37                    .background(ORIX.Palette.danger.opacity(0.1), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))38                    .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.danger.opacity(0.5)))39                    .accessibilityIdentifier("claude-turn-error")40                if !turn.answer.isEmpty {41                    Text("Partial answer received before the request ended (not validated):").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)42                    Text(verbatim: turn.answer).font(.system(size: 12, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary).textSelection(.enabled)43                }44            } else if let proposal = turn.proposal {45                if proposal.script != nil { scriptCard(proposal) }46                else if proposal.midiProfile != nil || !proposal.midiIssues.isEmpty { midiCard(proposal) }47                let explanation = proposal.explanation48                if !explanation.isEmpty {49                    MarkdownBlocks(nodes: MarkdownParser.parse(explanation).nodes, style: MarkdownStyle(file: nil, scale: 1), spacing: 8)50                        .accessibilityIdentifier("claude-turn-explanation")51                }52                if proposal.script == nil, proposal.midiProfile == nil, proposal.midiIssues.isEmpty, turn.task != .explain, turn.task != .plan {53                    Label("This answer contains no script to validate.", systemImage: "info.circle").font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary)54                }55            }56        }57        .alert("Run this automation live?", isPresented: Binding(get: { runMessage != nil }, set: { if !$0 { runMessage = nil } })) {58            Button("Run Live") { run() }.accessibilityIdentifier("claude-run-confirm")59            Button("Cancel", role: .cancel) {}60        } message: { Text(verbatim: runMessage ?? "") }61        .confirmationDialog("Save this MIDI mapping?", isPresented: $confirmMapping) {62            Button("Save and Activate") { saveMapping(activate: true) }63            Button("Save Without Activating") { saveMapping(activate: false) }64            Button("Cancel", role: .cancel) {}65        } message: { Text(verbatim: mappingMessage) }66        .accessibilityIdentifier("claude-turn")67    }6869    // MARK: Script proposal7071    private var automationName: String { turn.proposal?.compile?.program?.automations.first?.name ?? String(localized: "Claude proposal") }7273    private func scriptCard(_ p: AssistantProposal) -> some View {74        let script = p.script ?? ""75        return Panel(padding: 0) {76            VStack(alignment: .leading, spacing: 0) {77                HStack(spacing: 10) {78                    Image(systemName: "sparkles").foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)79                    Text(verbatim: automationName).font(.system(size: 14, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary).lineLimit(1)80                    Spacer()81                    Label(p.isValid ? "Validated" : "Not valid", systemImage: p.isValid ? "checkmark.seal.fill" : "xmark.seal.fill")82                        .font(.system(size: 11.5, weight: .semibold)).foregroundStyle(p.isValid ? ORIX.Palette.success : ORIX.Palette.danger)83                        .padding(.horizontal, 9).frame(height: 22)84                        .overlay(Capsule().strokeBorder(p.isValid ? ORIX.Palette.success : ORIX.Palette.danger))85                        .accessibilityIdentifier("claude-proposal-validity")86                }87                .padding(.horizontal, 14).padding(.vertical, 10)88                divider8990                ScrollView(.horizontal, showsIndicators: false) {91                    Text(ScriptHighlighter.attributed(script.trimmingCharacters(in: .newlines), size: 12)).lineSpacing(2.5).textSelection(.enabled)92                        .fixedSize(horizontal: true, vertical: true).padding(.horizontal, 14).padding(.vertical, 10)93                }94                .background(ORIX.Palette.well.opacity(0.55))95                .accessibilityLabel("Proposed script").accessibilityValue(Text(verbatim: script))96                .accessibilityIdentifier("claude-proposal-script")97                divider9899                section("Validation") {100                    if let c = p.compile {101                        if c.succeeded {102                            Label("Compiles without errors", systemImage: "checkmark.circle.fill").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.success)103                        } else {104                            Label("\(c.errors.count) compile errors", systemImage: "xmark.octagon.fill").font(.system(size: 12, weight: .semibold)).foregroundStyle(ORIX.Palette.danger)105                            DiagnosticsListView(diagnostics: c.errors)106                        }107                        if !c.warnings.isEmpty { DiagnosticsListView(diagnostics: c.warnings) }108                    }109                }110                .accessibilityIdentifier("claude-proposal-validation")111112                if let sim = p.simulation {113                    divider114                    section(turn.retested ? "Simulation (run again)" : "Simulation") {115                        SimulationSummaryView(simulation: sim, traceLines: showTrace ? 60 : 0)116                        if !sim.trace.isEmpty {117                            Button(showTrace ? "Hide Trace" : "Show Trace (\(sim.trace.count) lines)") { showTrace.toggle() }118                                .buttonStyle(.link).font(.system(size: 11)).accessibilityIdentifier("claude-proposal-trace")119                        }120                    }121                    .accessibilityIdentifier("claude-proposal-simulation")122                }123124                if let req = p.requirements {125                    divider126                    HStack(alignment: .top, spacing: ORIX.Space.lg) {127                        fact("Decks") {128                            if req.decks.isEmpty { Text("None addressed by name").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary) }129                            else { HStack(spacing: 4) { ForEach(req.decks.sorted(), id: \.self) { DeckBadge(index: $0, size: 20) } } }130                        }131                        fact("Effects") {132                            Text(verbatim: req.effects.isEmpty ? String(localized: "None") : req.effects.sorted().joined(separator: ", "))133                                .font(.system(size: 12)).foregroundStyle(req.effects.isEmpty ? ORIX.Palette.textSecondary : ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)134                        }135                        fact("Length") {136                            if let beats = req.lengthBeats {137                                Text("\(formatBeats(beats / ORIXScriptLanguage.beatsPerBar)) bars (\(formatBeats(beats)) beats)").font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)138                            } else {139                                Text("Open-ended: it waits for events or depends on values known only when it runs").font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)140                            }141                        }142                    }143                    .padding(.horizontal, 14).padding(.vertical, 10)144                    .accessibilityIdentifier("claude-proposal-requirements")145                }146147                if !p.risks.isEmpty {148                    divider149                    section("Check before running live") {150                        ForEach(Array(p.risks.enumerated()), id: \.offset) { _, risk in151                            HStack(alignment: .firstTextBaseline, spacing: 6) {152                                Image(systemName: "exclamationmark.triangle").font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).accessibilityHidden(true)153                                Text(verbatim: risk).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)154                            }155                        }156                    }157                    .accessibilityIdentifier("claude-proposal-risks")158                }159160                if turn.task == .fix || turn.task == .improve, let original = turn.originalScript {161                    divider162                    section("Changes against \"\(turn.originalName ?? "")\"") { ClaudeDiffView(old: original, new: script) }163                        .accessibilityIdentifier("claude-proposal-diff")164                }165166                divider167                HStack(spacing: 8) {168                    Button { save(script) } label: { Label(turn.saved ? "Saved" : "Save", systemImage: turn.saved ? "checkmark" : "tray.and.arrow.down") }169                        .disabled(turn.saved).help("Save to the script library, marked as written by AI")170                        .accessibilityIdentifier("claude-proposal-save")171                    Button { model.openInEditor(name: automationName, source: script, origin: .ai) } label: { Label("Edit", systemImage: "square.and.pencil") }172                        .help("Open in a new tab of the Automation editor")173                        .accessibilityIdentifier("claude-proposal-edit")174                    Button { studio.retest(turn.id); showTrace = true } label: { Label("Test", systemImage: "testtube.2") }175                        .disabled(p.compile?.succeeded != true).help("Run it in the simulator again and show the trace. The decks are not touched.")176                        .accessibilityIdentifier("claude-proposal-test")177                    Button { copyToPasteboard(script) } label: { Label("Copy", systemImage: "doc.on.doc") }178                        .accessibilityIdentifier("claude-proposal-copy")179                    Spacer()180                    if !p.isValid { Text("Run is unavailable: the proposal is not valid.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary) }181                    Button { runMessage = runWarning(p) } label: { Label("Run…", systemImage: "play.fill") }182                        .disabled(!p.isValid).help("Run on the live decks, after a confirmation")183                        .accessibilityIdentifier("claude-proposal-run")184                }185                .padding(.horizontal, 14).padding(.vertical, 10)186            }187        }188        .accessibilityIdentifier("claude-proposal")189    }190191    private var divider: some View { Rectangle().fill(ORIX.Palette.hairline).frame(height: 1) }192193    private func section<C: View>(_ title: LocalizedStringKey, @ViewBuilder _ content: () -> C) -> some View {194        VStack(alignment: .leading, spacing: 6) {195            SectionLabel(title)196            content()197        }198        .padding(.horizontal, 14).padding(.vertical, 10)199        .frame(maxWidth: .infinity, alignment: .leading)200    }201202    private func fact<C: View>(_ title: LocalizedStringKey, @ViewBuilder _ content: () -> C) -> some View {203        VStack(alignment: .leading, spacing: 5) { SectionLabel(title); content() }.frame(maxWidth: .infinity, alignment: .leading)204    }205206    private func save(_ script: String) {207        do {208            let record = try model.library.createScript(name: automationName, source: script, origin: .ai)209            model.libraryRevision += 1210            studio.update(turn.id) { $0.saved = true }211            model.show(notice: String(localized: "Saved \"\(record.name)\" to the script library"))212        } catch { model.show(notice: error.localizedDescription) }213    }214215    /// The confirmation text: which decks the script touches and which of them are playing right now.216    private func runWarning(_ p: AssistantProposal) -> String {217        let decks = (p.requirements?.decks ?? []).sorted()218        var parts: [String] = []219        if decks.isEmpty { parts.append(String(localized: "\"\(automationName)\" will run on the live mixer. It does not address a deck by name.")) }220        else { parts.append(String(localized: "\"\(automationName)\" will take control of deck \(decks.map { deckLetters[$0] }.joined(separator: ", ")) on the live mixer.")) }221        let playing = decks.filter { model.decks.indices.contains($0) && model.decks[$0].playing }222        if !playing.isEmpty { parts.append(String(localized: "Deck \(playing.map { deckLetters[$0] }.joined(separator: ", ")) is playing right now: the audience will hear the change.")) }223        else if model.decks.contains(where: \.playing) { parts.append(String(localized: "A deck is playing right now.")) }224        if let first = p.risks.first { parts.append(first) }225        parts.append(String(localized: "Emergency Stop in the status bar cancels it at any time."))226        return parts.joined(separator: "\n\n")227    }228229    private func run() {230        guard let p = turn.proposal, p.isValid, let script = p.script else { return }231        let errors = model.run(source: script, origin: "claude")232        if let first = errors.first { model.show(notice: first.message) }233    }234235    // MARK: MIDI proposal236237    private var mappingMessage: String {238        guard let p = turn.proposal, let profile = p.midiProfile else { return "" }239        var text = String(localized: "\"\(profile.name)\" with \(profile.mappings.count) mappings will be saved to the library. Activating it replaces the mapping in use.")240        if !p.midiIssues.isEmpty { text += "\n\n" + String(localized: "Dropped or invalid entries:") + "\n" + p.midiIssues.joined(separator: "\n") }241        return text242    }243244    private func controlLabel(_ c: MIDIControlID) -> String {245        switch c.kind {246        case .note: "Note \(c.number) · ch \(Int(c.channel) + 1)"247        case .controlChange: "CC \(c.number) · ch \(Int(c.channel) + 1)"248        case .pitchBend: "Pitch bend · ch \(Int(c.channel) + 1)"249        }250    }251252    private func midiCard(_ p: AssistantProposal) -> some View {253        Panel(padding: 0) {254            VStack(alignment: .leading, spacing: 0) {255                HStack(spacing: 10) {256                    Image(systemName: "pianokeys").foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)257                    Text(verbatim: p.midiProfile?.name ?? String(localized: "MIDI mapping")).font(.system(size: 14, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)258                    if let profile = p.midiProfile { Text("\(profile.mappings.count) mappings").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary) }259                    Spacer()260                }261                .padding(.horizontal, 14).padding(.vertical, 10)262                if !p.midiIssues.isEmpty {263                    divider264                    section("Dropped or invalid entries") {265                        ForEach(Array(p.midiIssues.enumerated()), id: \.offset) { _, issue in266                            HStack(alignment: .firstTextBaseline, spacing: 6) {267                                Image(systemName: "exclamationmark.triangle").font(.system(size: 11)).foregroundStyle(ORIX.Palette.warning).accessibilityHidden(true)268                                Text(verbatim: issue).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)269                            }270                        }271                    }272                    .accessibilityIdentifier("claude-midi-issues")273                }274                if let profile = p.midiProfile, !profile.mappings.isEmpty {275                    divider276                    Grid(alignment: .leading, horizontalSpacing: ORIX.Space.lg, verticalSpacing: 5) {277                        GridRow {278                            SectionLabel("Control"); SectionLabel("Target"); SectionLabel("Mode")279                        }280                        ForEach(profile.mappings) { m in281                            GridRow {282                                Text(verbatim: controlLabel(m.control)).font(ORIX.Typeface.value).foregroundStyle(ORIX.Palette.textPrimary)283                                Text(verbatim: ControlTargets.target(m.target).map { "\($0.name) (\(m.target))" } ?? m.target).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textPrimary)284                                Text(verbatim: m.mode.rawValue).font(.system(size: 12)).foregroundStyle(ORIX.Palette.textSecondary)285                            }286                        }287                    }288                    .padding(.horizontal, 14).padding(.vertical, 10)289                    .accessibilityIdentifier("claude-midi-mappings")290                }291                divider292                HStack {293                    Text("Nothing is mapped until you save. Check each control with MIDI learn afterwards.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary)294                    Spacer()295                    Button { confirmMapping = true } label: { Label(turn.saved ? "Saved" : "Save Mapping…", systemImage: turn.saved ? "checkmark" : "tray.and.arrow.down") }296                        .disabled(turn.saved || (p.midiProfile?.mappings.isEmpty ?? true))297                        .accessibilityIdentifier("claude-midi-save")298                }299                .padding(.horizontal, 14).padding(.vertical, 10)300            }301        }302        .accessibilityIdentifier("claude-midi-proposal")303    }304305    private func saveMapping(activate: Bool) {306        guard let profile = turn.proposal?.midiProfile else { return }307        do {308            try model.session.saveMIDIProfile(profile, activate: activate)309            studio.update(turn.id) { $0.saved = true }310            model.refreshNow()311            model.show(notice: activate ? String(localized: "MIDI mapping \"\(profile.name)\" saved and activated") : String(localized: "MIDI mapping \"\(profile.name)\" saved"))312        } catch { model.show(notice: error.localizedDescription) }313    }314}315316/// Line diff between the script the user had and the proposed one. Lines are marked with + and −, not by colour alone.317struct ClaudeDiffView: View {318    var old: String319    var new: String320321    var body: some View {322        let lines = ScriptAssistant.diff(old: old.trimmingCharacters(in: .newlines), new: new.trimmingCharacters(in: .newlines))323        let added = lines.filter { $0.kind == .added }.count, removed = lines.filter { $0.kind == .removed }.count324        VStack(alignment: .leading, spacing: 6) {325            Text(added == 0 && removed == 0 ? "No line changed." : "\(added) lines added, \(removed) lines removed").font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textSecondary)326            ScrollView(.horizontal, showsIndicators: false) {327                VStack(alignment: .leading, spacing: 0) {328                    ForEach(lines) { line in329                        HStack(spacing: 8) {330                            Text(verbatim: line.kind == .added ? "+" : (line.kind == .removed ? "−" : " "))331                                .font(.system(size: 12, weight: .bold, design: .monospaced)).frame(width: 12)332                                .accessibilityLabel(line.kind == .added ? Text("Added") : (line.kind == .removed ? Text("Removed") : Text("Unchanged")))333                            Text(verbatim: line.text.isEmpty ? " " : line.text).font(.system(size: 12, design: .monospaced))334                            Spacer(minLength: 0)335                        }336                        .foregroundStyle(line.kind == .added ? ORIX.Palette.success : (line.kind == .removed ? ORIX.Palette.danger : ORIX.Palette.textSecondary))337                        .padding(.horizontal, 6).padding(.vertical, 1)338                        .frame(minWidth: 560, alignment: .leading)339                        .background(line.kind == .added ? ORIX.Palette.success.opacity(0.12) : (line.kind == .removed ? ORIX.Palette.danger.opacity(0.12) : .clear))340                    }341                }342                .textSelection(.enabled)343            }344            .background(ORIX.Palette.well.opacity(0.55), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))345        }346    }347}348
Files main
Menu

Theme