CI / ci (push) Canceled after 0s
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
287 lines
13 KiB
Swift
287 lines
13 KiB
Swift
//
|
|
// SettingsModelWritePathTests.swift
|
|
// MuseionTests
|
|
//
|
|
// #136 (Profiles S3) — the write path's MODEL-side pins, split from
|
|
// SettingsModelTests (file-length ceiling, own-file precedent): fan-out
|
|
// lists, endpoint threading on a provider switch, per-target write
|
|
// coalescing, hydration mapping, and the no-key Test Connection guard.
|
|
// Shares RecordingWriter + liveShapedRegistry (internal, shared-helper
|
|
// convention).
|
|
//
|
|
|
|
import Foundation
|
|
@testable import Museion
|
|
import Testing
|
|
|
|
@Suite("SettingsModelWritePathTests")
|
|
struct SettingsModelWritePathTests {
|
|
// MARK: #136 — the real write path's model side
|
|
|
|
@Test @MainActor func `provider switch to a keyed zai threads the endpoint without re-firing keys`() async {
|
|
let writer = RecordingWriter()
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
// Key entered while nothing was on z.ai yet — it already landed in
|
|
// ALL THREE .env files (the writer's own test pins that), so the
|
|
// switch needs no key re-fire.
|
|
model.setAPIKey("sk-z", for: .zai)
|
|
model.setZaiKeyType(.coding)
|
|
await model.awaitPendingWrites()
|
|
// The two rapid edits COALESCE into one key write carrying the
|
|
// final state (key + coding endpoint family).
|
|
#expect(writer.keys.count == 1)
|
|
#expect(writer.keys[0].config.apiKey == "sk-z")
|
|
#expect(writer.keys[0].config.endpoint == ZaiKeyType.coding.endpoint)
|
|
|
|
model.setProvider(.zai, for: .pass1)
|
|
await model.awaitPendingWrites()
|
|
// The surface write carries the endpoint family LAST (setting
|
|
// model.provider clears a stale base_url — live-probed)…
|
|
let surface = writer.surfaces.last
|
|
#expect(surface?.config.provider == .zai)
|
|
#expect(surface?.zaiEndpoint == ZaiKeyType.coding.endpoint)
|
|
// …and no additional key write fired.
|
|
#expect(writer.keys.count == 1)
|
|
}
|
|
|
|
@Test @MainActor func `key writes fan out to the surfaces on that provider`() async {
|
|
let writer = RecordingWriter()
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
model.setProvider(.zai, for: .chat)
|
|
model.setProvider(.zai, for: .pass1)
|
|
await model.awaitPendingWrites()
|
|
model.setAPIKey("sk-z", for: .zai)
|
|
await model.awaitPendingWrites()
|
|
#expect(writer.keys.count == 1)
|
|
// chat first (ProfileSurface.allCases order); pass2 stays anthropic
|
|
// and is NOT in the fan-out.
|
|
#expect(writer.keys[0].profiles == [.chat, .pass1])
|
|
}
|
|
|
|
@Test @MainActor func `rapid key edits coalesce into one write with the final value`() async {
|
|
let writer = RecordingWriter()
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0.05)
|
|
model.setAPIKey("s", for: .anthropic)
|
|
model.setAPIKey("sk", for: .anthropic)
|
|
model.setAPIKey("sk-", for: .anthropic)
|
|
await model.awaitPendingWrites()
|
|
// A superseded write never spawns — partial key prefixes must not
|
|
// reach .env (the #135 finish-audit contract, now model-owned).
|
|
#expect(writer.keys.count == 1)
|
|
#expect(writer.keys[0].config.apiKey == "sk-")
|
|
}
|
|
|
|
@Test @MainActor func `hydrate maps profile reads and infers the zai key type`() async {
|
|
let writer = RecordingWriter()
|
|
writer.cannedReads[.chat] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), ZaiKeyType.coding.endpoint)
|
|
writer.cannedReads[.pass1] = (SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5-5", effort: .low), nil)
|
|
writer.cannedKeys[.zai] = "sk-stored"
|
|
// pass2 absent = unreadable/unknown provider — stays seeded.
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
await model.hydrate()
|
|
#expect(model.config(for: .chat) == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
|
|
#expect(model.config(for: .pass1).effort == .low)
|
|
#expect(model.config(for: .pass2) == .surfaceDefault)
|
|
// The coding base_url infers the key type + endpoint family.
|
|
#expect(model.zaiKeyType == .coding)
|
|
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
|
|
// Keys persist in the .env files — hydrate refills the field (a
|
|
// restart neither blanks the UI nor refuses Test Connection).
|
|
#expect(model.keyConfig(for: .zai).apiKey == "sk-stored")
|
|
}
|
|
|
|
@Test @MainActor func `a second edit waits for the in-flight write before replacing it`() async {
|
|
// 2026-10-28 audit pin: cancellation can't stop a past-the-guard
|
|
// write, so the newer write must QUEUE — the last edit is always
|
|
// the last write to land. Without the chain the successor records
|
|
// FIRST (["new", "old"]) and disk ends at the stale value.
|
|
let writer = RecordingWriter()
|
|
writer.holdFirstWrite = true
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
model.setModel("old", for: .chat) // task A
|
|
await Task.yield() // let A pass its debounce guard and consume the hold
|
|
model.setModel("new", for: .chat) // task B: cancels A (past its guard — a no-op), must wait
|
|
writer.releaseHolds()
|
|
await model.awaitPendingWrites()
|
|
#expect(writer.surfaces.map(\.config.model) == ["old", "new"])
|
|
}
|
|
|
|
@Test @MainActor func `hydrate never stomps an edit made while it was reading`() async {
|
|
// 2026-10-28 audit pin: hydration spans seconds of CLI reads; an
|
|
// edit that fires mid-read owns the truth — applying the stale
|
|
// read would revert the UI and the next edit would persist from
|
|
// the stale base.
|
|
let writer = RecordingWriter()
|
|
writer.cannedReads[.chat] = (SurfaceModelConfig(provider: .zai, model: "glm-old", effort: nil), nil)
|
|
writer.holdReads = true
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
let hydrating = Task { await model.hydrate() }
|
|
model.setModel("glm-new", for: .chat) // the user edits mid-read
|
|
writer.releaseHolds()
|
|
await hydrating.value
|
|
#expect(model.config(for: .chat).model == "glm-new")
|
|
}
|
|
|
|
@Test @MainActor func `hydrate seeds a custom zai base url instead of clobbering it`() async {
|
|
// 2026-10-28 audit pin: only the coding family maps back to the
|
|
// key type; any OTHER non-empty base_url seeds the endpoint field,
|
|
// so the next zai write-through threads the custom endpoint —
|
|
// never a family default over the user's URL.
|
|
let writer = RecordingWriter()
|
|
writer.cannedReads[.chat] = (SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil), "https://proxy.example/api/paas/v4")
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
await model.hydrate()
|
|
#expect(model.keyConfig(for: .zai).endpoint == "https://proxy.example/api/paas/v4")
|
|
model.setAPIKey("sk-z", for: .zai)
|
|
await model.awaitPendingWrites()
|
|
#expect(writer.keys.last?.config.endpoint == "https://proxy.example/api/paas/v4")
|
|
}
|
|
|
|
@Test @MainActor func `connection without a key fails fast off the network`() async {
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
|
await model.testConnection(for: .anthropic)
|
|
guard case let .done(outcome) = model.testStates[.anthropic], case .authFailed = outcome else {
|
|
Issue.record("expected the empty-key precondition to authFail, got \(String(describing: model.testStates[.anthropic]))")
|
|
return
|
|
}
|
|
// The probe model: a surface on the provider rides, else flagship.
|
|
#expect(model.probeModel(for: .anthropic) == ProfileSurface.defaultModelID)
|
|
#expect(model.probeModel(for: .zai) == ModelProvider.zai.switchDefaultModel)
|
|
}
|
|
|
|
// Scenario: Nous Portal as a fourth provider — From user story #175
|
|
// Given Hermes' own registry offers the `nous` slug (OpenAI-compatible
|
|
// inference API — one account bill behind key and subscription alike)
|
|
// When Settings offers Nous Portal
|
|
// Then the pinned facts match the live-probed wire: the portal inference
|
|
// endpoint, the env var hermes' tooling maps the slug to, and the label.
|
|
@Test func `nous provider facts pin the portal wire`() {
|
|
#expect(ModelProvider.nous.rawValue == "nous")
|
|
#expect(ModelProvider.nous.label == "Nous Portal")
|
|
#expect(ModelProvider.nous.defaultEndpoint == "https://inference-api.nousresearch.com/v1")
|
|
#expect(ModelProvider.nous.envVarName == "NOUS_API_KEY")
|
|
}
|
|
|
|
// Scenario: Test Connection on an unkeyed Nous Portal — From user story #175
|
|
// Given hermes logged into the Nous Portal (the shared auth.json session —
|
|
// the engine's own credential; API key and subscription bill the same
|
|
// account credits)
|
|
// When the user tests Nous with no key pasted
|
|
// Then the probe borrows the session's agent_key as its Bearer — and with
|
|
// no session either, it names the portal login path, not a bare "no key".
|
|
@Test @MainActor func `nous connection borrows the shared portal session key`() async throws {
|
|
final class AuthSaw: @unchecked Sendable { var header: String? }
|
|
let saw = AuthSaw()
|
|
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-auth-\(UUID().uuidString)")
|
|
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
|
let authPath = dir.appendingPathComponent("auth.json").path
|
|
try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8)
|
|
|
|
let model = SettingsModel(
|
|
registry: liveShapedRegistry(),
|
|
writer: RecordingWriter(),
|
|
writeDebounce: 0,
|
|
probeTransport: { request in
|
|
saw.header = request.value(forHTTPHeaderField: "Authorization")
|
|
if request.url!.path.hasSuffix("/models") {
|
|
return (probeData(#"{"object":"list","data":[{},{},{},{}]}"#), probeHTTPResponse(200))
|
|
}
|
|
return (
|
|
Data("data: {\"choices\":[{\"delta\":{\"content\":\"Hi\"},\"finish_reason\":\"stop\"}]}\n\n".utf8),
|
|
probeHTTPResponse(200),
|
|
)
|
|
},
|
|
portalAuthPath: authPath,
|
|
)
|
|
await model.testConnection(for: .nous)
|
|
#expect(saw.header == "Bearer ak-shared-123")
|
|
guard case let .done(outcome) = model.testStates[.nous], case .works = outcome else {
|
|
Issue.record("expected works over the session key, got \(String(describing: model.testStates[.nous]))")
|
|
return
|
|
}
|
|
}
|
|
|
|
/// Finish-audit #175: the implicit session credential never rides a
|
|
/// hand-edited endpoint — a custom endpoint with an empty key refuses
|
|
/// before any network, pointing at the key field.
|
|
@Test @MainActor func `nous session key never rides a custom endpoint`() async throws {
|
|
let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nous-gate-\(UUID().uuidString)")
|
|
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
|
|
let authPath = dir.appendingPathComponent("auth.json").path
|
|
try #"{"providers":{"nous":{"agent_key":"ak-shared-123"}}}"#.write(toFile: authPath, atomically: true, encoding: .utf8)
|
|
|
|
let model = SettingsModel(
|
|
registry: liveShapedRegistry(),
|
|
writer: RecordingWriter(),
|
|
writeDebounce: 0,
|
|
probeTransport: { _ in
|
|
Issue.record("a custom endpoint must never receive the session key")
|
|
throw URLError(.badURL)
|
|
},
|
|
portalAuthPath: authPath,
|
|
)
|
|
model.setEndpoint("http://proxy.example/v1", for: .nous)
|
|
await model.testConnection(for: .nous)
|
|
guard case let .done(outcome) = model.testStates[.nous], case let .authFailed(detail) = outcome else {
|
|
Issue.record("expected the custom-endpoint refusal, got \(String(describing: model.testStates[.nous]))")
|
|
return
|
|
}
|
|
#expect(detail.contains("paste an API key"))
|
|
}
|
|
|
|
@Test @MainActor func `nous connection with no key and no login names the portal path`() async {
|
|
let missing = FileManager.default.temporaryDirectory
|
|
.appendingPathComponent("nous-auth-missing-\(UUID().uuidString)").path
|
|
let model = SettingsModel(
|
|
registry: liveShapedRegistry(),
|
|
writer: RecordingWriter(),
|
|
writeDebounce: 0,
|
|
portalAuthPath: missing,
|
|
)
|
|
await model.testConnection(for: .nous)
|
|
guard case let .done(outcome) = model.testStates[.nous], case let .authFailed(detail) = outcome else {
|
|
Issue.record("expected authFailed, got \(String(describing: model.testStates[.nous]))")
|
|
return
|
|
}
|
|
#expect(detail.contains("hermes auth add nous"))
|
|
}
|
|
|
|
// Scenario: Saving a Chat model change reaches the resident engine
|
|
// From user story #137 acceptance 2
|
|
// Given the Settings pane is open
|
|
// When a Chat surface model write succeeds (provider/model/effort/reset)
|
|
// Then onChatSurfaceWrite fires after the write lands — pass-surface
|
|
// writes and key writes never fire it, and failed writes don't either.
|
|
|
|
@Test @MainActor func `a successful chat surface write fires onChatSurfaceWrite`() async {
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
|
var fired = 0
|
|
model.onChatSurfaceWrite = { fired += 1 }
|
|
model.setModel("claude-sonnet-5", for: .chat)
|
|
await model.awaitPendingWrites()
|
|
#expect(fired == 1)
|
|
}
|
|
|
|
@Test @MainActor func `pass surface writes and key writes never fire onChatSurfaceWrite`() async {
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
|
|
var fired = 0
|
|
model.onChatSurfaceWrite = { fired += 1 }
|
|
model.setEffort(.max, for: .pass1)
|
|
model.setAPIKey("sk-a", for: .anthropic)
|
|
await model.awaitPendingWrites()
|
|
#expect(fired == 0)
|
|
}
|
|
|
|
@Test @MainActor func `a failed chat write never fires onChatSurfaceWrite`() async {
|
|
let writer = RecordingWriter()
|
|
writer.failSurfaceWrites = true
|
|
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
|
|
var fired = 0
|
|
model.onChatSurfaceWrite = { fired += 1 }
|
|
model.setModel("claude-sonnet-5", for: .chat)
|
|
await model.awaitPendingWrites()
|
|
#expect(fired == 0)
|
|
#expect(model.lastWriteError != nil)
|
|
}
|
|
}
|