Files
museion/MuseionTests/SettingsModelTests.swift
T
AlexKucera 5ad605eb3c 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
2026-10-27 18:32:30 +01:00

378 lines
16 KiB
Swift

//
// SettingsModelTests.swift
// MuseionTests
//
// #135 (Profiles S2) — the Settings page's view-model mapping: provider →
// effort options, custom-model state, key-type → endpoint family, and the
// write-path seam S3 implements.
//
// #136 (Profiles S3) — the real write path's model side: hydration reads
// each profile's model block (unknown providers stay seeded), key writes
// land in all three .env files (no switch re-fire — they pre-land),
// rapid edits coalesce per target (partial key prefixes never spawn),
// and Test Connection fails fast without a key.
//
// Scenario: Provider pins its effort ladder — Given a surface page whose
// provider is known, when the reasoning-effort menu builds (or the provider
// switches), then the menu offers exactly that provider's ladder — z.ai
// low/high/max, OpenAI + Anthropic low/medium/high/xhigh/max — always led
// by "unset · provider default" (one model.reasoning_effort key, nil).
//
// Scenario: Custom is the default state — Given the #132 seed
// claude-sonnet-5-5 (NOT in hermes' registry cache), when a surface page
// opens, then the model reads as custom (not in registry); a provider
// switch lands on that provider's pinned default model with effort reset;
// an empty registry leaves every model custom (free text is first-class).
//
// Scenario: z.ai key type picks the endpoint family — Given the Provider
// Keys page, when the key-type toggle flips, then the endpoint swaps
// /api/paas/v4 ↔ /api/coding/paas/v4 — unless the writer typed a custom
// endpoint, which survives the toggle.
//
// Scenario: Changes route through the write path — Given any Settings
// change, when it commits, then the injectable writer receives it (S3's
// seam: `hermes config set` for surface model blocks, `.env` fan-out for
// provider keys); a FAILED write surfaces its reason in the strip and the
// next successful write clears it.
//
// Scenario: Hydrated config can be stale — Given a surface whose stored
// effort sits outside its provider's ladder (a hand-edited config.yaml S3
// will read), when the page renders, then the read boundary clamps the
// effort to unset rather than show a blank menu selection.
//
import AppKit
import Foundation
@testable import Museion
import Testing
/// Records write-path calls; the injected seam's test double.
@MainActor
final class RecordingWriter: SettingsWriting {
/// A labeled record, not a tuple — SwiftLint's `large_tuple` (the #134
/// ConfigWrite precedent).
struct KeyWriteRecord: Equatable {
let provider: ModelProvider
let config: ProviderKeyConfig
let profiles: [ProfileSurface]
}
struct SurfaceWriteRecord: Equatable {
let surface: ProfileSurface
let config: SurfaceModelConfig
let zaiEndpoint: String?
}
var surfaces: [SurfaceWriteRecord] = []
var keys: [KeyWriteRecord] = []
/// Knob: surface writes throw while set (the failure-path tests).
var failSurfaceWrites = false
/// #136: canned readSurface results — the hydration tests' truth.
var cannedReads: [ProfileSurface: (SurfaceModelConfig, String?)] = [:]
/// #136: canned persisted keys for readProviderKey.
var cannedKeys: [ModelProvider: String] = [:]
/// 2026-10-28 audit pins: one-shot — the NEXT writeSurface suspends
/// until releaseHolds() (the write-ordering pin: the successor must
/// queue behind the in-flight write); latched — EVERY readSurface
/// suspends until releaseHolds() (the hydrate-race pin).
var holdFirstWrite = false
var holdReads = false
private var released = false
private var writeHold: CheckedContinuation<Void, Never>?
private var readHolds: [CheckedContinuation<Void, Never>] = []
func releaseHolds() {
released = true
writeHold?.resume()
writeHold = nil
readHolds.forEach { $0.resume() }
readHolds.removeAll()
}
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig, zaiEndpoint: String?) async throws {
if failSurfaceWrites {
throw NSError(domain: "test", code: 1, userInfo: [NSLocalizedDescriptionKey: "config set failed"])
}
if holdFirstWrite, !released {
holdFirstWrite = false
await withCheckedContinuation { writeHold = $0 }
}
surfaces.append(SurfaceWriteRecord(surface: surface, config: config, zaiEndpoint: zaiEndpoint))
}
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, profiles: [ProfileSurface]) async throws {
keys.append(KeyWriteRecord(provider: provider, config: config, profiles: profiles))
}
func readSurface(_ surface: ProfileSurface) async throws -> (config: SurfaceModelConfig, baseURL: String?)? {
if holdReads, !released {
await withCheckedContinuation { readHolds.append($0) }
}
return cannedReads[surface]
}
func readProviderKey(provider: ModelProvider) async throws -> String? {
cannedKeys[provider]
}
}
/// The real cache's shape, subset — shared with SettingsModelWritePathTests
/// (shared-helper convention; claude-sonnet-5-5 deliberately absent —
/// custom is the default state).
func liveShapedRegistry() -> ModelRegistry {
ModelRegistry(models: [
.zai: ["glm-4.5", "glm-5", "glm-5.3", "glm-5.3-flashx"],
.anthropic: ["claude-fable-5.1", "claude-opus-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
.openaiAPI: ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4-mini"],
])
}
@Suite("SettingsModelTests")
struct SettingsModelTests {
// MARK: Provider → effort options
@Test func `provider pins its effort ladder`() {
#expect(ModelProvider.zai.effortOptions == [.low, .high, .max])
#expect(ModelProvider.openaiAPI.effortOptions == [.low, .medium, .high, .xhigh, .max])
#expect(ModelProvider.anthropic.effortOptions == [.low, .medium, .high, .xhigh, .max])
}
@Test @MainActor func `effort unset is the leading default state`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
for surface in ProfileSurface.allCases {
#expect(model.config(for: surface).effort == nil)
}
}
@Test @MainActor func `provider switch rebuilds the effort menu and resets effort`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
model.setEffort(.max, for: .pass1)
model.setProvider(.zai, for: .pass1)
// zai's ladder drops xhigh/medium — the menu rebuilds from the new
// provider and the old choice must not survive as residue.
#expect(model.config(for: .pass1).effort == nil)
#expect(model.config(for: .pass1).provider == .zai)
}
// MARK: Custom-model state
@Test @MainActor func `the seeded sonnet model reads as custom not in registry`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
#expect(model.config(for: .pass1).model == ProfileSurface.defaultModelID)
#expect(model.isCustom(.pass1))
#expect(model.isCustom(.pass2))
#expect(model.isCustom(.chat))
// One seed truth: the Settings seed provider must stay the provisioner's
// #132 seed provider (defaultModelProvider) — Restore Defaults and
// fresh provisioning diverge silently if these drift apart.
#expect(SurfaceModelConfig.surfaceDefault.provider.rawValue == ProfileSurface.defaultModelProvider)
}
@Test @MainActor func `a registry model reads as known`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
// Chat's provider is anthropic by default — an in-registry id reads known.
model.setModel("claude-sonnet-5", for: .chat)
#expect(!model.isCustom(.chat))
}
@Test @MainActor func `provider switch lands on the provider's pinned default model`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
model.setProvider(.zai, for: .chat)
#expect(model.config(for: .chat).model == "glm-5.3")
#expect(!model.isCustom(.chat))
model.setProvider(.openaiAPI, for: .chat)
#expect(model.config(for: .chat).model == "gpt-6.1-sol")
model.setProvider(.anthropic, for: .chat)
#expect(model.config(for: .chat).model == "claude-sonnet-5")
}
@Test @MainActor func `an empty registry leaves every model custom free text stays first class`() {
let model = SettingsModel(registry: ModelRegistry(), writer: RecordingWriter(), writeDebounce: 0)
#expect(model.isCustom(.pass1))
model.setModel("any-model-id-anyone-types", for: .pass1)
#expect(model.config(for: .pass1).model == "any-model-id-anyone-types")
#expect(model.isCustom(.pass1))
}
@Test @MainActor func `blank model edits never commit`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
model.setModel(" ", for: .pass2)
#expect(model.config(for: .pass2).model == ProfileSurface.defaultModelID)
}
// MARK: Restore Defaults
@Test @MainActor func `reset returns a changed surface to the seed and persists it`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
model.setProvider(.zai, for: .pass2)
model.setEffort(.max, for: .pass2)
await model.awaitPendingWrites()
// #136: rapid successive edits coalesce per target — ONE write with
// the final value (a superseded write never spawns).
#expect(writer.surfaces.count == 1)
#expect(writer.surfaces[0].config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .max))
model.resetToDefault(for: .pass2)
await model.awaitPendingWrites()
#expect(model.config(for: .pass2) == SurfaceModelConfig(provider: .anthropic, model: ProfileSurface.defaultModelID, effort: nil))
#expect(writer.surfaces.count == 2)
// Already at the seed — a second reset is a no-op, no write.
model.resetToDefault(for: .pass2)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 2)
}
// MARK: Key-type → endpoint family
@Test func `zai key type maps to its endpoint family`() {
#expect(ZaiKeyType.standard.endpoint == "https://api.z.ai/api/paas/v4")
#expect(ZaiKeyType.coding.endpoint == "https://api.z.ai/api/coding/paas/v4")
}
@Test @MainActor func `zai toggle swaps the endpoint family`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.standard.endpoint)
model.setZaiKeyType(.coding)
#expect(model.zaiKeyType == .coding)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
model.setZaiKeyType(.standard)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.standard.endpoint)
}
@Test @MainActor func `a custom zai endpoint survives the toggle`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
model.setEndpoint("https://proxy.internal:8443/v4", for: .zai)
model.setZaiKeyType(.coding)
#expect(model.keyConfig(for: .zai).endpoint == "https://proxy.internal:8443/v4")
}
@Test @MainActor func `a cleared zai endpoint still adopts the new family`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), writeDebounce: 0)
model.setEndpoint("", for: .zai)
model.setZaiKeyType(.coding)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
}
// MARK: Write-path seam
@Test @MainActor func `surface changes route through the writer`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
model.setProvider(.zai, for: .pass1)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 1)
let record = writer.surfaces[0]
#expect(record.surface == .pass1)
#expect(record.config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
// A zai surface ALWAYS carries the endpoint family (written last —
// setting model.provider clears a stale base_url); the standard
// key type's family at the seed.
#expect(record.zaiEndpoint == ZaiKeyType.standard.endpoint)
}
@Test @MainActor func `key changes route through the writer per provider`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
model.setZaiKeyType(.coding)
model.setAPIKey("sk-test", for: .anthropic)
await model.awaitPendingWrites()
#expect(writer.keys.count == 2)
let first = writer.keys[0]
#expect(first.provider == .zai)
// The endpoint field carries the family (keyType's job, 2026-10-28
// audit: the dead param is gone).
#expect(first.config.endpoint == ZaiKeyType.coding.endpoint)
let second = writer.keys[1]
#expect(second.provider == .anthropic)
}
@Test @MainActor func `a failed write surfaces lastWriteError and a later success clears it`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer, writeDebounce: 0)
writer.failSurfaceWrites = true
model.setModel("glm-5.3", for: .chat)
await model.awaitPendingWrites()
#expect(model.lastWriteError == "config set failed")
writer.failSurfaceWrites = false
model.setModel("claude-sonnet-5", for: .chat)
await model.awaitPendingWrites()
#expect(model.lastWriteError == nil)
// The failed write never landed; the successful one did.
#expect(writer.surfaces.count == 1)
}
// MARK: Hydration clamp
@Test @MainActor func `an effort outside the provider's ladder reads clamped to unset`() {
// S3 will hydrate from config.yaml a user may have hand-edited —
// zai carries no `medium` rung, so the read boundary drops it rather
// than render a blank menu selection.
let stale = SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .medium)
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), surfaces: [.pass1: stale])
#expect(model.config(for: .pass1).effort == nil)
// An in-ladder effort passes through untouched.
let valid = SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5", effort: .medium)
let model2 = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), surfaces: [.pass2: valid])
#expect(model2.config(for: .pass2).effort == .medium)
}
// MARK: Model combobox wiring (dogfood fix #135)
@Test @MainActor func `combobox list pick action and end editing all commit`() {
// The bug (probe-observed): comboBoxSelectionDidChange fires BEFORE
// stringValue updates — the handler must take the pick from the
// selection index; Enter (action) and blur (end-editing) read the
// settled stringValue.
let box = NSComboBox()
box.addItems(withObjectValues: ["glm-4.5", "glm-5.2"])
box.selectItem(at: 1)
box.stringValue = "glm-4.5" // the stale value AppKit still holds at notification time
var committed: [String] = []
let coordinator = ModelComboBox.Coordinator { committed.append($0) }
coordinator.lastLocalValue = "glm-4.5"
coordinator.comboBoxSelectionDidChange(
Notification(name: Notification.Name("ComboBoxSelectionDidChangeNotification"), object: box),
)
#expect(committed == ["glm-5.2"]) // the PICKED item, not the stale string
#expect(box.stringValue == "glm-5.2") // the handler re-syncs the box
// Idempotent: the re-sync and the follow-up events never double-commit.
coordinator.picked(box)
coordinator.controlTextDidEndEditing(
Notification(name: Notification.Name("NSTextDidEndEditingNotification"), object: box),
)
#expect(committed == ["glm-5.2"])
// Enter/action on a NEW value commits through the same rail.
box.stringValue = "glm-5.1"
coordinator.picked(box)
#expect(committed == ["glm-5.2", "glm-5.1"])
// Blank edits never commit.
box.stringValue = " "
coordinator.picked(box)
#expect(committed == ["glm-5.2", "glm-5.1"])
}
// MARK: Registry loading
@Test func `registry loads from hermes' picker cache leniently`() {
let path = (NSTemporaryDirectory() as NSString)
.appendingPathComponent("settings-registry-\(UUID().uuidString).json")
let json = """
{"zai": {"fp": "abc", "at": 123, "models": ["glm-5.3"]},
"openai-api": {"fp": "def", "at": 123, "models": ["gpt-5.6-sol"]},
"unknown-provider": {"fp": "x", "at": 1, "models": ["whatever"]}}
"""
try? json.write(toFile: path, atomically: true, encoding: .utf8)
let registry = ModelRegistry.load(path: path)
#expect(registry.list(for: .zai) == ["glm-5.3"])
#expect(registry.list(for: .openaiAPI) == ["gpt-5.6-sol"])
#expect(registry.list(for: .anthropic) == [])
// Unknown providers and an unreadable file degrade to free-text-only.
#expect(registry.list(for: .anthropic)
== ModelRegistry.load(path: "/nonexistent/cache.json").list(for: .anthropic))
}
}