Files
museion/MuseionTests/ProviderProbeTransportTests.swift
T
AlexKucera b2db859887
CI / ci (push) Canceled after 0s
feat(settings): add Nous Portal provider (#175)
Settings gains hermes' `nous` slug as a fourth provider on every
surface and the Provider Keys page — endpoint
https://inference-api.nousresearch.com/v1, NOUS_API_KEY, the
5-level OpenAI-compatible effort ladder, switch flagship
anthropic/claude-sonnet-5 (live-probed: the portal's docs-listed
Hermes-4 ids 404 — the inference API serves the OpenRouter catalog,
so the switch keeps the app's sonnet posture billed through Nous).
The probe speaks plain OpenAI chat-completions; an unkeyed test
borrows the shared Portal session's agent_key (the engine's own
credential — hermes' nous runtime is OAuth-only, and a portal key
and subscription bill the same account credits), gated to the
official https endpoint so the implicit credential never rides a
user-edited URL. Pass readiness rides the same fallback, so a
logged-in machine runs passes with no key. Suite 635.

Closes #175
2026-11-05 15:59:41 +01:00

171 lines
7.7 KiB
Swift

//
// ProviderProbeTransportTests.swift
// MuseionTests
//
// #136 (Profiles S3) — the Test Connection probe's REQUEST shapes and the
// transport-driven flow, split from ProviderProbeTests (type-body ceiling,
// MCPToolsPromoteTests precedent): the per-provider auth/wire pins and
// probe() over canned transports (no-key fail-fast, end-to-end works,
// /models auth short-circuit, transport errors → unreachable).
//
import Foundation
@testable import Museion
import Testing
@Suite("ProviderProbeTransportTests")
struct ProviderProbeTransportTests {
// MARK: Requests (auth + wire shapes per factsheet)
/// 2026-10-28 live incident, pinned for all three providers: without
/// Content-Type the request reads as form-urlencoded — z.ai answers 200
/// + an error envelope, OpenAI can't parse the body.
@Test func `every chat request carries the json content type`() throws {
for provider in ModelProvider.allCases {
let config = ProviderProbe.Config(provider: provider, endpoint: provider.defaultEndpoint, apiKey: "k", model: "m")
let request = try #require(ProviderProbe.makeChatRequest(config))
#expect(request.value(forHTTPHeaderField: "Content-Type") == "application/json")
}
}
@Test func `anthropic requests auth via header with a pinned version and required max_tokens`() throws {
let config = ProviderProbe.Config(
provider: .anthropic, endpoint: "https://api.anthropic.com", apiKey: "sk-ant", model: "claude-sonnet-5-5",
)
let request = try #require(ProviderProbe.makeChatRequest(config))
#expect(request.value(forHTTPHeaderField: "x-api-key") == "sk-ant")
#expect(request.value(forHTTPHeaderField: "anthropic-version") == "2023-06-01")
#expect(request.value(forHTTPHeaderField: "Authorization") == nil)
let body = try #require(request.httpBody)
#expect(try #require(String(bytes: body, encoding: .utf8)).contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#))
}
@Test func `zai chat carries the stable glm wire format and bearer auth`() throws {
let config = ProviderProbe.Config(
provider: .zai, endpoint: ZaiKeyType.coding.endpoint, apiKey: "sk-zai", model: "glm-5.3",
)
let request = try #require(ProviderProbe.makeChatRequest(config))
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer sk-zai")
let bodyData = try #require(request.httpBody)
let body = try #require(String(bytes: bodyData, encoding: .utf8))
#expect(body.contains(#""thinking":{"type":"enabled"}"#))
#expect(body.contains(#""reasoning_effort":"low""#)) // keeps thinking minimal
// The cap is 512 — the live 2026-10-28 tail proved 64 starves
// glm-5.3 (reasoning_tokens 64/64, finish=length, no content).
#expect(body.contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#))
#expect(request.url?.absoluteString == "\(ZaiKeyType.coding.endpoint)/chat/completions")
}
/// #175: Nous Portal is plain OpenAI chat-completions on the wire —
/// live-probed 2026-11-05 (messages body answers finish=stop; the
/// portal router has no z.ai-style thinking knobs) — Bearer auth like
/// z.ai/openai, `/chat/completions` + `/models` on the versioned base.
@Test func `nous chat speaks the plain chat completions dialect`() throws {
let config = ProviderProbe.Config(
provider: .nous, endpoint: ModelProvider.nous.defaultEndpoint, apiKey: "sk-nous", model: "anthropic/claude-sonnet-5",
)
let request = try #require(ProviderProbe.makeChatRequest(config))
#expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer sk-nous")
#expect(request.url?.absoluteString == "https://inference-api.nousresearch.com/v1/chat/completions")
#expect(ProviderProbe.modelsURL(for: .nous, endpoint: ModelProvider.nous.defaultEndpoint)?
.absoluteString == "https://inference-api.nousresearch.com/v1/models")
let bodyData = try #require(request.httpBody)
let body = try #require(String(bytes: bodyData, encoding: .utf8))
#expect(body.contains(#""messages""#))
#expect(body.contains(#""max_tokens":\#(ProviderProbe.probeTokenCap)"#))
#expect(!body.contains("thinking")) // no z.ai reasoning knobs on the portal router
#expect(!body.contains("reasoning_effort"))
}
@Test func `openai chat speaks the responses api and urls append cleanly`() throws {
let config = ProviderProbe.Config(
provider: .openaiAPI, endpoint: "https://api.openai.com/v1/", apiKey: "sk-oai", model: "gpt-6.1-sol",
)
let request = try #require(ProviderProbe.makeChatRequest(config))
let bodyData = try #require(request.httpBody)
let body = try #require(String(bytes: bodyData, encoding: .utf8))
// Responses dialect (2026-10-28 maintainer correction): input +
// max_output_tokens; the chat-completions params never ride.
#expect(body.contains(#""input":"hi""#))
#expect(body.contains(#""max_output_tokens":\#(ProviderProbe.probeTokenCap)"#))
#expect(body.contains(#""model":"gpt-6.1-sol""#))
#expect(!body.contains("messages")) // chat-completions is the retired path
#expect(!body.contains("max_completion_tokens"))
#expect(!body.contains(#""max_tokens":"#)) // any max_tokens form
#expect(request.url?.absoluteString == "https://api.openai.com/v1/responses")
#expect(ProviderProbe.chatURL(for: .anthropic, endpoint: "https://api.anthropic.com")?
.absoluteString == "https://api.anthropic.com/v1/messages")
#expect(ProviderProbe.chatURL(for: .zai, endpoint: "not a url") == nil) // garbage endpoint, no trap
}
// MARK: probe() over a canned transport
@Test func `probe without a key fails fast without touching the network`() async {
let outcome = await ProviderProbe.probe(
ProviderProbe.Config(provider: .anthropic, endpoint: "https://api.anthropic.com", apiKey: "", model: "m"),
transport: { _ in
Issue.record("transport must not be called without a key")
throw URLError(.badURL)
},
)
guard case .authFailed = outcome else {
Issue.record("expected authFailed precondition, got \(outcome)")
return
}
}
@Test func `probe works end to end with models count`() async {
let zaiWorks = """
data: {"choices":[{"delta":{"content":"Hi"},"finish_reason":null}]}
data: {"choices":[{"delta":{},"finish_reason":"stop"}]}
data: [DONE]
"""
let outcome = await ProviderProbe.probe(
ProviderProbe.Config(provider: .zai, endpoint: ZaiKeyType.standard.endpoint, apiKey: "sk-zai", model: "glm-5.3"),
transport: { request in
if request.url!.path.hasSuffix("/models") {
return (probeData(#"{"object":"list","data":[{},{},{}]}"#), probeHTTPResponse(200))
}
return (Data(zaiWorks.utf8), probeHTTPResponse(200))
},
)
guard case let .works(latencyMS, modelCount) = outcome else {
Issue.record("expected works, got \(outcome)")
return
}
#expect(modelCount == 3)
#expect(latencyMS >= 0)
}
@Test func `probe short-circuits on a models auth failure and reports transport errors unreachable`() async {
let authRejected = await ProviderProbe.probe(
ProviderProbe.Config(provider: .openaiAPI, endpoint: "https://api.openai.com/v1", apiKey: "bad", model: "gpt-5.6-sol"),
transport: { request in
if request.url!.path.hasSuffix("/models") {
return (
probeData(#"{"error":{"message":"Incorrect API key","code":"invalid_api_key"}}"#),
probeHTTPResponse(401),
)
}
Issue.record("chat must not run after /models rejected the key")
return (Data(), probeHTTPResponse(200))
},
)
guard case .authFailed = authRejected else {
Issue.record("expected authFailed, got \(authRejected)")
return
}
let offline = await ProviderProbe.probe(
ProviderProbe.Config(provider: .anthropic, endpoint: "https://api.anthropic.com", apiKey: "sk-ant", model: "m"),
transport: { _ in throw URLError(.cannotConnectToHost) },
)
guard case .unreachable = offline else {
Issue.record("expected unreachable, got \(offline)")
return
}
}
}