SPB Git

Repository Public License

RegistryTests.swift 19.4 KB 304 lines swift

1import Foundation2import NavigatorCore3import Testing4@testable import ProviderKit56/// Secret source that records what it was asked, standing in for the Keychain.7actor RecordingSecrets: ProviderSecretSource {8    private(set) var values: [String: String] = [:]9    private(set) var deleted: [String] = []10    func secret(for account: String) -> String? { values[account] }11    func setSecret(_ value: String, for account: String) { values[account] = value }12    func deleteSecret(for account: String) { values[account] = nil; deleted.append(account) }13}1415@Suite struct ProviderRegistryTests {16    private func registry(_ test: TestEnvironment, store: InMemoryProviderConfigurationStore = .init(), secrets: RecordingSecrets = .init(),17                          ledger: InMemoryUsageLedger = .init(), runtimes: [any LocalModelRuntime] = [], clock: Locked<Date> = Locked(Date(timeIntervalSince1970: 1_800_000_000)))18        -> ProviderRegistry {19        ProviderRegistry(store: store, secrets: secrets, environment: test.environment, ledger: ledger, localRuntimes: runtimes,20                         device: DeviceCapability(physicalMemoryBytes: 32_000_000_000, platform: .macOS), now: { clock.get() })21    }2223    @Test func startsEmptyWithNoDefault() async throws {24        let registry = registry(TestEnvironment([]))25        try await registry.load()26        #expect(await registry.configurations.isEmpty)27        #expect(await registry.defaultProviderID == nil)28        // With nothing configured the browser simply has no AI: asking for the default is an error, not a crash.29        await #expect(throws: ProviderError.self) { try await registry.defaultProvider() }30    }3132    @Test func configurationsPersistAndKeysNeverReachTheStore() async throws {33        let store = InMemoryProviderConfigurationStore(), secrets = RecordingSecrets()34        let first = registry(TestEnvironment([]), store: store, secrets: secrets)35        let anthropic = ProviderConfiguration(id: "a1", family: .anthropic, displayName: "Claude", model: "claude-opus-5-5",36                                              limits: ProviderLimits(maxOutputTokens: 4_000, maxRequestsPerMinute: 10, monthlyBudgetUSD: 20))37        let local = ProviderConfiguration(id: "c1", family: .compatible, displayName: "Ollama", baseURL: "http://localhost:11434/v1", model: "llama3.2",38                                          headers: ["X-Team": "browser"])39        try await first.upsert(anthropic)40        try await first.upsert(local)41        try await first.setAPIKey("  \(testKey)\n", for: "a1")42        try await first.setDefaultProvider(id: "a1")43        try await first.setUserPrice(ModelPrice(inputPerMillion: 0.2, outputPerMillion: 0.4), family: .compatible, model: "llama3.2")4445        #expect(try await first.hasAPIKey(for: "a1"))46        #expect(try await !first.hasAPIKey(for: "c1"))47        #expect(await secrets.values == ["provider.a1.api-key": testKey])   // trimmed, under the configuration's account4849        let saved = try #require(await store.loadProviderConfigurations())50        let json = String(decoding: saved, as: UTF8.self)51        #expect(!json.contains(testKey))52        #expect(!json.lowercased().contains("apikey") && !json.lowercased().contains("api_key") && !json.contains("secret"))5354        let second = registry(TestEnvironment([]), store: store, secrets: secrets)55        try await second.load()56        #expect(await second.configurations == [anthropic, local])57        #expect(await second.defaultProviderID == "a1")58        #expect(await second.price(family: .compatible, model: "llama3.2")?.source == .user)59        #expect(await second.configuration(id: "a1")?.limits.monthlyBudgetUSD == 20)60    }6162    @Test func upsertReplacesAndRemoveDeletesTheKey() async throws {63        let secrets = RecordingSecrets()64        let registry = registry(TestEnvironment([]), secrets: secrets)65        var configuration = ProviderConfiguration(id: "o1", family: .openAI, model: "gpt-6.2-sol")66        try await registry.upsert(configuration)67        configuration.model = "gpt-6-luna"68        try await registry.upsert(configuration)69        #expect(await registry.configurations.map(\.model) == ["gpt-6-luna"])70        try await registry.setAPIKey(testKey, for: "o1")71        try await registry.setDefaultProvider(id: "o1")72        try await registry.remove(id: "o1")73        #expect(await registry.configurations.isEmpty)74        #expect(await registry.defaultProviderID == nil)75        #expect(await secrets.values.isEmpty)76        #expect(await secrets.deleted == ["provider.o1.api-key"])77        await #expect(throws: ProviderError.self) { try await registry.setAPIKey("x", for: "o1") }78        await #expect(throws: ProviderError.self) { try await registry.setDefaultProvider(id: "o1") }79    }8081    @Test func emptyKeyDeletesIt() async throws {82        let secrets = RecordingSecrets()83        let registry = registry(TestEnvironment([]), secrets: secrets)84        try await registry.upsert(ProviderConfiguration(id: "o1", family: .openAI, model: "m"))85        try await registry.setAPIKey(testKey, for: "o1")86        try await registry.setAPIKey("   ", for: "o1")87        #expect(try await !registry.hasAPIKey(for: "o1"))88    }8990    @Test func invalidConfigurationsAreRefused() async {91        let registry = registry(TestEnvironment([]))92        let invalid: [ProviderConfiguration] = [93            ProviderConfiguration(family: .compatible, model: "m"),                                                    // no base URL94            ProviderConfiguration(family: .compatible, baseURL: "http://api.example.com/v1", model: "m"),              // public host over HTTP, no opt-in95            ProviderConfiguration(family: .compatible, baseURL: "https://x.example/v1", model: "m", headers: ["Authorization": "Bearer k"]),96            ProviderConfiguration(family: .anthropic, baseURL: "http://localhost:8080/v1", model: "m"),                // a hosted key never goes over HTTP97            ProviderConfiguration(family: .openAI, displayName: "  ", model: "m"),98            ProviderConfiguration(family: .openAI, model: "m", limits: ProviderLimits(maxRequestsPerMinute: 0)),99            ProviderConfiguration(family: .openAI, model: "m", limits: ProviderLimits(monthlyBudgetUSD: -1)),100            ProviderConfiguration(family: .local, model: "m"),                                                         // no runtime chosen101        ]102        for configuration in invalid {103            await #expect(throws: ProviderError.self, "\(configuration)") { try await registry.upsert(configuration) }104        }105        #expect(await registry.configurations.isEmpty)106    }107108    @Test func insecureCompatibleEndpointIsAcceptedOnlyWithOptIn() async throws {109        let registry = registry(TestEnvironment([]))110        try await registry.upsert(ProviderConfiguration(id: "c", family: .compatible, baseURL: "http://api.example.com/v1", model: "m", allowInsecureHTTP: true))111        try await registry.upsert(ProviderConfiguration(id: "l", family: .compatible, baseURL: "http://192.168.2.103:8000/v1", model: "m"))112        #expect(await registry.configurations.count == 2)113    }114115    @Test func createsTheRightProviderForEachFamily() async throws {116        let registry = registry(TestEnvironment([]), runtimes: [FakeRuntime()])117        try await registry.upsert(ProviderConfiguration(id: "a", family: .anthropic, model: "m"))118        try await registry.upsert(ProviderConfiguration(id: "o", family: .openAI, model: "m"))119        try await registry.upsert(ProviderConfiguration(id: "r", family: .openRouter, model: "m"))120        try await registry.upsert(ProviderConfiguration(id: "c", family: .compatible, baseURL: "http://localhost:1234/v1", model: "m"))121        try await registry.upsert(ProviderConfiguration(id: "l", family: .local, model: "fake-small", localRuntimeID: "fake"))122        #expect(try await registry.unmeteredProvider(for: "a") is AnthropicProvider)123        #expect(try await registry.unmeteredProvider(for: "o") is OpenAIProvider)124        #expect(try await registry.unmeteredProvider(for: "r") is OpenRouterProvider)125        #expect(try await registry.unmeteredProvider(for: "c") is CompatibleProvider)126        #expect(try await registry.unmeteredProvider(for: "l") is LocalProvider)127        #expect(try await registry.provider(for: "a").family == .anthropic)128        await #expect(throws: ProviderError.self) { try await registry.unmeteredProvider(for: "missing") }129    }130131    @Test func keyIsReadAtRequestTimeFromTheSecretSource() async throws {132        let test = TestEnvironment([.sse(HTTPFamily.openAI.textStream), .sse(HTTPFamily.openAI.textStream)])133        let registry = registry(test)134        try await registry.upsert(ProviderConfiguration(id: "o", family: .openAI, model: "gpt-6.2-sol"))135        let provider = try await registry.provider(for: "o")136        await #expect(throws: ProviderError.missingKey(provider: "OpenAI")) { try await provider.complete(provider.request(messages: [.user("Hi")])) }137        #expect(test.transport.requests.isEmpty)138139        try await registry.setAPIKey(testKey, for: "o")140        let response = try await provider.complete(provider.request(messages: [.user("Hi")]))   // same provider value, new key141        #expect(response.text == "Hello, wörld")142        #expect(test.transport.requests[0].value(forHTTPHeaderField: "Authorization") == "Bearer \(testKey)")143        #expect(test.transport.body()["model"] == "gpt-6.2-sol")144    }145146    @Test func customBaseURLIsUsedForHostedFamilies() async throws {147        let test = TestEnvironment([.sse(HTTPFamily.anthropic.textStream)])148        let registry = registry(test)149        try await registry.upsert(ProviderConfiguration(id: "a", family: .anthropic, baseURL: "https://gateway.example.com/anthropic/v1", model: "m"))150        try await registry.setAPIKey(testKey, for: "a")151        _ = try await registry.provider(for: "a").complete(sampleRequest())152        #expect(test.transport.requests[0].url?.absoluteString == "https://gateway.example.com/anthropic/v1/messages")153    }154155    // MARK: Limits156157    @Test func maxOutputTokensLimitCapsEveryRequest() async throws {158        let test = TestEnvironment([.sse(HTTPFamily.anthropic.textStream), .sse(HTTPFamily.anthropic.textStream), .sse(HTTPFamily.anthropic.textStream)])159        let registry = registry(test)160        try await registry.upsert(ProviderConfiguration(id: "a", family: .anthropic, model: "m", limits: ProviderLimits(maxOutputTokens: 1_000)))161        try await registry.setAPIKey(testKey, for: "a")162        let provider = try await registry.provider(for: "a")163        _ = try await provider.complete(sampleRequest())                                                     // unset → the cap164        _ = try await provider.complete(sampleRequest(options: GenerationOptions(maxOutputTokens: 50_000)))  // above → the cap165        _ = try await provider.complete(sampleRequest(options: GenerationOptions(maxOutputTokens: 200)))     // below → kept166        #expect((0..<3).map { test.transport.body($0)["max_tokens"]?.intValue } == [1_000, 1_000, 200])167    }168169    @Test func requestsPerMinuteLimitRefusesWithoutSending() async throws {170        let clock = Locked(Date(timeIntervalSince1970: 1_800_000_000))171        let test = TestEnvironment(Array(repeating: .sse(HTTPFamily.openAI.textStream), count: 5))172        let registry = registry(test, clock: clock)173        try await registry.upsert(ProviderConfiguration(id: "o", family: .openAI, displayName: "Work GPT", model: "m", limits: ProviderLimits(maxRequestsPerMinute: 2)))174        try await registry.setAPIKey(testKey, for: "o")175        _ = try await registry.provider(for: "o").complete(sampleRequest())176        clock.mutate { $0 += 10 }177        _ = try await registry.provider(for: "o").complete(sampleRequest())   // a second provider value shares the window178        clock.mutate { $0 += 10 }179        let (events, error) = await collect(try registry.provider(for: "o").stream(sampleRequest()))180        #expect(events.isEmpty)181        #expect(error == .limitExceeded("“Work GPT” is limited to 2 requests per minute. Try again in 40 s."))182        #expect(test.transport.requests.count == 2)183        clock.mutate { $0 += 41 }   // the first request left the window184        _ = try await registry.provider(for: "o").complete(sampleRequest())185        #expect(test.transport.requests.count == 3)186    }187188    @Test func monthlyBudgetStopsRequestsOnceTheEstimateReachesIt() async throws {189        let clock = Locked(Date(timeIntervalSince1970: 1_800_000_000))190        let test = TestEnvironment(Array(repeating: .sse(HTTPFamily.anthropic.textStream), count: 5))191        let ledger = InMemoryUsageLedger()192        let registry = registry(test, ledger: ledger, clock: clock)193        // claude-opus-5-5: 10 fresh × $4 + 5 read × $0.20 + 2 write × $5 + 7 out × $20 per million = $0.000191 per fixture response.194        try await registry.upsert(ProviderConfiguration(id: "a", family: .anthropic, model: "claude-opus-5-5", limits: ProviderLimits(monthlyBudgetUSD: 0.0003)))195        try await registry.setAPIKey(testKey, for: "a")196        let provider = try await registry.provider(for: "a")197        let request = provider.request(messages: [.user("Hi")])198        _ = try await provider.complete(request)199        #expect(abs(await registry.monthToDate(for: "a").estimatedCostUSD - 0.000191) < 1e-12)200        _ = try await provider.complete(request)   // $0.000191 < $0.0003: still allowed201        let (_, error) = await collect(provider.stream(request))202        guard case .limitExceeded(let message) = error else { Issue.record("expected limitExceeded, got \(String(describing: error))"); return }203        #expect(message.contains("monthly budget"))204        #expect(message.contains("estimated"))205        #expect(test.transport.requests.count == 2)206        // A new calendar month starts a new budget.207        clock.mutate { $0 += 40 * 86_400 }208        _ = try await provider.complete(request)209        #expect(test.transport.requests.count == 3)210    }211212    // MARK: Accounting213214    @Test func usageIsRecordedPerProviderAndPerSpace() async throws {215        let test = TestEnvironment([.sse(HTTPFamily.anthropic.textStream), .sse(HTTPFamily.anthropic.toolStream)])216        let ledger = InMemoryUsageLedger()217        let registry = registry(test, ledger: ledger)218        try await registry.upsert(ProviderConfiguration(id: "a", family: .anthropic, model: "claude-opus-5-5"))219        try await registry.setAPIKey(testKey, for: "a")220        let research = SpaceID(), personal = SpaceID()221        _ = try await registry.provider(for: "a", space: research).complete(sampleRequest())222        _ = try await registry.provider(for: "a", space: personal).complete(sampleRequest(tools: [sampleTool]))223        let records = await ledger.allRecords()224        #expect(records.map(\.spaceID) == [research, personal])225        #expect(records[0].usage?.inputTokens == 17)226        #expect(records[0].model == "test-model")227        #expect(records[0].cost == nil)   // "test-model" has no price: unknown, not zero228        let bySpace = await ledger.totalsBySpace()229        #expect(bySpace[research]?.outputTokens == 7)230        #expect(bySpace[personal]?.outputTokens == 25)231        #expect(await ledger.totals(providerID: "a").requests == 2)232        #expect(await ledger.totals(providerID: "a").requestsWithUnknownCost == 2)233    }234235    @Test func unreportedUsageIsRecordedAsUnknown() async throws {236        let stream = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"x\"},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n"237        let test = TestEnvironment([.sse(stream)])238        let ledger = InMemoryUsageLedger()239        let registry = registry(test, ledger: ledger)240        try await registry.upsert(ProviderConfiguration(id: "c", family: .compatible, baseURL: "http://localhost:1234/v1", model: "llama3.2"))241        _ = try await registry.provider(for: "c").complete(sampleRequest())242        let totals = await ledger.totals(providerID: "c")243        #expect(totals.requests == 1)244        #expect(totals.requestsWithUnknownUsage == 1)245        #expect(totals.inputTokens == 0 && totals.outputTokens == 0)246        #expect(await ledger.allRecords()[0].usage == nil)247    }248249    @Test func failedRequestsAreRecordedButRefusedOnesAreNot() async throws {250        let test = TestEnvironment([.json(HTTPFamily.openAI.errorBody("bad", type: "authentication_error"), status: 401)])251        let ledger = InMemoryUsageLedger()252        let registry = registry(test, ledger: ledger)253        try await registry.upsert(ProviderConfiguration(id: "o", family: .openAI, model: "m", limits: ProviderLimits(maxRequestsPerMinute: 1)))254        try await registry.setAPIKey(testKey, for: "o")255        let provider = try await registry.provider(for: "o")256        #expect(await collect(provider.stream(sampleRequest())).error == .invalidKey("bad"))257        guard case .limitExceeded = await collect(provider.stream(sampleRequest())).error else { Issue.record("expected limitExceeded"); return }258        #expect(await ledger.totals(providerID: "o").requests == 1)259    }260261    @Test func openRouterLivePricesFeedEstimates() async throws {262        let models = #"{"data":[{"id":"vendor/model-a","pricing":{"prompt":"0.000001","completion":"0.000002"}}]}"#263        let test = TestEnvironment([.json(models)])264        let registry = registry(test)265        try await registry.upsert(ProviderConfiguration(id: "r", family: .openRouter, model: "vendor/model-a"))266        #expect(await registry.estimateCost(usage: ProviderUsage(inputTokens: 1_000_000, outputTokens: 1_000_000), family: .openRouter, model: "vendor/model-a") == nil)267        #expect(try await registry.provider(for: "r").listModels().count == 1)268        let estimate = try #require(await registry.estimateCost(usage: ProviderUsage(inputTokens: 1_000_000, outputTokens: 1_000_000), family: .openRouter, model: "vendor/model-a"))269        #expect(estimate.usd == 3)270        #expect(estimate.label.contains("estimate"))271    }272273    @Test func meteredStreamCancelsTheRequest() async throws {274        let test = TestEnvironment([.init(chunks: [Data("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"}}]}\n\n".utf8)], hangs: true)])275        let registry = registry(test)276        try await registry.upsert(ProviderConfiguration(id: "o", family: .openAI, model: "m"))277        try await registry.setAPIKey(testKey, for: "o")278        let provider = try await registry.provider(for: "o")279        let sawText = Locked(false)280        let consumer = Task {281            do { for try await event in provider.stream(sampleRequest()) { if case .textDelta = event { sawText.set(true) } } } catch {}282        }283        #expect(await eventually { sawText.get() })284        consumer.cancel()285        #expect(await eventually { test.transport.terminatedStreams == 1 })286    }287288    @Test func configurationDescriptionCarriesNoSecret() {289        let configuration = ProviderConfiguration(id: "a", family: .anthropic, displayName: "Claude", model: "claude-opus-5-5")290        #expect(configuration.description == "Claude [anthropic] model=claude-opus-5-5")291        #expect(Mirror(reflecting: configuration).children.allSatisfy { !($0.label ?? "").lowercased().contains("key") })292    }293294    @Test func secretStoreAdapterRoundTrips() async throws {295        let store = InMemorySecretStore()296        let source = SecretStoreSecretSource(store)297        try await source.setSecret(testKey, for: "provider.x.api-key")298        #expect(try await source.secret(for: "provider.x.api-key") == testKey)299        #expect(await store.secretKeys() == ["provider.x.api-key"])300        try await source.deleteSecret(for: "provider.x.api-key")301        #expect(try await source.secret(for: "provider.x.api-key") == nil)302    }303}304
Files main
Menu

Theme