SPB Git

Repository Public

ClaudeStudioModel.swift 12.5 KB 270 lines swift

1// ORIX DJ2// File: App/Sources/Features/ClaudeStudio/ClaudeStudioModel.swift3// Description: State and request pipeline of Claude Studio: what is shared, the conversation, streaming, cancellation4//              and local validation of every answer. A proposal is never run from here: running is a user action.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Observation10import ORIXDJCore11import SwiftUI1213extension AssistantTask {14    var summary: LocalizedStringKey {15        switch self {16        case .generate: "Describe a transition; get a validated script."17        case .explain: "What a script does, bar by bar, and its risks."18        case .fix: "Correct it from compiler and simulator messages."19        case .improve: "Change a working script towards a goal."20        case .effect: "Effect units, values and curves, as a script."21        case .midi: "A controller mapping, checked against the targets."22        case .plan: "Track order, transitions and effects for a set."23        }24    }2526    var symbol: String {27        switch self {28        case .generate: "wand.and.stars"29        case .explain: "text.magnifyingglass"30        case .fix: "wrench.and.screwdriver"31        case .improve: "arrow.up.right.circle"32        case .effect: "slider.horizontal.3"33        case .midi: "pianokeys"34        case .plan: "list.bullet.rectangle"35        }36    }3738    var localizedTitle: LocalizedStringKey { LocalizedStringKey(title) }3940    /// Explain, Fix and Improve work on a script the user already has.41    var needsScript: Bool { self == .explain || self == .fix || self == .improve }42    var promptOptional: Bool { self == .explain || self == .fix }4344    var examples: [String] {45        switch self {46        case .generate: [47                "Bring deck B in over 16 bars with a high-pass sweep, swap the bass on bar 9, then fade deck A out.",48                "A four-bar echo-out on deck A that ends with a brake, then start deck B on the next bar.",49                "Every 8 bars, close a low-pass on deck A for one bar and open it again.",50            ]51        case .explain: ["Explain it for someone who has never written a script.", "Which lines could surprise me in front of a crowd?"]52        case .fix: ["It stops deck A too early.", "The filter stays closed after the automation ends."]53        case .improve: ["Make the transition twice as long and smoother.", "Restore every control it changes once deck A has stopped.", "Remove anything that has no audible effect."]54        case .effect: ["A dub delay throw on deck A: open the delay for one beat every four bars.", "A riser: reverb and a high-pass that build over 8 bars, then cut on the downbeat."]55        case .midi: ["A two-deck controller with play, cue and sync buttons, volume faders, a crossfader and three EQ knobs per deck.", "Map eight pads to automation triggers 1 to 8."]56        case .plan: ["A 20-minute warm-up from 120 to 126 BPM with the tracks I have loaded.", "How do I move from a house track to a breakbeat track without a train wreck?"]57        }58    }5960    var promptPlaceholder: LocalizedStringKey {61        switch self {62        case .generate: "Describe the automation you want…"63        case .explain: "Optional: what you want explained…"64        case .fix: "Optional: what goes wrong when it runs…"65        case .improve: "What should be better…"66        case .effect: "Describe the effect…"67        case .midi: "Describe your controller…"68        case .plan: "Describe the set or the moment…"69        }70    }71}7273struct ClaudeTurn: Identifiable {74    let id = UUID()75    var task: AssistantTask76    var prompt: String77    /// The exact user message that was sent.78    var sentText: String79    var answer: String80    var proposal: AssistantProposal?81    var error: String?82    var result: AnthropicResult?83    /// The script that was shared, for the diff of Fix and Improve.84    var originalScript: String?85    var originalName: String?86    var saved = false87    var retested = false88}8990struct ClaudePendingRequest: Identifiable {91    let id = UUID()92    var request: AnthropicRequest93    var task: AssistantTask94    var prompt: String95    var originalScript: String?96    var originalName: String?97}9899struct ScriptCheck: Sendable, Equatable {100    var source: String101    var diagnostics: [Diagnostic]102    var summary: String?103104    static func run(_ source: String) -> ScriptCheck {105        let compiled = ScriptCompiler.compile(source)106        var summary: String?107        if let program = compiled.program, let sim = Simulator.run(program) {108            var lines = ["State after \(formatBeats(sim.beats)) beats: " + (sim.timedOut ? "still running" : (sim.error != nil ? "failed" : "finished")) + ", \(sim.actions.count) actions"]109            if let e = sim.error { lines.append("Error: \(e.description)") }110            lines += sim.warnings.prefix(5).map { "Warning at beat \(formatBeats($0.beat)): \($0.text)" }111            summary = lines.joined(separator: "\n")112        }113        return ScriptCheck(source: source, diagnostics: compiled.diagnostics, summary: summary)114    }115}116117@MainActor @Observable118final class ClaudeStudioModel {119    var task: AssistantTask = .generate { didSet { if task != oldValue { includeScript = task.needsScript } } }120    var prompt = ""121122    // What is shared. Track titles are private library data: off unless the user turns them on.123    var includeDecks = true124    var includeTitles = false125    var includeEffects = true126    var includeScript = false127    var includeDiagnostics = true128    var includeController = true129    /// Document used as "current script"; nil follows the active editor tab.130    var documentID: UUID?131    private(set) var scriptCheck: ScriptCheck?132133    private(set) var turns: [ClaudeTurn] = []134    private(set) var streaming = false135    private(set) var validating = false136    private(set) var streamText = ""137    private(set) var streamingTask: AssistantTask?138    private(set) var streamingPrompt = ""139    var pending: ClaudePendingRequest?140141    @ObservationIgnored private var sendTask: Task<Void, Never>?142143    func document(_ model: AppModel) -> ScriptDocument? {144        model.documents.first { $0.id == documentID } ?? model.activeDocument145    }146147    /// Exactly what `AssistantContext.rendered()` will contain for the current choices.148    func context(_ model: AppModel) -> AssistantContext {149        var c = AssistantContext.capture(model.engine)150        c.includeDecks = includeDecks; c.includeTitles = includeDecks && includeTitles; c.includeEffects = includeEffects151        c.includeScript = includeScript; c.includeDiagnostics = includeDiagnostics152        if includeScript, let doc = document(model) {153            c.script = doc.source154            if includeDiagnostics, let check = scriptCheck, check.source == doc.source { c.diagnostics = check.diagnostics; c.simulationSummary = check.summary }155        }156        if task == .midi, includeController {157            let names = model.midiSources.filter(\.isOnline).map(\.name)158            if !names.isEmpty { c.controllerDescription = names.joined(separator: ", ") }159        }160        return c161    }162163    /// Compiles and simulates the shared script so that its messages can be part of the context.164    func check(_ source: String?) async {165        guard let source, !source.isEmpty else { scriptCheck = nil; return }166        if scriptCheck?.source == source { return }167        try? await Task.sleep(nanoseconds: 250_000_000)168        if Task.isCancelled { return }169        let result = await Task.detached(priority: .utility) { ScriptCheck.run(source) }.value170        if !Task.isCancelled { scriptCheck = result }171    }172173    var history: [AnthropicMessage] {174        turns.filter { $0.error == nil }.flatMap { [AnthropicMessage(role: "user", content: $0.sentText), AnthropicMessage(role: "assistant", content: $0.answer)] }175    }176177    func blocker(_ model: AppModel) -> LocalizedStringKey? {178        if streaming || validating { return "A request is in progress." }179        if task.needsScript {180            if !includeScript { return "This task works on the current script: switch \"Current script\" on in the context." }181            if document(model)?.source.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?? true { return "The current script is empty." }182        }183        if !task.promptOptional, prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { return "Describe what you want first." }184        return nil185    }186187    func buildRequest(_ model: AppModel) -> ClaudePendingRequest {188        let doc = includeScript ? document(model) : nil189        let request = ScriptAssistant.request(task: task, prompt: prompt, context: context(model), history: history)190        return ClaudePendingRequest(request: request, task: task, prompt: prompt.trimmingCharacters(in: .whitespacesAndNewlines), originalScript: doc?.source, originalName: doc?.name)191    }192193    /// Starts a request, or asks for confirmation first when the user wants to see every outgoing text.194    func send(_ model: AppModel) {195        guard blocker(model) == nil else { return }196        let p = buildRequest(model)197        if model.settings.anthropic.confirmBeforeSending { pending = p } else { perform(p, model) }198    }199200    func confirmPending(_ model: AppModel) {201        guard let p = pending else { return }202        pending = nil203        perform(p, model)204    }205206    func perform(_ p: ClaudePendingRequest, _ model: AppModel) {207        guard !streaming else { return }208        let access = ClaudeAccess.shared209        let sent = p.request.messages.last?.content ?? ""210        guard let key = access.keyForRequest() else {211            turns.append(ClaudeTurn(task: p.task, prompt: p.prompt, sentText: sent, answer: "", error: AnthropicError.noKey.errorDescription))212            return213        }214        let client = access.client(model)215        let settings = model.settings.anthropic216        streaming = true; streamText = ""; streamingTask = p.task; streamingPrompt = p.prompt217        prompt = ""218        let (stream, continuation) = AsyncStream<String>.makeStream()219        sendTask = Task { [weak self] in220            // Text deltas arrive on the network thread; the stream delivers them here in order.221            let reader = Task { @MainActor [weak self] in for await piece in stream { self?.streamText += piece } }222            var turn = ClaudeTurn(task: p.task, prompt: p.prompt, sentText: sent, answer: "", originalScript: p.originalScript, originalName: p.originalName)223            do {224                let result = try await client.send(p.request, settings: settings, apiKey: key) { continuation.yield($0) }225                continuation.finish(); await reader.value226                turn.answer = result.text; turn.result = result227                self?.streamText = result.text228                self?.validating = true229                let task = p.task230                turn.proposal = await Task.detached(priority: .userInitiated) { ScriptAssistant.evaluate(answer: result.text, task: task) }.value231            } catch let e as AnthropicError {232                continuation.finish(); await reader.value233                turn.answer = self?.streamText ?? ""234                turn.error = e.errorDescription ?? String(localized: "The request failed.")235            } catch {236                continuation.finish(); await reader.value237                turn.answer = self?.streamText ?? ""238                turn.error = error is CancellationError ? AnthropicError.cancelled.errorDescription : error.localizedDescription239            }240            guard let self else { return }241            self.turns.append(turn)242            self.streaming = false; self.validating = false; self.streamText = ""; self.streamingTask = nil243            // A failed request gives the prompt back so that it can be sent again.244            if turn.error != nil, self.prompt.isEmpty { self.prompt = p.prompt }245        }246    }247248    func stop() { sendTask?.cancel() }249250    func newConversation() {251        stop()252        turns.removeAll()253    }254255    func update(_ id: UUID, _ change: (inout ClaudeTurn) -> Void) {256        if let i = turns.firstIndex(where: { $0.id == id }) { change(&turns[i]) }257    }258259    /// Runs the proposal of a turn through the simulator again (it never touches the decks).260    func retest(_ id: UUID) {261        guard let turn = turns.first(where: { $0.id == id }), let script = turn.proposal?.script else { return }262        Task {263            let outcome = await Task.detached(priority: .userInitiated) { ScriptOutcome.evaluate(script) }.value264            update(id) { $0.proposal?.simulation = outcome.simulation; $0.retested = true }265        }266    }267268    var lastResult: AnthropicResult? { turns.last { $0.result != nil }?.result }269}270
Files main
Menu

Theme