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,151 @@
|
||||
//
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user