Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX DJ9// File : App/Sources/Features/Settings/AISettingsTab.swift10// Description : Settings → AI → Anthropic: the user's own API key11// (Keychain), validation against the Models API, the model12// picker built only from the verified list, effort, output13// and request limits.14// Module : Features15// Repository : https://git.spboucher.ai/orix-dj16// Created : 2026-11-2117// Last Modified : 2026-11-2118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author : Simon-Pierre Boucher24// Position : Professor of Finance25// Institution : Université du Québec en Outaouais (UQO)26// Department : Département des sciences administratives27// Organization : SP Boucher28//29// Website : https://spboucher.ai30// Git : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General : info@spboucher.ai37// Professional : contact@spboucher.ai38// Direct : simon@spboucher.ai39// Research : research@spboucher.ai40// Development : dev@spboucher.ai41// Support : support@spboucher.ai42// Security/Admin : admin@spboucher.ai43// Notifications : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification : Public70// Distribution : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License : None specified (no license file in this repository)84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import ORIXDJCore92import SwiftUI9394struct AISettingsTab: View {95 enum Status: Equatable { case unknown, validating, connected(Int), failed(String) }9697 @Environment(AppModel.self) private var model98 @Environment(AppSettings.self) private var settings99 @State private var access = ClaudeAccess.shared100 @State private var newKey = ""101 @State private var status: Status = .unknown102 @State private var confirmRemove = false103 @State private var saveFailed = false104105 private static let efforts: [(String?, LocalizedStringKey)] = [(nil, "Model default"), ("low", "Low effort"), ("medium", "Medium effort"), ("high", "High effort"), ("xhigh", "Extra high effort"), ("max", "Maximum effort")]106107 private var storedModelVerified: Bool { settings.verifiedModels.contains { $0.id == settings.anthropic.model } }108109 var body: some View {110 @Bindable var settings = settings111 SettingsPage {112 SettingsCard(title: "Anthropic API key") {113 keyRows114 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)115 SettingsNote("Claude Studio uses your own Anthropic API key. The key is stored in the macOS Keychain, sent only to api.anthropic.com over HTTPS, never to ORIX servers, and never written to projects or logs. What is shared with each request is previewed in Claude Studio before it is sent.", symbol: "lock.shield")116 }117118 SettingsCard(title: "Model") {119 if settings.verifiedModels.isEmpty {120 SettingsNote("Validate the key to list the models it can use. The model can only be chosen from that list.")121 } else {122 SettingsRow(title: "Model", detail: "Only models returned by Anthropic for this key are listed.", divider: !storedModelVerified) {123 Picker("Model", selection: $settings.anthropic.model) {124 ForEach(settings.verifiedModels) { m in Text(verbatim: m.displayName == m.id ? m.id : "\(m.displayName) (\(m.id))").tag(m.id) }125 if !storedModelVerified { Text(verbatim: "\(settings.anthropic.model) (not available)").tag(settings.anthropic.model) }126 }127 .labelsHidden().frame(width: 320, alignment: .trailing)128 .accessibilityLabel("Model").accessibilityIdentifier("settings-ai-model")129 }130 if !storedModelVerified {131 SettingsNote("The stored model \"\(settings.anthropic.model)\" is not in the list returned for this key. Pick one of the listed models.", symbol: "exclamationmark.triangle", tint: ORIX.Palette.warning)132 .accessibilityIdentifier("settings-ai-model-missing")133 }134 }135 Rectangle().fill(ORIX.Palette.hairline).frame(height: 1).padding(.leading, 14)136 SettingsRow(title: "Effort", detail: "How much work the model puts into an answer. Higher effort is slower and uses more tokens.") {137 Picker("Effort", selection: $settings.anthropic.effort) {138 ForEach(Array(Self.efforts.enumerated()), id: \.offset) { _, e in Text(e.1).tag(e.0) }139 }140 .labelsHidden().frame(width: 200, alignment: .trailing)141 .accessibilityLabel("Effort").accessibilityIdentifier("settings-ai-effort")142 }143 let ceiling = settings.verifiedModels.first { $0.id == settings.anthropic.model }?.maxOutputTokens144 let tokensDetail: LocalizedStringKey = if let ceiling { "The longest answer accepted. This model allows up to \(ceiling)." } else { "The longest answer accepted." }145 SettingsRow(title: "Maximum output tokens", detail: tokensDetail, divider: false) {146 HStack(spacing: 6) {147 TextField("Maximum output tokens", value: $settings.anthropic.maxOutputTokens, format: .number.grouping(.never))148 .textFieldStyle(.roundedBorder).multilineTextAlignment(.trailing).frame(width: 90).monospacedDigit()149 .accessibilityIdentifier("settings-ai-max-tokens")150 Stepper("Maximum output tokens", value: $settings.anthropic.maxOutputTokens, in: 1000 ... (ceiling ?? 128_000), step: 1000).labelsHidden()151 }152 }153 }154155 SettingsCard(title: "Requests") {156 SettingsRow(title: "Requests per hour", detail: "ORIX DJ refuses to send more than this, as a guard against surprises on your Anthropic bill.") {157 HStack(spacing: 6) {158 Text(verbatim: "\(settings.anthropic.maxRequestsPerHour)").font(ORIX.Typeface.value).frame(width: 40, alignment: .trailing)159 Stepper("Requests per hour", value: $settings.anthropic.maxRequestsPerHour, in: 1 ... 600, step: 5).labelsHidden()160 .accessibilityIdentifier("settings-ai-request-limit")161 }162 }163 TimelineView(.periodic(from: .now, by: 5)) { _ in164 SettingsRow(title: "Used in the last hour", detail: "Counted since ORIX DJ started.") {165 Text(verbatim: "\(access.client(model).requestsInLastHour) / \(settings.anthropic.maxRequestsPerHour)").font(ORIX.Typeface.readout(15)).foregroundStyle(ORIX.Palette.textPrimary)166 .accessibilityIdentifier("settings-ai-requests-used")167 }168 }169 SettingsRow(title: "Ask before every request", detail: "Shows the exact text that will be sent and waits for your confirmation.") {170 Toggle("Ask before every request", isOn: $settings.anthropic.confirmBeforeSending).labelsHidden().toggleStyle(.switch)171 .accessibilityIdentifier("settings-ai-confirm")172 }173 SettingsRow(title: "Retry declined requests on a fallback model", detail: "When the chosen model declines a request, Anthropic may answer it with its default fallback model instead; the answer then names the model that wrote it.", divider: false) {174 Toggle("Retry declined requests on a fallback model", isOn: $settings.anthropic.refusalFallback).labelsHidden().toggleStyle(.switch)175 .accessibilityIdentifier("settings-ai-fallback")176 }177 }178 }179 .onAppear {180 access.configure(model)181 if case .unknown = status, access.hasKey, !settings.verifiedModels.isEmpty { status = .connected(settings.verifiedModels.count) }182 // `-ORIXSettingsValidate YES` presses Validate when the tab opens (screenshots, UI tests).183 if case .unknown = status, access.hasKey, UserDefaults.standard.bool(forKey: "ORIXSettingsValidate") { validate() }184 }185 .onChange(of: settings.anthropic.maxOutputTokens) { _, v in186 let clamped = min(128_000, max(256, v)); if clamped != v { settings.anthropic.maxOutputTokens = clamped }187 }188 .confirmationDialog("Remove the Anthropic API key?", isPresented: $confirmRemove) {189 Button("Remove Key", role: .destructive) { remove() }190 Button("Cancel", role: .cancel) {}191 } message: { Text("The key is deleted from the Keychain of this Mac and the list of verified models is cleared. Claude Studio stops working until a key is entered again. The key itself stays valid at Anthropic.") }192 .accessibilityIdentifier("settings-ai")193 }194195 @ViewBuilder private var keyRows: some View {196 if access.isStub {197 SettingsRow(title: "Debug stub transport", detail: "This debug instance was launched with a local stub: requests are answered on this Mac with canned data and no key is used or stored.") {198 Button("Validate") { validate() }.disabled(status == .validating).accessibilityIdentifier("settings-ai-validate")199 }200 } else if let masked = access.maskedKey {201 SettingsRow(title: "Stored key", detail: "Only this shortened form is ever shown.") {202 HStack(spacing: 8) {203 Text(verbatim: masked).font(ORIX.Typeface.mono).foregroundStyle(ORIX.Palette.textPrimary)204 .accessibilityLabel("Stored key, masked").accessibilityIdentifier("settings-ai-masked-key")205 Button("Validate") { validate() }.disabled(status == .validating).accessibilityIdentifier("settings-ai-validate")206 Button("Remove Key…", role: .destructive) { confirmRemove = true }.accessibilityIdentifier("settings-ai-remove")207 }208 }209 }210 if !access.isStub {211 SettingsRow(title: access.maskedKey == nil ? "API key" : "Replace the key", detail: "Create a key in the Anthropic Console, then paste it here.") {212 HStack(spacing: 8) {213 SecureField("sk-ant-…", text: $newKey)214 .textFieldStyle(.roundedBorder).frame(width: 250)215 .onSubmit { save() }216 .accessibilityLabel("Anthropic API key").accessibilityIdentifier("settings-ai-key-field")217 Button("Save Key") { save() }.disabled(newKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)218 .accessibilityIdentifier("settings-ai-save")219 }220 }221 if saveFailed { SettingsNote("The key could not be saved to the Keychain.", symbol: "xmark.octagon", tint: ORIX.Palette.danger) }222 }223 HStack(spacing: 8) {224 switch status {225 case .unknown:226 Label(access.hasKey ? "Not validated yet" : "No key stored", systemImage: access.hasKey ? "questionmark.circle" : "key.slash").foregroundStyle(ORIX.Palette.textSecondary)227 case .validating:228 ProgressView().controlSize(.small); Text("Contacting Anthropic…").foregroundStyle(ORIX.Palette.textSecondary)229 case let .connected(n):230 Label("Connected — \(n) models available", systemImage: "checkmark.circle.fill").foregroundStyle(ORIX.Palette.success)231 case let .failed(message):232 Label { Text(verbatim: message) } icon: { Image(systemName: "xmark.octagon.fill") }.foregroundStyle(ORIX.Palette.danger)233 }234 Spacer()235 }236 .font(.system(size: 12, weight: .medium))237 .padding(.horizontal, 14).padding(.vertical, 10)238 .accessibilityElement(children: .combine)239 .accessibilityIdentifier("settings-ai-status")240 }241242 private func save() {243 let key = newKey244 newKey = ""245 saveFailed = !access.save(key)246 guard !saveFailed else { return }247 // A different key may see different models: the old list no longer applies.248 settings.verifiedModels = []249 status = .unknown250 validate()251 }252253 private func remove() {254 access.remove()255 settings.verifiedModels = []256 status = .unknown257 }258259 private func validate() {260 guard let key = access.keyForRequest() else { status = .failed(AnthropicError.noKey.errorDescription ?? ""); return }261 let client = access.client(model)262 status = .validating263 Task {264 do {265 let models = try await client.models(apiKey: key)266 settings.verifiedModels = models267 if !models.contains(where: { $0.id == settings.anthropic.model }), models.contains(where: { $0.id == AnthropicSettings.defaultModel }) {268 settings.anthropic.model = AnthropicSettings.defaultModel269 }270 status = .connected(models.count)271 } catch let e as AnthropicError {272 if e == .unauthorized { settings.verifiedModels = [] }273 status = .failed(e.errorDescription ?? String(localized: "The key could not be validated."))274 } catch { status = .failed(error.localizedDescription) }275 }276 }277}278