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(ai): add ChatGPT subscription provider infrastructure
cyenxeaea698d9600
diff --git a/macos/App/DependencyInjection/DependencyContainer.swift b/macos/App/DependencyInjection/DependencyContainer.swiftindex 638545f..5c576d3 100644--- a/macos/App/DependencyInjection/DependencyContainer.swift+++ b/macos/App/DependencyInjection/DependencyContainer.swift@@ -86,14 +86,29 @@ final class DependencyContainer {lazy var providerRegistry = ProviderRegistry()+ /// OAuth service for ChatGPT-subscription providers. Holds no state on the+ /// MainActor; callers from `ProviderRegistry` (an actor) reach it through+ /// the container intentionally — provider-construction happens before the+ /// service is invoked.+ lazy var chatGPTOAuthService: ChatGPTOAuthService = ChatGPTOAuthService(keychainService: keychainService)+/// Load all enabled providers from persistence and register them with the registry./// Call once at app startup. Safe to call again after config changes.func bootstrapProviderRegistry() async {await providerRegistry.removeAll()let configs = (try? await llmProviderRepository.fetchAll()) ?? []for config in configs where config.enabled {- let apiKey = (try? keychainService.load(key: "ai.apikey.\(config.id.uuidString)")) ?? ""- await providerRegistry.register(config, apiKey: apiKey)+ switch config.type {+ case .chatGPT:+ // No long-lived API key — the bundle lives in Keychain under+ // `ai.chatgpt.tokens.<uuid>`. Skip registration if the user+ // added the provider but never completed sign-in.+ guard (try? keychainService.loadChatGPTTokens(providerId: config.id)) != nil else { continue }+ await providerRegistry.register(config, apiKey: "", chatGPTOAuthService: chatGPTOAuthService)+ default:+ let apiKey = (try? keychainService.load(key: "ai.apikey.\(config.id.uuidString)")) ?? ""+ await providerRegistry.register(config, apiKey: apiKey)+ }}}diff --git a/macos/Core/Enums/ProviderType.swift b/macos/Core/Enums/ProviderType.swiftindex e6a6ecf..4332b5a 100644--- a/macos/Core/Enums/ProviderType.swift+++ b/macos/Core/Enums/ProviderType.swift@@ -11,6 +11,9 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case geminicase ollama+ // Subscription-based access via OAuth (own provider class)+ case chatGPT = "chatgpt"+// OpenAI-compatible family (all use OpenAIProvider)case openAI = "openai"case azureOpenAI = "azure-openai"@@ -35,6 +38,7 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case .anthropic: return "Anthropic (Claude)"case .gemini: return "Google Gemini"case .ollama: return "Ollama (Local)"+ case .chatGPT: return "OpenAI (Sign in)"case .openAI: return "OpenAI"case .azureOpenAI: return "Azure OpenAI"case .groq: return "Groq"@@ -57,6 +61,7 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case .anthropic: return .anthropiccase .gemini: return .geminicase .ollama: return .local+ case .chatGPT: return .subscriptioncase .openAI, .azureOpenAI, .groq, .deepseek, .mistral, .xAI,.perplexity, .openRouter, .together, .fireworks, .dashscope,.dashscopeCoding, .openAICompatible:@@ -68,6 +73,7 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case anthropic = "Anthropic"case gemini = "Google"case openAICompat = "OpenAI-Compatible"+ case subscription = "Subscription / OAuth"case local = "Local"}@@ -76,6 +82,7 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case .anthropic: return "https://api.anthropic.com/v1"case .gemini: return "https://generativelanguage.googleapis.com/v1beta/openai"case .ollama: return "http://localhost:11434"+ case .chatGPT: return "https://chatgpt.com/backend-api/codex"case .openAI: return "https://api.openai.com/v1"case .azureOpenAI: return "https://YOUR-RESOURCE.openai.azure.com/openai"case .groq: return "https://api.groq.com/openai/v1"@@ -97,6 +104,7 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case .anthropic: return "claude-sonnet-4-6"case .gemini: return "gemini-2.5-flash"case .ollama: return "llama3"+ case .chatGPT: return "gpt-5.4"case .openAI: return "gpt-4o"case .azureOpenAI: return "gpt-4o"case .groq: return "llama-3.3-70b-versatile"@@ -114,7 +122,9 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {}var requiresAPIKey: Bool {- self != .ollama+ // .chatGPT uses OAuth tokens (Keychain blob), not a long-lived API key.+ // .ollama is local and unauthenticated.+ self != .ollama && self != .chatGPT}var allowsPrivateHosts: Bool {@@ -136,6 +146,7 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case .anthropic: return "a.circle.fill"case .gemini: return "g.circle.fill"case .ollama: return "desktopcomputer"+ case .chatGPT: return "person.crop.circle.badge.checkmark"case .openAI: return "bubble.left.and.text.bubble.right.fill"case .azureOpenAI: return "cloud.fill"case .groq: return "bolt.circle.fill"@@ -157,6 +168,11 @@ enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {case .anthropic: return ["claude-sonnet-4-6", "claude-haiku-4-5-20251001", "claude-opus-4-6"]case .gemini: return ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"]case .ollama: return ["llama3", "codellama", "mistral"]+ // ChatGPT model slugs are owned by the Responses API and the only+ // authoritative list comes from `/backend-api/codex/models`. Hard-coding+ // names here would invent IDs that don't exist server-side; if the live+ // fetch fails the user must type a slug manually.+ case .chatGPT: return []case .openAI: return ["gpt-4o", "gpt-4o-mini", "o1", "o1-mini"]case .azureOpenAI: return ["gpt-4o", "gpt-4o-mini"]case .groq: return ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768"]diff --git a/macos/Services/AI/Auth/ChatGPTOAuthConstants.swift b/macos/Services/AI/Auth/ChatGPTOAuthConstants.swiftnew file mode 100644index 0000000..66af945--- /dev/null+++ b/macos/Services/AI/Auth/ChatGPTOAuthConstants.swift@@ -0,0 +1,53 @@+// ChatGPTOAuthConstants.swift+// Gridex+//+// Endpoint + parameter constants for the ChatGPT OAuth flow. All values mirror+// OpenAI's Codex CLI v2.x behaviour (see codex-rs/login/src/server.rs in the+// openai/codex repo). Reusing the public Codex client_id is a deliberate+// trade-off — see plan F.2 disclaimer.++import Foundation++enum ChatGPTOAuthConstants {+ /// The public OAuth client_id baked into OpenAI's Codex CLI. Reused here+ /// because the authorize endpoint only accepts loopback redirect URIs that+ /// were registered for this client. OpenAI may revoke it at any time.+ static let clientId = "app_EMoamEEZ73f0CkXaXp7hrann"++ /// Base of the OAuth issuer. `/oauth/authorize` and `/oauth/token` hang off this.+ static let issuer = URL(string: "https://auth.openai.com")!++ /// Scope set required by the Codex CLI flow. `offline_access` is what gives+ /// us a refresh_token; the `api.connectors.*` scopes are what lets the+ /// access_token reach `chatgpt.com/backend-api/codex`.+ static let scopes = "openid profile email offline_access api.connectors.read api.connectors.invoke"++ /// Backend used by signed-in callers. Distinct from `api.openai.com/v1`.+ /// Derived from ProviderType so Core remains the single source of truth.+ static let backend = URL(string: ProviderType.chatGPT.defaultBaseURL)!++ /// Identifier sent as the `originator` query param. Codex CLI uses+ /// `codex_cli_rs`; we identify ourselves so a future audit can tell.+ /// Deviates from the original plan ("gridex_cli") on purpose — this client+ /// is a macOS GUI, not a CLI, and the value is informational only (the+ /// auth server doesn't gate behaviour on it).+ static let originator = "gridex_macos"++ /// 3 minutes — long enough for password manager + 2FA, short enough to+ /// guarantee `signIn` does not hang the UI indefinitely.+ static let callbackTimeout: TimeInterval = 180++ /// Refresh tokens slightly before the JWT actually expires, so a request+ /// in flight at `exp` doesn't hit a 401.+ static let refreshSkew: TimeInterval = 30++ /// Loopback ports tried in order. The OAuth client_id is registered for+ /// `http://localhost:<any-port>/auth/callback`; Codex CLI defaults to 1455.+ /// We follow the same order so that a stuck listener from a prior `codex`+ /// invocation in the same shell doesn't immediately collide.+ static let preferredPorts: [UInt16] = [1455, 1456, 1457, 1458]++ /// Path component of the redirect URI. Used by both the listener and the+ /// authorize-URL builder to stay in sync.+ static let callbackPath = "/auth/callback"+}diff --git a/macos/Services/AI/Auth/ChatGPTOAuthLoopbackServer.swift b/macos/Services/AI/Auth/ChatGPTOAuthLoopbackServer.swiftnew file mode 100644index 0000000..4d02ea0--- /dev/null+++ b/macos/Services/AI/Auth/ChatGPTOAuthLoopbackServer.swift@@ -0,0 +1,364 @@+// ChatGPTOAuthLoopbackServer.swift+// Gridex+//+// Single-shot loopback HTTP listener used by the ChatGPT OAuth flow.+// The browser receives a `redirect_uri=http://localhost:<port>/auth/callback`+// query param; once it follows the redirect with `code` + `state` we parse+// them out, send a tiny "you can close this window" page back, and tear down.+//+// Trust verified by reverse-engineering Codex CLI: the OAuth client_id accepts+// any loopback port for this redirect path. Binding to 127.0.0.1 (not 0.0.0.0)+// prevents LAN-side hijack.++import Foundation+import Network+import os++/// Result extracted from the browser's GET to `/auth/callback`.+struct ChatGPTOAuthCallback: Sendable {+ let code: String+ let state: String+}++enum ChatGPTOAuthLoopbackError: Error, LocalizedError, CustomStringConvertible {+ case noPortAvailable(tried: [UInt16])+ case timedOut(after: TimeInterval)+ case malformedRequest(reason: String)+ case authError(code: String, description: String?)+ /// `NWListener` reported `.cancelled` before reaching `.ready`. Distinct+ /// from `malformedRequest` because no browser request is involved.+ case listenerCancelled++ var description: String {+ switch self {+ case .noPortAvailable(let tried):+ return "Could not bind any of the loopback ports: \(tried)"+ case .timedOut(let s):+ return "OAuth callback did not arrive within \(Int(s))s"+ case .malformedRequest(let why):+ return "Browser callback was malformed: \(why)"+ case .authError(let code, let desc):+ return "Authorization server returned error '\(code)': \(desc ?? "(no description)")"+ case .listenerCancelled:+ return "OAuth loopback listener was cancelled before becoming ready"+ }+ }++ /// Foundation reads this for `error.localizedDescription`. Without this+ /// override callers see the default `Error._domain`-prefixed string and+ /// lose the `description` payload we built above.+ var errorDescription: String? { description }+}++/// One-shot loopback HTTP server. Create it, call `start()`, then `awaitCallback()`,+/// then it self-tears-down. Re-using an instance after success is not supported.+///+/// The class is `@unchecked Sendable` because `NWListener` callbacks fire on+/// internal queues — we serialize state mutation through a lock.+final class ChatGPTOAuthLoopbackServer: @unchecked Sendable {++ private static let log = Logger(subsystem: "com.gridex.gridex", category: "ChatGPTOAuth")++ private let lock = NSLock()+ private var listener: NWListener?+ private var connections: [NWConnection] = []+ private var continuation: CheckedContinuation<ChatGPTOAuthCallback, Error>?+ private var resolvedResult: Result<ChatGPTOAuthCallback, Error>?+ private var resolved = false+ /// The 180-second timeout sleeper. Tracked so a successful callback can+ /// cancel it instead of leaving a stranded Task that wakes up minutes+ /// later only to find `resolved == true` and exit.+ private var timeoutTask: Task<Void, Never>?++ private(set) var actualPort: UInt16 = 0++ /// Best-effort response body sent to the browser after a successful callback.+ /// Plain HTML (Safari frequently ignores `window.close()` from non-script-opened+ /// tabs, but the JS attempt is harmless on Chrome/Firefox).+ private static let successPage =+"""+<!doctype html><html><head><meta charset="utf-8"><title>Gridex sign-in</title>+<style>body{font:14px -apple-system;color:#333;text-align:center;padding:80px}</style>+</head><body><h2>Sign-in complete</h2>+<p>You can close this tab and return to Gridex.</p>+<script>setTimeout(()=>window.close(),500)</script>+</body></html>+"""++ private static let errorPage =+"""+<!doctype html><html><head><meta charset="utf-8"><title>Gridex sign-in</title>+<style>body{font:14px -apple-system;color:#333;text-align:center;padding:80px}</style>+</head><body><h2>Sign-in failed</h2>+<p>Return to Gridex for details. You can close this tab.</p>+</body></html>+"""++ /// Starts the listener on the first available port from `preferredPorts`,+ /// then falls back to a kernel-assigned ephemeral port. Returns the port+ /// that was bound.+ func start(preferredPorts: [UInt16] = ChatGPTOAuthConstants.preferredPorts) async throws -> UInt16 {+ // Build a candidate list: preferred first, then `0` (ephemeral) as last resort.+ let candidates = preferredPorts + [0]+ var triedPorts: [UInt16] = []++ for candidate in candidates {+ triedPorts.append(candidate)+ do {+ let port: UInt16 = try await tryBind(port: candidate)+ actualPort = port+ Self.log.info("OAuth loopback listening on 127.0.0.1:\(port)")+ return port+ } catch {+ Self.log.notice("OAuth loopback port \(candidate) unavailable: \(error.localizedDescription, privacy: .public)")+ continue+ }+ }+ throw ChatGPTOAuthLoopbackError.noPortAvailable(tried: triedPorts)+ }++ /// Awaits a single callback or fails with `.timedOut`. Calling this without+ /// a preceding `start()` returns immediately with a programming error.+ func awaitCallback(timeout: TimeInterval) async throws -> ChatGPTOAuthCallback {+ precondition(actualPort != 0 || listener != nil, "must call start() before awaitCallback()")++ return try await withTaskCancellationHandler {+ try await withCheckedThrowingContinuation { (cont: CheckedContinuation<ChatGPTOAuthCallback, Error>) in+ lock.lock()+ if resolved {+ let result = self.resolvedResult+ lock.unlock()+ switch result {+ case .success(let callback):+ cont.resume(returning: callback)+ case .failure(let error):+ cont.resume(throwing: error)+ case .none:+ cont.resume(throwing: ChatGPTOAuthLoopbackError.malformedRequest(reason: "already resolved"))+ }+ return+ }+ self.continuation = cont+ let task = Task { [weak self] in+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))+ guard let self else { return }+ if Task.isCancelled { return }+ self.resolveFailure(ChatGPTOAuthLoopbackError.timedOut(after: timeout))+ }+ self.timeoutTask = task+ lock.unlock()+ }+ } onCancel: {+ self.resolveFailure(CancellationError())+ }+ }++ /// Tear down all sockets. Idempotent.+ func stop() {+ lock.lock()+ defer { lock.unlock() }+ listener?.cancel()+ listener = nil+ for c in connections { c.cancel() }+ connections.removeAll()+ }++ // MARK: - Internal++ private func tryBind(port: UInt16) async throws -> UInt16 {+ let nwPort: NWEndpoint.Port = (port == 0) ? .any : NWEndpoint.Port(rawValue: port)!+ let params = NWParameters.tcp+ params.requiredLocalEndpoint = NWEndpoint.hostPort(host: .ipv4(.loopback), port: nwPort)++ let listener = try NWListener(using: params)+ self.listener = listener++ listener.newConnectionHandler = { [weak self] conn in+ self?.handleConnection(conn)+ }++ // Bridge `state` → async via continuation. Resume only on .ready/.failed/.cancelled.+ let actualPort: UInt16 = try await withCheckedThrowingContinuation { (cont: CheckedContinuation<UInt16, Error>) in+ var resumed = false+ listener.stateUpdateHandler = { state in+ guard !resumed else { return }+ switch state {+ case .ready:+ resumed = true+ let p = listener.port?.rawValue ?? port+ cont.resume(returning: p)+ case .failed(let err):+ resumed = true+ cont.resume(throwing: err)+ case .cancelled:+ resumed = true+ cont.resume(throwing: ChatGPTOAuthLoopbackError.listenerCancelled)+ default:+ break+ }+ }+ listener.start(queue: .global(qos: .userInitiated))+ }+ return actualPort+ }++ private func handleConnection(_ conn: NWConnection) {+ lock.lock()+ connections.append(conn)+ lock.unlock()++ conn.start(queue: .global(qos: .userInitiated))+ receiveRequest(conn, accumulated: Data())+ }++ /// Accumulates bytes until `\r\n\r\n` end-of-headers, then parses the GET line.+ /// We don't need to read the body — the OAuth callback is GET-only.+ private func receiveRequest(_ conn: NWConnection, accumulated: Data) {+ conn.receive(minimumIncompleteLength: 1, maximumLength: 8192) { [weak self] chunk, _, isComplete, error in+ guard let self else { return }++ var buffer = accumulated+ if let chunk { buffer.append(chunk) }++ if let error = error {+ Self.log.error("OAuth loopback receive error: \(error.localizedDescription, privacy: .public)")+ conn.cancel()+ self.resolveFailure(error)+ return+ }++ // Look for end-of-headers (CRLF CRLF or LF LF as a fallback).+ if let range = buffer.range(of: Data("\r\n\r\n".utf8)) ?? buffer.range(of: Data("\n\n".utf8)) {+ let head = buffer[..<range.lowerBound]+ self.processHead(head, on: conn)+ return+ }++ if isComplete {+ conn.cancel()+ self.resolveFailure(ChatGPTOAuthLoopbackError.malformedRequest(reason: "connection closed before headers ended"))+ return+ }++ if buffer.count > 64 * 1024 {+ // Defensive cap — a real OAuth callback URL is well under 4 KB.+ conn.cancel()+ self.resolveFailure(ChatGPTOAuthLoopbackError.malformedRequest(reason: "headers exceed 64KB"))+ return+ }++ self.receiveRequest(conn, accumulated: buffer)+ }+ }++ private func processHead(_ head: Data, on conn: NWConnection) {+ guard let text = String(data: head, encoding: .utf8) else {+ sendErrorPage(conn)+ resolveFailure(ChatGPTOAuthLoopbackError.malformedRequest(reason: "request bytes are not UTF-8"))+ return+ }++ let firstLine = text.split(whereSeparator: { $0 == "\r" || $0 == "\n" }).first ?? ""+ let parts = firstLine.split(separator: " ", maxSplits: 2)+ guard parts.count >= 2 else {+ sendErrorPage(conn)+ resolveFailure(ChatGPTOAuthLoopbackError.malformedRequest(reason: "request line malformed: \(firstLine)"))+ return+ }+ // parts[0] = "GET", parts[1] = "/auth/callback?code=...&state=..."+ let pathAndQuery = String(parts[1])++ // Use URLComponents to parse query items robustly.+ // We prepend a fake host because URLComponents doesn't like bare paths.+ guard let comps = URLComponents(string: "http://localhost\(pathAndQuery)") else {+ sendErrorPage(conn)+ resolveFailure(ChatGPTOAuthLoopbackError.malformedRequest(reason: "could not parse path: \(pathAndQuery)"))+ return+ }++ if comps.path != ChatGPTOAuthConstants.callbackPath {+ // Probably a /favicon.ico or stray probe — keep listening for the real one.+ sendErrorPage(conn)+ return+ }++ let items = comps.queryItems ?? []+ let code = items.first(where: { $0.name == "code" })?.value+ let state = items.first(where: { $0.name == "state" })?.value+ let errCode = items.first(where: { $0.name == "error" })?.value+ let errDesc = items.first(where: { $0.name == "error_description" })?.value++ if let errCode = errCode {+ sendErrorPage(conn)+ resolveFailure(ChatGPTOAuthLoopbackError.authError(code: errCode, description: errDesc))+ return+ }++ guard let code = code, let state = state else {+ sendErrorPage(conn)+ resolveFailure(ChatGPTOAuthLoopbackError.malformedRequest(reason: "missing code or state in callback"))+ return+ }++ sendSuccessPage(conn)+ resolveSuccess(ChatGPTOAuthCallback(code: code, state: state))+ }++ private func sendSuccessPage(_ conn: NWConnection) {+ sendHTML(conn, status: 200, body: Self.successPage)+ }++ private func sendErrorPage(_ conn: NWConnection) {+ sendHTML(conn, status: 400, body: Self.errorPage)+ }++ private func sendHTML(_ conn: NWConnection, status: Int, body: String) {+ let bytes = body.data(using: .utf8) ?? Data()+ let head = """+HTTP/1.1 \(status) OK\r+Content-Type: text/html; charset=utf-8\r+Content-Length: \(bytes.count)\r+Connection: close\r+\r++"""+ var packet = Data(head.utf8)+ packet.append(bytes)+ conn.send(content: packet, completion: .contentProcessed { _ in+ conn.cancel()+ })+ }++ private func resolveSuccess(_ callback: ChatGPTOAuthCallback) {+ lock.lock()+ guard !resolved else { lock.unlock(); return }+ resolved = true+ self.resolvedResult = .success(callback)+ let cont = self.continuation+ let timer = self.timeoutTask+ self.continuation = nil+ self.timeoutTask = nil+ lock.unlock()++ timer?.cancel()+ cont?.resume(returning: callback)+ // Tear down all sockets — listener fires last.+ stop()+ }++ private func resolveFailure(_ error: Error) {+ lock.lock()+ guard !resolved else { lock.unlock(); return }+ resolved = true+ self.resolvedResult = .failure(error)+ let cont = self.continuation+ let timer = self.timeoutTask+ self.continuation = nil+ self.timeoutTask = nil+ lock.unlock()++ timer?.cancel()+ cont?.resume(throwing: error)+ stop()+ }+}diff --git a/macos/Services/AI/Auth/ChatGPTOAuthService.swift b/macos/Services/AI/Auth/ChatGPTOAuthService.swiftnew file mode 100644index 0000000..065ba60--- /dev/null+++ b/macos/Services/AI/Auth/ChatGPTOAuthService.swift@@ -0,0 +1,298 @@+// ChatGPTOAuthService.swift+// Gridex+//+// Owns the full ChatGPT OAuth lifecycle:+// - signIn(providerId:) — interactive PKCE flow, opens the browser+// - tokenBundle(providerId:) — non-interactive, refreshes if access token+// is within `refreshSkew` of expiring+// - signOut(providerId:) — clears the Keychain blob+// - currentStatus(providerId:) — UI helper, no network+//+// Concurrency model: actor. In-flight refreshes are coalesced per providerId so+// that a burst of `tokenBundle()` calls only triggers one network round-trip.++import AppKit+import Foundation+import os++actor ChatGPTOAuthService {++ private static let log = Logger(subsystem: "com.gridex.gridex", category: "ChatGPTOAuth")++ private let keychain: KeychainServiceProtocol+ private let urlSession: URLSession+ private var refreshInFlight: [UUID: Task<ChatGPTTokenBundle, Error>] = [:]++ init(keychainService: KeychainServiceProtocol, urlSession: URLSession = .shared) {+ self.keychain = keychainService+ self.urlSession = urlSession+ }++ enum SignInStatus: Equatable, Sendable {+ case signedOut+ case signedIn(email: String?, plan: String?)+ }++ // MARK: - Public API++ /// Runs the full PKCE flow: opens browser, waits for /auth/callback,+ /// exchanges the code for tokens, persists them, returns the bundle.+ /// Call from any context — interaction with NSWorkspace happens on MainActor+ /// internally.+ @discardableResult+ func signIn(providerId: UUID) async throws -> ChatGPTTokenBundle {+ Self.log.info("ChatGPT OAuth sign-in starting for provider \(providerId.uuidString, privacy: .public)")++ let verifier = PKCE.makeVerifier()+ let challenge = PKCE.challenge(for: verifier)+ let state = PKCE.makeState()++ let server = ChatGPTOAuthLoopbackServer()+ let port = try await server.start()+ let redirectURI = "http://localhost:\(port)\(ChatGPTOAuthConstants.callbackPath)"++ // Open the browser. NSWorkspace must be touched on the main thread.+ let authURL = buildAuthorizeURL(challenge: challenge, state: state, redirectURI: redirectURI)+ Self.log.debug("Opening browser to authorize URL")+ let didOpenBrowser = await MainActor.run {+ NSWorkspace.shared.open(authURL)+ }+ guard didOpenBrowser else {+ server.stop()+ Self.log.error("ChatGPT OAuth sign-in failed: LaunchServices could not open browser")+ throw GridexError.aiProviderError("Could not open browser for ChatGPT sign-in")+ }++ // Block on the browser callback (or 3-min timeout).+ let callback: ChatGPTOAuthCallback+ do {+ callback = try await server.awaitCallback(timeout: ChatGPTOAuthConstants.callbackTimeout)+ } catch {+ server.stop()+ Self.log.error("OAuth callback failed: \(error.localizedDescription, privacy: .public)")+ throw GridexError.aiProviderError("Sign-in failed: \(error.localizedDescription)")+ }++ // CSRF check — the auth server echoes our `state` back to the redirect URI.+ guard callback.state == state else {+ Self.log.error("OAuth state mismatch — possible CSRF")+ throw GridexError.aiProviderError("State mismatch — sign-in aborted (possible CSRF)")+ }++ // Exchange the authorization code for tokens.+ let tokens = try await exchangeCodeForTokens(+ code: callback.code,+ verifier: verifier,+ redirectURI: redirectURI+ )++ let bundle = try buildBundle(from: tokens)+ try keychain.saveChatGPTTokens(providerId: providerId, bundle: bundle)+ Self.log.info("ChatGPT OAuth sign-in complete; email=\(bundle.email ?? "?", privacy: .private)")++ // Bring Gridex back to the front — Safari may not auto-close the tab.+ await MainActor.run {+ NSApp.activate(ignoringOtherApps: true)+ }++ return bundle+ }++ /// Returns a usable token bundle, refreshing via `refresh_token` if the+ /// stored `access_token` is within `refreshSkew` of expiring.+ /// Coalesces concurrent calls per `providerId`.+ func tokenBundle(providerId: UUID) async throws -> ChatGPTTokenBundle {+ guard let bundle = try keychain.loadChatGPTTokens(providerId: providerId) else {+ throw GridexError.aiAPIKeyMissing+ }++ let exp = JWTDecoder.expiration(of: bundle.accessToken) ?? .distantPast+ if Date() < exp.addingTimeInterval(-ChatGPTOAuthConstants.refreshSkew) {+ return bundle+ }++ if let inflight = refreshInFlight[providerId] {+ return try await inflight.value+ }++ let task = Task<ChatGPTTokenBundle, Error> { [self] in+ try await self.performRefresh(bundle: bundle, providerId: providerId)+ }+ refreshInFlight[providerId] = task+ defer { refreshInFlight[providerId] = nil }+ return try await task.value+ }++ /// Deletes the persisted bundle. Cheap; does not call the auth server.+ func signOut(providerId: UUID) throws {+ Self.log.info("ChatGPT sign-out for \(providerId.uuidString, privacy: .public)")+ try keychain.deleteChatGPTTokens(providerId: providerId)+ }++ /// Non-network status used by the settings sheet to render "Signed in as ..."+ /// chrome.+ func currentStatus(providerId: UUID) -> SignInStatus {+ guard let bundle = try? keychain.loadChatGPTTokens(providerId: providerId) else {+ return .signedOut+ }+ return .signedIn(email: bundle.email, plan: bundle.planType)+ }++ // MARK: - Internal++ private struct TokenResponse: Decodable {+ let access_token: String+ let refresh_token: String?+ let id_token: String?+ }++ private func buildAuthorizeURL(challenge: String, state: String, redirectURI: String) -> URL {+ var comps = URLComponents(url: ChatGPTOAuthConstants.issuer.appendingPathComponent("oauth/authorize"),+ resolvingAgainstBaseURL: false)!+ comps.queryItems = [+ URLQueryItem(name: "response_type", value: "code"),+ URLQueryItem(name: "client_id", value: ChatGPTOAuthConstants.clientId),+ URLQueryItem(name: "redirect_uri", value: redirectURI),+ URLQueryItem(name: "scope", value: ChatGPTOAuthConstants.scopes),+ URLQueryItem(name: "code_challenge", value: challenge),+ URLQueryItem(name: "code_challenge_method", value: "S256"),+ URLQueryItem(name: "state", value: state),+ URLQueryItem(name: "id_token_add_organizations", value: "true"),+ URLQueryItem(name: "codex_cli_simplified_flow", value: "true"),+ URLQueryItem(name: "originator", value: ChatGPTOAuthConstants.originator),+ ]+ return comps.url!+ }++ private func exchangeCodeForTokens(code: String, verifier: String, redirectURI: String) async throws -> TokenResponse {+ let url = ChatGPTOAuthConstants.issuer.appendingPathComponent("oauth/token")+ var req = URLRequest(url: url)+ req.httpMethod = "POST"+ req.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")++ // form-encode body+ let body = [+ "grant_type": "authorization_code",+ "code": code,+ "redirect_uri": redirectURI,+ "client_id": ChatGPTOAuthConstants.clientId,+ "code_verifier": verifier,+ ]+ .map { "\($0.key)=\(encode($0.value))" }+ .joined(separator: "&")+ req.httpBody = Data(body.utf8)++ let (data, response) = try await urlSession.data(for: req)+ guard let http = response as? HTTPURLResponse else {+ throw GridexError.aiProviderError("Token exchange: non-HTTP response")+ }+ guard (200..<300).contains(http.statusCode) else {+ let detail = parseErrorBody(data)+ Self.log.error("Token exchange failed: HTTP \(http.statusCode) \(detail, privacy: .public)")+ throw GridexError.aiProviderError("Token exchange failed (HTTP \(http.statusCode)): \(detail)")+ }++ do {+ return try JSONDecoder().decode(TokenResponse.self, from: data)+ } catch {+ Self.log.error("Token exchange: malformed body — \(error.localizedDescription, privacy: .public)")+ throw GridexError.aiProviderError("Token exchange returned an unexpected payload")+ }+ }++ /// JSON-bodied refresh per Codex CLI behaviour. The auth server returns the+ /// new access_token (and may rotate refresh_token + id_token). When fields+ /// are absent we keep the old values.+ private func performRefresh(bundle: ChatGPTTokenBundle, providerId: UUID) async throws -> ChatGPTTokenBundle {+ Self.log.info("ChatGPT token refresh for \(providerId.uuidString, privacy: .public)")+ let url = ChatGPTOAuthConstants.issuer.appendingPathComponent("oauth/token")+ var req = URLRequest(url: url)+ req.httpMethod = "POST"+ req.setValue("application/json", forHTTPHeaderField: "Content-Type")++ let body: [String: String] = [+ "client_id": ChatGPTOAuthConstants.clientId,+ "grant_type": "refresh_token",+ "refresh_token": bundle.refreshToken,+ ]+ req.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (data, response) = try await urlSession.data(for: req)+ guard let http = response as? HTTPURLResponse else {+ throw GridexError.aiProviderError("Refresh: non-HTTP response")+ }++ if (200..<300).contains(http.statusCode) {+ let parsed = try JSONDecoder().decode(TokenResponse.self, from: data)+ // Merge new values over the old bundle. refresh_token / id_token may rotate.+ var updated = bundle+ updated.accessToken = parsed.access_token+ if let rt = parsed.refresh_token, !rt.isEmpty { updated.refreshToken = rt }+ if let idt = parsed.id_token, !idt.isEmpty {+ updated.idToken = idt+ applyClaims(into: &updated)+ }+ updated.obtainedAt = Date()+ try keychain.saveChatGPTTokens(providerId: providerId, bundle: updated)+ Self.log.info("Refresh ok; new exp=\(JWTDecoder.expiration(of: updated.accessToken)?.timeIntervalSince1970 ?? 0)")+ return updated+ }++ // Failure path. If the auth server says the refresh_token is no longer+ // valid, blow the bundle away and surface aiAPIKeyMissing — the UI will+ // prompt the user to sign in again.+ let detail = parseErrorBody(data)+ let lower = detail.lowercased()+ let dead = ["refresh_token_expired", "refresh_token_reused", "refresh_token_invalidated"]+ if dead.contains(where: lower.contains) {+ Self.log.notice("Refresh token rejected (\(detail, privacy: .public)); clearing keychain")+ try? keychain.deleteChatGPTTokens(providerId: providerId)+ throw GridexError.aiAPIKeyMissing+ }+ throw GridexError.aiProviderError("Refresh failed (HTTP \(http.statusCode)): \(detail)")+ }++ /// Decodes the id_token claims into the bundle's UI-friendly fields.+ private func applyClaims(into bundle: inout ChatGPTTokenBundle) {+ guard let claims = try? JWTDecoder.payload(of: bundle.idToken) else { return }+ bundle.email = claims["email"] as? String ?? bundle.email+ bundle.accountId = claims["chatgpt_account_id"] as? String ?? bundle.accountId+ bundle.planType = claims["chatgpt_plan_type"] as? String ?? bundle.planType+ }++ /// Build a fresh bundle from a successful token exchange response.+ private func buildBundle(from tokens: TokenResponse) throws -> ChatGPTTokenBundle {+ guard let idToken = tokens.id_token, !idToken.isEmpty else {+ throw GridexError.aiProviderError("Token exchange returned no id_token")+ }+ guard let refresh = tokens.refresh_token, !refresh.isEmpty else {+ throw GridexError.aiProviderError("Token exchange returned no refresh_token (offline_access scope missing?)")+ }+ var b = ChatGPTTokenBundle(+ accessToken: tokens.access_token,+ refreshToken: refresh,+ idToken: idToken+ )+ applyClaims(into: &b)+ return b+ }++ private func encode(_ value: String) -> String {+ // Application/x-www-form-urlencoded — URL-encode + use `+` for spaces.+ var allowed = CharacterSet.urlQueryAllowed+ allowed.remove(charactersIn: "+&=")+ return value.addingPercentEncoding(withAllowedCharacters: allowed) ?? value+ }++ private func parseErrorBody(_ data: Data) -> String {+ if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {+ if let err = json["error"] as? String {+ if let desc = json["error_description"] as? String { return "\(err): \(desc)" }+ return err+ }+ if let msg = json["message"] as? String { return msg }+ }+ return String(data: data, encoding: .utf8)?+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? "(empty body)"+ }+}diff --git a/macos/Services/AI/ProviderFactory.swift b/macos/Services/AI/ProviderFactory.swiftindex 8ec8b14..23fd097 100644--- a/macos/Services/AI/ProviderFactory.swift+++ b/macos/Services/AI/ProviderFactory.swift@@ -8,7 +8,20 @@import Foundationenum ProviderFactory {- static func make(config: ProviderConfig, apiKey: String) -> any LLMService {+ /// Build the concrete `LLMService` for a config. `apiKey` is ignored for+ /// `.chatGPT` (it uses OAuth tokens via `chatGPTOAuthService`); pass empty+ /// for that case.+ ///+ /// `chatGPTOAuthService` must be provided when `config.type == .chatGPT`;+ /// other types ignore it. We pass it explicitly (rather than reach for+ /// `DependencyContainer.shared`) because the factory is callable from+ /// non-MainActor contexts (`ProviderRegistry` is an actor) — and the+ /// container is `@MainActor`-isolated.+ static func make(+ config: ProviderConfig,+ apiKey: String,+ chatGPTOAuthService: ChatGPTOAuthService? = nil+ ) -> any LLMService {let base = config.resolvedBaseURLswitch config.type {case .anthropic:@@ -17,6 +30,11 @@ enum ProviderFactory {return GeminiProvider(apiKey: apiKey, baseURL: base)case .ollama:return OllamaProvider(baseURLString: base)+ case .chatGPT:+ guard let svc = chatGPTOAuthService else {+ preconditionFailure("ChatGPT provider requires chatGPTOAuthService")+ }+ return ChatGPTProvider(providerId: config.id, baseURL: base, oauthService: svc)case .openAI, .azureOpenAI, .groq, .deepseek, .mistral, .xAI,.perplexity, .openRouter, .together, .fireworks, .dashscope,.dashscopeCoding, .openAICompatible:@@ -24,7 +42,8 @@ enum ProviderFactory {}}- /// Convenience for legacy callers that only know the type.+ /// Convenience for legacy callers that only know the type. Cannot build a+ /// ChatGPT provider — that requires an explicit provider id + OAuth service.static func make(type: ProviderType, apiKey: String, baseURL: String? = nil) -> any LLMService {let config = ProviderConfig(name: type.rawValue,diff --git a/macos/Services/AI/ProviderRegistry.swift b/macos/Services/AI/ProviderRegistry.swiftindex f59acc3..85c2bb0 100644--- a/macos/Services/AI/ProviderRegistry.swift+++ b/macos/Services/AI/ProviderRegistry.swift@@ -17,8 +17,17 @@ actor ProviderRegistry {private var entries: [String: Entry] = [:]/// Register or replace a provider by name.- func register(_ config: ProviderConfig, apiKey: String) {- let service = ProviderFactory.make(config: config, apiKey: apiKey)+ /// Pass `chatGPTOAuthService` when `config.type == .chatGPT`; ignored otherwise.+ func register(+ _ config: ProviderConfig,+ apiKey: String,+ chatGPTOAuthService: ChatGPTOAuthService? = nil+ ) {+ let service = ProviderFactory.make(+ config: config,+ apiKey: apiKey,+ chatGPTOAuthService: chatGPTOAuthService+ )entries[config.name] = Entry(config: config, service: service)}diff --git a/macos/Services/AI/Providers/ChatGPTProvider.swift b/macos/Services/AI/Providers/ChatGPTProvider.swiftnew file mode 100644index 0000000..2ee2d18--- /dev/null+++ b/macos/Services/AI/Providers/ChatGPTProvider.swift@@ -0,0 +1,273 @@+// ChatGPTProvider.swift+// Gridex+//+// LLMService implementation backed by the ChatGPT subscription via the+// Codex CLI OAuth flow. Talks to `chatgpt.com/backend-api/codex/responses`+// (the Responses API), NOT the standard `api.openai.com/v1/chat/completions`.+//+// Token refresh happens lazily inside each request — see+// `ChatGPTOAuthService.tokenBundle(...)`. The provider holds a reference to+// the OAuth service rather than caching a token, so a refresh in one call+// is visible to the next.++import Foundation+import os++final class ChatGPTProvider: LLMService, Sendable {++ private static let log = Logger(subsystem: "com.gridex.gridex", category: "ChatGPTProvider")++ let providerName = "ChatGPT"++ private let providerId: UUID+ private let baseURL: String+ private let oauthService: ChatGPTOAuthService+ private let urlSession: URLSession++ init(+ providerId: UUID,+ baseURL: String = ChatGPTOAuthConstants.backend.absoluteString,+ oauthService: ChatGPTOAuthService,+ urlSession: URLSession = .shared+ ) {+ self.providerId = providerId+ let trimmed = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)+ self.baseURL = trimmed.hasSuffix("/") ? String(trimmed.dropLast()) : trimmed+ self.oauthService = oauthService+ self.urlSession = urlSession+ }++ // MARK: - LLMService++ func stream(+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) -> AsyncThrowingStream<String, Error> {+ AsyncThrowingStream { continuation in+ Task {+ do {+ let bundle = try await self.oauthService.tokenBundle(providerId: self.providerId)+ let request = try self.buildResponsesRequest(+ bundle: bundle,+ messages: messages,+ systemPrompt: systemPrompt,+ model: model,+ maxTokens: maxTokens,+ temperature: temperature+ )++ let (byteStream, response) = try await self.urlSession.bytes(for: request)+ guard let http = response as? HTTPURLResponse else {+ continuation.finish(throwing: GridexError.aiStreamingError("Non-HTTP response"))+ return+ }+ if http.statusCode == 401 || http.statusCode == 403 {+ await self.clearRejectedToken(endpoint: "/responses", statusCode: http.statusCode)+ continuation.finish(throwing: GridexError.aiAPIKeyMissing)+ return+ }+ guard http.statusCode == 200 else {+ // Drain a bounded chunk of the body for diagnostics.+ var bodyBytes: [UInt8] = []+ for try await byte in byteStream {+ bodyBytes.append(byte)+ if bodyBytes.count > 4096 { break }+ }+ let bodyData = Data(bodyBytes)+ let bodyText = String(data: bodyData, encoding: .utf8) ?? ""+ Self.log.error("/responses HTTP \(http.statusCode) body: \(bodyText, privacy: .public)")+ let parsed = Self.extractErrorMessage(from: bodyData)+ let snippet = bodyText.prefix(300)+ let msg = parsed ?? "HTTP \(http.statusCode): \(snippet)"+ continuation.finish(throwing: GridexError.aiProviderError(msg))+ return+ }++ try await self.parseSSE(stream: byteStream, into: continuation)+ continuation.finish()+ } catch {+ continuation.finish(throwing: error)+ }+ }+ }+ }++ func availableModels() async throws -> [LLMModel] {+ let bundle = try await oauthService.tokenBundle(providerId: providerId)+ var components = URLComponents(string: "\(baseURL)/models")!+ components.queryItems = [URLQueryItem(name: "client_version", value: "1.0.0")]+ var request = URLRequest(url: components.url!)+ request.setValue("Bearer \(bundle.accessToken)", forHTTPHeaderField: "Authorization")+ if let accountId = bundle.accountId {+ request.setValue(accountId, forHTTPHeaderField: "ChatGPT-Account-ID")+ }++ let (data, http) = try await LLMRetry.perform(request, session: urlSession)++ if http.statusCode == 401 || http.statusCode == 403 {+ await clearRejectedToken(endpoint: "/models", statusCode: http.statusCode)+ throw GridexError.aiAPIKeyMissing+ }+ guard http.statusCode == 200 else {+ throw GridexError.aiProviderError("HTTP \(http.statusCode) on /models")+ }++ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {+ throw GridexError.aiProviderError("Unexpected /models response shape")+ }+ guard let arr = json["models"] as? [[String: Any]] else {+ throw GridexError.aiProviderError("/models response missing 'models' array")+ }++ let visible = arr.compactMap { m -> LLMModel? in+ guard let slug = m["slug"] as? String else { return nil }+ // Filter to user-listable models — the API returns hidden/deprecated+ // entries that are not actually usable through `/responses`.+ let supported = (m["supported_in_api"] as? Bool) ?? true+ let visibility = m["visibility"] as? String ?? "list"+ guard supported, visibility == "list" else { return nil }+ return LLMModel(+ id: slug,+ name: (m["name"] as? String) ?? slug,+ provider: providerName,+ contextWindow: (m["context_window"] as? Int) ?? 128_000,+ supportsStreaming: true+ )+ }+ return visible+ }++ /// Re-uses `availableModels()` as a cheap probe — a 200 there proves the+ /// access_token is currently good. ProviderEditSheet hides the Test button+ /// for ChatGPT, so this method is mostly here for protocol conformance + tests.+ func validateAPIKey() async throws -> Bool {+ _ = try await availableModels()+ return true+ }++ // MARK: - Internal — request building++ private func buildResponsesRequest(+ bundle: ChatGPTTokenBundle,+ messages: [LLMMessage],+ systemPrompt: String,+ model: String,+ maxTokens: Int,+ temperature: Double+ ) throws -> URLRequest {+ guard let url = URL(string: "\(baseURL)/responses") else {+ throw GridexError.aiProviderError("Invalid baseURL: \(baseURL)")+ }+ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.setValue("Bearer \(bundle.accessToken)", forHTTPHeaderField: "Authorization")+ if let accountId = bundle.accountId {+ request.setValue(accountId, forHTTPHeaderField: "ChatGPT-Account-ID")+ }+ // Codex CLI sends this; harmless if the server ignores it.+ request.setValue("responses=v1", forHTTPHeaderField: "OpenAI-Beta")++ // System role → top-level `instructions`. Other roles flow into `input`.+ // Wire format mirrors Codex CLI's actual /responses traffic:+ // - each input item is a typed `message` object+ // - content is an array of {type, text} parts (input_text / output_text)+ // - we DO NOT send temperature or max_output_tokens — GPT-5 family+ // rejects custom temperature, and Codex relies on server defaults+ // for output length. Sending either field returns HTTP 400.+ let inputMessages: [[String: Any]] = messages+ .filter { $0.role != .system }+ .map { msg in+ let partType = (msg.role == .assistant) ? "output_text" : "input_text"+ return [+ "type": "message",+ "role": msg.role.rawValue,+ "content": [+ ["type": partType, "text": msg.content],+ ],+ ]+ }++ let body: [String: Any] = [+ "model": model,+ "instructions": systemPrompt,+ "input": inputMessages,+ "stream": true,+ "store": false,+ ]+ request.httpBody = try JSONSerialization.data(withJSONObject: body)+ // Body contains the user's prompt + system instructions. Logging it+ // verbatim — even at .debug — leaks chat content to Console.app on+ // dev builds. Only emit size/message count and non-content tuning params.+ Self.log.debug("temperature=\(temperature) maxTokens=\(maxTokens) ignored for ChatGPT backend")+ Self.log.debug("/responses request: \(request.httpBody?.count ?? 0) bytes, \(inputMessages.count) message(s)")+ return request+ }++ // MARK: - Internal — SSE parsing++ /// Streams `URLSession.AsyncBytes` line-by-line and yields text deltas to+ /// the continuation. Recognises three event kinds:+ /// - response.output_text.delta → yield `delta` field+ /// - response.completed → finish stream+ /// - response.error → finish with thrown error+ /// Other events are ignored.+ private func parseSSE(+ stream: URLSession.AsyncBytes,+ into continuation: AsyncThrowingStream<String, Error>.Continuation+ ) async throws {+ var currentEvent: String? = nil++ for try await line in stream.lines {+ if line.isEmpty {+ currentEvent = nil+ continue+ }+ if line.hasPrefix("event: ") {+ currentEvent = String(line.dropFirst("event: ".count))+ continue+ }+ if line.hasPrefix(":") {+ // SSE comment / keep-alive — ignore.+ continue+ }+ guard line.hasPrefix("data: ") else { continue }+ let payload = String(line.dropFirst("data: ".count))+ if payload == "[DONE]" { break } // not used by Responses API but harmless++ guard let data = payload.data(using: .utf8) else { continue }++ switch currentEvent {+ case "response.output_text.delta":+ if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let delta = json["delta"] as? String {+ continuation.yield(delta)+ }+ case "response.error":+ throw GridexError.aiStreamingError(Self.extractErrorMessage(from: data) ?? payload)+ case "response.completed":+ return+ default:+ Self.log.debug("Ignoring unrecognized SSE event: \(currentEvent ?? "(none)", privacy: .public)")+ continue+ }+ }+ }++ private func clearRejectedToken(endpoint: String, statusCode: Int) async {+ Self.log.notice("\(endpoint, privacy: .public) returned \(statusCode); clearing ChatGPT token bundle")+ try? await oauthService.signOut(providerId: providerId)+ }++ /// Pull a human-readable error message out of a Responses-API JSON body,+ /// in either nested (`{"error":{"message":...}}`) or flat (`{"message":...}`)+ /// form. Returns nil when the body isn't JSON or has neither shape.+ private static func extractErrorMessage(from data: Data) -> String? {+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }+ if let err = json["error"] as? [String: Any], let m = err["message"] as? String { return m }+ return json["message"] as? String+ }+}diff --git a/macos/Tests/GridexTests/ChatGPTOAuthServiceTests.swift b/macos/Tests/GridexTests/ChatGPTOAuthServiceTests.swiftnew file mode 100644index 0000000..24ef567--- /dev/null+++ b/macos/Tests/GridexTests/ChatGPTOAuthServiceTests.swift@@ -0,0 +1,601 @@+// ChatGPTOAuthServiceTests.swift+// Gridex+//+// Mocked-network tests for ChatGPTOAuthService.tokenBundle(...) refresh path:+// 1. Concurrent calls with an expired access_token coalesce into ONE+// auth.openai.com round-trip (per-providerId in-flight de-dup).+// 2. `error: refresh_token_expired` from the server clears the keychain+// blob and surfaces aiAPIKeyMissing for the caller to prompt re-login.+// 3. A 200 response without `refresh_token` keeps the previously-stored one+// (server may rotate, may not — we mustn't drop it).+//+// We do not exercise the interactive `signIn(...)` path here — that opens+// NSWorkspace + the loopback server, which is end-to-end manual territory.++import XCTest+@testable import Gridex++final class ChatGPTOAuthServiceTests: XCTestCase {++ override func setUp() {+ super.setUp()+ MockURLProtocol.reset()+ }++ override func tearDown() {+ MockURLProtocol.reset()+ super.tearDown()+ }++ // MARK: - 1. Concurrent refresh de-duplication++ func test_concurrentTokenBundle_coalescesToSingleRefresh() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeExpiredBundle()++ // Server takes 200ms to respond, giving every concurrent caller a+ // chance to race into refreshInFlight before the first task finishes.+ MockURLProtocol.responseDelay = 0.2+ MockURLProtocol.responder = { _ in+ let body = Self.tokenJSON(+ accessToken: Self.freshAccessJWT(),+ refreshToken: "rotated-refresh",+ idToken: Self.idJWTFixture()+ )+ return (Self.okResponse(), body)+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )++ // Fan out 5 concurrent calls. All 5 must succeed; the server must+ // see exactly 1 hit (the actor coalesces the rest onto the same Task).+ try await withThrowingTaskGroup(of: ChatGPTTokenBundle.self) { group in+ for _ in 0..<5 {+ group.addTask { try await service.tokenBundle(providerId: providerId) }+ }+ var results: [ChatGPTTokenBundle] = []+ for try await b in group { results.append(b) }+ XCTAssertEqual(results.count, 5)+ for b in results {+ XCTAssertEqual(b.refreshToken, "rotated-refresh", "all callers see the rotated token")+ }+ }++ XCTAssertEqual(MockURLProtocol.requestCount, 1,+ "5 concurrent calls must collapse into a single refresh request")+ }++ // MARK: - 2. Refresh-token-expired path++ func test_refreshTokenExpired_clearsKeychainAndThrowsAPIKeyMissing() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeExpiredBundle()++ MockURLProtocol.responder = { _ in+ let body = Data(#"{"error":"refresh_token_expired","error_description":"jwt is expired"}"#.utf8)+ return (Self.errorResponse(status: 400), body)+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )++ do {+ _ = try await service.tokenBundle(providerId: providerId)+ XCTFail("expected aiAPIKeyMissing to be thrown")+ } catch GridexError.aiAPIKeyMissing {+ // expected+ } catch {+ XCTFail("expected aiAPIKeyMissing, got \(error)")+ }++ XCTAssertNil(keychain.bundle, "expired refresh_token must purge the keychain blob")+ }++ // MARK: - 3. Optional refresh_token preservation++ func test_refreshSuccessWithoutRotation_keepsOldRefreshToken() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ let original = Self.makeExpiredBundle(refreshToken: "original-refresh")+ keychain.bundle = original++ MockURLProtocol.responder = { _ in+ // Server rotates access_token + id_token but omits refresh_token.+ let body = Self.tokenJSON(+ accessToken: Self.freshAccessJWT(),+ refreshToken: nil,+ idToken: Self.idJWTFixture()+ )+ return (Self.okResponse(), body)+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )++ let updated = try await service.tokenBundle(providerId: providerId)+ XCTAssertEqual(updated.refreshToken, "original-refresh",+ "missing refresh_token in response must keep the old one")+ XCTAssertNotEqual(updated.accessToken, original.accessToken,+ "access_token should still be rotated")+ }++ // MARK: - 4. Provider auth rejection cleanup++ func test_streamUnauthorized_clearsKeychainAndThrowsAPIKeyMissing() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeFreshBundle()++ MockURLProtocol.responder = { _ in+ let body = Data(#"{"error":{"message":"unauthorized"}}"#.utf8)+ return (Self.errorResponse(status: 401), body)+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )+ let provider = ChatGPTProvider(+ providerId: providerId,+ oauthService: service,+ urlSession: Self.mockedSession()+ )++ do {+ var iterator = provider.stream(+ messages: [LLMMessage(role: .user, content: "hi")],+ systemPrompt: "",+ model: "gpt-test",+ maxTokens: 1,+ temperature: 0+ ).makeAsyncIterator()+ _ = try await iterator.next()+ XCTFail("expected aiAPIKeyMissing")+ } catch GridexError.aiAPIKeyMissing {+ // expected+ } catch {+ XCTFail("expected aiAPIKeyMissing, got \(error)")+ }++ XCTAssertNil(keychain.bundle, "401 from /responses must clear the stale bundle")+ }++ func test_availableModelsForbidden_clearsKeychainAndThrowsAPIKeyMissing() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeFreshBundle()++ MockURLProtocol.responder = { _ in+ let body = Data(#"{"error":{"message":"forbidden"}}"#.utf8)+ return (Self.errorResponse(status: 403), body)+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )+ let provider = ChatGPTProvider(+ providerId: providerId,+ oauthService: service,+ urlSession: Self.mockedSession()+ )++ do {+ _ = try await provider.availableModels()+ XCTFail("expected aiAPIKeyMissing")+ } catch GridexError.aiAPIKeyMissing {+ // expected+ } catch {+ XCTFail("expected aiAPIKeyMissing, got \(error)")+ }++ XCTAssertNil(keychain.bundle, "403 from /models must clear the stale bundle")+ }++ // MARK: - 5. tokenBundle short-circuit + missing keychain++ /// A non-expired access_token must NOT trigger a refresh round-trip — every+ /// production request hits this path. Regression here means we'd hammer+ /// auth.openai.com on every call and risk being rate-limited.+ func test_tokenBundle_freshToken_skipsNetworkRefresh() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeFreshBundle(refreshToken: "kept-refresh")++ MockURLProtocol.responder = { _ in+ XCTFail("fresh token must not hit auth.openai.com")+ return (Self.errorResponse(status: 500), Data())+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )++ let bundle = try await service.tokenBundle(providerId: providerId)+ XCTAssertEqual(bundle.refreshToken, "kept-refresh")+ XCTAssertEqual(MockURLProtocol.requestCount, 0,+ "non-expired token must not trigger refresh")+ }++ /// When the user added a ChatGPT provider row but never completed sign-in,+ /// `tokenBundle()` must surface `aiAPIKeyMissing` so the UI can prompt for+ /// re-login. DependencyContainer.bootstrap relies on this contract.+ func test_tokenBundle_missingKeychain_throwsAPIKeyMissing() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )++ do {+ _ = try await service.tokenBundle(providerId: providerId)+ XCTFail("expected aiAPIKeyMissing")+ } catch GridexError.aiAPIKeyMissing {+ // expected+ } catch {+ XCTFail("expected aiAPIKeyMissing, got \(error)")+ }++ XCTAssertEqual(MockURLProtocol.requestCount, 0,+ "must not call auth.openai.com when no bundle exists")+ }++ // MARK: - 6. ChatGPTProvider SSE streaming++ /// Locks the SSE happy path — accumulating deltas and finishing on+ /// `response.completed`. This is ChatGPTProvider's core contract; without+ /// this test a regression in `parseSSE` would silently drop tokens or+ /// hang forever, and only end-to-end testing would catch it.+ func test_streamHappyPath_yieldsDeltasAndFinishes() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeFreshBundle()++ // SSE wire format: `event: …\ndata: …` followed by a blank line that+ // terminates the event. The two trailing blank lines below are+ // load-bearing — the second one terminates `response.completed`.+ let sse = """+ event: response.output_text.delta+ data: {"delta":"Hello"}++ event: response.output_text.delta+ data: {"delta":", "}++ event: response.output_text.delta+ data: {"delta":"world"}++ event: response.completed+ data: {}+++ """++ MockURLProtocol.responder = { _ in+ (Self.sseResponse(), Data(sse.utf8))+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )+ let provider = ChatGPTProvider(+ providerId: providerId,+ oauthService: service,+ urlSession: Self.mockedSession()+ )++ var collected = ""+ for try await chunk in provider.stream(+ messages: [LLMMessage(role: .user, content: "hi")],+ systemPrompt: "",+ model: "gpt-test",+ maxTokens: 1,+ temperature: 0+ ) {+ collected += chunk+ }+ XCTAssertEqual(collected, "Hello, world",+ "deltas must concatenate in arrival order")+ }++ /// `response.error` events must surface as `aiStreamingError` with the+ /// server's message. The chat UI depends on this to render rate-limit /+ /// content-policy failures inline rather than as a generic crash.+ func test_streamErrorEvent_throwsStreamingError() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeFreshBundle()++ // Trailing blank line terminates the `response.error` event.+ let sse = """+ event: response.error+ data: {"message":"rate limited"}+++ """++ MockURLProtocol.responder = { _ in+ (Self.sseResponse(), Data(sse.utf8))+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )+ let provider = ChatGPTProvider(+ providerId: providerId,+ oauthService: service,+ urlSession: Self.mockedSession()+ )++ do {+ for try await _ in provider.stream(+ messages: [LLMMessage(role: .user, content: "hi")],+ systemPrompt: "",+ model: "gpt-test",+ maxTokens: 1,+ temperature: 0+ ) {}+ XCTFail("expected aiStreamingError")+ } catch let GridexError.aiStreamingError(message) {+ XCTAssertEqual(message, "rate limited",+ "server's error message must propagate to caller")+ } catch {+ XCTFail("expected aiStreamingError, got \(error)")+ }+ }++ // MARK: - 7. availableModels filtering++ /// Locks the list-filter contract — `supported_in_api == false` and+ /// `visibility != "list"` rows must be dropped. Server returns hidden /+ /// deprecated entries; without this filter the UI's model picker would+ /// surface unusable slugs that 400 on /responses.+ func test_availableModels_filtersHiddenAndUnsupported() async throws {+ let providerId = UUID()+ let keychain = MockKeychain()+ keychain.bundle = Self.makeFreshBundle()++ let body: [String: Any] = [+ "models": [+ ["slug": "gpt-5", "name": "GPT-5",+ "supported_in_api": true, "visibility": "list",+ "context_window": 200_000],+ ["slug": "gpt-internal", "name": "Internal",+ "supported_in_api": true, "visibility": "hidden"],+ ["slug": "gpt-deprecated", "name": "Old",+ "supported_in_api": false, "visibility": "list"],+ ["slug": "gpt-mini", "name": "GPT-mini",+ "supported_in_api": true, "visibility": "list"],+ ],+ ]+ let data = try JSONSerialization.data(withJSONObject: body)++ MockURLProtocol.responder = { _ in+ (Self.modelsResponse(), data)+ }++ let service = ChatGPTOAuthService(+ keychainService: keychain,+ urlSession: Self.mockedSession()+ )+ let provider = ChatGPTProvider(+ providerId: providerId,+ oauthService: service,+ urlSession: Self.mockedSession()+ )++ let models = try await provider.availableModels()+ XCTAssertEqual(Set(models.map(\.id)), Set(["gpt-5", "gpt-mini"]),+ "only supported + visible='list' models survive")+ XCTAssertEqual(models.first(where: { $0.id == "gpt-5" })?.contextWindow,+ 200_000,+ "context_window from response must propagate")+ }++ // MARK: - 8. Loopback callback ordering++ func test_loopbackCallbackBeforeAwait_isBuffered() async throws {+ let server = ChatGPTOAuthLoopbackServer()+ let port = try await server.start(preferredPorts: [])+ defer { server.stop() }++ let url = URL(string: "http://127.0.0.1:\(port)\(ChatGPTOAuthConstants.callbackPath)?code=early-code&state=early-state")!+ _ = try await URLSession.shared.data(from: url)++ let callback = try await server.awaitCallback(timeout: 1)+ XCTAssertEqual(callback.code, "early-code")+ XCTAssertEqual(callback.state, "early-state")+ }++ // MARK: - Fixtures++ /// In-memory `ChatGPTTokenBundle` JWT fixtures encode the same exp claim+ /// the service inspects via JWTDecoder. Header is `{"alg":"none"}`.+ private static func makeJWT(payload: String) -> String {+ let header = #"{"alg":"none","typ":"JWT"}"#+ let h = PKCE.base64URL(Data(header.utf8))+ let p = PKCE.base64URL(Data(payload.utf8))+ return "\(h).\(p)."+ }++ /// access_token whose exp is 60s in the past — guaranteed to trigger refresh.+ private static func expiredAccessJWT() -> String {+ let exp = Int(Date().addingTimeInterval(-60).timeIntervalSince1970)+ return makeJWT(payload: #"{"exp":\#(exp),"sub":"u"}"#)+ }++ /// access_token with exp 1 hour in the future. Keeps tests deterministic.+ private static func freshAccessJWT() -> String {+ let exp = Int(Date().addingTimeInterval(3600).timeIntervalSince1970)+ return makeJWT(payload: #"{"exp":\#(exp),"sub":"u"}"#)+ }++ private static func idJWTFixture() -> String {+ makeJWT(payload: #"{"email":"[email protected]","chatgpt_account_id":"acc","chatgpt_plan_type":"plus"}"#)+ }++ private static func makeExpiredBundle(refreshToken: String = "old-refresh") -> ChatGPTTokenBundle {+ ChatGPTTokenBundle(+ accessToken: expiredAccessJWT(),+ refreshToken: refreshToken,+ idToken: idJWTFixture(),+ accountId: "acc",+ email: "[email protected]",+ planType: "plus",+ obtainedAt: Date(timeIntervalSince1970: 1_700_000_000)+ )+ }++ private static func makeFreshBundle(refreshToken: String = "old-refresh") -> ChatGPTTokenBundle {+ ChatGPTTokenBundle(+ accessToken: freshAccessJWT(),+ refreshToken: refreshToken,+ idToken: idJWTFixture(),+ accountId: "acc",+ email: "[email protected]",+ planType: "plus",+ obtainedAt: Date(timeIntervalSince1970: 1_700_000_000)+ )+ }++ private static func tokenJSON(accessToken: String, refreshToken: String?, idToken: String) -> Data {+ var dict: [String: Any] = ["access_token": accessToken, "id_token": idToken]+ if let refreshToken { dict["refresh_token"] = refreshToken }+ return try! JSONSerialization.data(withJSONObject: dict)+ }++ private static func okResponse() -> HTTPURLResponse {+ HTTPURLResponse(+ url: URL(string: "https://auth.openai.com/oauth/token")!,+ statusCode: 200,+ httpVersion: "HTTP/1.1",+ headerFields: ["Content-Type": "application/json"]+ )!+ }++ private static func errorResponse(status: Int) -> HTTPURLResponse {+ HTTPURLResponse(+ url: URL(string: "https://auth.openai.com/oauth/token")!,+ statusCode: status,+ httpVersion: "HTTP/1.1",+ headerFields: ["Content-Type": "application/json"]+ )!+ }++ private static func sseResponse() -> HTTPURLResponse {+ HTTPURLResponse(+ url: URL(string: "https://chatgpt.com/backend-api/codex/responses")!,+ statusCode: 200,+ httpVersion: "HTTP/1.1",+ headerFields: ["Content-Type": "text/event-stream"]+ )!+ }++ private static func modelsResponse() -> HTTPURLResponse {+ HTTPURLResponse(+ url: URL(string: "https://chatgpt.com/backend-api/codex/models")!,+ statusCode: 200,+ httpVersion: "HTTP/1.1",+ headerFields: ["Content-Type": "application/json"]+ )!+ }++ private static func mockedSession() -> URLSession {+ let cfg = URLSessionConfiguration.ephemeral+ cfg.protocolClasses = [MockURLProtocol.self]+ return URLSession(configuration: cfg)+ }+}++// MARK: - Mock keychain (in-memory, single-bundle)++private final class MockKeychain: KeychainServiceProtocol, @unchecked Sendable {+ private let lock = NSLock()+ private var _bundle: ChatGPTTokenBundle?++ var bundle: ChatGPTTokenBundle? {+ get { lock.lock(); defer { lock.unlock() }; return _bundle }+ set { lock.lock(); defer { lock.unlock() }; _bundle = newValue }+ }++ func save(key: String, value: String) throws { fatalError("unused in these tests") }+ func load(key: String) throws -> String? { fatalError("unused in these tests") }+ func delete(key: String) throws { fatalError("unused in these tests") }+ func update(key: String, value: String) throws { fatalError("unused in these tests") }++ func saveChatGPTTokens(providerId: UUID, bundle: ChatGPTTokenBundle) throws {+ self.bundle = bundle+ }++ func loadChatGPTTokens(providerId: UUID) throws -> ChatGPTTokenBundle? {+ self.bundle+ }++ func deleteChatGPTTokens(providerId: UUID) throws {+ self.bundle = nil+ }+}++// MARK: - Mock URLProtocol++/// URLSession passes every request through this protocol when attached to the+/// session config. We track call count + emit canned responses so the service+/// thinks it's talking to auth.openai.com.+private final class MockURLProtocol: URLProtocol, @unchecked Sendable {+ nonisolated(unsafe) static var requestCount: Int = 0+ nonisolated(unsafe) static var responseDelay: TimeInterval = 0+ nonisolated(unsafe) static var responder: ((URLRequest) -> (HTTPURLResponse, Data))?+ private static let lock = NSLock()++ static func reset() {+ lock.lock(); defer { lock.unlock() }+ requestCount = 0+ responseDelay = 0+ responder = nil+ }++ override class func canInit(with request: URLRequest) -> Bool { true }+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }++ override func startLoading() {+ Self.lock.lock()+ Self.requestCount += 1+ let responder = Self.responder+ let delay = Self.responseDelay+ Self.lock.unlock()++ let work: @Sendable () -> Void = { [weak self] in+ guard let self else { return }+ guard let responder else {+ let err = NSError(domain: "MockURLProtocolNoResponder", code: -1)+ self.client?.urlProtocol(self, didFailWithError: err)+ return+ }+ let (response, data) = responder(self.request)+ self.client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ self.client?.urlProtocol(self, didLoad: data)+ self.client?.urlProtocolDidFinishLoading(self)+ }++ if delay > 0 {+ DispatchQueue.global().asyncAfter(deadline: .now() + delay, execute: work)+ } else {+ DispatchQueue.global().async(execute: work)+ }+ }++ override func stopLoading() {}+}