Files
museion/MuseionTests/SettingsModelTests.swift
T
AlexKucera 42a27cc8a3
CI / ci (push) Canceled after 0s
feat(settings): sidebar + detail Settings page (#135)
Profiles S2 over the variant C verdict (#130): Settings becomes a
sidebar + detail shell — Content (the #17 Home control, unchanged) ·
Pass 1 · Pass 2 · Chat ('· Sessions' rides it) · Provider Keys. Each
surface page edits its model block in memory: provider menu, an
NSComboBox sourcing hermes' registry cache with first-class free text
(the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the
default state, pinned), per-provider effort menus led by
'unset · provider default' (zai low/high/max; OpenAI + Anthropic the
five-rung ladder), variant B's current-model headline, and a
user-requested Restore Defaults back to the seed. Provider Keys carries
endpoint, the z.ai key-type toggle swapping the endpoint family
(paas/v4 ↔ coding/paas/v4 — a custom endpoint survives), and masked
keys with reveal; no Keychain (#131).

Persistence is S3's job: every change routes through an injectable
SettingsWriting seam whose implementer contract is frozen now (MUST
debounce — the key field fires per keystroke; secrets via stdin/env,
never argv; error text redacted before it renders). Write failures
surface in an orange strip, cleared by the next success.

Dogfood fix, log-observed via os_log probes on the live app:
comboBoxSelectionDidChange fires BEFORE stringValue updates — the pick
is read from objectValueOfSelectedItem and the box re-synced by hand,
or the model never learns a dropdown pick. Two blind fixes failed
before the probe round settled it; pinned against the stale-string
fixture and filed to the swift wiki.

Finish-audit fanout (ponytail/security/general): Ship/SHIP/APPROVE —
applied the SettingsWriting contract, an inlined one-caller wrapper,
a corrected registry-leniency comment, and a seed-provider pin;
declined deleting the hydration clamp (trust-boundary validation for
S3's config.yaml reads); deferred endpoint scheme validation to S3's
write boundary. Suite: 432 passed / 432 (xcresult-verified). DOX:
Museion/AGENTS.md, MuseionTests/AGENTS.md, CHANGELOG, session log.

Closes #135
2026-10-27 11:52:39 +01:00

323 lines
14 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.
//
// 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
private 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 keyType: ZaiKeyType?
}
var surfaces: [(ProfileSurface, SurfaceModelConfig)] = []
var keys: [KeyWriteRecord] = []
/// Knob: surface writes throw while set (the failure-path tests).
var failSurfaceWrites = false
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig) async throws {
if failSurfaceWrites {
throw NSError(domain: "test", code: 1, userInfo: [NSLocalizedDescriptionKey: "config set failed"])
}
surfaces.append((surface, config))
}
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, keyType: ZaiKeyType?) async throws {
keys.append(KeyWriteRecord(provider: provider, config: config, keyType: keyType))
}
}
@Suite("SettingsModelTests")
struct SettingsModelTests {
/// The real cache's shape, subset — zai + anthropic + openai-api lists,
/// with claude-sonnet-5-5 deliberately absent (live truth: the seed is
/// NOT in the registry, so custom is the default state).
private 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"],
])
}
// 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())
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())
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())
#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())
// 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())
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-5.6-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())
#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())
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)
model.setProvider(.zai, for: .pass2)
model.setEffort(.max, for: .pass2)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 2)
model.resetToDefault(for: .pass2)
await model.awaitPendingWrites()
#expect(model.config(for: .pass2) == SurfaceModelConfig(provider: .anthropic, model: ProfileSurface.defaultModelID, effort: nil))
#expect(writer.surfaces.count == 3)
// Already at the seed — a second reset is a no-op, no write.
model.resetToDefault(for: .pass2)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 3)
}
// 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())
#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())
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())
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)
model.setProvider(.zai, for: .pass1)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 1)
let (surface, config) = writer.surfaces[0]
#expect(surface == .pass1)
#expect(config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
}
@Test @MainActor func `key changes route through the writer with key type only for zai`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
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)
#expect(first.keyType == .coding)
#expect(first.config.endpoint == ZaiKeyType.coding.endpoint)
let second = writer.keys[1]
#expect(second.provider == .anthropic)
#expect(second.keyType == nil)
}
@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)
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))
}
}