Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Astra9// File : Packages/AstraUI/Sources/Models/ProviderKeySheet.swift10// Module : Models11// Repository : https://git.spboucher.ai/orix-astra12// Created : 2026-11-2113// Last Modified : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author : Simon-Pierre Boucher20// Position : Professor of Finance21// Institution : Université du Québec en Outaouais (UQO)22// Department : Département des sciences administratives23// Organization : SP Boucher24//25// Website : https://spboucher.ai26// Git : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General : info@spboucher.ai33// Professional : contact@spboucher.ai34// Direct : simon@spboucher.ai35// Research : research@spboucher.ai36// Development : dev@spboucher.ai37// Support : support@spboucher.ai38// Security/Admin : admin@spboucher.ai39// Notifications : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification : Public66// Distribution : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License : Proprietary, all rights reserved (see license file)80// License File : LICENSE81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SwiftUI89import AstraCore90import AstraDesign9192extension ProviderKind {93 /// Where a person creates a key for this provider.94 var keyConsoleURL: URL? {95 switch self {96 case .openAI: URL(string: "https://platform.openai.com/api-keys")97 case .anthropic: URL(string: "https://platform.claude.com/settings/keys")98 case .google: URL(string: "https://aistudio.google.com/apikey")99 case .xAI: URL(string: "https://console.x.ai")100 case .openRouter: URL(string: "https://openrouter.ai/settings/keys")101 default: nil102 }103 }104 var dataNote: String {105 switch self {106 case .openRouter: "OpenRouter forwards each request to an upstream provider it selects. The provider that served an answer is shown in the answer's details."107 default: "Requests go straight from this iPhone to \(displayName) over TLS, under the terms of your \(displayName) account."108 }109 }110}111112/// Add, test, replace or remove a provider key. The key is written to the Keychain and never shown again in full.113struct ProviderKeySheet: View {114 @Environment(AppModel.self) private var app115 @Environment(\.dismiss) private var dismiss116 let kind: ProviderKind117 @State private var key = ""118 @State private var working = false119 @State private var result: ConnectionStatus?120 @State private var confirmRemove = false121 @FocusState private var focused: Bool122123 private var state: ProviderState { app.library.providers[kind] ?? ProviderState() }124125 var body: some View {126 NavigationStack {127 Form {128 Section {129 HStack(spacing: 12) {130 ProviderLogo(provider: kind, size: 44)131 VStack(alignment: .leading, spacing: 2) {132 Text(kind.displayName).font(AstraFont.headline)133 Text(state.hasKey ? "Key on file: \(state.maskedKey ?? "saved")" : "No key saved").font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)134 }135 }136 .accessibilityElement(children: .combine)137 }138 Section {139 SecureField(state.hasKey ? "Replace with a new key" : "Paste your API key", text: $key)140 .textContentType(.password).autocorrectionDisabled().textInputAutocapitalization(.never)141 .focused($focused).accessibilityIdentifier("key-field")142 Button {143 if let s = Pasteboard.string?.trimmingCharacters(in: .whitespacesAndNewlines), !s.isEmpty { key = s } else { app.show("The clipboard is empty.", .error) }144 } label: { Label("Paste from clipboard", systemImage: "doc.on.clipboard") }145 Button {146 Task { await save() }147 } label: {148 HStack { Text(state.hasKey ? "Replace and test" : "Save and test"); if working { Spacer(); ProgressView() } }149 }150 .disabled(key.trimmingCharacters(in: .whitespacesAndNewlines).count < 8 || working)151 .accessibilityIdentifier("key-save")152 } header: { Text("API key") } footer: {153 Text("Stored in the iOS Keychain on this device only (not synced, not in backups to other devices). It is sent only to \(kind.displayName).")154 }155 if let result {156 Section {157 Label(result.ok ? "Connection works" : "Connection failed", systemImage: result.ok ? "checkmark.circle.fill" : "xmark.octagon.fill")158 .foregroundStyle(result.ok ? AstraColor.success : AstraColor.danger)159 Text(result.detail).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)160 if let n = result.modelCount { LabeledContent("Models available", value: "\(n)") }161 if let credit = result.remainingCreditUSD { LabeledContent("Remaining credit", value: CostEstimate.format(credit)) }162 }163 }164 if state.hasKey {165 Section {166 Button { Task { working = true; result = await app.library.refresh(kind); working = false } } label: { Label("Test connection again", systemImage: "arrow.clockwise") }167 .disabled(working)168 Button(role: .destructive) { confirmRemove = true } label: { Label("Remove key", systemImage: "trash") }.accessibilityIdentifier("key-remove")169 }170 }171 Section {172 if let url = kind.keyConsoleURL { Link(destination: url) { Label("Create a key at \(url.host ?? kind.displayName)", systemImage: "arrow.up.right.square") } }173 Text(kind.dataNote).font(AstraFont.footnote).foregroundStyle(AstraColor.textSecondary)174 } header: { Text("About this provider") }175 }176 .scrollContentBackground(.hidden).background(AstraColor.background)177 .navigationTitle("Provider key").navigationBarTitleDisplayMode(.inline)178 .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }179 .confirmationDialog("Remove the \(kind.displayName) key?", isPresented: $confirmRemove, titleVisibility: .visible) {180 Button("Remove key", role: .destructive) { Task { await app.library.removeKey(for: kind); result = nil; app.show("Key removed", .success) } }181 Button("Cancel", role: .cancel) {}182 } message: { Text("The key is deleted from the Keychain. Existing chats are kept but cannot continue with this provider until a key is added again.") }183 .onAppear { if !state.hasKey { focused = true } }184 }185 .presentationDetents([.large])186 }187188 private func save() async {189 working = true; defer { working = false }190 let value = key191 key = "" // the field is cleared at once: the key is never left on screen192 result = await app.library.setKey(value, for: kind)193 if result?.ok == true { AstraHaptics.success() } else { AstraHaptics.error() }194 }195}196197struct EndpointDraft: Identifiable {198 var profile: EndpointProfile199 var isNew: Bool200 var id: String { profile.id }201}202203/// Create or edit a custom OpenAI-compatible endpoint.204struct EndpointSheet: View {205 @Environment(AppModel.self) private var app206 @Environment(\.dismiss) private var dismiss207 @State var draft: EndpointDraft208 @State private var key = ""209 @State private var headerName = ""210 @State private var headerValue = ""211 @State private var problem: String?212 @State private var working = false213 @State private var confirmInsecure = false214215 var body: some View {216 NavigationStack {217 Form {218 Section {219 TextField("Name", text: $draft.profile.name).accessibilityIdentifier("endpoint-name")220 TextField("https://host/v1", text: $draft.profile.baseURL)221 .keyboardType(.URL).autocorrectionDisabled().textInputAutocapitalization(.never).accessibilityIdentifier("endpoint-url")222 TextField("Default model ID (optional)", text: Binding(get: { draft.profile.defaultModelID ?? "" }, set: { draft.profile.defaultModelID = $0.isEmpty ? nil : $0 }))223 .autocorrectionDisabled().textInputAutocapitalization(.never)224 } header: { Text("Endpoint") } footer: { Text("The base URL up to the version segment. ORIX Astra calls /chat/completions and /models under it.") }225 Section {226 SecureField(app.library.endpointHasKey(draft.profile.id) ? "Key on file. Enter a new one to replace it" : "API key (optional)", text: $key)227 .textContentType(.password).autocorrectionDisabled().textInputAutocapitalization(.never)228 } header: { Text("Authentication") } footer: { Text("Sent as a Bearer token. Stored in the Keychain.") }229 Section {230 Toggle("Allow plain HTTP on my local network", isOn: Binding(get: { draft.profile.allowInsecureHTTP }, set: { on in231 if on { confirmInsecure = true } else { draft.profile.allowInsecureHTTP = false }232 }))233 } footer: {234 Text("Off by default. Plain HTTP is unencrypted: anyone on the same network can read your prompts and key. It is only ever allowed for addresses on your own network.")235 }236 Section {237 ForEach(draft.profile.extraHeaders.keys.sorted(), id: \.self) { name in238 LabeledContent(name) { Text(draft.profile.extraHeaders[name] ?? "").foregroundStyle(AstraColor.textSecondary) }239 .swipeActions { Button(role: .destructive) { draft.profile.extraHeaders[name] = nil } label: { Label("Delete", systemImage: "trash") } }240 }241 HStack {242 TextField("Header", text: $headerName).autocorrectionDisabled().textInputAutocapitalization(.never)243 TextField("Value", text: $headerValue).autocorrectionDisabled().textInputAutocapitalization(.never)244 Button { draft.profile.extraHeaders[headerName.trimmingCharacters(in: .whitespaces)] = headerValue; headerName = ""; headerValue = "" } label: { Image(systemName: "plus.circle.fill") }245 .disabled(headerName.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityLabel("Add header")246 }247 } header: { Text("Extra headers (advanced)") } footer: { Text("For non-secret headers only. Credentials belong in the key field.") }248 if let problem { Section { Label(problem, systemImage: "exclamationmark.triangle.fill").foregroundStyle(AstraColor.danger).font(AstraFont.footnote) } }249 if !draft.isNew {250 Section { Button(role: .destructive) { Task { await app.library.deleteEndpoint(draft.profile.id); dismiss() } } label: { Label("Delete endpoint", systemImage: "trash") } }251 }252 }253 .scrollContentBackground(.hidden).background(AstraColor.background)254 .navigationTitle(draft.isNew ? "New endpoint" : "Edit endpoint").navigationBarTitleDisplayMode(.inline)255 .toolbar {256 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }257 ToolbarItem(placement: .confirmationAction) {258 if working { ProgressView() } else { Button("Save") { Task { await save() } }.disabled(draft.profile.name.trimmingCharacters(in: .whitespaces).isEmpty).accessibilityIdentifier("endpoint-save") }259 }260 }261 .confirmationDialog("Allow unencrypted HTTP?", isPresented: $confirmInsecure, titleVisibility: .visible) {262 Button("Allow for this endpoint", role: .destructive) { draft.profile.allowInsecureHTTP = true }263 Button("Cancel", role: .cancel) {}264 } message: { Text("Prompts, answers and the API key will travel unencrypted on your local network.") }265 }266 }267268 private func save() async {269 working = true; defer { working = false }270 draft.profile.name = draft.profile.name.trimmingCharacters(in: .whitespaces)271 draft.profile.baseURL = draft.profile.baseURL.trimmingCharacters(in: .whitespaces)272 do {273 try await app.library.saveEndpoint(draft.profile, key: key)274 key = ""275 if let e = app.library.endpointErrors[draft.profile.id] { problem = "Saved, but the server did not answer the model list request: \(e.message)"; draft.isNew = false }276 else { app.show("Endpoint saved", .success); dismiss() }277 } catch { problem = AstraError.wrap(error).message }278 }279}280