Repository Public
1// ORIX DJ2// File: App/Sources/Features/ClaudeStudio/ClaudeStudioView.swift3// Description: Claude Studio: task picker, prompt and the context panel (what is shared, with the exact text) on the4// left; the conversation with streamed answers and validated proposals on the right.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import ORIXDJCore9import SwiftUI1011struct ClaudeStudioView: View {12 @Environment(AppModel.self) private var model13 @Environment(AppSettings.self) private var settings14 @Environment(\.openSettings) private var openSettings15 @State private var studio = ClaudeStudioModel()16 @State private var access = ClaudeAccess.shared17 @State private var appliedLaunchOptions = false18 @FocusState private var promptFocused: Bool1920 var body: some View {21 Group {22 if access.hasKey {23 HStack(spacing: 0) {24 leftColumn.frame(width: 400)25 Rectangle().fill(ORIX.Palette.hairline).frame(width: 1)26 conversation.frame(maxWidth: .infinity, maxHeight: .infinity)27 }28 } else {29 setup30 }31 }32 .background(ORIX.Palette.canvas)33 .onAppear { access.configure(model); access.refresh(); applyLaunchOptions() }34 .modifier(SettingsLaunchOption())35 .sheet(item: Binding(get: { studio.pending }, set: { studio.pending = $0 })) { p in36 ClaudeConfirmSheet(pending: p, modelID: settings.anthropic.model, historyCount: studio.history.count, isStub: access.isStub,37 onCancel: { studio.pending = nil }, onSend: { studio.confirmPending(model) })38 }39 .accessibilityElement(children: .contain).accessibilityIdentifier("claude-root")40 }4142 private func applyLaunchOptions() {43 guard !appliedLaunchOptions else { return }44 appliedLaunchOptions = true45 let defaults = UserDefaults.standard46 if let t = defaults.string(forKey: "ORIXClaudeTask").flatMap(AssistantTask.init(rawValue:)) { studio.task = t }47 // Pre-filled prompts are a screenshot aid: they are honoured only with the debug stub, never with a real key.48 guard let text = defaults.string(forKey: "ORIXClaudePrompt"), access.hasKey, access.isStub else { return }49 studio.prompt = text50 Task {51 // Let the shared script be compiled first so that its messages are part of the context.52 try? await Task.sleep(nanoseconds: 900_000_000)53 studio.send(model)54 // Unattended confirmation exists for screenshots only, and only when no request can leave this Mac.55 if access.isStub, defaults.bool(forKey: "ORIXClaudeAutoConfirm") { studio.confirmPending(model) }56 }57 }5859 private func showAISettings() {60 SettingsNavigation.shared.tab = .ai61 openSettings()62 }6364 // MARK: Setup state6566 private var setup: some View {67 VStack(spacing: ORIX.Space.md) {68 Image(systemName: "key.horizontal").font(.system(size: 34, weight: .light)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)69 Text("Claude Studio needs your Anthropic API key").font(.system(size: 20, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)70 Text("Claude Studio writes, explains and fixes ORIX Script automations with Claude. It uses your own Anthropic API key, and requests are billed by Anthropic to your account.")71 .font(.system(size: 13)).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.center).frame(maxWidth: 520)72 Panel(padding: ORIX.Space.md) {73 VStack(alignment: .leading, spacing: 10) {74 setupPoint("checkmark.circle", "Everything else in ORIX DJ works without a key: decks, mixer, effects, library, Auto DJ, automations, recording and MIDI.")75 setupPoint("lock.shield", "The key is stored in the macOS Keychain and sent only to api.anthropic.com over HTTPS.")76 setupPoint("eye", "Before a request is sent you see the exact text that is shared. Audio is never uploaded.")77 setupPoint("hand.raised", "A script written by Claude is compiled and simulated first, and never runs unless you start it.")78 }79 .frame(maxWidth: .infinity, alignment: .leading)80 }81 .frame(width: 580)82 Button { showAISettings() } label: { Label("Open Settings → AI", systemImage: "gearshape").padding(.horizontal, 6) }83 .controlSize(.large).keyboardShortcut(.defaultAction)84 .accessibilityIdentifier("claude-open-settings")85 }86 .padding(ORIX.Space.xl)87 .frame(maxWidth: .infinity, maxHeight: .infinity)88 .accessibilityElement(children: .contain).accessibilityIdentifier("claude-setup")89 }9091 private func setupPoint(_ symbol: String, _ text: LocalizedStringKey) -> some View {92 HStack(alignment: .firstTextBaseline, spacing: 10) {93 Image(systemName: symbol).font(.system(size: 13)).foregroundStyle(ORIX.Palette.accentSecondary).frame(width: 18).accessibilityHidden(true)94 Text(text).font(.system(size: 12.5)).foregroundStyle(ORIX.Palette.textPrimary).fixedSize(horizontal: false, vertical: true)95 }96 }9798 // MARK: Left column99100 private var leftColumn: some View {101 ScrollView {102 VStack(alignment: .leading, spacing: ORIX.Space.md) {103 taskPicker104 promptEditor105 ClaudeContextPanel(studio: studio)106 }107 .padding(ORIX.Space.sm)108 }109 .background(ORIX.Palette.canvas)110 }111112 private var taskPicker: some View {113 VStack(alignment: .leading, spacing: 6) {114 SectionLabel("Task")115 Panel(padding: 4) {116 VStack(spacing: 1) {117 ForEach(AssistantTask.allCases) { t in118 let selected = studio.task == t119 Button { studio.task = t } label: {120 HStack(spacing: 10) {121 Image(systemName: t.symbol).font(.system(size: 13, weight: .medium)).foregroundStyle(selected ? ORIX.Palette.accent : ORIX.Palette.textSecondary).frame(width: 20)122 VStack(alignment: .leading, spacing: 1) {123 Text(t.localizedTitle).font(.system(size: 12.5, weight: selected ? .semibold : .medium)).foregroundStyle(ORIX.Palette.textPrimary)124 Text(t.summary).font(.system(size: 10.5)).foregroundStyle(ORIX.Palette.textSecondary).lineLimit(1).minimumScaleFactor(0.85)125 }126 Spacer(minLength: 4)127 if selected { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)).foregroundStyle(ORIX.Palette.accent) }128 }129 .padding(.horizontal, 8).padding(.vertical, 4)130 .help(t.summary)131 .background(selected ? ORIX.Palette.surfaceRaised : .clear, in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))132 .contentShape(Rectangle())133 }134 .buttonStyle(.plain)135 .accessibilityAddTraits(selected ? [.isSelected] : [])136 .accessibilityIdentifier("claude-task-\(t.rawValue)")137 }138 }139 }140 }141 }142143 private var promptEditor: some View {144 VStack(alignment: .leading, spacing: 6) {145 SectionLabel(studio.turns.isEmpty ? "Request" : "Follow-up")146 Panel(padding: 8) {147 VStack(alignment: .leading, spacing: 8) {148 ZStack(alignment: .topLeading) {149 TextEditor(text: $studio.prompt)150 .font(.system(size: 13)).scrollContentBackground(.hidden)151 .focused($promptFocused)152 .frame(minHeight: 58, maxHeight: 120)153 .accessibilityLabel("Request to Claude")154 .accessibilityIdentifier("claude-prompt")155 if studio.prompt.isEmpty {156 Text(studio.task.promptPlaceholder).font(.system(size: 13)).foregroundStyle(ORIX.Palette.textTertiary)157 .padding(.leading, 5).allowsHitTesting(false).accessibilityHidden(true)158 }159 }160 .padding(6)161 .background(ORIX.Palette.well.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))162 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(promptFocused ? ORIX.Palette.accent : ORIX.Palette.hairline, lineWidth: 1))163164 VStack(alignment: .leading, spacing: 4) {165 Text("Examples").font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textTertiary).textCase(.uppercase)166 ForEach(studio.task.examples, id: \.self) { example in167 Button { studio.prompt = example; promptFocused = true } label: {168 HStack(alignment: .firstTextBaseline, spacing: 6) {169 Image(systemName: "arrow.up.left").font(.system(size: 9, weight: .bold)).foregroundStyle(ORIX.Palette.textTertiary)170 Text(verbatim: example).font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary).multilineTextAlignment(.leading).frame(maxWidth: .infinity, alignment: .leading)171 }172 .contentShape(Rectangle())173 }174 .buttonStyle(.plain)175 .help("Use this example as the request")176 .accessibilityIdentifier("claude-example")177 }178 }179180 HStack(spacing: 8) {181 let blocker = studio.blocker(model)182 if let blocker, !studio.streaming, !studio.validating {183 Text(blocker).font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)184 } else if settings.anthropic.confirmBeforeSending {185 Text("You will see the exact text before it is sent.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)186 }187 Spacer(minLength: 4)188 Button { studio.send(model) } label: { Label(settings.anthropic.confirmBeforeSending ? "Review and Send" : "Send", systemImage: "paperplane.fill") }189 .keyboardShortcut(.return, modifiers: .command)190 .disabled(blocker != nil)191 .help("Send the request (⌘↩)")192 .accessibilityIdentifier("claude-send")193 }194 }195 }196 }197 }198199 // MARK: Conversation200201 private var conversation: some View {202 VStack(spacing: 0) {203 HStack(spacing: ORIX.Space.sm) {204 Text("Conversation").font(.system(size: 12.5, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)205 if access.isStub {206 Label("Debug stub: canned answers, offline", systemImage: "wrench.and.screwdriver")207 .font(.system(size: 10.5, weight: .semibold)).foregroundStyle(ORIX.Palette.warning)208 .padding(.horizontal, 8).frame(height: 20).overlay(Capsule().strokeBorder(ORIX.Palette.warning))209 .accessibilityIdentifier("claude-stub-badge")210 }211 Spacer()212 if let r = studio.lastResult {213 Text(verbatim: "\(r.model) · in \(r.inputTokens) · out \(r.outputTokens) · cache read \(r.cacheReadTokens)")214 .font(ORIX.Typeface.caption).foregroundStyle(ORIX.Palette.textTertiary).lineLimit(1)215 .help("Model and token usage of the last request, as reported by the API.")216 .accessibilityLabel(Text("Last request: model \(r.model), \(r.inputTokens) input tokens, \(r.outputTokens) output tokens, \(r.cacheReadTokens) tokens read from cache"))217 .accessibilityIdentifier("claude-usage")218 }219 Button { studio.newConversation() } label: { Label("New Conversation", systemImage: "plus.bubble") }220 .disabled(studio.turns.isEmpty && !studio.streaming)221 .help("Forget the previous turns and start again")222 .accessibilityIdentifier("claude-new-conversation")223 }224 .controlSize(.small)225 .padding(.horizontal, ORIX.Space.md).frame(height: 38)226 .background(ORIX.Palette.surface)227 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)228229 if studio.turns.isEmpty, !studio.streaming {230 EmptyState(symbol: "sparkles", title: "Ask for an automation",231 message: "Pick a task, describe what you want and send it. The answer streams in here; any script it contains is compiled and simulated before you decide what to do with it. Nothing runs by itself.")232 .accessibilityIdentifier("claude-empty")233 } else {234 ScrollViewReader { proxy in235 ScrollView {236 VStack(alignment: .leading, spacing: ORIX.Space.lg) {237 ForEach(studio.turns) { turn in ClaudeTurnView(turn: turn, studio: studio).id(turn.id) }238 if studio.streaming { streamingView.id("streaming") }239 Color.clear.frame(height: 1).id("end")240 }241 .padding(ORIX.Space.md)242 .frame(maxWidth: 980, alignment: .leading)243 .frame(maxWidth: .infinity, alignment: .leading)244 }245 .onChange(of: studio.turns.count) { _, _ in if let last = studio.turns.last { proxy.scrollTo(last.id, anchor: .top) } }246 .onChange(of: studio.streaming) { _, on in if on { proxy.scrollTo("streaming", anchor: .top) } }247 }248 .accessibilityIdentifier("claude-conversation")249 }250 }251 }252253 private var streamingView: some View {254 VStack(alignment: .leading, spacing: 10) {255 if let t = studio.streamingTask { ClaudeRequestHeader(task: t, prompt: studio.streamingPrompt) }256 Panel(padding: ORIX.Space.sm) {257 VStack(alignment: .leading, spacing: 10) {258 HStack(spacing: 8) {259 ProgressView().controlSize(.small)260 Text(studio.validating ? "Compiling and simulating the proposal…" : (studio.streamText.isEmpty ? "Waiting for the first words…" : "Claude is answering…"))261 .font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textSecondary)262 Spacer()263 Button(role: .cancel) { studio.stop() } label: { Label("Stop", systemImage: "stop.fill") }264 .disabled(studio.validating)265 .keyboardShortcut(".", modifiers: .command)266 .help("Cancel this request")267 .accessibilityIdentifier("claude-stop")268 }269 if !studio.streamText.isEmpty {270 Text(verbatim: studio.streamText).font(.system(size: 12.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textPrimary)271 .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading)272 .accessibilityIdentifier("claude-stream-text")273 }274 }275 }276 }277 }278}279280/// The task and the user's words at the top of a turn.281struct ClaudeRequestHeader: View {282 var task: AssistantTask283 var prompt: String284285 var body: some View {286 HStack(alignment: .firstTextBaseline, spacing: 8) {287 Label(task.localizedTitle, systemImage: task.symbol).font(.system(size: 11, weight: .semibold)).foregroundStyle(ORIX.Palette.accent)288 .padding(.horizontal, 8).padding(.vertical, 3)289 .background(ORIX.Palette.accent.opacity(0.12), in: Capsule())290 if !prompt.isEmpty {291 Text(verbatim: prompt).font(.system(size: 13, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)292 }293 }294 }295}296297/// What is shared with a request: the switches and the exact text.298struct ClaudeContextPanel: View {299 @Environment(AppModel.self) private var model300 @Bindable var studio: ClaudeStudioModel301302 var body: some View {303 VStack(alignment: .leading, spacing: 6) {304 SectionLabel("Shared with the request")305 Panel(padding: 10) {306 VStack(alignment: .leading, spacing: 6) {307 toggle("Deck states", "Loaded or empty, playing or paused, tempo and key.", $studio.includeDecks, id: "decks")308 toggle("Track titles (private, off by default)", "Titles of the loaded tracks. Private library data: off unless you switch it on.", $studio.includeTitles, id: "titles").disabled(!studio.includeDecks)309 toggle("Active effects", "Names of the effect units that are switched on.", $studio.includeEffects, id: "effects")310 toggle("Current script", "The text of a script open in the editor.", $studio.includeScript, id: "script")311 if studio.includeScript { documentPicker }312 toggle("Compiler messages and simulator output", "For the current script: what the compiler and the simulator report.", $studio.includeDiagnostics, id: "diagnostics").disabled(!studio.includeScript)313 if studio.task == .midi {314 toggle("Connected MIDI controller names", "So that the mapping can be made for your hardware.", $studio.includeController, id: "controller")315 }316 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1)317 Text("Exact text that will be sent").font(ORIX.Typeface.label).foregroundStyle(ORIX.Palette.textTertiary).textCase(.uppercase)318 TimelineView(.periodic(from: .now, by: 1)) { _ in319 ScrollView {320 Text(verbatim: studio.context(model).rendered())321 .font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary)322 .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(8)323 }324 .frame(height: 150)325 .background(ORIX.Palette.well.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))326 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))327 }328 .accessibilityLabel("Preview of the shared context")329 .accessibilityIdentifier("claude-context-preview")330 HStack(alignment: .firstTextBaseline, spacing: 6) {331 Image(systemName: "waveform.slash").font(.system(size: 11)).foregroundStyle(ORIX.Palette.accentSecondary).accessibilityHidden(true)332 Text("Audio is never uploaded. Your request, the ORIX Script language reference and the text above are all that is sent.")333 .font(.system(size: 11)).foregroundStyle(ORIX.Palette.textSecondary).fixedSize(horizontal: false, vertical: true)334 }335 }336 }337 }338 .task(id: studio.includeScript ? studio.document(model)?.source : nil) {339 await studio.check(studio.includeScript ? studio.document(model)?.source : nil)340 }341 .accessibilityIdentifier("claude-context")342 }343344 private func toggle(_ title: LocalizedStringKey, _ detail: LocalizedStringKey, _ value: Binding<Bool>, id: String) -> some View {345 Toggle(isOn: value) {346 Text(title).font(.system(size: 12, weight: .medium)).foregroundStyle(ORIX.Palette.textPrimary)347 .frame(maxWidth: .infinity, alignment: .leading)348 }349 .toggleStyle(.switch).controlSize(.mini)350 .help(detail)351 .accessibilityIdentifier("claude-share-\(id)")352 }353354 private var documentPicker: some View {355 HStack(spacing: 8) {356 Image(systemName: "doc.text").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)357 Picker("Script", selection: $studio.documentID) {358 Text(verbatim: String(localized: "Active editor tab") + (model.activeDocument.map { " (\($0.name))" } ?? "")).tag(UUID?.none)359 ForEach(model.documents) { d in Text(verbatim: d.name).tag(UUID?.some(d.id)) }360 }361 .labelsHidden().controlSize(.small)362 .accessibilityLabel("Script to share").accessibilityIdentifier("claude-document")363 }364 .padding(.leading, 4)365 }366}367368/// Shown before every request when "Ask before every request" is on: the exact outgoing text.369struct ClaudeConfirmSheet: View {370 var pending: ClaudePendingRequest371 var modelID: String372 var historyCount: Int373 var isStub: Bool374 var onCancel: () -> Void375 var onSend: () -> Void376 @State private var showReference = false377378 var body: some View {379 VStack(alignment: .leading, spacing: ORIX.Space.sm) {380 HStack(spacing: 10) {381 Image(systemName: "paperplane").font(.system(size: 20)).foregroundStyle(ORIX.Palette.accent).accessibilityHidden(true)382 VStack(alignment: .leading, spacing: 2) {383 Text("Send this to Anthropic?").font(.system(size: 16, weight: .semibold)).foregroundStyle(ORIX.Palette.textPrimary)384 Group {385 if isStub { Text("Debug stub: the request stays on this Mac. Model setting: \(modelID).") }386 else { Text("To api.anthropic.com over HTTPS, with your API key. Model: \(modelID).") }387 }388 .font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary)389 }390 }391 SectionLabel("Your message, exactly as sent")392 ScrollView {393 Text(verbatim: pending.request.messages.last?.content ?? "")394 .font(.system(size: 11.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textPrimary)395 .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(10)396 }397 .frame(minHeight: 220, maxHeight: 320)398 .background(ORIX.Palette.well.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))399 .overlay(RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous).strokeBorder(ORIX.Palette.hairline, lineWidth: 1))400 .accessibilityIdentifier("claude-confirm-text")401402 VStack(alignment: .leading, spacing: 4) {403 if historyCount > 0 {404 Label("Also sent: the \(historyCount) earlier messages of this conversation, unchanged.", systemImage: "bubble.left.and.bubble.right")405 }406 Label("Also sent: the fixed ORIX Script language reference (\(pending.request.system.count) characters). It contains nothing about you or your music.", systemImage: "book")407 Label("Not sent: audio, files, library contents, anything not shown here.", systemImage: "waveform.slash")408 }409 .font(.system(size: 11.5)).foregroundStyle(ORIX.Palette.textSecondary)410411 DisclosureGroup("Show the language reference", isExpanded: $showReference) {412 ScrollView {413 Text(verbatim: pending.request.system).font(.system(size: 10.5, design: .monospaced)).foregroundStyle(ORIX.Palette.textSecondary)414 .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(8)415 }416 .frame(height: 160)417 .background(ORIX.Palette.well.opacity(0.6), in: RoundedRectangle(cornerRadius: ORIX.Radius.control, style: .continuous))418 }419 .font(.system(size: 11.5))420 .accessibilityIdentifier("claude-confirm-reference")421422 HStack {423 Text("Switch this confirmation off in Settings → AI.").font(.system(size: 11)).foregroundStyle(ORIX.Palette.textTertiary)424 Spacer()425 Button("Cancel", role: .cancel, action: onCancel).keyboardShortcut(.cancelAction).accessibilityIdentifier("claude-confirm-cancel")426 Button("Send", action: onSend).keyboardShortcut(.defaultAction).accessibilityIdentifier("claude-confirm-send")427 }428 }429 .padding(ORIX.Space.lg)430 .frame(width: 680)431 .background(ORIX.Palette.surface)432 .accessibilityIdentifier("claude-confirm")433 }434}435