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
269 lines
8.9 KiB
Swift
269 lines
8.9 KiB
Swift
//
|
|
// 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("<html>bad gateway</html>".utf8),
|
|
provider: .anthropic,
|
|
) else {
|
|
Issue.record("expected requestFailed for foreign body")
|
|
return
|
|
}
|
|
#expect(foreignStatus == 502)
|
|
}
|
|
|
|
// MARK: Chat decode — the three SSE dialects
|
|
|
|
@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)
|
|
}
|
|
}
|