// // ProviderProbeTests.swift // MuseionTests // // #136 (Profiles S3) — scenario: // // ## Scenario: Test Connection tells the truth // From user story #136 // Given a provider key and endpoint in Settings // When the user clicks Test Connection // Then the verdict distinguishes works (latency + model count) from // wrong-key-type from unreachable from auth-failed — decoded per the // factsheet envelopes, never gated on status 200 alone (§1.5 starvation // is a 200). // import Foundation @testable import Museion import Testing /// Canned probe responses — free functions shared with /// ProviderProbeTransportTests (shared-helper convention); nonisolated for /// @Sendable transport closures. nonisolated func probeHTTPResponse(_ status: Int) -> HTTPURLResponse { HTTPURLResponse(url: URL(string: "https://api.test/v1")!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: nil)! } nonisolated func probeData(_ json: String) -> Data { Data(json.utf8) } @Suite("ProviderProbeTests") struct ProviderProbeTests { // MARK: Error decode — the factsheet envelopes (§1.6/§2.5/§3.5) @Test func `zai 1113 decodes as wrong key type for this endpoint family`() { let outcome = ProviderProbe.decodeError( status: 403, body: probeData(#"{"error":{"code":"1113","message":"Insufficient balance"}}"#), provider: .zai, ) guard case .wrongKeyType = outcome else { Issue.record("expected wrongKeyType, got \(outcome)") return } } @Test func `zai 401 decodes as auth failed with the provider message`() { let outcome = ProviderProbe.decodeError( status: 401, body: probeData(#"{"error":{"code":"401","message":"token expired or incorrect"}}"#), provider: .zai, ) guard case let .authFailed(detail) = outcome else { Issue.record("expected authFailed, got \(outcome)") return } #expect(detail.contains("token expired")) } @Test func `anthropic auth error carries the request id`() { let outcome = ProviderProbe.decodeError( status: 401, body: probeData(#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"},"request_id":"req_123"}"#), provider: .anthropic, ) guard case let .authFailed(detail) = outcome else { Issue.record("expected authFailed, got \(outcome)") return } #expect(detail.contains("invalid x-api-key")) #expect(detail.contains("req_123")) } @Test func `openai invalid_api_key decodes as auth failed`() { let outcome = ProviderProbe.decodeError( status: 401, body: probeData(#"{"error":{"message":"Incorrect API key","type":"invalid_request_error","param":null,"code":"invalid_api_key"}}"#), provider: .openaiAPI, ) guard case .authFailed = outcome else { Issue.record("expected authFailed, got \(outcome)") return } } @Test func `rate limit and unparseable bodies decode as request failures`() { guard case let .requestFailed(status, detail) = ProviderProbe.decodeError( status: 429, body: probeData(#"{"error":{"message":"rate limited"}}"#), provider: .zai, ) else { Issue.record("expected requestFailed") return } #expect(status == 429) #expect(detail.contains("rate limited")) // Foreign body (HTML error page): the status still names it. guard case let .requestFailed(foreignStatus, _) = ProviderProbe.decodeError( status: 502, body: Data("bad gateway".utf8), provider: .anthropic, ) else { Issue.record("expected requestFailed for foreign body") return } #expect(foreignStatus == 502) } // MARK: Chat decode — the SSE dialects // Scenario: Nous Portal decode — From user story #175 // Given the portal's OpenAI-compatible chat SSE (live-captured // 2026-11-05: delta.content chunks, finish stop) and its bare // {status, message} error envelope (no error object — a bad model id // answers HTTP 404 + message) // When the probe decodes a nous response // Then content decodes works, and the error decodes requestFailed // carrying the portal's own message — never a bare "HTTP 404". @Test func `nous sse decodes works and the portal error envelope carries its message`() { let sse = """ data: {"choices":[{"delta":{"content":"Hi there!"},"finish_reason":null}]} data: {"choices":[{"delta":{},"finish_reason":"stop"}]} data: [DONE] """ guard case .works = ProviderProbe.decodeChat( provider: .nous, body: Data(sse.utf8), modelCount: 385, latencyMS: 900, ) else { Issue.record("expected works over the portal SSE") return } guard case let .requestFailed(status, detail) = ProviderProbe.decodeError( status: 404, body: probeData( #"{"status":404,"message":"Model 'x' not found in our configuration."}"#, ), provider: .nous, ) else { Issue.record("expected requestFailed for the portal envelope") return } #expect(status == 404) #expect(detail.contains("not found")) // Finish-audit #175: the fallback credential's own failure mode — // 401 over the bare envelope decodes authFailed carrying the // message (an expired/revoked agent_key). guard case let .authFailed(authDetail) = ProviderProbe.decodeError( status: 401, body: probeData(#"{"status":401,"message":"token expired"}"#), provider: .nous, ) else { Issue.record("expected authFailed for the bare 401 envelope") return } #expect(authDetail.contains("token expired")) } @Test func `zai sse content decodes works and empty length decodes starved`() { let sse = """ data: {"choices":[{"delta":{"reasoning_content":"thinking…"},"finish_reason":null}]} data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":null}]} data: {"choices":[{"delta":{"content":"!"},"finish_reason":"stop"}]} data: {"choices":[{"delta":{},"finish_reason":null}]} data: [DONE] """ guard case let .works(_, modelCount) = ProviderProbe.decodeChat( provider: .zai, body: Data(sse.utf8), modelCount: 11, latencyMS: 412, ) else { Issue.record("expected works") return } #expect(modelCount == 11) let starved = """ data: {"choices":[{"delta":{"reasoning_content":"…"},"finish_reason":"length"}]} data: [DONE] """ guard case .starved = ProviderProbe.decodeChat( provider: .zai, body: Data(starved.utf8), modelCount: 11, latencyMS: 10, ) else { Issue.record("expected starved (§1.5: 200 + finish=length + empty content)") return } } @Test func `anthropic sse decodes works and starved via stop reasons`() { let sse = """ event: message_start data: {"type":"message_start","message":{}} event: content_block_delta data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hel"}} data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"lo"}} event: message_delta data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}} event: message_stop data: {"type":"message_stop"} """ guard case let .works(_, modelCount) = ProviderProbe.decodeChat( provider: .anthropic, body: Data(sse.utf8), modelCount: 14, latencyMS: 300, ) else { Issue.record("expected works") return } #expect(modelCount == 14) let starved = """ data: {"type":"message_delta","delta":{"stop_reason":"max_tokens"}} """ guard case .starved = ProviderProbe.decodeChat( provider: .anthropic, body: Data(starved.utf8), modelCount: 14, latencyMS: 10, ) else { Issue.record("expected starved") return } } @Test func `openai responses sse decodes works starved and failed`() { // The Responses dialect (2026-10-28 maintainer correction): // response.output_text.delta carries text, response.completed // closes the turn. The leading response.created carries // "error": null on every snapshot — JSON null is not nil, and the // 2026-10-28 dogfood showed a null tripping the envelope check // (healthy stream decoded as "HTTP 200"). let sse = """ event: response.created data: {"type":"response.created","response":{"status":"in_progress","error":null}} event: response.output_text.delta data: {"type":"response.output_text.delta","delta":"Hey"} event: response.completed data: {"type":"response.completed","response":{"status":"completed","error":null}} """ guard case let .works(_, modelCount) = ProviderProbe.decodeChat( provider: .openaiAPI, body: Data(sse.utf8), modelCount: 135, latencyMS: 250, ) else { Issue.record("expected works") return } #expect(modelCount == 135) // Cap starved: incomplete status, no text. let starved = """ data: {"type":"response.incomplete","response":{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"}}} """ guard case .starved = ProviderProbe.decodeChat( provider: .openaiAPI, body: Data(starved.utf8), modelCount: 135, latencyMS: 10, ) else { Issue.record("expected starved for incomplete with no text") return } // response.failed carries response.error — decoded as a request // failure, never a silent "works" on an empty 200. let failed = """ data: {"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"boom"}}} """ guard case let .requestFailed(status, detail) = ProviderProbe.decodeChat( provider: .openaiAPI, body: Data(failed.utf8), modelCount: 135, latencyMS: 10, ) else { Issue.record("expected requestFailed for response.failed") return } #expect(status == 200) #expect(detail.contains("boom")) } @Test func `a 200-carried error envelope decodes as the provider error`() { // Live 2026-10-28: z.ai answers a wrong content-type as HTTP 200 // with a plain-JSON error envelope — the decoder must surface the // provider message, not "no content". let envelope = #"{"error":{"message":"Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported","code":"500"}}"# let body = Data(envelope.utf8) guard case let .requestFailed(status, detail) = ProviderProbe.decodeChat( provider: .zai, body: body, modelCount: 11, latencyMS: 10, ) else { Issue.record("expected requestFailed for the 200 envelope") return } #expect(status == 200) #expect(detail.contains("not supported")) } // MARK: SSE + models parsing (pure) @Test func `sse payloads skip event lines DONE and blanks`() { let payloads = ProviderProbe.ssePayloads(""" event: message_start data: {"a":1} data: [DONE] data: not json """) #expect(payloads.count == 1) } @Test func `models count decodes all three listing shapes`() { #expect(ProviderProbe.decodeModelsCount(probeData(#"{"object":"list","data":[{},{},{}]}"#)) == 3) #expect(ProviderProbe.decodeModelsCount(probeData(#"{"data":[{"id":"claude-haiku-5-5"}]}"#)) == 1) #expect(ProviderProbe.decodeModelsCount(probeData(#"{"data":[]}"#)) == 0) #expect(ProviderProbe.decodeModelsCount(probeData("not json")) == nil) } }