A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.
C++
feat(settings): UI for ChatGPT subscription sign-in
cyenxa4e74ee75d0c
diff --git a/macos/Presentation/Views/AIChat/AIChatView.swift b/macos/Presentation/Views/AIChat/AIChatView.swiftindex 7280357..bf9d897 100644--- a/macos/Presentation/Views/AIChat/AIChatView.swift+++ b/macos/Presentation/Views/AIChat/AIChatView.swift@@ -4,6 +4,7 @@// SwiftUI AI chat panel with streaming responses.import SwiftUI+import os// Observable message class — mutations don't trigger ForEach diffingfinal class ChatDisplayMessage: ObservableObject, Identifiable {@@ -23,6 +24,8 @@ final class ChatDisplayMessage: ObservableObject, Identifiable {}struct AIChatView: View {+ private static let log = Logger(subsystem: "com.gridex.gridex", category: "AIChat")+@EnvironmentObject private var appState: AppState@AppStorage("ai.activeProviderID") private var activeProviderID: String = ""@AppStorage("ai.activeModel") private var activeModel: String = ""@@ -605,17 +608,25 @@ struct AIChatView: View {private func refreshAPIKeyState() {// Multi-provider path: an active provider ID is set.if !activeProviderID.isEmpty, let uuid = UUID(uuidString: activeProviderID) {- let key = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(uuid.uuidString)")- // Ollama has no key but is still usable → treat presence of an active ID as ready- // unless we can verify the config requires a key and none is set.Task {let config = try? await DependencyContainer.shared.llmProviderRepository.fetchByID(uuid)- await MainActor.run {- if let config, config.enabled {- apiKeyLoaded = !config.type.requiresAPIKey || (key != nil && !key!.isEmpty)- } else {- apiKeyLoaded = false+ let ready: Bool+ if let config, config.enabled {+ switch config.type {+ case .chatGPT:+ ready = (try? DependencyContainer.shared.keychainService+ .loadChatGPTTokens(providerId: uuid)) != nil+ default:+ let key = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(uuid.uuidString)")+ // Ollama has no key but is still usable; API-key providers+ // need a non-empty stored key.+ ready = !config.type.requiresAPIKey || (key != nil && !key!.isEmpty)}+ } else {+ ready = false+ }+ await MainActor.run {+ apiKeyLoaded = ready}}return@@ -638,7 +649,23 @@ struct AIChatView: View {key: ProviderEditSheet.keychainKey(id: uuid))) ?? ""if config.type.requiresAPIKey, apiKey.isEmpty { return nil }- let service = ProviderFactory.make(config: config, apiKey: apiKey)+ // ChatGPT (Sign in) requires the OAuth service; if not signed in,+ // the Keychain bundle is missing — fail clearly instead of crashing.+ if config.type == .chatGPT {+ guard (try? DependencyContainer.shared.keychainService+ .loadChatGPTTokens(providerId: uuid)) != nil else {+ Self.log.notice("Active ChatGPT provider \(uuid.uuidString, privacy: .public) has no token bundle; marking AI chat not ready")+ await MainActor.run {+ apiKeyLoaded = false+ }+ return nil+ }+ }+ let service = ProviderFactory.make(+ config: config,+ apiKey: apiKey,+ chatGPTOAuthService: DependencyContainer.shared.chatGPTOAuthService+ )let modelToUse = activeModel.isEmpty ? config.model : activeModelreturn (service, modelToUse)}@@ -740,6 +767,14 @@ struct AIChatView: View {for try await token in stream {assistantMsg.content += token}+ } catch GridexError.aiAPIKeyMissing {+ await MainActor.run {+ apiKeyLoaded = false+ refreshAPIKeyState()+ }+ if assistantMsg.content.isEmpty {+ assistantMsg.content = "Error: \(GridexError.aiAPIKeyMissing.localizedDescription)"+ }} catch {if assistantMsg.content.isEmpty {assistantMsg.content = "Error: \(error.localizedDescription)"diff --git a/macos/Presentation/Windows/Settings/ProviderEditSheet.swift b/macos/Presentation/Windows/Settings/ProviderEditSheet.swiftindex 961ebd2..4f7910b 100644--- a/macos/Presentation/Windows/Settings/ProviderEditSheet.swift+++ b/macos/Presentation/Windows/Settings/ProviderEditSheet.swift@@ -5,6 +5,7 @@// API key lives in Keychain keyed by the config UUID (ai.apikey.<uuid>), never// in SwiftData.+import osimport SwiftUIstruct ProviderEditSheet: View {@@ -13,11 +14,32 @@ struct ProviderEditSheet: View {/// Called when the sheet saves successfully. Parent should reload list.let onSaved: (ProviderConfig) -> Void+ init(editing: ProviderConfig?, onSaved: @escaping (ProviderConfig) -> Void) {+ self.editing = editing+ self.onSaved = onSaved++ if let editing {+ _resolvedId = State(initialValue: editing.id)+ _name = State(initialValue: editing.name)+ _type = State(initialValue: editing.type)+ _apiBase = State(initialValue: editing.apiBase ?? editing.type.defaultBaseURL)+ _model = State(initialValue: editing.model)+ _enabled = State(initialValue: editing.enabled)+ }+ }+@Environment(\.dismiss) private var dismiss+ private static let log = Logger(subsystem: "com.gridex.gridex", category: "ProviderEditSheet")+private let keychain: KeychainServiceProtocol = DependencyContainer.shared.keychainServiceprivate let repository: any LLMProviderRepository = DependencyContainer.shared.llmProviderRepository+ /// Provider id used by both the OAuth flow (`ai.chatgpt.tokens.<id>` keychain+ /// key) and the eventual SwiftData row. Generated eagerly so a Sign-in click+ /// on a brand-new provider persists tokens under the id we'll reuse on Save.+ @State private var resolvedId: UUID = UUID()+@State private var name: String = ""@State private var type: ProviderType = .anthropic@State private var apiBase: String = ProviderType.anthropic.defaultBaseURL@@ -33,6 +55,18 @@ struct ProviderEditSheet: View {@State private var urlError: String?@State private var saveError: String?+ // ChatGPT OAuth state (only used when type == .chatGPT)+ @State private var chatGPTStatus: ChatGPTOAuthService.SignInStatus = .signedOut+ @State private var isSigningIn: Bool = false+ @State private var signInError: String?++ /// True when this session may produce a Keychain token bundle that hasn't+ /// been confirmed by Save. Add mode and edits that switch a non-ChatGPT row+ /// to ChatGPT both need rollback on dismiss; editing an existing ChatGPT row+ /// is exempt because the bundle already belongs to that persisted provider.+ @State private var dirtyChatGPTSignIn: Bool = false+ @State private var chatGPTSignInTask: Task<Void, Never>?+enum FetchResult: Equatable {case nonecase loaded(Int)@@ -47,10 +81,19 @@ struct ProviderEditSheet: View {private var isEdit: Bool { editing != nil }private var canSave: Bool {- !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty &&- urlError == nil &&- (!type.requiresAPIKey || !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) &&- !model.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ let nameOK = !name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty+ let modelOK = !model.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty++ if type == .chatGPT {+ if case .signedIn = chatGPTStatus {+ return nameOK && modelOK+ }+ return false+ }+ return nameOK+ && urlError == nil+ && (!type.requiresAPIKey || !apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ && modelOK}var body: some View {@@ -63,6 +106,23 @@ struct ProviderEditSheet: View {}.frame(width: 560, height: 540).onAppear(perform: load)+ .onDisappear {+ let pendingSignIn = chatGPTSignInTask+ chatGPTSignInTask = nil+ pendingSignIn?.cancel()++ // Add-mode sign-in may still complete after the sheet closes. Wait+ // for cancellation/completion, then clear any bundle that may have+ // been written under an unsaved provider id.+ guard dirtyChatGPTSignIn else { return }+ let pid = resolvedId+ Task {+ if let pendingSignIn {+ await pendingSignIn.value+ }+ try? await DependencyContainer.shared.chatGPTOAuthService.signOut(providerId: pid)+ }+ }}// MARK: - Header@@ -100,20 +160,58 @@ struct ProviderEditSheet: View {.onChange(of: type) { _, newType in applyTypeDefaults(newType) }}- Section("Endpoint") {- TextField("API Base URL", text: $apiBase)- .textFieldStyle(.roundedBorder)- .onChange(of: apiBase) { _, newValue in validateURL(newValue) }- if let urlError {- Text(urlError).font(.system(size: 11)).foregroundStyle(.red)- }- if type.requiresAPIKey {- SecureField("API Key", text: $apiKey)+ Section(type == .chatGPT ? "Authentication" : "Endpoint") {+ if type == .chatGPT {+ chatGPTAuthBlock+ } else {+ TextField("API Base URL", text: $apiBase).textFieldStyle(.roundedBorder)+ .onChange(of: apiBase) { _, newValue in validateURL(newValue) }+ if let urlError {+ Text(urlError).font(.system(size: 11)).foregroundStyle(.red)+ }+ if type.requiresAPIKey {+ SecureField("API Key", text: $apiKey)+ .textFieldStyle(.roundedBorder)+ }}}+ if shouldShowModelSection {+ modelSection+ }+Section {+ Toggle("Enabled", isOn: $enabled)+ }+ }+ .formStyle(.grouped)+ }++ private var shouldShowModelSection: Bool {+ guard type == .chatGPT else { return true }+ if case .signedIn = chatGPTStatus {+ return true+ }+ return false+ }++ private var modelSection: some View {+ Section {+ if type == .chatGPT {+ if !availableModels.isEmpty {+ Picker("Model", selection: $model) {+ Text("Select a model").tag("")+ if !model.isEmpty, !availableModels.contains(where: { $0.id == model }) {+ Text(model).tag(model)+ }+ ForEach(availableModels) { m in+ Text(m.name).tag(m.id)+ }+ }+ .onChange(of: model) { _, _ in testResult = .none }+ }+ } else {if !availableModels.isEmpty {Picker("Available", selection: $model) {ForEach(availableModels) { m in@@ -131,72 +229,78 @@ struct ProviderEditSheet: View {}testResult = .none}- } header: {- HStack {- Text("Model")- Spacer()- if isLoadingModels { ProgressView().controlSize(.small) }- }- } footer: {- switch fetchResult {- case .none:- Text("Click **Fetch Models** below to load the list from the API, or type a model ID manually.")- .font(.system(size: 11))- .foregroundStyle(.secondary)- case .loaded(let count) where count > 0:- Text("\(count) models loaded from API.")- .font(.system(size: 11))- .foregroundStyle(.green)- case .loaded:- Text("Endpoint responded but returned no models — type a model ID manually.")- .font(.system(size: 11))- .foregroundStyle(.orange)- case .failure(let msg):- Text(msg)- .font(.system(size: 11))- .foregroundStyle(.red)- }}+ } header: {+ HStack {+ Text("Model")+ Spacer()+ if isLoadingModels { ProgressView().controlSize(.small) }+ }+ } footer: {+ modelSectionFooter+ }+ }- Section {- Toggle("Enabled", isOn: $enabled)+ @ViewBuilder+ private var modelSectionFooter: some View {+ switch fetchResult {+ case .none:+ if type != .chatGPT {+ Text("Click **Fetch Models** below to load the list from the API, or type a model ID manually.")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)}+ case .loaded(let count) where count > 0:+ Text("\(count) models loaded from API.")+ .font(.system(size: 11))+ .foregroundStyle(.green)+ case .loaded:+ Text("Endpoint responded but returned no models.")+ .font(.system(size: 11))+ .foregroundStyle(.orange)+ case .failure(let msg):+ Text(msg)+ .font(.system(size: 11))+ .foregroundStyle(.red)}- .formStyle(.grouped)}// MARK: - Footerprivate var footer: some View {HStack(spacing: 8) {- Button(action: fetchModels) {- HStack(spacing: 6) {- if isLoadingModels { ProgressView().controlSize(.small) }- Text("Fetch Models")+ // Fetch Models / Test only apply to API-key providers — ChatGPT+ // uses OAuth and populates models implicitly after sign-in.+ if type != .chatGPT {+ Button(action: fetchModels) {+ HStack(spacing: 6) {+ if isLoadingModels { ProgressView().controlSize(.small) }+ Text("Fetch Models")+ }}- }- .disabled(isLoadingModels || (type.requiresAPIKey && apiKey.isEmpty) || urlError != nil)+ .disabled(isLoadingModels || (type.requiresAPIKey && apiKey.isEmpty) || urlError != nil)- Button(action: testConnection) {- HStack(spacing: 6) {- if isTesting { ProgressView().controlSize(.small) }- Text("Test")+ Button(action: testConnection) {+ HStack(spacing: 6) {+ if isTesting { ProgressView().controlSize(.small) }+ Text("Test")+ }+ }+ .disabled(isTesting+ || (type.requiresAPIKey && apiKey.isEmpty)+ || urlError != nil+ || model.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ .help("Send a 1-token request to verify the key + URL + model combination")++ switch testResult {+ case .none: EmptyView()+ case .success:+ Label("Connected", systemImage: "checkmark.circle.fill")+ .foregroundStyle(.green).font(.system(size: 12))+ case .failure(let msg):+ Label(msg, systemImage: "xmark.circle.fill")+ .foregroundStyle(.red).font(.system(size: 12)).lineLimit(1)}- }- .disabled(isTesting- || (type.requiresAPIKey && apiKey.isEmpty)- || urlError != nil- || model.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)- .help("Send a 1-token request to verify the key + URL + model combination")-- switch testResult {- case .none: EmptyView()- case .success:- Label("Connected", systemImage: "checkmark.circle.fill")- .foregroundStyle(.green).font(.system(size: 12))- case .failure(let msg):- Label(msg, systemImage: "xmark.circle.fill")- .foregroundStyle(.red).font(.system(size: 12)).lineLimit(1)}Spacer()@@ -220,12 +324,13 @@ struct ProviderEditSheet: View {private func load() {if let editing {- name = editing.name- type = editing.type- apiBase = editing.apiBase ?? editing.type.defaultBaseURL- model = editing.model- enabled = editing.enabled- apiKey = (try? keychain.load(key: Self.keychainKey(id: editing.id))) ?? ""+ if editing.type == .chatGPT {+ // No API key for OAuth providers; status comes from the keychain bundle.+ apiKey = ""+ Task { await refreshChatGPTStatus() }+ } else {+ apiKey = (try? keychain.load(key: Self.keychainKey(id: editing.id))) ?? ""+ }} else {applyTypeDefaults(type)}@@ -233,6 +338,21 @@ struct ProviderEditSheet: View {}private func applyTypeDefaults(_ newType: ProviderType) {+ if newType == .chatGPT {+ // Endpoint and key are owned by the OAuth flow — clear them so the+ // form state can't poison the eventual save.+ apiBase = ""+ apiKey = ""+ model = ""+ availableModels = []+ fetchResult = .none+ testResult = .none+ urlError = nil+ chatGPTStatus = .signedOut+ signInError = nil+ Task { await refreshChatGPTStatus() }+ return+ }apiBase = newType.defaultBaseURLmodel = "" // user must fetch or type — avoids presetting a model the endpoint may not supportavailableModels = []@@ -244,6 +364,9 @@ struct ProviderEditSheet: View {}private func validateURL(_ value: String) {+ // ChatGPT doesn't expose an API base URL field — its endpoint is fixed.+ if type == .chatGPT { urlError = nil; return }+if value.isEmpty, type == .openAICompatible {urlError = "Base URL is required for custom providers"return@@ -328,6 +451,169 @@ struct ProviderEditSheet: View {}}+ // MARK: - ChatGPT OAuth UI block++ @ViewBuilder+ private var chatGPTAuthBlock: some View {+ switch chatGPTStatus {+ case .signedIn(let email, let plan):+ HStack(spacing: 8) {+ Image(systemName: "checkmark.seal.fill").foregroundStyle(.green)+ VStack(alignment: .leading, spacing: 2) {+ Text("Signed in as \(email ?? "(unknown)")")+ .font(.system(size: 12, weight: .medium))+ if let plan {+ Text("Plan: \(plan)")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ }+ }+ Spacer()+ Button("Sign out", role: .destructive) { signOutChatGPT() }+ .controlSize(.small)+ }+ case .signedOut:+ VStack(alignment: .leading, spacing: 8) {+ Button(action: signInChatGPT) {+ HStack(spacing: 6) {+ if isSigningIn { ProgressView().controlSize(.small) }+ Image(systemName: "person.crop.circle.badge.checkmark")+ Text(isSigningIn ? "Waiting for browser…" : "Sign in with OpenAI")+ }+ }+ .buttonStyle(.borderedProminent)+ .disabled(isSigningIn)++ if let signInError {+ Text(signInError)+ .font(.system(size: 11))+ .foregroundStyle(.red)+ }++ Text("Uses OpenAI's Codex CLI public OAuth client. Not officially supported by OpenAI. Requires a paid ChatGPT plan; may break if OpenAI changes the API. Credentials never leave this device.")+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ }+ }++ private func signInChatGPT() {+ let pid = resolvedId+ let shouldRollbackOnCancel = editing?.type != .chatGPT+ isSigningIn = true+ signInError = nil+ if shouldRollbackOnCancel {+ dirtyChatGPTSignIn = true+ }++ chatGPTSignInTask?.cancel()+ chatGPTSignInTask = Task {+ let svc = DependencyContainer.shared.chatGPTOAuthService+ do {+ _ = try await svc.signIn(providerId: pid)+ // The bundle is unconfirmed until Save unless this is a+ // re-sign-in for a row that was already ChatGPT when opened.+ await MainActor.run { if shouldRollbackOnCancel { dirtyChatGPTSignIn = true } }+ // refreshChatGPTStatus() itself fans out to loadChatGPTModels()+ // when availableModels is empty (true post-sign-in), so calling+ // it twice would double-hit /models.+ await refreshChatGPTStatus()+ await MainActor.run {+ isSigningIn = false+ chatGPTSignInTask = nil+ }+ } catch {+ await MainActor.run {+ if shouldRollbackOnCancel {+ dirtyChatGPTSignIn = false+ }+ signInError = error.localizedDescription+ isSigningIn = false+ chatGPTSignInTask = nil+ }+ }+ }+ }++ private func signOutChatGPT() {+ let pid = resolvedId+ Task {+ let svc = DependencyContainer.shared.chatGPTOAuthService+ try? await svc.signOut(providerId: pid)+ await refreshChatGPTStatus()+ await MainActor.run {+ chatGPTSignInTask?.cancel()+ chatGPTSignInTask = nil+ availableModels = []+ model = ""+ fetchResult = .none+ // Bundle is gone; nothing for onDisappear to clean up.+ dirtyChatGPTSignIn = false+ }+ }+ }++ private func refreshChatGPTStatus() async {+ let pid = resolvedId+ let status = await DependencyContainer.shared.chatGPTOAuthService.currentStatus(providerId: pid)+ // Hop to the main actor only to update view state; decide on the+ // follow-up model load there too (it reads availableModels), then+ // await it in the caller's task instead of detaching a new Task.+ // Detached tasks here would outlive the sheet on dismiss.+ let needsModelLoad: Bool = await MainActor.run {+ chatGPTStatus = status+ if case .signedIn = status, availableModels.isEmpty {+ return true+ }+ return false+ }+ if needsModelLoad {+ await loadChatGPTModels()+ }+ }++ /// Populate `availableModels` from the ChatGPT backend after sign-in.+ /// Falls back to `type.fallbackModelIDs` when the network call fails.+ private func loadChatGPTModels() async {+ await MainActor.run { isLoadingModels = true }+ let pid = resolvedId+ let svc = DependencyContainer.shared.chatGPTOAuthService+ // Bypass ProviderRegistry on purpose: in add-mode the SwiftData row+ // doesn't exist yet (Save hasn't run), so the registry can't resolve+ // by name. The OAuth service is the only stateful dep — sheet-local+ // construction is safe and disposable. After Save, ProviderRegistry+ // would build an equivalent stateless ChatGPTProvider with the same+ // providerId + oauthService actor and default resolvedBaseURL.+ let provider = ChatGPTProvider(providerId: pid, oauthService: svc)+ do {+ let models = try await provider.availableModels()+ await MainActor.run {+ isLoadingModels = false+ if models.isEmpty {+ applyBuiltInFallback(reason: "endpoint returned no models")+ } else {+ availableModels = models+ fetchResult = .loaded(models.count)+ Self.log.debug("Loaded \(models.count) OpenAI sign-in model(s); selected=\(model, privacy: .public)")+ }+ }+ } catch GridexError.aiAPIKeyMissing {+ await MainActor.run {+ isLoadingModels = false+ chatGPTStatus = .signedOut+ availableModels = []+ fetchResult = .none+ signInError = "Sign-in expired. Please sign in again."+ }+ } catch {+ await MainActor.run {+ isLoadingModels = false+ applyBuiltInFallback(reason: error.localizedDescription)+ }+ }+ }+/// Populate the picker with the provider type's built-in model IDs when the/// live API can't give us a list. Non-fatal — user can still type any model.private func applyBuiltInFallback(reason: String) {@@ -349,11 +635,13 @@ struct ProviderEditSheet: View {private func save() {let trimmedKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)let trimmedBase = apiBase.trimmingCharacters(in: .whitespacesAndNewlines)+ // ChatGPT: ignore apiBase/apiKey form fields entirely. The endpoint is+ // baked into the type, the credentials live under ai.chatgpt.tokens.<id>.let config = ProviderConfig(- id: editing?.id ?? UUID(),+ id: resolvedId,name: name.trimmingCharacters(in: .whitespacesAndNewlines),type: type,- apiBase: trimmedBase.isEmpty ? nil : trimmedBase,+ apiBase: type == .chatGPT ? nil : (trimmedBase.isEmpty ? nil : trimmedBase),model: model.trimmingCharacters(in: .whitespacesAndNewlines),enabled: enabled,createdAt: editing?.createdAt ?? Date()@@ -366,17 +654,36 @@ struct ProviderEditSheet: View {} else {try await repository.save(config)}- // Persist API key (or clear it)- let keychainKey = Self.keychainKey(id: config.id)- if trimmedKey.isEmpty {- try? keychain.delete(key: keychainKey)++ if config.type == .chatGPT {+ // Tokens are already in Keychain from the Sign-in flow.+ // Drop any stale API key under the same id — user may+ // have switched type from API-key to ChatGPT mid-edit.+ try? keychain.delete(key: Self.keychainKey(id: config.id))+ await DependencyContainer.shared.providerRegistry.register(+ config,+ apiKey: "",+ chatGPTOAuthService: DependencyContainer.shared.chatGPTOAuthService+ )} else {- try keychain.save(key: keychainKey, value: trimmedKey)+ // Reverse cleanup: discard any orphan ChatGPT token bundle+ // left behind if the user signed in then switched type.+ try? keychain.deleteChatGPTTokens(providerId: config.id)+ // Persist API key (or clear it)+ let keychainKey = Self.keychainKey(id: config.id)+ if trimmedKey.isEmpty {+ try? keychain.delete(key: keychainKey)+ } else {+ try keychain.save(key: keychainKey, value: trimmedKey)+ }+ // Update registry+ await DependencyContainer.shared.providerRegistry.register(config, apiKey: trimmedKey)}- // Update registry- await DependencyContainer.shared.providerRegistry.register(config, apiKey: trimmedKey)await MainActor.run {+ // SwiftData row now owns the id — clear the rollback arm+ // before dismiss(), or onDisappear will sign us back out.+ dirtyChatGPTSignIn = falseonSaved(config)dismiss()}diff --git a/macos/Presentation/Windows/Settings/SettingsView.swift b/macos/Presentation/Windows/Settings/SettingsView.swiftindex 4134638..32bcd91 100644--- a/macos/Presentation/Windows/Settings/SettingsView.swift+++ b/macos/Presentation/Windows/Settings/SettingsView.swift@@ -268,7 +268,15 @@ struct AISettingsView: View {try? await repository.update(updated)let apiKey = (try? keychain.load(key: ProviderEditSheet.keychainKey(id: p.id))) ?? ""if enabled {- await DependencyContainer.shared.providerRegistry.register(updated, apiKey: apiKey)+ // Pass the OAuth service unconditionally — non-ChatGPT factory+ // branches ignore it, ChatGPT requires it (otherwise the+ // factory hits preconditionFailure when re-enabling a+ // ChatGPT provider).+ await DependencyContainer.shared.providerRegistry.register(+ updated,+ apiKey: apiKey,+ chatGPTOAuthService: DependencyContainer.shared.chatGPTOAuthService+ )} else {await DependencyContainer.shared.providerRegistry.unregister(updated.name)}@@ -279,7 +287,11 @@ struct AISettingsView: View {private func delete(_ p: ProviderConfig) {Task {try? await repository.delete(p.id)+ // Clean up both credential variants — only one is set in practice,+ // but deleting both is cheap and avoids leaks if the type was ever+ // changed from API-key to ChatGPT (or vice versa) for the same id.try? keychain.delete(key: ProviderEditSheet.keychainKey(id: p.id))+ try? keychain.deleteChatGPTTokens(providerId: p.id)await DependencyContainer.shared.providerRegistry.unregister(p.name)await MainActor.run { reload() }}