Skip to content

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(macos): add Check for Updates button + fix AI provider label

Tobib43a318b6bcc
diff --git a/.github/workflows/mac-release.yml b/.github/workflows/mac-release.yml
index 7aeced9..1b4e6ba 100644
--- a/.github/workflows/mac-release.yml
+++ b/.github/workflows/mac-release.yml
@@ -1,151 +1,151 @@
-# macOS Release pipeline for Gridex
-# ---------------------------------------------------------------------
-# Triggers on push to main branch or manually via workflow_dispatch.
-# Produces a notarized universal DMG (arm64 + x86_64) uploaded to
-# Cloudflare R2 and a Sparkle appcast.xml updated at the same prefix.
-#
-# Required GitHub Secrets:
-# MACOS_CERT_P12_BASE64 Developer ID Application cert (.p12, base64-encoded)
-# MACOS_CERT_PASSWORD Password for the .p12 archive
-# SIGN_IDENTITY Cert common name or SHA-1 fingerprint
-# NOTARY_APPLE_ID Apple ID used for notarization
-# NOTARY_PASSWORD App-specific password for that Apple ID
-# NOTARY_TEAM_ID Apple Developer Team ID
-# CLOUDFLARE_API_TOKEN R2 write-capable Cloudflare API token
-# CLOUDFLARE_ACCOUNT_ID Cloudflare account ID
-# ---------------------------------------------------------------------
-
-name: macOS Release
-
-on:
- push:
- branches:
- - main
- workflow_dispatch:
- inputs:
- version:
- description: "Version to release (e.g. 0.1.0). Only used for manual runs."
- required: false
- default: "0.0.0-manual"
-
-permissions:
- contents: write # needed to attach artifacts to GitHub Releases
-
-jobs:
- release:
- runs-on: macos-14 # Apple Silicon — arm64 native, x86_64 cross-compiled
- timeout-minutes: 90
-
- steps:
- - name: Checkout
- uses: actions/checkout@v4
- with:
- fetch-depth: 0
-
- - name: Select Xcode 16
- run: |
- XCODE=$(ls /Applications | grep "^Xcode_16" | sort -V | tail -1)
- sudo xcode-select -s "/Applications/$XCODE/Contents/Developer"
- swift --version
-
- - name: Read version from Info.plist
- id: ver
- run: |
- if [[ "${{ github.event_name }}" == "workflow_dispatch" && "${{ github.event.inputs.version }}" != "0.0.0-manual" ]]; then
- VERSION="${{ github.event.inputs.version }}"
- else
- VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" macos/Resources/Info.plist)
- fi
- TAG="v${VERSION}"
- echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- echo "tag=$TAG" >> "$GITHUB_OUTPUT"
- echo "Version: $VERSION / Tag: $TAG"
-
- - name: Bump version in Info.plist (workflow_dispatch override)
- if: github.event_name == 'workflow_dispatch'
- run: |
- VERSION="${{ steps.ver.outputs.version }}"
- IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION"
- BUILD=$(( MAJOR * 10000 + MINOR * 100 + PATCH ))
- /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $VERSION" \
- macos/Resources/Info.plist
- /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD" \
- macos/Resources/Info.plist
- echo "Set version $VERSION (build $BUILD)"
-
- - name: Import Developer ID certificate
- env:
- CERT_P12_BASE64: ${{ secrets.MACOS_CERT_P12_BASE64 }}
- CERT_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }}
- run: |
- KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain"
- KEYCHAIN_PASS="ci-$(uuidgen)"
-
- echo "$CERT_P12_BASE64" | base64 --decode > "$RUNNER_TEMP/cert.p12"
-
- security create-keychain -p "$KEYCHAIN_PASS" "$KEYCHAIN_PATH"
- security set-keychain-settings -t 3600 -u "$KEYCHAIN_PATH"
- security unlock-keychain -p "$KEYCHAIN_PASS" "$KEYCHAIN_PATH"
-
- security import "$RUNNER_TEMP/cert.p12" \
- -k "$KEYCHAIN_PATH" \
- -P "$CERT_PASSWORD" \
- -T /usr/bin/codesign
-
- # Allow codesign to access the key without a password prompt
- security set-key-partition-list \
- -S apple-tool:,apple:,codesign: \
- -s -k "$KEYCHAIN_PASS" "$KEYCHAIN_PATH"
-
- # Add to search list so codesign can find the cert
- security list-keychains -d user -s "$KEYCHAIN_PATH" login.keychain
-
- rm "$RUNNER_TEMP/cert.p12"
-
- - name: Store notarytool credentials
- env:
- NOTARY_APPLE_ID: ${{ secrets.NOTARY_APPLE_ID }}
- NOTARY_PASSWORD: ${{ secrets.NOTARY_PASSWORD }}
- NOTARY_TEAM_ID: ${{ secrets.NOTARY_TEAM_ID }}
- run: |
- xcrun notarytool store-credentials gridex-notarize \
- --apple-id "$NOTARY_APPLE_ID" \
- --password "$NOTARY_PASSWORD" \
- --team-id "$NOTARY_TEAM_ID"
-
- - name: Build universal release (arm64 + x86_64)
- env:
- SIGN_IDENTITY: ${{ secrets.SIGN_IDENTITY }}
- NOTARY_PROFILE: gridex-notarize
- run: ./scripts/release-all.sh
-
- - name: Import Sparkle EdDSA private key
- env:
- SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
- run: |
- security add-generic-password \
- -s "https://sparkle-project.org" \
- -a "ed25519" \
- -p "$SPARKLE_PRIVATE_KEY" \
- -U
-
- - name: Install Wrangler CLI
- run: npm install -g wrangler
-
- - name: Publish DMG + appcast to Cloudflare R2
- env:
- CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
- run: ./scripts/publish.sh
-
- - name: Attach DMG to GitHub Release
- env:
- GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- run: |
- TAG="${{ steps.ver.outputs.tag }}"
- DMG=$(ls dist/Gridex-*.dmg | head -1)
- gh release create "$TAG" "$DMG" \
- --title "Gridex $TAG" \
- --notes "Gridex $TAG — universal macOS build (Apple Silicon + Intel)" \
- --latest 2>/dev/null || \
- gh release upload "$TAG" "$DMG" --clobber
+# # macOS Release pipeline for Gridex
+# # ---------------------------------------------------------------------
+# # Triggers on push to main branch or manually via workflow_dispatch.
+# # Produces a notarized universal DMG (arm64 + x86_64) uploaded to
+# # Cloudflare R2 and a Sparkle appcast.xml updated at the same prefix.
+# #
+# # Required GitHub Secrets:
+# # MACOS_CERT_P12_BASE64 Developer ID Application cert (.p12, base64-encoded)
+# # MACOS_CERT_PASSWORD Password for the .p12 archive
+# # SIGN_IDENTITY Cert common name or SHA-1 fingerprint
+# # NOTARY_APPLE_ID Apple ID used for notarization
+# # NOTARY_PASSWORD App-specific password for that Apple ID
+# # NOTARY_TEAM_ID Apple Developer Team ID
+# # CLOUDFLARE_API_TOKEN R2 write-capable Cloudflare API token
+# # CLOUDFLARE_ACCOUNT_ID Cloudflare account ID
+# # ---------------------------------------------------------------------
+
+# name: macOS Release
+
+# on:
+# push:
+# branches:
+# - main
+# workflow_dispatch:
+# inputs:
+# version:
+# description: "Version to release (e.g. 0.1.0). Only used for manual runs."
+# required: false
+# default: "0.0.0-manual"
+
+# permissions:
+# contents: write # needed to attach artifacts to GitHub Releases
+
+# jobs:
+# release:
+# runs-on: macos-14 # Apple Silicon — arm64 native, x86_64 cross-compiled
+# timeout-minutes: 90
+
+# steps:
+# - name: Checkout
+# uses: actions/checkout@v4
+# with:
+# fetch-depth: 0
+
+# - name: Select Xcode 16
+# run: |
+# XCODE=$(ls /Applications | grep "^Xcode_16" | sort -V | tail -1)
+# sudo xcode-select -s "/Applications/$XCODE/Contents/Developer"
+# swift --version
+
+# - name: Read version from Info.plist
+# id: ver
+# run: |
+# if [[ "${{ github.event_name }}" == "workflow_dispatch" && "${{ github.event.inputs.version }}" != "0.0.0-manual" ]]; then
+# VERSION="${{ github.event.inputs.version }}"
+# else
+# VERSION=$(/usr/libexec/PlistBuddy -c "Print :CFBundleShortVersionString" macos/Resources/Info.plist)
+# fi
+# TAG="v${VERSION}"
+# echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+# echo "tag=$TAG" >> "$GITHUB_OUTPUT"
+# echo "Version: $VERSION / Tag: $TAG"
+
+# - name: Bump version in Info.plist (workflow_dispatch override)
+# if: github.event_name == 'workflow_dispatch'
+# run: |
+# VERSION="${{ steps.ver.outputs.version }}"
+# IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION"
+# BUILD=$(( MAJOR * 10000 + MINOR * 100 + PATCH ))
+# /usr/libexec/PlistBuddy -c "Set :CFBundleShortVersionString $VERSION" \
+# macos/Resources/Info.plist
+# /usr/libexec/PlistBuddy -c "Set :CFBundleVersion $BUILD" \
+# macos/Resources/Info.plist
+# echo "Set version $VERSION (build $BUILD)"
+
+# - name: Import Developer ID certificate
+# env:
+# CERT_P12_BASE64: ${{ secrets.MACOS_CERT_P12_BASE64 }}
+# CERT_PASSWORD: ${{ secrets.MACOS_CERT_PASSWORD }}
+# run: |
+# KEYCHAIN_PATH="$RUNNER_TEMP/build.keychain"
+# KEYCHAIN_PASS="ci-$(uuidgen)"
+
+# echo "$CERT_P12_BASE64" | base64 --decode > "$RUNNER_TEMP/cert.p12"
+
+# security create-keychain -p "$KEYCHAIN_PASS" "$KEYCHAIN_PATH"
+# security set-keychain-settings -t 3600 -u "$KEYCHAIN_PATH"
+# security unlock-keychain -p "$KEYCHAIN_PASS" "$KEYCHAIN_PATH"
+
+# security import "$RUNNER_TEMP/cert.p12" \
+# -k "$KEYCHAIN_PATH" \
+# -P "$CERT_PASSWORD" \
+# -T /usr/bin/codesign
+
+# # Allow codesign to access the key without a password prompt
+# security set-key-partition-list \
+# -S apple-tool:,apple:,codesign: \
+# -s -k "$KEYCHAIN_PASS" "$KEYCHAIN_PATH"
+
+# # Add to search list so codesign can find the cert
+# security list-keychains -d user -s "$KEYCHAIN_PATH" login.keychain
+
+# rm "$RUNNER_TEMP/cert.p12"
+
+# - name: Store notarytool credentials
+# env:
+# NOTARY_APPLE_ID: ${{ secrets.NOTARY_APPLE_ID }}
+# NOTARY_PASSWORD: ${{ secrets.NOTARY_PASSWORD }}
+# NOTARY_TEAM_ID: ${{ secrets.NOTARY_TEAM_ID }}
+# run: |
+# xcrun notarytool store-credentials gridex-notarize \
+# --apple-id "$NOTARY_APPLE_ID" \
+# --password "$NOTARY_PASSWORD" \
+# --team-id "$NOTARY_TEAM_ID"
+
+# - name: Build universal release (arm64 + x86_64)
+# env:
+# SIGN_IDENTITY: ${{ secrets.SIGN_IDENTITY }}
+# NOTARY_PROFILE: gridex-notarize
+# run: ./scripts/release-all.sh
+
+# - name: Import Sparkle EdDSA private key
+# env:
+# SPARKLE_PRIVATE_KEY: ${{ secrets.SPARKLE_PRIVATE_KEY }}
+# run: |
+# security add-generic-password \
+# -s "https://sparkle-project.org" \
+# -a "ed25519" \
+# -p "$SPARKLE_PRIVATE_KEY" \
+# -U
+
+# - name: Install Wrangler CLI
+# run: npm install -g wrangler
+
+# - name: Publish DMG + appcast to Cloudflare R2
+# env:
+# CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+# CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+# run: ./scripts/publish.sh
+
+# - name: Attach DMG to GitHub Release
+# env:
+# GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+# run: |
+# TAG="${{ steps.ver.outputs.tag }}"
+# DMG=$(ls dist/Gridex-*.dmg | head -1)
+# gh release create "$TAG" "$DMG" \
+# --title "Gridex $TAG" \
+# --notes "Gridex $TAG — universal macOS build (Apple Silicon + Intel)" \
+# --latest 2>/dev/null || \
+# gh release upload "$TAG" "$DMG" --clobber
diff --git a/.gitignore b/.gitignore
index 652a75f..bb2584b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -105,4 +105,6 @@ windows/vendor/webview2/
# Generated version header — written by build-unpackaged.ps1 -Version
# from the CI tag, falls back to 0.0.0-dev locally via __has_include.
windows/Gridex/GridexVersion.generated.h
-dist
\ No newline at end of file
+dist
+.wangler
+.env.example
\ No newline at end of file
diff --git a/macos/App/DependencyInjection/DependencyContainer.swift b/macos/App/DependencyInjection/DependencyContainer.swift
index 11e2233..ab75b67 100644
--- a/macos/App/DependencyInjection/DependencyContainer.swift
+++ b/macos/App/DependencyInjection/DependencyContainer.swift
@@ -19,6 +19,7 @@ final class DependencyContainer {
let schema = Schema([
SavedConnectionEntity.self,
QueryHistoryEntity.self,
+ LLMProviderEntity.self,
])
let config = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
do {
@@ -38,6 +39,7 @@ final class DependencyContainer {
lazy var connectionRepository: any ConnectionRepository = SwiftDataConnectionRepository(modelContainer: modelContainer)
lazy var queryHistoryRepository: any QueryHistoryRepository = SwiftDataQueryHistoryRepository(modelContainer: modelContainer)
+ lazy var llmProviderRepository: any LLMProviderRepository = SwiftDataLLMProviderRepository(modelContainer: modelContainer)
// MARK: - Services
@@ -52,13 +54,23 @@ final class DependencyContainer {
// MARK: - AI
- func makeLLMService(provider: String, apiKey: String, baseURL: String? = nil) -> any LLMService {
- switch provider {
- case "anthropic": return AnthropicProvider(apiKey: apiKey)
- case "openai": return OpenAIProvider(apiKey: apiKey)
- case "ollama": return OllamaProvider()
- case "gemini": return GeminiProvider(apiKey: apiKey, baseURL: baseURL ?? "https://generativelanguage.googleapis.com/v1beta/openai")
- default: return AnthropicProvider(apiKey: apiKey)
+ lazy var providerRegistry = ProviderRegistry()
+
+ /// 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)
}
}
+
+ /// Build a one-off LLMService. Primary path for the single-active-provider UI;
+ /// multi-provider callers should go through `providerRegistry`.
+ func makeLLMService(provider: String, apiKey: String, baseURL: String? = nil) -> any LLMService {
+ let type = ProviderType(rawValue: provider) ?? .anthropic
+ return ProviderFactory.make(type: type, apiKey: apiKey, baseURL: baseURL)
+ }
}
diff --git a/macos/App/Lifecycle/AppDelegate.swift b/macos/App/Lifecycle/AppDelegate.swift
index 367ea88..c12c46e 100644
--- a/macos/App/Lifecycle/AppDelegate.swift
+++ b/macos/App/Lifecycle/AppDelegate.swift
@@ -20,6 +20,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
NSApplication.shared.setActivationPolicy(.regular)
NSApplication.shared.activate(ignoringOtherApps: true)
+ // Load persisted LLM provider configs into the in-memory registry so
+ // AIChatView / other callers can resolve them by name without waiting.
+ Task { await DependencyContainer.shared.bootstrapProviderRegistry() }
+
// Thin scrollbars app-wide; horizontal always visible
UserDefaults.standard.set("Always", forKey: "AppleShowScrollBars")
diff --git a/macos/Core/Enums/ProviderType.swift b/macos/Core/Enums/ProviderType.swift
new file mode 100644
index 0000000..e6a6ecf
--- /dev/null
+++ b/macos/Core/Enums/ProviderType.swift
@@ -0,0 +1,200 @@
+// ProviderType.swift
+// Gridex
+
+import Foundation
+
+/// Supported LLM providers. Most entries dispatch to `OpenAIProvider` with a
+/// preset `baseURL` — they all speak the OpenAI `/chat/completions` SSE shape.
+enum ProviderType: String, Codable, Sendable, CaseIterable, Identifiable {
+ // Native formats (own provider class)
+ case anthropic
+ case gemini
+ case ollama
+
+ // OpenAI-compatible family (all use OpenAIProvider)
+ case openAI = "openai"
+ case azureOpenAI = "azure-openai"
+ case groq
+ case deepseek
+ case mistral
+ case xAI = "xai"
+ case perplexity
+ case openRouter = "openrouter"
+ case together
+ case fireworks
+ case dashscope
+ case dashscopeCoding = "dashscope-coding"
+ case openAICompatible = "openai-compatible"
+
+ var id: String { rawValue }
+
+ // MARK: - Metadata
+
+ var displayName: String {
+ switch self {
+ case .anthropic: return "Anthropic (Claude)"
+ case .gemini: return "Google Gemini"
+ case .ollama: return "Ollama (Local)"
+ case .openAI: return "OpenAI"
+ case .azureOpenAI: return "Azure OpenAI"
+ case .groq: return "Groq"
+ case .deepseek: return "DeepSeek"
+ case .mistral: return "Mistral"
+ case .xAI: return "xAI (Grok)"
+ case .perplexity: return "Perplexity"
+ case .openRouter: return "OpenRouter"
+ case .together: return "Together AI"
+ case .fireworks: return "Fireworks AI"
+ case .dashscope: return "DashScope (Qwen)"
+ case .dashscopeCoding: return "DashScope Bailian (Coding)"
+ case .openAICompatible: return "OpenAI-Compatible (Custom)"
+ }
+ }
+
+ /// Group used in the type picker UI.
+ var family: Family {
+ switch self {
+ case .anthropic: return .anthropic
+ case .gemini: return .gemini
+ case .ollama: return .local
+ case .openAI, .azureOpenAI, .groq, .deepseek, .mistral, .xAI,
+ .perplexity, .openRouter, .together, .fireworks, .dashscope,
+ .dashscopeCoding, .openAICompatible:
+ return .openAICompat
+ }
+ }
+
+ enum Family: String, CaseIterable {
+ case anthropic = "Anthropic"
+ case gemini = "Google"
+ case openAICompat = "OpenAI-Compatible"
+ case local = "Local"
+ }
+
+ var defaultBaseURL: String {
+ switch self {
+ case .anthropic: return "https://api.anthropic.com/v1"
+ case .gemini: return "https://generativelanguage.googleapis.com/v1beta/openai"
+ case .ollama: return "http://localhost:11434"
+ 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"
+ case .deepseek: return "https://api.deepseek.com/v1"
+ case .mistral: return "https://api.mistral.ai/v1"
+ case .xAI: return "https://api.x.ai/v1"
+ case .perplexity: return "https://api.perplexity.ai"
+ case .openRouter: return "https://openrouter.ai/api/v1"
+ case .together: return "https://api.together.xyz/v1"
+ case .fireworks: return "https://api.fireworks.ai/inference/v1"
+ case .dashscope: return "https://dashscope.aliyuncs.com/compatible-mode/v1"
+ case .dashscopeCoding: return "https://coding-intl.dashscope.aliyuncs.com/v1"
+ case .openAICompatible: return ""
+ }
+ }
+
+ var defaultModel: String {
+ switch self {
+ case .anthropic: return "claude-sonnet-4-6"
+ case .gemini: return "gemini-2.5-flash"
+ case .ollama: return "llama3"
+ case .openAI: return "gpt-4o"
+ case .azureOpenAI: return "gpt-4o"
+ case .groq: return "llama-3.3-70b-versatile"
+ case .deepseek: return "deepseek-chat"
+ case .mistral: return "mistral-large-latest"
+ case .xAI: return "grok-2-latest"
+ case .perplexity: return "llama-3.1-sonar-large-128k-online"
+ case .openRouter: return "anthropic/claude-sonnet-4"
+ case .together: return "meta-llama/Llama-3.3-70B-Instruct-Turbo"
+ case .fireworks: return "accounts/fireworks/models/llama-v3p3-70b-instruct"
+ case .dashscope: return "qwen-plus"
+ case .dashscopeCoding: return "qwen3-coder-plus"
+ case .openAICompatible: return ""
+ }
+ }
+
+ var requiresAPIKey: Bool {
+ self != .ollama
+ }
+
+ var allowsPrivateHosts: Bool {
+ self == .ollama || self == .openAICompatible
+ }
+
+ /// True when the provider has no live `/models` listing endpoint — the UI should
+ /// use the built-in catalog (`fallbackModelIDs`) directly instead of a network call.
+ /// Mirrors goclaw's hardcoded-catalog providers (DashScope, Bailian, MiniMax).
+ var hasHardcodedCatalog: Bool {
+ switch self {
+ case .dashscope, .dashscopeCoding: return true
+ default: return false
+ }
+ }
+
+ var iconName: String {
+ switch self {
+ case .anthropic: return "a.circle.fill"
+ case .gemini: return "g.circle.fill"
+ case .ollama: return "desktopcomputer"
+ case .openAI: return "bubble.left.and.text.bubble.right.fill"
+ case .azureOpenAI: return "cloud.fill"
+ case .groq: return "bolt.circle.fill"
+ case .deepseek: return "magnifyingglass.circle.fill"
+ case .mistral: return "wind"
+ case .xAI: return "x.circle.fill"
+ case .perplexity: return "questionmark.circle.fill"
+ case .openRouter: return "arrow.triangle.branch"
+ case .together: return "person.2.fill"
+ case .fireworks: return "sparkles"
+ case .dashscope: return "cpu.fill"
+ case .dashscopeCoding: return "chevron.left.forwardslash.chevron.right"
+ case .openAICompatible: return "slider.horizontal.3"
+ }
+ }
+
+ var fallbackModelIDs: [String] {
+ switch self {
+ 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"]
+ 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"]
+ case .deepseek: return ["deepseek-chat", "deepseek-reasoner"]
+ case .mistral: return ["mistral-large-latest", "mistral-small-latest", "codestral-latest"]
+ case .xAI: return ["grok-2-latest", "grok-2-vision-latest"]
+ case .perplexity: return ["llama-3.1-sonar-large-128k-online", "llama-3.1-sonar-small-128k-online"]
+ case .openRouter: return ["anthropic/claude-sonnet-4", "openai/gpt-4o", "meta-llama/llama-3.3-70b"]
+ case .together: return ["meta-llama/Llama-3.3-70B-Instruct-Turbo", "mistralai/Mixtral-8x7B-Instruct-v0.1"]
+ case .fireworks: return ["accounts/fireworks/models/llama-v3p3-70b-instruct"]
+ case .dashscope:
+ // DashScope doesn't expose /v1/models — catalog mirrors goclaw's dashScopeModels()
+ return [
+ "qwen3.6-plus",
+ "qwen3.5-plus",
+ "qwen3.5-flash",
+ "qwen3.5-turbo",
+ "qwen3-max",
+ "qwen3-plus",
+ "qwen3-turbo",
+ "wan2.6-image",
+ "wan2.1-image",
+ "wan2.6-video",
+ ]
+ case .dashscopeCoding:
+ // Bailian Coding catalog — mirrors goclaw's bailianModels()
+ return [
+ "qwen3.6-plus",
+ "qwen3.5-plus",
+ "kimi-k2.5",
+ "GLM-5",
+ "MiniMax-M2.5",
+ "qwen3-max-2026-01-23",
+ "qwen3-coder-next",
+ "qwen3-coder-plus",
+ "glm-4.7",
+ ]
+ case .openAICompatible: return []
+ }
+ }
+}
diff --git a/macos/Core/Models/AI/ProviderConfig.swift b/macos/Core/Models/AI/ProviderConfig.swift
new file mode 100644
index 0000000..6080db4
--- /dev/null
+++ b/macos/Core/Models/AI/ProviderConfig.swift
@@ -0,0 +1,42 @@
+// ProviderConfig.swift
+// Gridex
+//
+// Runtime-level configuration for an LLM provider instance.
+// Persisted form lives in LLMProviderEntity; this struct is the in-memory DTO
+// passed from repository → factory → provider.
+
+import Foundation
+
+struct ProviderConfig: Sendable, Identifiable, Equatable {
+ let id: UUID
+ var name: String // user-defined slug, e.g. "my-claude"
+ var type: ProviderType
+ var apiBase: String? // nil → type.defaultBaseURL
+ var model: String // default model for this instance
+ var enabled: Bool
+ var createdAt: Date
+
+ init(
+ id: UUID = UUID(),
+ name: String,
+ type: ProviderType,
+ apiBase: String? = nil,
+ model: String? = nil,
+ enabled: Bool = true,
+ createdAt: Date = Date()
+ ) {
+ self.id = id
+ self.name = name
+ self.type = type
+ self.apiBase = apiBase
+ self.model = model ?? type.defaultModel
+ self.enabled = enabled
+ self.createdAt = createdAt
+ }
+
+ /// Resolved base URL — falls back to the type default when apiBase is nil/empty.
+ var resolvedBaseURL: String {
+ if let apiBase, !apiBase.isEmpty { return apiBase }
+ return type.defaultBaseURL
+ }
+}
diff --git a/macos/Core/Types/LLMRetry.swift b/macos/Core/Types/LLMRetry.swift
new file mode 100644
index 0000000..7df81e6
--- /dev/null
+++ b/macos/Core/Types/LLMRetry.swift
@@ -0,0 +1,87 @@
+// LLMRetry.swift
+// Gridex
+//
+// Exponential-backoff retry for provider HTTP calls.
+// Mirrors goclaw's internal/providers/retry.go — retries on 429, 5xx, and transient
+// network errors, with jittered delay. Streaming requests are NOT retried once
+// the first byte has been read (caller's responsibility to short-circuit).
+
+import Foundation
+
+struct LLMRetryPolicy: Sendable {
+ var maxAttempts: Int
+ var baseDelay: TimeInterval
+ var maxDelay: TimeInterval
+
+ static let `default` = LLMRetryPolicy(maxAttempts: 3, baseDelay: 0.5, maxDelay: 8.0)
+ static let none = LLMRetryPolicy(maxAttempts: 1, baseDelay: 0, maxDelay: 0)
+}
+
+enum LLMRetry {
+ /// Perform a non-streaming HTTP request with retry on transient failures.
+ /// Returns the (data, HTTPURLResponse) pair on success; throws on exhaustion.
+ static func perform(
+ _ request: URLRequest,
+ session: URLSession = .shared,
+ policy: LLMRetryPolicy = .default
+ ) async throws -> (Data, HTTPURLResponse) {
+ var attempt = 0
+ var lastError: Error?
+
+ while attempt < policy.maxAttempts {
+ attempt += 1
+ do {
+ let (data, response) = try await session.data(for: request)
+ guard let http = response as? HTTPURLResponse else {
+ throw GridexError.aiProviderError("Non-HTTP response")
+ }
+
+ if shouldRetry(status: http.statusCode), attempt < policy.maxAttempts {
+ try await sleep(for: delay(attempt: attempt, policy: policy))
+ continue
+ }
+ return (data, http)
+ } catch {
+ lastError = error
+ if isTransient(error), attempt < policy.maxAttempts {
+ try await sleep(for: delay(attempt: attempt, policy: policy))
+ continue
+ }
+ throw error
+ }
+ }
+ throw lastError ?? GridexError.aiProviderError("Retry exhausted")
+ }
+
+ // MARK: - Helpers
+
+ private static func shouldRetry(status: Int) -> Bool {
+ status == 408 || status == 425 || status == 429 || (500...599).contains(status)
+ }
+
+ private static func isTransient(_ error: Error) -> Bool {
+ let ns = error as NSError
+ guard ns.domain == NSURLErrorDomain else { return false }
+ switch ns.code {
+ case NSURLErrorTimedOut,
+ NSURLErrorCannotConnectToHost,
+ NSURLErrorNetworkConnectionLost,
+ NSURLErrorNotConnectedToInternet,
+ NSURLErrorDNSLookupFailed:
+ return true
+ default:
+ return false
+ }
+ }
+
+ private static func delay(attempt: Int, policy: LLMRetryPolicy) -> TimeInterval {
+ let exp = policy.baseDelay * pow(2.0, Double(attempt - 1))
+ let capped = min(exp, policy.maxDelay)
+ let jitter = Double.random(in: 0...(capped * 0.25))
+ return capped + jitter
+ }
+
+ private static func sleep(for seconds: TimeInterval) async throws {
+ try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))
+ }
+}
diff --git a/macos/Core/Types/ProviderURLValidator.swift b/macos/Core/Types/ProviderURLValidator.swift
new file mode 100644
index 0000000..7c3df4b
--- /dev/null
+++ b/macos/Core/Types/ProviderURLValidator.swift
@@ -0,0 +1,84 @@
+// ProviderURLValidator.swift
+// Gridex
+//
+// SSRF-conscious URL validation for provider apiBase entries.
+// Mirrors goclaw internal/http/providers.go host validation: require http(s),
+// reject raw IP + loopback + link-local unless the provider type legitimately
+// targets local hosts (Ollama).
+
+import Foundation
+
+enum ProviderURLValidationError: LocalizedError {
+ case emptyURL
+ case invalidURL
+ case unsupportedScheme(String)
+ case privateHostNotAllowed(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .emptyURL: return "URL is empty"
+ case .invalidURL: return "URL is not valid"
+ case .unsupportedScheme(let s): return "Scheme '\(s)' is not supported — use http or https"
+ case .privateHostNotAllowed(let h): return "Host '\(h)' is not allowed for this provider"
+ }
+ }
+}
+
+enum ProviderURLValidator {
+ /// Validate `raw` for a provider of `type`. Returns the normalised URL string.
+ /// - Loopback/private hosts are allowed only when `type.allowsPrivateHosts` is true.
+ static func validate(_ raw: String, for type: ProviderType) throws -> String {
+ let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !trimmed.isEmpty else { throw ProviderURLValidationError.emptyURL }
+ guard let url = URL(string: trimmed),
+ let scheme = url.scheme?.lowercased(),
+ let host = url.host, !host.isEmpty else {
+ throw ProviderURLValidationError.invalidURL
+ }
+ guard scheme == "http" || scheme == "https" else {
+ throw ProviderURLValidationError.unsupportedScheme(scheme)
+ }
+ if !type.allowsPrivateHosts, isPrivateHost(host) {
+ throw ProviderURLValidationError.privateHostNotAllowed(host)
+ }
+ // Strip any trailing slash.
+ return trimmed.hasSuffix("/") ? String(trimmed.dropLast()) : trimmed
+ }
+
+ // MARK: - Private
+
+ static func isPrivateHost(_ host: String) -> Bool {
+ let lower = host.lowercased()
+ if lower == "localhost" || lower == "0.0.0.0" { return true }
+ if lower.hasSuffix(".local") || lower.hasSuffix(".internal") { return true }
+
+ // IPv4 literal?
+ let parts = lower.split(separator: ".")
+ if parts.count == 4, let octets = try? parts.map({ (p: Substring) -> Int in
+ guard let n = Int(p), (0...255).contains(n) else { throw GridexError.internalError("bad octet") }
+ return n
+ }) {
+ return isPrivateIPv4(octets)
+ }
+
+ // IPv6 loopback / link-local
+ if lower == "::1" { return true }
+ if lower.hasPrefix("fe80:") || lower.hasPrefix("fc") || lower.hasPrefix("fd") { return true }
+ return false
+ }
+
+ private static func isPrivateIPv4(_ o: [Int]) -> Bool {
+ guard o.count == 4 else { return false }
+ // 10.0.0.0/8
+ if o[0] == 10 { return true }
+ // 172.16.0.0/12
+ if o[0] == 172, (16...31).contains(o[1]) { return true }
+ // 192.168.0.0/16
+ if o[0] == 192 && o[1] == 168 { return true }
+ // 127.0.0.0/8 loopback
+ if o[0] == 127 { return true }
+ // 169.254.0.0/16 link-local
+ if o[0] == 169 && o[1] == 254 { return true }
+ return false
+ }
+}
diff --git a/macos/Data/Persistence/Models/LLMProviderEntity.swift b/macos/Data/Persistence/Models/LLMProviderEntity.swift
new file mode 100644
index 0000000..43f79c3
--- /dev/null
+++ b/macos/Data/Persistence/Models/LLMProviderEntity.swift
@@ -0,0 +1,57 @@
+// LLMProviderEntity.swift
+// Gridex
+//
+// SwiftData model for persisted LLM provider configurations.
+// The API key is stored in the Keychain (key = "ai.apikey.<id>"), never in DB.
+
+import Foundation
+import SwiftData
+
+@Model
+final class LLMProviderEntity {
+ @Attribute(.unique) var id: UUID
+ var name: String
+ var typeRaw: String
+ var apiBase: String?
+ var model: String
+ var enabled: Bool
+ var createdAt: Date
+
+ init(
+ id: UUID = UUID(),
+ name: String,
+ typeRaw: String,
+ apiBase: String? = nil,
+ model: String,
+ enabled: Bool = true,
+ createdAt: Date = Date()
+ ) {
+ self.id = id
+ self.name = name
+ self.typeRaw = typeRaw
+ self.apiBase = apiBase
+ self.model = model
+ self.enabled = enabled
+ self.createdAt = createdAt
+ }
+
+ func toConfig() -> ProviderConfig {
+ ProviderConfig(
+ id: id,
+ name: name,
+ type: ProviderType(rawValue: typeRaw) ?? .anthropic,
+ apiBase: apiBase,
+ model: model,
+ enabled: enabled,
+ createdAt: createdAt
+ )
+ }
+
+ func apply(_ config: ProviderConfig) {
+ name = config.name
+ typeRaw = config.type.rawValue
+ apiBase = config.apiBase
+ model = config.model
+ enabled = config.enabled
+ }
+}
diff --git a/macos/Data/Persistence/Repositories/SwiftDataLLMProviderRepository.swift b/macos/Data/Persistence/Repositories/SwiftDataLLMProviderRepository.swift
new file mode 100644
index 0000000..dd64e0c
--- /dev/null
+++ b/macos/Data/Persistence/Repositories/SwiftDataLLMProviderRepository.swift
@@ -0,0 +1,73 @@
+// SwiftDataLLMProviderRepository.swift
+// Gridex
+
+import Foundation
+import SwiftData
+
+final class SwiftDataLLMProviderRepository: LLMProviderRepository, @unchecked Sendable {
+ private let modelContainer: ModelContainer
+
+ init(modelContainer: ModelContainer) {
+ self.modelContainer = modelContainer
+ }
+
+ @MainActor
+ func fetchAll() async throws -> [ProviderConfig] {
+ let context = modelContainer.mainContext
+ let descriptor = FetchDescriptor<LLMProviderEntity>(
+ sortBy: [SortDescriptor(\.createdAt)]
+ )
+ return try context.fetch(descriptor).map { $0.toConfig() }
+ }
+
+ @MainActor
+ func fetchByID(_ id: UUID) async throws -> ProviderConfig? {
+ let context = modelContainer.mainContext
+ var descriptor = FetchDescriptor<LLMProviderEntity>(
+ predicate: #Predicate { $0.id == id }
+ )
+ descriptor.fetchLimit = 1
+ return try context.fetch(descriptor).first?.toConfig()
+ }
+
+ @MainActor
+ func save(_ config: ProviderConfig) async throws {
+ let context = modelContainer.mainContext
+ let entity = LLMProviderEntity(
+ id: config.id,
+ name: config.name,
+ typeRaw: config.type.rawValue,
+ apiBase: config.apiBase,
+ model: config.model,
+ enabled: config.enabled,
+ createdAt: config.createdAt
+ )
+ context.insert(entity)
+ try context.save()
+ }
+
+ @MainActor
+ func update(_ config: ProviderConfig) async throws {
+ let context = modelContainer.mainContext
+ let id = config.id
+ var descriptor = FetchDescriptor<LLMProviderEntity>(
+ predicate: #Predicate { $0.id == id }
+ )
+ descriptor.fetchLimit = 1
+ guard let entity = try context.fetch(descriptor).first else { return }
+ entity.apply(config)
+ try context.save()
+ }
+
+ @MainActor
+ func delete(_ id: UUID) async throws {
+ let context = modelContainer.mainContext
+ let descriptor = FetchDescriptor<LLMProviderEntity>(
+ predicate: #Predicate { $0.id == id }
+ )
+ if let entity = try context.fetch(descriptor).first {
+ context.delete(entity)
+ try context.save()
+ }
+ }
+}
diff --git a/macos/Domain/Repositories/LLMProviderRepository.swift b/macos/Domain/Repositories/LLMProviderRepository.swift
new file mode 100644
index 0000000..a53e405
--- /dev/null
+++ b/macos/Domain/Repositories/LLMProviderRepository.swift
@@ -0,0 +1,12 @@
+// LLMProviderRepository.swift
+// Gridex
+
+import Foundation
+
+protocol LLMProviderRepository: Sendable {
+ func fetchAll() async throws -> [ProviderConfig]
+ func fetchByID(_ id: UUID) async throws -> ProviderConfig?
+ func save(_ config: ProviderConfig) async throws
+ func update(_ config: ProviderConfig) async throws
+ func delete(_ id: UUID) async throws
+}
diff --git a/macos/Presentation/Views/AIChat/AIChatView.swift b/macos/Presentation/Views/AIChat/AIChatView.swift
index 040a8d6..4d82474 100644
--- a/macos/Presentation/Views/AIChat/AIChatView.swift
+++ b/macos/Presentation/Views/AIChat/AIChatView.swift
@@ -24,6 +24,10 @@ final class ChatDisplayMessage: ObservableObject, Identifiable {
struct AIChatView: View {
@EnvironmentObject private var appState: AppState
+ @AppStorage("ai.activeProviderID") private var activeProviderID: String = ""
+ @AppStorage("ai.activeModel") private var activeModel: String = ""
+ // Legacy single-provider settings — kept for backward compat until user
+ // migrates to the multi-provider list in Settings → AI.
@AppStorage("ai.provider") private var providerType = "gemini"
@AppStorage("ai.provider.baseURL") private var baseURL = "https://generativelanguage.googleapis.com/v1beta/openai"
@AppStorage("ai.provider.enabled") private var isEnabled = true
@@ -34,6 +38,7 @@ struct AIChatView: View {
@State private var apiKeyLoaded = false
@State private var attachedTables: Set<String> = []
@State private var showTablePicker = false
+ @State private var providers: [ProviderConfig] = []
private var messages: [ChatDisplayMessage] {
get {
@@ -80,7 +85,11 @@ struct AIChatView: View {
} message: {
Text(errorMessage ?? "")
}
- .onAppear { refreshAPIKeyState() }
+ .onAppear {
+ refreshAPIKeyState()
+ Task { await loadProviders() }
+ }
+ .onChange(of: activeProviderID) { _, _ in refreshAPIKeyState() }
.onChange(of: providerType) { _, _ in refreshAPIKeyState() }
.onChange(of: isEnabled) { _, _ in refreshAPIKeyState() }
}
@@ -106,15 +115,7 @@ struct AIChatView: View {
VStack(alignment: .leading, spacing: 1) {
Text("AI Assistant")
.font(.system(size: 13, weight: .semibold))
- HStack(spacing: 4) {
- Circle()
- .fill(apiKeyLoaded ? Color.green : Color.orange)
- .frame(width: 6, height: 6)
- Text(apiKeyLoaded ? selectedModel : "Not configured")
- .font(.system(size: 10))
- .foregroundStyle(.secondary)
- .lineLimit(1)
- }
+ providerPicker
}
Spacer()
@@ -150,6 +151,93 @@ struct AIChatView: View {
}
}
+ // MARK: - Provider / model picker (inline switcher)
+
+ /// Status pill under "AI Assistant" — tapping opens a Menu to switch provider
+ /// and model without leaving the chat.
+ private var providerPicker: some View {
+ Menu {
+ if providers.isEmpty {
+ Text("No providers configured — open Settings → AI")
+ Divider()
+ SettingsLink { Text("Open Settings") }
+ } else {
+ ForEach(providers) { p in
+ Section(p.name) {
+ ForEach(modelOptions(for: p), id: \.self) { modelID in
+ Button(action: { select(provider: p, model: modelID) }) {
+ if p.id.uuidString == activeProviderID &&
+ (activeModel.isEmpty ? p.model : activeModel) == modelID {
+ Label(modelID, systemImage: "checkmark")
+ } else {
+ Label(modelID, systemImage: p.type.iconName)
+ }
+ }
+ }
+ }
+ }
+ Divider()
+ SettingsLink { Label("Manage providers…", systemImage: "gearshape") }
+ }
+ } label: {
+ HStack(spacing: 4) {
+ Circle()
+ .fill(apiKeyLoaded ? Color.green : Color.orange)
+ .frame(width: 6, height: 6)
+ Text(currentProviderLabel)
+ .font(.system(size: 10))
+ .foregroundStyle(.secondary)
+ .lineLimit(1)
+ Image(systemName: "chevron.down")
+ .font(.system(size: 7, weight: .semibold))
+ .foregroundStyle(.secondary)
+ }
+ }
+ .menuStyle(.borderlessButton)
+ .menuIndicator(.hidden)
+ .fixedSize()
+ }
+
+ private var currentProviderLabel: String {
+ if !activeProviderID.isEmpty {
+ if let p = providers.first(where: { $0.id.uuidString == activeProviderID }) {
+ let m = activeModel.isEmpty ? p.model : activeModel
+ return "\(p.name) · \(m)"
+ }
+ // Provider ID set but list not loaded yet
+ if providers.isEmpty {
+ return "Loading…"
+ }
+ // Provider ID doesn't match any — stale reference
+ return "Not configured"
+ }
+ // Legacy single-provider mode
+ return apiKeyLoaded ? selectedModel : "Not configured"
+ }
+
+ /// Models to show under a provider in the menu: fetched list union with the
+ /// configured default so the user-set model is always visible.
+ private func modelOptions(for p: ProviderConfig) -> [String] {
+ var ids = p.type.fallbackModelIDs
+ if !p.model.isEmpty, !ids.contains(p.model) {
+ ids.insert(p.model, at: 0)
+ }
+ return ids
+ }
+
+ private func select(provider: ProviderConfig, model: String) {
+ activeProviderID = provider.id.uuidString
+ activeModel = model
+ refreshAPIKeyState()
+ }
+
+ @MainActor
+ private func loadProviders() async {
+ if let list = try? await DependencyContainer.shared.llmProviderRepository.fetchAll() {
+ providers = list.filter(\.enabled)
+ }
+ }
+
private var setupPrompt: some View {
VStack(spacing: 16) {
Spacer()
@@ -512,11 +600,56 @@ struct AIChatView: View {
// MARK: - Logic
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
+ }
+ }
+ }
+ return
+ }
+ // Legacy path.
guard isEnabled else { apiKeyLoaded = false; return }
let key = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(providerType)")
apiKeyLoaded = key != nil && !key!.isEmpty
}
+ /// Resolve the LLMService + model to use for the next request.
+ /// Prefers the multi-provider registry; falls back to legacy @AppStorage.
+ /// If the user picked a different model from the header menu (stored in
+ /// `activeModel`), it overrides the config's default.
+ private func resolveLLMService() async -> (service: any LLMService, model: String)? {
+ if !activeProviderID.isEmpty, let uuid = UUID(uuidString: activeProviderID),
+ let config = try? await DependencyContainer.shared.llmProviderRepository.fetchByID(uuid),
+ config.enabled {
+ let apiKey = (try? DependencyContainer.shared.keychainService.load(
+ key: ProviderEditSheet.keychainKey(id: uuid)
+ )) ?? ""
+ if config.type.requiresAPIKey, apiKey.isEmpty { return nil }
+ let service = ProviderFactory.make(config: config, apiKey: apiKey)
+ let modelToUse = activeModel.isEmpty ? config.model : activeModel
+ return (service, modelToUse)
+ }
+ // Legacy
+ guard let apiKey = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(providerType)"),
+ !apiKey.isEmpty else { return nil }
+ let service = DependencyContainer.shared.makeLLMService(
+ provider: providerType,
+ apiKey: apiKey,
+ baseURL: baseURL
+ )
+ return (service, selectedModel)
+ }
+
private func sendMessage() {
let text = inputText.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty else { return }
@@ -530,18 +663,13 @@ struct AIChatView: View {
let currentAttached = attachedTables
Task {
- guard let apiKey = try? DependencyContainer.shared.keychainService.load(key: "ai.apikey.\(providerType)"),
- !apiKey.isEmpty else {
- errorMessage = "API key not configured"
+ guard let resolved = await resolveLLMService() else {
+ errorMessage = "No active AI provider configured. Open Settings → AI to add one."
isStreaming = false
return
}
-
- let service = DependencyContainer.shared.makeLLMService(
- provider: providerType,
- apiKey: apiKey,
- baseURL: baseURL
- )
+ let service = resolved.service
+ let modelID = resolved.model
// Build system prompt — general rules only
var systemPrompt = "You are a helpful database assistant. Answer concisely."
@@ -602,7 +730,7 @@ struct AIChatView: View {
let stream = service.stream(
messages: llmMessages,
systemPrompt: systemPrompt,
- model: selectedModel,
+ model: modelID,
maxTokens: AppConstants.AI.defaultMaxTokens,
temperature: AppConstants.AI.defaultTemperature
)
diff --git a/macos/Presentation/Views/Main/MainView.swift b/macos/Presentation/Views/Main/MainView.swift
index 161b430..49983a0 100644
--- a/macos/Presentation/Views/Main/MainView.swift
+++ b/macos/Presentation/Views/Main/MainView.swift
@@ -121,6 +121,7 @@ struct HomeView: View {
@State private var renameGroupName = ""
@State private var editingConnection: ConnectionConfig?
@State private var showConnectionError = false
+ @ObservedObject private var updater = UpdaterService.shared
var body: some View {
HStack(spacing: 0) {
@@ -228,6 +229,24 @@ struct HomeView: View {
Text("AI-Native Database IDE")
.font(.system(size: 12))
.foregroundStyle(.tertiary)
+
+ // Version + Check for Updates
+ HStack(spacing: 6) {
+ Text("v\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0")")
+ .font(.system(size: 10))
+ .foregroundStyle(.quaternary)
+
+ Button {
+ updater.checkForUpdates()
+ } label: {
+ Text("Check for Updates")
+ .font(.system(size: 10))
+ .foregroundStyle(.blue)
+ }
+ .buttonStyle(.plain)
+ .disabled(!updater.canCheckForUpdates)
+ }
+ .padding(.top, 2)
}
}
diff --git a/macos/Presentation/Windows/Settings/ProviderEditSheet.swift b/macos/Presentation/Windows/Settings/ProviderEditSheet.swift
new file mode 100644
index 0000000..961ebd2
--- /dev/null
+++ b/macos/Presentation/Windows/Settings/ProviderEditSheet.swift
@@ -0,0 +1,394 @@
+// ProviderEditSheet.swift
+// Gridex
+//
+// Add / edit form for a single LLM provider configuration.
+// API key lives in Keychain keyed by the config UUID (ai.apikey.<uuid>), never
+// in SwiftData.
+
+import SwiftUI
+
+struct ProviderEditSheet: View {
+ /// Existing config to edit, or nil for create.
+ let editing: ProviderConfig?
+ /// Called when the sheet saves successfully. Parent should reload list.
+ let onSaved: (ProviderConfig) -> Void
+
+ @Environment(\.dismiss) private var dismiss
+
+ private let keychain: KeychainServiceProtocol = DependencyContainer.shared.keychainService
+ private let repository: any LLMProviderRepository = DependencyContainer.shared.llmProviderRepository
+
+ @State private var name: String = ""
+ @State private var type: ProviderType = .anthropic
+ @State private var apiBase: String = ProviderType.anthropic.defaultBaseURL
+ @State private var apiKey: String = ""
+ @State private var model: String = ""
+ @State private var enabled: Bool = true
+
+ @State private var availableModels: [LLMModel] = []
+ @State private var isLoadingModels = false
+ @State private var fetchResult: FetchResult = .none
+ @State private var testResult: TestResult = .none
+ @State private var isTesting = false
+ @State private var urlError: String?
+ @State private var saveError: String?
+
+ enum FetchResult: Equatable {
+ case none
+ case loaded(Int)
+ case failure(String)
+ }
+
+ enum TestResult: Equatable {
+ case none
+ case success
+ case failure(String)
+ }
+
+ 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
+ }
+
+ var body: some View {
+ VStack(spacing: 0) {
+ header
+ Divider()
+ form
+ Divider()
+ footer
+ }
+ .frame(width: 560, height: 540)
+ .onAppear(perform: load)
+ }
+
+ // MARK: - Header
+
+ private var header: some View {
+ HStack {
+ Image(systemName: type.iconName)
+ .font(.system(size: 20))
+ .foregroundStyle(.tint)
+ Text(isEdit ? "Edit Provider" : "Add Provider")
+ .font(.headline)
+ Spacer()
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 14)
+ }
+
+ // MARK: - Form
+
+ private var form: some View {
+ Form {
+ Section {
+ TextField("Name", text: $name, prompt: Text("e.g. my-claude"))
+ .textFieldStyle(.roundedBorder)
+
+ Picker("Type", selection: $type) {
+ ForEach(ProviderType.Family.allCases, id: \.self) { family in
+ Section(family.rawValue) {
+ ForEach(ProviderType.allCases.filter { $0.family == family }) { t in
+ Label(t.displayName, systemImage: t.iconName).tag(t)
+ }
+ }
+ }
+ }
+ .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)
+ .textFieldStyle(.roundedBorder)
+ }
+ }
+
+ Section {
+ if !availableModels.isEmpty {
+ Picker("Available", selection: $model) {
+ ForEach(availableModels) { m in
+ Text(m.name).tag(m.id)
+ }
+ }
+ }
+ TextField("Model ID", text: $model, prompt: Text("e.g. qwen3-coder-plus, gpt-4o"))
+ .textFieldStyle(.roundedBorder)
+ .onChange(of: model) { _, newValue in
+ // Clear stale red messages once the user acts on them.
+ if case .failure = fetchResult,
+ !newValue.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ fetchResult = .none
+ }
+ 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)
+ }
+ }
+
+ Section {
+ Toggle("Enabled", isOn: $enabled)
+ }
+ }
+ .formStyle(.grouped)
+ }
+
+ // MARK: - Footer
+
+ private var footer: some View {
+ HStack(spacing: 8) {
+ Button(action: fetchModels) {
+ HStack(spacing: 6) {
+ if isLoadingModels { ProgressView().controlSize(.small) }
+ Text("Fetch Models")
+ }
+ }
+ .disabled(isLoadingModels || (type.requiresAPIKey && apiKey.isEmpty) || urlError != nil)
+
+ 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)
+ }
+
+ Spacer()
+
+ if let saveError {
+ Text(saveError).font(.system(size: 11)).foregroundStyle(.red).lineLimit(1)
+ }
+
+ Button("Cancel") { dismiss() }
+ .keyboardShortcut(.cancelAction)
+
+ Button("Save") { save() }
+ .keyboardShortcut(.defaultAction)
+ .disabled(!canSave)
+ }
+ .padding(.horizontal, 20)
+ .padding(.vertical, 12)
+ }
+
+ // MARK: - Actions
+
+ 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))) ?? ""
+ } else {
+ applyTypeDefaults(type)
+ }
+ validateURL(apiBase)
+ }
+
+ private func applyTypeDefaults(_ newType: ProviderType) {
+ apiBase = newType.defaultBaseURL
+ model = "" // user must fetch or type — avoids presetting a model the endpoint may not support
+ availableModels = []
+ fetchResult = .none
+ testResult = .none
+ isLoadingModels = false
+ isTesting = false
+ validateURL(apiBase)
+ }
+
+ private func validateURL(_ value: String) {
+ if value.isEmpty, type == .openAICompatible {
+ urlError = "Base URL is required for custom providers"
+ return
+ }
+ do {
+ _ = try ProviderURLValidator.validate(value, for: type)
+ urlError = nil
+ } catch {
+ urlError = error.localizedDescription
+ }
+ }
+
+ /// Verify the key + model combination by sending a 1-token chat request.
+ /// Works with endpoints that don't support /models listing (e.g. coding-intl
+ /// DashScope). Error messages come from the server, so the user can see why.
+ private func testConnection() {
+ isTesting = true
+ testResult = .none
+ let t = type
+ let base = apiBase.trimmingCharacters(in: .whitespacesAndNewlines)
+ let key = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let probeModel = model.trimmingCharacters(in: .whitespacesAndNewlines)
+
+ Task {
+ do {
+ let config = ProviderConfig(name: "__probe__", type: t, apiBase: base, model: probeModel)
+ let service = ProviderFactory.make(config: config, apiKey: key)
+ let ok = try await service.validateAPIKey()
+ await MainActor.run {
+ testResult = ok ? .success : .failure("Invalid credentials")
+ isTesting = false
+ }
+ } catch {
+ await MainActor.run {
+ testResult = .failure(error.localizedDescription)
+ isTesting = false
+ }
+ }
+ }
+ }
+
+ /// Populate the model picker. Strategy mirrors goclaw:
+ /// - Providers with no live listing (DashScope, Bailian) → use built-in catalog directly.
+ /// - Everything else → call the provider's `availableModels()` and populate from server.
+ /// On failure, fall back to the type's built-in catalog when available.
+ private func fetchModels() {
+ let t = type
+ if t.hasHardcodedCatalog {
+ applyBuiltInFallback(reason: "provider uses a built-in catalog")
+ return
+ }
+
+ isLoadingModels = true
+ fetchResult = .none
+ let base = apiBase.trimmingCharacters(in: .whitespacesAndNewlines)
+ let key = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+
+ Task {
+ let probeConfig = ProviderConfig(name: "__probe__", type: t, apiBase: base, model: "x")
+ let service = ProviderFactory.make(config: probeConfig, apiKey: key)
+
+ do {
+ let models = try await service.availableModels()
+ await MainActor.run {
+ if models.isEmpty {
+ applyBuiltInFallback(reason: "endpoint returned no models")
+ } else {
+ availableModels = models
+ fetchResult = .loaded(models.count)
+ if model.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ model = models[0].id
+ }
+ }
+ isLoadingModels = false
+ }
+ } catch {
+ await MainActor.run {
+ applyBuiltInFallback(reason: error.localizedDescription)
+ isLoadingModels = false
+ }
+ }
+ }
+ }
+
+ /// 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) {
+ let fallbacks = type.fallbackModelIDs
+ if fallbacks.isEmpty {
+ availableModels = []
+ fetchResult = .failure("Couldn't fetch (\(reason)) — type a model ID manually.")
+ return
+ }
+ availableModels = fallbacks.map {
+ LLMModel(id: $0, name: $0, provider: type.displayName, contextWindow: 0, supportsStreaming: true)
+ }
+ fetchResult = .loaded(fallbacks.count)
+ if model.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
+ model = fallbacks[0]
+ }
+ }
+
+ private func save() {
+ let trimmedKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let trimmedBase = apiBase.trimmingCharacters(in: .whitespacesAndNewlines)
+ let config = ProviderConfig(
+ id: editing?.id ?? UUID(),
+ name: name.trimmingCharacters(in: .whitespacesAndNewlines),
+ type: type,
+ apiBase: trimmedBase.isEmpty ? nil : trimmedBase,
+ model: model.trimmingCharacters(in: .whitespacesAndNewlines),
+ enabled: enabled,
+ createdAt: editing?.createdAt ?? Date()
+ )
+
+ Task {
+ do {
+ if isEdit {
+ try await repository.update(config)
+ } 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)
+ } else {
+ try keychain.save(key: keychainKey, value: trimmedKey)
+ }
+ // Update registry
+ await DependencyContainer.shared.providerRegistry.register(config, apiKey: trimmedKey)
+
+ await MainActor.run {
+ onSaved(config)
+ dismiss()
+ }
+ } catch {
+ await MainActor.run { saveError = error.localizedDescription }
+ }
+ }
+ }
+
+ // MARK: - Helpers
+
+ static func keychainKey(id: UUID) -> String {
+ "ai.apikey.\(id.uuidString)"
+ }
+}
diff --git a/macos/Presentation/Windows/Settings/SettingsView.swift b/macos/Presentation/Windows/Settings/SettingsView.swift
index 228b565..be546eb 100644
--- a/macos/Presentation/Windows/Settings/SettingsView.swift
+++ b/macos/Presentation/Windows/Settings/SettingsView.swift
@@ -68,199 +68,210 @@ struct GeneralSettingsView: View {
}
struct AISettingsView: View {
- private let keychainService: KeychainServiceProtocol = DependencyContainer.shared.keychainService
+ private let keychain: KeychainServiceProtocol = DependencyContainer.shared.keychainService
+ private let repository: any LLMProviderRepository = DependencyContainer.shared.llmProviderRepository
- @AppStorage("ai.provider") private var providerType = "gemini"
- @AppStorage("ai.provider.baseURL") private var baseURL = "https://generativelanguage.googleapis.com/v1beta/openai"
- @AppStorage("ai.provider.enabled") private var isEnabled = true
- @AppStorage("ai.provider.model") private var selectedModel = "gemini-2.5-flash"
+ @AppStorage("ai.activeProviderID") private var activeProviderID: String = ""
- @State private var apiKey = ""
- @State private var isValidating = false
- @State private var validationResult: ValidationResult?
- @State private var availableModels: [LLMModel] = []
- @State private var isLoadingModels = false
+ @State private var providers: [ProviderConfig] = []
+ @State private var editing: EditingTarget?
+ @State private var loadError: String?
- private enum ValidationResult {
- case success, failure(String)
- }
+ private enum EditingTarget: Identifiable {
+ case add
+ case edit(ProviderConfig)
- private let providerTypes = [
- ("gemini", "Google Gemini"),
- ("anthropic", "Anthropic"),
- ("openai", "OpenAI"),
- ("ollama", "Ollama"),
- ]
+ var id: String {
+ switch self {
+ case .add: return "__add__"
+ case .edit(let c): return c.id.uuidString
+ }
+ }
+ }
var body: some View {
- Form {
- Picker("Provider", selection: $providerType) {
- ForEach(providerTypes, id: \.0) { value, label in
- Text(label).tag(value)
- }
- }
- .onChange(of: providerType) { _, newValue in
- applyProviderDefaults(newValue)
+ VStack(spacing: 0) {
+ activeSection
+ Divider()
+ providersList
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ .onAppear(perform: reload)
+ .sheet(item: $editing) { target in
+ switch target {
+ case .add:
+ ProviderEditSheet(editing: nil) { _ in reload() }
+ case .edit(let config):
+ ProviderEditSheet(editing: config) { _ in reload() }
}
+ }
+ }
- if providerType != "ollama" {
- TextField("API Base URL", text: $baseURL)
- SecureField("API Key", text: $apiKey)
- }
+ // MARK: - Active picker
- HStack {
- Picker("Model", selection: $selectedModel) {
- if availableModels.isEmpty {
- ForEach(fallbackModels, id: \.self) { model in
- Text(model).tag(model)
- }
- } else {
- ForEach(availableModels) { model in
- Text(model.name).tag(model.id)
+ private var activeSection: some View {
+ Form {
+ Section("Active Provider") {
+ if enabledProviders.isEmpty {
+ Text("No provider configured yet. Click + to add one.")
+ .foregroundStyle(.secondary)
+ .font(.system(size: 12))
+ } else {
+ Picker("Used by AI chat", selection: $activeProviderID) {
+ ForEach(enabledProviders) { p in
+ Label("\(p.name) — \(p.type.displayName)", systemImage: p.type.iconName)
+ .tag(p.id.uuidString)
}
}
}
- Button(action: fetchModels) {
- if isLoadingModels {
- ProgressView()
- .controlSize(.small)
- } else {
- Image(systemName: "arrow.clockwise")
- }
- }
- .buttonStyle(.plain)
- .disabled(isLoadingModels || (providerType != "ollama" && apiKey.isEmpty))
- .help("Fetch models from API")
}
+ }
+ .formStyle(.grouped)
+ .frame(height: 100)
+ }
- Toggle("Enabled", isOn: $isEnabled)
+ // MARK: - Providers list
+ private var providersList: some View {
+ VStack(spacing: 0) {
HStack {
- Button(action: validateConnection) {
- HStack(spacing: 6) {
- if isValidating {
- ProgressView()
- .controlSize(.small)
- }
- Text("Validate")
- }
+ Text("Providers").font(.headline)
+ Spacer()
+ Button(action: { editing = .add }) {
+ Label("Add Provider", systemImage: "plus")
}
- .disabled(isValidating || (providerType != "ollama" && apiKey.isEmpty))
-
- if let result = validationResult {
- switch result {
- 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)
+ }
+ .padding(.horizontal, 20)
+ .padding(.top, 12)
+ .padding(.bottom, 8)
+
+ if providers.isEmpty {
+ VStack(spacing: 8) {
+ Image(systemName: "brain")
+ .font(.system(size: 32))
+ .foregroundStyle(.secondary)
+ Text("No providers yet")
+ .foregroundStyle(.secondary)
+ Text("Add Anthropic, OpenAI, Gemini, Ollama, Groq, DeepSeek and more.")
+ .font(.system(size: 11))
+ .foregroundStyle(.tertiary)
+ }
+ .frame(maxWidth: .infinity, maxHeight: .infinity)
+ } else {
+ List {
+ ForEach(providers) { p in
+ providerRow(p)
}
}
+ .listStyle(.inset(alternatesRowBackgrounds: true))
}
- }
- .formStyle(.grouped)
- .frame(maxWidth: .infinity, maxHeight: .infinity)
- .onAppear {
- loadAPIKey()
- fetchModels()
- }
- .onChange(of: apiKey) { _, newValue in saveAPIKey(newValue) }
- }
- private var fallbackModels: [String] {
- switch providerType {
- case "gemini": return ["gemini-2.5-flash", "gemini-2.5-pro", "gemini-2.0-flash"]
- case "anthropic": return ["claude-sonnet-4-6", "claude-haiku-4-5-20251001", "claude-opus-4-6"]
- case "openai": return ["gpt-4o", "gpt-4o-mini"]
- case "ollama": return ["llama3", "codellama", "mistral"]
- default: return []
+ if let loadError {
+ Text(loadError)
+ .font(.system(size: 11))
+ .foregroundStyle(.red)
+ .padding(.horizontal, 20)
+ .padding(.bottom, 8)
+ }
}
}
- private func fetchModels() {
- isLoadingModels = true
- Task {
- let service = DependencyContainer.shared.makeLLMService(
- provider: providerType,
- apiKey: apiKey,
- baseURL: baseURL
- )
- do {
- let models = try await service.availableModels()
- await MainActor.run {
- availableModels = models
- if !models.isEmpty && !models.contains(where: { $0.id == selectedModel }) {
- selectedModel = models[0].id
+ private func providerRow(_ p: ProviderConfig) -> some View {
+ HStack(spacing: 10) {
+ Image(systemName: p.type.iconName)
+ .font(.system(size: 16))
+ .foregroundStyle(.tint)
+ .frame(width: 24)
+
+ VStack(alignment: .leading, spacing: 2) {
+ HStack(spacing: 6) {
+ Text(p.name).font(.system(size: 13, weight: .medium))
+ if p.id.uuidString == activeProviderID {
+ Text("ACTIVE")
+ .font(.system(size: 9, weight: .bold))
+ .padding(.horizontal, 5).padding(.vertical, 1)
+ .background(Color.accentColor.opacity(0.18))
+ .foregroundStyle(.tint)
+ .clipShape(RoundedRectangle(cornerRadius: 3))
}
- isLoadingModels = false
- }
- } catch {
- await MainActor.run {
- availableModels = []
- isLoadingModels = false
}
+ Text("\(p.type.displayName) · \(p.model)")
+ .font(.system(size: 11))
+ .foregroundStyle(.secondary)
}
- }
- }
- private func applyProviderDefaults(_ provider: String) {
- switch provider {
- case "gemini":
- baseURL = "https://generativelanguage.googleapis.com/v1beta/openai"
- selectedModel = "gemini-2.5-flash"
- case "anthropic":
- baseURL = "https://api.anthropic.com/v1"
- selectedModel = "claude-sonnet-4-6"
- case "openai":
- baseURL = "https://api.openai.com/v1"
- selectedModel = "gpt-4o"
- case "ollama":
- baseURL = "http://localhost:11434"
- selectedModel = "llama3"
- default: break
+ Spacer()
+
+ Toggle("", isOn: Binding(
+ get: { p.enabled },
+ set: { toggleEnabled(p, $0) }
+ ))
+ .labelsHidden()
+ .toggleStyle(.switch)
+ .controlSize(.small)
+
+ Button(action: { editing = .edit(p) }) {
+ Image(systemName: "pencil")
+ }
+ .buttonStyle(.plain)
+ .help("Edit")
+
+ Button(action: { delete(p) }) {
+ Image(systemName: "trash")
+ }
+ .buttonStyle(.plain)
+ .foregroundStyle(.red)
+ .help("Delete")
}
- loadAPIKey()
- availableModels = []
- fetchModels()
+ .padding(.vertical, 4)
}
- private func loadAPIKey() {
- apiKey = (try? keychainService.load(key: "ai.apikey.\(providerType)")) ?? ""
- }
+ // MARK: - Data
- private func saveAPIKey(_ key: String) {
- if key.isEmpty {
- try? keychainService.delete(key: "ai.apikey.\(providerType)")
- } else {
- try? keychainService.save(key: "ai.apikey.\(providerType)", value: key)
- }
+ private var enabledProviders: [ProviderConfig] {
+ providers.filter(\.enabled)
}
- private func validateConnection() {
- isValidating = true
- validationResult = nil
+ private func reload() {
Task {
do {
- let service = DependencyContainer.shared.makeLLMService(
- provider: providerType,
- apiKey: apiKey,
- baseURL: baseURL
- )
- let valid = try await service.validateAPIKey()
+ let list = try await repository.fetchAll()
await MainActor.run {
- validationResult = valid ? .success : .failure("Invalid API key")
- isValidating = false
+ providers = list
+ loadError = nil
+ // Ensure activeProviderID points at a valid enabled entry
+ if !list.contains(where: { $0.id.uuidString == activeProviderID && $0.enabled }),
+ let first = list.first(where: { $0.enabled }) {
+ activeProviderID = first.id.uuidString
+ }
}
} catch {
- await MainActor.run {
- validationResult = .failure(error.localizedDescription)
- isValidating = false
- }
+ await MainActor.run { loadError = error.localizedDescription }
+ }
+ }
+ }
+
+ private func toggleEnabled(_ p: ProviderConfig, _ enabled: Bool) {
+ var updated = p
+ updated.enabled = enabled
+ Task {
+ 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)
+ } else {
+ await DependencyContainer.shared.providerRegistry.unregister(updated.name)
}
+ await MainActor.run { reload() }
+ }
+ }
+
+ private func delete(_ p: ProviderConfig) {
+ Task {
+ try? await repository.delete(p.id)
+ try? keychain.delete(key: ProviderEditSheet.keychainKey(id: p.id))
+ await DependencyContainer.shared.providerRegistry.unregister(p.name)
+ await MainActor.run { reload() }
}
}
}
diff --git a/macos/Resources/Info.plist b/macos/Resources/Info.plist
index b77a14c..3d11006 100644
--- a/macos/Resources/Info.plist
+++ b/macos/Resources/Info.plist
@@ -32,9 +32,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
- <string>0.0.1</string>
+ <string>0.0.2</string>
<key>CFBundleVersion</key>
- <string>1</string>
+ <string>2</string>
<key>LSMinimumSystemVersion</key>
<string>14.0</string>
<key>NSAppTransportSecurity</key>
diff --git a/macos/Services/AI/ProviderFactory.swift b/macos/Services/AI/ProviderFactory.swift
new file mode 100644
index 0000000..8ec8b14
--- /dev/null
+++ b/macos/Services/AI/ProviderFactory.swift
@@ -0,0 +1,37 @@
+// ProviderFactory.swift
+// Gridex
+//
+// Dispatch ProviderConfig → concrete LLMService.
+// The OpenAI-compatible family all share `OpenAIProvider` with a preset baseURL,
+// so adding a new vendor is usually just an enum case, not a new class.
+
+import Foundation
+
+enum ProviderFactory {
+ static func make(config: ProviderConfig, apiKey: String) -> any LLMService {
+ let base = config.resolvedBaseURL
+ switch config.type {
+ case .anthropic:
+ return AnthropicProvider(apiKey: apiKey, baseURL: base)
+ case .gemini:
+ return GeminiProvider(apiKey: apiKey, baseURL: base)
+ case .ollama:
+ return OllamaProvider(baseURLString: base)
+ case .openAI, .azureOpenAI, .groq, .deepseek, .mistral, .xAI,
+ .perplexity, .openRouter, .together, .fireworks, .dashscope,
+ .dashscopeCoding, .openAICompatible:
+ return OpenAIProvider(apiKey: apiKey, baseURL: base, probeModel: config.model)
+ }
+ }
+
+ /// Convenience for legacy callers that only know the type.
+ static func make(type: ProviderType, apiKey: String, baseURL: String? = nil) -> any LLMService {
+ let config = ProviderConfig(
+ name: type.rawValue,
+ type: type,
+ apiBase: baseURL,
+ model: type.defaultModel
+ )
+ return make(config: config, apiKey: apiKey)
+ }
+}
diff --git a/macos/Services/AI/ProviderRegistry.swift b/macos/Services/AI/ProviderRegistry.swift
new file mode 100644
index 0000000..f59acc3
--- /dev/null
+++ b/macos/Services/AI/ProviderRegistry.swift
@@ -0,0 +1,50 @@
+// ProviderRegistry.swift
+// Gridex
+//
+// Thread-safe registry of live LLMService instances keyed by user-defined name.
+// Mirrors goclaw internal/providers/registry.go — on replacement the prior
+// instance is released (concrete providers hold only short-lived URLSession
+// tasks, so nothing further is required).
+
+import Foundation
+
+actor ProviderRegistry {
+ private struct Entry {
+ let config: ProviderConfig
+ let service: any LLMService
+ }
+
+ 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)
+ entries[config.name] = Entry(config: config, service: service)
+ }
+
+ /// Remove a provider by name. No-op if missing.
+ func unregister(_ name: String) {
+ entries.removeValue(forKey: name)
+ }
+
+ /// Remove all providers.
+ func removeAll() {
+ entries.removeAll()
+ }
+
+ /// Resolve a provider by name. Returns nil if not registered.
+ func resolve(_ name: String) -> (any LLMService)? {
+ entries[name]?.service
+ }
+
+ /// Resolve the first enabled provider of a given type. Handy when the UI
+ /// still drives selection by type rather than name.
+ func resolve(type: ProviderType) -> (any LLMService)? {
+ entries.values.first(where: { $0.config.type == type && $0.config.enabled })?.service
+ }
+
+ /// All registered configs, for UI listing.
+ func listConfigs() -> [ProviderConfig] {
+ entries.values.map(\.config).sorted { $0.createdAt < $1.createdAt }
+ }
+}
diff --git a/macos/Services/AI/Providers/AnthropicProvider.swift b/macos/Services/AI/Providers/AnthropicProvider.swift
index a300668..4746028 100644
--- a/macos/Services/AI/Providers/AnthropicProvider.swift
+++ b/macos/Services/AI/Providers/AnthropicProvider.swift
@@ -8,9 +8,13 @@ import Foundation
final class AnthropicProvider: LLMService, @unchecked Sendable {
let providerName = "Anthropic"
private let apiKey: String
+ private let baseURL: String
+ private let anthropicVersion = "2023-06-01"
- init(apiKey: String) {
- self.apiKey = apiKey
+ init(apiKey: String, baseURL: String = "https://api.anthropic.com/v1") {
+ self.apiKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let trimmedURL = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ self.baseURL = trimmedURL.hasSuffix("/") ? String(trimmedURL.dropLast()) : trimmedURL
}
func stream(
@@ -23,11 +27,11 @@ final class AnthropicProvider: LLMService, @unchecked Sendable {
AsyncThrowingStream { continuation in
Task {
do {
- var request = URLRequest(url: URL(string: "https://api.anthropic.com/v1/messages")!)
+ var request = URLRequest(url: URL(string: "\(baseURL)/messages")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "content-type")
request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
- request.setValue("2023-06-01", forHTTPHeaderField: "anthropic-version")
+ request.setValue(anthropicVersion, forHTTPHeaderField: "anthropic-version")
let body: [String: Any] = [
"model": model,
@@ -35,14 +39,14 @@ final class AnthropicProvider: LLMService, @unchecked Sendable {
"temperature": temperature,
"stream": true,
"system": systemPrompt,
- "messages": messages.map { ["role": $0.role.rawValue, "content": $0.content] }
+ "messages": messages.map { ["role": $0.role.rawValue, "content": $0.content] },
]
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (stream, response) = try await URLSession.shared.bytes(for: request)
-
- guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
- continuation.finish(throwing: GridexError.aiProviderError("HTTP error"))
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ continuation.finish(throwing: GridexError.aiProviderError("Anthropic HTTP \(code)"))
return
}
@@ -65,15 +69,46 @@ final class AnthropicProvider: LLMService, @unchecked Sendable {
}
func availableModels() async throws -> [LLMModel] {
- [
- LLMModel(id: "claude-sonnet-4-6", name: "Claude Sonnet 4.6", provider: providerName, contextWindow: 200000, supportsStreaming: true),
- LLMModel(id: "claude-haiku-4-5-20251001", name: "Claude Haiku 4.5", provider: providerName, contextWindow: 200000, supportsStreaming: true),
- LLMModel(id: "claude-opus-4-6", name: "Claude Opus 4.6", provider: providerName, contextWindow: 200000, supportsStreaming: true),
- ]
+ // Use Anthropic's official models endpoint. Auth is x-api-key (NOT Bearer).
+ // Response: {"data":[{"id":"...","display_name":"..."}]}
+ var request = URLRequest(url: URL(string: "\(baseURL)/models")!)
+ request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
+ request.setValue(anthropicVersion, forHTTPHeaderField: "anthropic-version")
+
+ let (data, http) = try await LLMRetry.perform(request)
+ if http.statusCode == 401 || http.statusCode == 403 {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode): check API key")
+ }
+ guard http.statusCode == 200 else {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode)")
+ }
+
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let arr = json["data"] as? [[String: Any]] else {
+ return []
+ }
+ return arr.compactMap { m -> LLMModel? in
+ guard let id = m["id"] as? String else { return nil }
+ let display = (m["display_name"] as? String) ?? id
+ return LLMModel(id: id, name: display, provider: providerName, contextWindow: 200000, supportsStreaming: true)
+ }
}
func validateAPIKey() async throws -> Bool {
- // TODO: Make a minimal API call to validate
- return !apiKey.isEmpty
+ // Minimal, cheap probe: 1-token message. 200 → valid, 401/403 → invalid.
+ var request = URLRequest(url: URL(string: "\(baseURL)/messages")!)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ request.setValue(apiKey, forHTTPHeaderField: "x-api-key")
+ request.setValue(anthropicVersion, forHTTPHeaderField: "anthropic-version")
+ let body: [String: Any] = [
+ "model": "claude-haiku-4-5-20251001",
+ "max_tokens": 1,
+ "messages": [["role": "user", "content": "."]],
+ ]
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+
+ let (_, http) = try await LLMRetry.perform(request, policy: .none)
+ return http.statusCode == 200
}
}
diff --git a/macos/Services/AI/Providers/GeminiProvider.swift b/macos/Services/AI/Providers/GeminiProvider.swift
index 5ef8770..f374a94 100644
--- a/macos/Services/AI/Providers/GeminiProvider.swift
+++ b/macos/Services/AI/Providers/GeminiProvider.swift
@@ -11,8 +11,9 @@ final class GeminiProvider: LLMService, @unchecked Sendable {
private let baseURL: String
init(apiKey: String, baseURL: String = "https://generativelanguage.googleapis.com/v1beta/openai") {
- self.apiKey = apiKey
- self.baseURL = baseURL.hasSuffix("/") ? String(baseURL.dropLast()) : baseURL
+ self.apiKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let trimmedURL = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ self.baseURL = trimmedURL.hasSuffix("/") ? String(trimmedURL.dropLast()) : trimmedURL
}
func stream(
@@ -73,34 +74,32 @@ final class GeminiProvider: LLMService, @unchecked Sendable {
}
func availableModels() async throws -> [LLMModel] {
- var request = URLRequest(url: URL(string: "\(baseURL)/models")!)
- request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")
- let (data, response) = try await URLSession.shared.data(for: request)
-
- guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {
- // Fallback to known models
- return defaultModels
+ // Use Google's native models endpoint — it gives the full list with display
+ // names. The OpenAI-compat shim at /v1beta/openai/models is limited to a
+ // subset. Auth is via ?key= query param (NOT Bearer).
+ let endpoint = "https://generativelanguage.googleapis.com/v1beta/models?key=\(apiKey)"
+ guard let url = URL(string: endpoint) else {
+ throw GridexError.aiProviderError("Invalid Gemini URL")
+ }
+ let (data, http) = try await LLMRetry.perform(URLRequest(url: url))
+ if http.statusCode == 401 || http.statusCode == 403 {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode): check API key")
+ }
+ guard http.statusCode == 200 else {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode)")
}
guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
- let modelsArray = json["data"] as? [[String: Any]] else {
- return defaultModels
+ let arr = json["models"] as? [[String: Any]] else {
+ return []
}
-
- let models = modelsArray.compactMap { model -> LLMModel? in
- guard let id = model["id"] as? String else { return nil }
- return LLMModel(id: id, name: id, provider: providerName, contextWindow: 1000000, supportsStreaming: true)
+ return arr.compactMap { m -> LLMModel? in
+ // name = "models/gemini-2.5-flash" — strip the prefix for the usable ID
+ guard let rawName = m["name"] as? String else { return nil }
+ let id = rawName.hasPrefix("models/") ? String(rawName.dropFirst(7)) : rawName
+ let display = (m["displayName"] as? String) ?? id
+ return LLMModel(id: id, name: display, provider: providerName, contextWindow: 1000000, supportsStreaming: true)
}
-
- return models.isEmpty ? defaultModels : models
- }
-
- private var defaultModels: [LLMModel] {
- [
- LLMModel(id: "gemini-2.5-flash", name: "Gemini 2.5 Flash", provider: providerName, contextWindow: 1000000, supportsStreaming: true),
- LLMModel(id: "gemini-2.5-pro", name: "Gemini 2.5 Pro", provider: providerName, contextWindow: 1000000, supportsStreaming: true),
- LLMModel(id: "gemini-2.0-flash", name: "Gemini 2.0 Flash", provider: providerName, contextWindow: 1000000, supportsStreaming: true),
- ]
}
func validateAPIKey() async throws -> Bool {
diff --git a/macos/Services/AI/Providers/OllamaProvider.swift b/macos/Services/AI/Providers/OllamaProvider.swift
index 2c7b3c5..48f1fd2 100644
--- a/macos/Services/AI/Providers/OllamaProvider.swift
+++ b/macos/Services/AI/Providers/OllamaProvider.swift
@@ -1,7 +1,8 @@
// OllamaProvider.swift
// Gridex
//
-// Local Ollama LLM integration.
+// Local Ollama LLM integration. Uses the native /api/chat (NDJSON streaming)
+// and /api/tags endpoints — not the OpenAI-compat shim — so no API key needed.
import Foundation
@@ -10,7 +11,16 @@ final class OllamaProvider: LLMService, @unchecked Sendable {
private let baseURL: URL
init(baseURL: URL = URL(string: "http://localhost:11434")!) {
- self.baseURL = baseURL
+ // Ollama's native API lives at the root — strip any /v1 suffix users might
+ // add when thinking "OpenAI-compatible".
+ var s = baseURL.absoluteString
+ if s.hasSuffix("/v1") { s.removeLast(3) }
+ if s.hasSuffix("/") { s.removeLast() }
+ self.baseURL = URL(string: s) ?? baseURL
+ }
+
+ convenience init(baseURLString: String) {
+ self.init(baseURL: URL(string: baseURLString) ?? URL(string: "http://localhost:11434")!)
}
func stream(
@@ -22,24 +32,85 @@ final class OllamaProvider: LLMService, @unchecked Sendable {
) -> AsyncThrowingStream<String, Error> {
AsyncThrowingStream { continuation in
Task {
- // TODO: Implement Ollama streaming API
- continuation.finish(throwing: GridexError.unsupportedOperation("Ollama provider not yet implemented"))
+ do {
+ var request = URLRequest(url: baseURL.appendingPathComponent("/api/chat"))
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+
+ var msgs: [[String: Any]] = [["role": "system", "content": systemPrompt]]
+ msgs += messages.map { ["role": $0.role.rawValue, "content": $0.content] }
+
+ let body: [String: Any] = [
+ "model": model,
+ "messages": msgs,
+ "stream": true,
+ "options": [
+ "num_predict": maxTokens,
+ "temperature": temperature,
+ ],
+ ]
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+
+ let (stream, response) = try await URLSession.shared.bytes(for: request)
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ continuation.finish(throwing: GridexError.aiProviderError("Ollama HTTP \(code)"))
+ return
+ }
+
+ // NDJSON: one JSON object per line
+ for try await line in stream.lines {
+ guard !line.isEmpty,
+ let data = line.data(using: .utf8),
+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
+ continue
+ }
+ if let msg = obj["message"] as? [String: Any],
+ let content = msg["content"] as? String,
+ !content.isEmpty {
+ continuation.yield(content)
+ }
+ if obj["done"] as? Bool == true { break }
+ }
+ continuation.finish()
+ } catch {
+ continuation.finish(throwing: error)
+ }
}
}
}
func availableModels() async throws -> [LLMModel] {
- // TODO: GET /api/tags to list installed models
- return []
+ var request = URLRequest(url: baseURL.appendingPathComponent("/api/tags"))
+ request.timeoutInterval = 5
+ let (data, http) = try await LLMRetry.perform(request, policy: .none)
+ guard http.statusCode == 200,
+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let arr = json["models"] as? [[String: Any]] else {
+ return []
+ }
+
+ return arr.compactMap { m -> LLMModel? in
+ guard let id = m["name"] as? String else { return nil }
+ // Build a richer display name from details: "family paramSize quantLevel"
+ // e.g. "llama 8.0B Q4_K_M". Mirrors goclaw's approach.
+ let details = m["details"] as? [String: Any]
+ var parts: [String] = []
+ if let v = details?["family"] as? String, !v.isEmpty { parts.append(v) }
+ if let v = details?["parameter_size"] as? String, !v.isEmpty { parts.append(v) }
+ if let v = details?["quantization_level"] as? String, !v.isEmpty { parts.append(v) }
+ let name = parts.isEmpty ? id : parts.joined(separator: " ")
+ let ctx = details?["context_length"] as? Int ?? 8192
+ return LLMModel(id: id, name: name, provider: providerName, contextWindow: ctx, supportsStreaming: true)
+ }
}
func validateAPIKey() async throws -> Bool {
- // Ollama doesn't need an API key, just check if server is running
var request = URLRequest(url: baseURL.appendingPathComponent("/api/tags"))
request.timeoutInterval = 5
do {
- let (_, response) = try await URLSession.shared.data(for: request)
- return (response as? HTTPURLResponse)?.statusCode == 200
+ let (_, http) = try await LLMRetry.perform(request, policy: .none)
+ return http.statusCode == 200
} catch {
return false
}
diff --git a/macos/Services/AI/Providers/OpenAIProvider.swift b/macos/Services/AI/Providers/OpenAIProvider.swift
index 976c191..d2d30ea 100644
--- a/macos/Services/AI/Providers/OpenAIProvider.swift
+++ b/macos/Services/AI/Providers/OpenAIProvider.swift
@@ -2,15 +2,23 @@
// Gridex
//
// OpenAI GPT API integration with streaming support.
+// Works for any OpenAI-compatible endpoint (set baseURL accordingly).
import Foundation
final class OpenAIProvider: LLMService, @unchecked Sendable {
let providerName = "OpenAI"
private let apiKey: String
+ private let baseURL: String
+ /// Used only for the `validateAPIKey()` probe — real requests receive the model
+ /// from the caller (`stream(model:)`).
+ private let probeModel: String
- init(apiKey: String) {
- self.apiKey = apiKey
+ init(apiKey: String, baseURL: String = "https://api.openai.com/v1", probeModel: String = "gpt-4o-mini") {
+ self.apiKey = apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let trimmedURL = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ self.baseURL = trimmedURL.hasSuffix("/") ? String(trimmedURL.dropLast()) : trimmedURL
+ self.probeModel = probeModel
}
func stream(
@@ -22,20 +30,103 @@ final class OpenAIProvider: LLMService, @unchecked Sendable {
) -> AsyncThrowingStream<String, Error> {
AsyncThrowingStream { continuation in
Task {
- // TODO: Implement OpenAI streaming API
- continuation.finish(throwing: GridexError.unsupportedOperation("OpenAI provider not yet implemented"))
+ do {
+ var request = URLRequest(url: URL(string: "\(baseURL)/chat/completions")!)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")
+
+ var msgs: [[String: Any]] = [["role": "system", "content": systemPrompt]]
+ msgs += messages.map { ["role": $0.role.rawValue, "content": $0.content] }
+
+ let body: [String: Any] = [
+ "model": model,
+ "max_tokens": maxTokens,
+ "temperature": temperature,
+ "stream": true,
+ "messages": msgs,
+ ]
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+
+ let (stream, response) = try await URLSession.shared.bytes(for: request)
+ guard let http = response as? HTTPURLResponse, http.statusCode == 200 else {
+ let code = (response as? HTTPURLResponse)?.statusCode ?? 0
+ continuation.finish(throwing: GridexError.aiProviderError("OpenAI HTTP \(code)"))
+ return
+ }
+
+ for try await line in stream.lines {
+ guard line.hasPrefix("data: ") else { continue }
+ let data = String(line.dropFirst(6))
+ guard data != "[DONE]" else { break }
+
+ if let json = try? JSONSerialization.jsonObject(with: Data(data.utf8)) as? [String: Any],
+ let choices = json["choices"] as? [[String: Any]],
+ let delta = choices.first?["delta"] as? [String: Any],
+ let content = delta["content"] as? String {
+ continuation.yield(content)
+ }
+ }
+ continuation.finish()
+ } catch {
+ continuation.finish(throwing: error)
+ }
}
}
}
func availableModels() async throws -> [LLMModel] {
- [
- LLMModel(id: "gpt-4o", name: "GPT-4o", provider: providerName, contextWindow: 128000, supportsStreaming: true),
- LLMModel(id: "gpt-4o-mini", name: "GPT-4o Mini", provider: providerName, contextWindow: 128000, supportsStreaming: true),
- ]
+ var request = URLRequest(url: URL(string: "\(baseURL)/models")!)
+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")
+
+ let (data, http) = try await LLMRetry.perform(request)
+
+ // Surface auth/endpoint problems as real errors instead of silently
+ // returning a fake list — the settings UI needs truthful feedback.
+ if http.statusCode == 401 || http.statusCode == 403 {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode): check API key")
+ }
+ if http.statusCode == 404 {
+ throw GridexError.aiProviderError("HTTP 404: endpoint doesn't support /models listing")
+ }
+ guard http.statusCode == 200 else {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode)")
+ }
+
+ guard let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let arr = json["data"] as? [[String: Any]] else {
+ return []
+ }
+ return arr.compactMap { m -> LLMModel? in
+ guard let id = m["id"] as? String else { return nil }
+ return LLMModel(id: id, name: id, provider: providerName, contextWindow: 128000, supportsStreaming: true)
+ }
}
func validateAPIKey() async throws -> Bool {
- return !apiKey.isEmpty
+ // Probe /chat/completions with a 1-token request. `/models` is not universally
+ // supported (DashScope, Azure, some OpenRouter routes return 404 / different
+ // auth), but `/chat/completions` is the common denominator for OpenAI-compat
+ // providers. 401 → bad key, 200 → good key, other → surface an error message.
+ var request = URLRequest(url: URL(string: "\(baseURL)/chat/completions")!)
+ request.httpMethod = "POST"
+ request.setValue("application/json", forHTTPHeaderField: "content-type")
+ request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "authorization")
+ let body: [String: Any] = [
+ "model": probeModel,
+ "max_tokens": 1,
+ "messages": [["role": "user", "content": "."]],
+ ]
+ request.httpBody = try JSONSerialization.data(withJSONObject: body)
+
+ let (data, http) = try await LLMRetry.perform(request, policy: .none)
+ if http.statusCode == 200 { return true }
+ // Extract error.message from the body so the UI can surface something useful.
+ if let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let err = json["error"] as? [String: Any],
+ let msg = err["message"] as? String {
+ throw GridexError.aiProviderError("HTTP \(http.statusCode): \(msg)")
+ }
+ throw GridexError.aiProviderError("HTTP \(http.statusCode)")
}
}
diff --git a/macos/Services/Updater/UpdaterService.swift b/macos/Services/Updater/UpdaterService.swift
index 1a88eba..60c5a23 100644
--- a/macos/Services/Updater/UpdaterService.swift
+++ b/macos/Services/Updater/UpdaterService.swift
@@ -19,12 +19,6 @@ final class UpdaterService: ObservableObject {
@Published var canCheckForUpdates: Bool = false
private init() {
- let os = ProcessInfo.processInfo.operatingSystemVersion
- guard os.majorVersion < 26 else {
- controller = nil
- return
- }
-
let c = SPUStandardUpdaterController(
startingUpdater: true,
updaterDelegate: nil,