feat(settings): profiles write path + Test Connection (#136)
Profiles S3 over the S2 shell: every Settings change now persists. Model/effort writes ride the engine's own CLI — `hermes -p <profile> config set/unset` for model.provider / model.default / model.reasoning_effort / model.base_url (zai endpoint family written LAST: setting model.provider clears a stale base_url, live-probed; unset-when-absent is idempotent success). Provider keys upsert VAR=value into ALL THREE profiles' .env — a key entered before any surface is on its provider still persists and pre-lands for any later switch (maintainer ruling 2026-10-28; no switch re-fire). 0600, foreign lines preserved byte-for-byte, line-broken values refused at the shared sink (env-file injection guard), NSLock serializes the read-upsert-write across concurrent provider writes. Hydration reads model blocks and keys back at pane open — a restart neither blanks the key fields nor refuses Test Connection; an edit made mid-read owns the truth (no stomp), and a custom z.ai base_url seeds the endpoint field instead of being clobbered to a family default. Per-target writes coalesce AND chain past the debounce guard: cancellation can't stop a past-the-guard CLI write, so the newer write queues — the last edit is always the last write to land (finish-audit race fix, pinned). Test Connection = two-step probe (GET /models, then a minimal streaming chat) with honest decode per the factsheet: zai 1113 → wrong key type, 401s → auth failed (Anthropic request_id), finish=length → starved, empty 200 → request failed, errors riding a 2xx decoded as the provider error. Live-probed wire corrections (dogfood, 2026-10-28): Content-Type application/json on every request — URLSession defaults to form-urlencoded and providers diverge (zai 200+envelope, OpenAI 400, Anthropic tolerates); OpenAI speaks the Responses API (/responses, input + max_output_tokens, flagship gpt-6.1-sol); probe token cap 512 (64 starved reasoning models into "no content"); OpenAI's "error": null event snapshots don't decode as failures. Finish-audit (ponytail + security + general reviewers): write-ordering race + .env lost update + hydrate stomp + custom-endpoint clobber fixed and pinned (one-shot hold / latched read knobs in the test double); ~30 lines of dead flexibility cut (keyType protocol param, works(reply:) payload, unused timeout knob, double JSON round trips). Suite 468/468 xcresult-verified; swiftlint clean; factsheet §6 correction logged. Closes #136
This commit is contained in:
1 parent
42a27cc8a3
commit
5ad605eb3c
20 files changed
+1983
-161
No files matched your search
@@ -0,0 +1,149 @@
|
||||
//
|
||||
// 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")
|
||||
}
|
||||
|
||||
@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
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user