Files
museion/Museion/SettingsModel.swift
T
AlexKucera 1c697440d8
CI / ci (push) Canceled after 0s
feat(mentor): per-surface engine lifecycle (#137)
Profiles S4: passes run on their OWN one-shot engines —
`hermes acp -p museion-passN` spawns per pass run and tears down at
the verdict, so a model switch costs nothing (the next spawn reads
fresh config). The verdict streams into a TRANSIENT unrostered
transcript (#129's ruling: one Sessions surface over the chat
engine; a rostered pass session would be unresumable by the chat
engine). `beginPassSession` died with it — passes never mint
sessions; the #28 roster pins flipped to the transient posture.

The chat engine stays resident (adopted museion profile): a Chat
model change in Settings fires onChatSurfaceWrite after a
successful chat-surface write only, wired to requestRestart —
re-spawn in place when idle (resuming the pre-restart active
session), deferred to turn end while any turn streams (#129).

Missing-key posture (#132): refreshPassReadiness reads both pass
profiles' providers and their .env keys at pane entry; Run Pass
disables naming the provider with an Open Settings link, .unknown
never blocks, and the guard refuses before anything touches disk.

Finish-audit (ponytail/security/general fanout) applied: the
general reviewer's Medium — a session/new/load/fork completing
mid-pass stole the active surface and lost the Cancel to the wrong
engine — fixed with ONE claimActive gate across the post-await
activation writers, pinned deterministically via the fake's
loadReplayHold park + a mode-file flip (flip-verified: guard off
fails on the steal observables and the misrouted-cancel hang).
Also fixed: a spawn-window cancel loss in stopStreaming (keyed on
the transient entry, not the late-arriving wire id), and a
PRE-EXISTING rescan bug where a stale scan snapshot "vanished" a
just-opened piece and killed its session, cancelling the edit
debounce — the vanish-kill now re-checks disk and the watched
home. Ponytail cut ~59 lines of test duplication; the app target's
only force-unwrap is gone.

Suite 477 (was 472): EngineLifecycleTests new (own-engine
end-to-end, held-pass cancel, idle + deferred restart ordering,
readiness, steal pin), +3 Settings hook pins, one duplicate pin
deduplicated. swiftformat clean, swiftlint at HEAD baseline.

Closes #137
2026-10-28 17:26:40 +01:00

413 lines
15 KiB
Swift

//
// SettingsModel.swift
// Museion
//
// #135 (Profiles S2): the Settings page's in-memory model + the injectable
// write-path protocol. Per ADR-0014 the per-surface model block IS each
// Hermes profile's `model:` block and provider keys fan out to every
// profile on that provider.
//
// #136 (Profiles S3): the real write path — HermesSettingsWriter (CLI
// rail + .env fan-out) is the production writer; the model hydrates from
// the profiles at pane open, COALESCES rapid edits per target (the key
// field fires per keystroke — a superseded write is canceled before it
// ever spawns, so partial key prefixes never reach `.env`), and runs the
// Test Connection probe per provider.
//
// swiftlint:disable file_length
// One Settings model, one write story: state, hydration, coalescing, and
// the #137 restart hook read as one unit; a page-per-file split follows if
// the file keeps growing.
import Foundation
import Observation
/// The three providers Settings offers (#135). Raw values are Hermes' own
/// provider slugs (`CANONICAL_PROVIDERS`) — the same ids key the registry
/// cache; OpenAI's slug is `openai-api`.
nonisolated enum ModelProvider: String, CaseIterable, Sendable {
case zai
case anthropic
case openaiAPI = "openai-api"
var label: String {
switch self {
case .zai: "z.ai"
case .anthropic: "Anthropic"
case .openaiAPI: "OpenAI"
}
}
/// #128: the per-provider ladders Hermes clamps per route — one
/// `model.reasoning_effort` key, surfaced per provider.
var effortOptions: [ReasoningEffort] {
switch self {
case .zai: [.low, .high, .max]
case .anthropic, .openaiAPI: [.low, .medium, .high, .xhigh, .max]
}
}
/// The model a provider switch lands on (prototype #130's pinned
/// flagships — registry order is capability-sorted, not default-sorted;
/// #136 dogfood: OpenAI's flagship is gpt-6.1-sol, the current
/// Responses-era default).
var switchDefaultModel: String {
switch self {
case .zai: "glm-5.3"
case .anthropic: "claude-sonnet-5"
case .openaiAPI: "gpt-6.1-sol"
}
}
/// Default endpoint families (factsheet §1; z.ai's is key-type keyed).
var defaultEndpoint: String {
switch self {
case .zai: ZaiKeyType.standard.endpoint
case .anthropic: "https://api.anthropic.com"
case .openaiAPI: "https://api.openai.com/v1"
}
}
/// #136: the `.env` var Hermes' own provider registry maps each slug to
/// (`hermes_cli/auth.py` live-read): zai→GLM_API_KEY (ZAI_/Z_AI_ are
/// aliases), anthropic→ANTHROPIC_API_KEY, openai-api→OPENAI_API_KEY.
var envVarName: String {
switch self {
case .zai: "GLM_API_KEY"
case .anthropic: "ANTHROPIC_API_KEY"
case .openaiAPI: "OPENAI_API_KEY"
}
}
}
nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable {
case low
case medium
case high
case xhigh
case max
}
/// z.ai's two key types pick the endpoint family (factsheet §1.1) — coding
/// plan keys are distribution-restricted; shipped Museion uses standard.
nonisolated enum ZaiKeyType: String, CaseIterable, Sendable {
case standard
case coding
var endpoint: String {
switch self {
case .standard: "https://api.z.ai/api/paas/v4"
case .coding: "https://api.z.ai/api/coding/paas/v4"
}
}
var label: String {
switch self {
case .standard: "Standard (pay-as-you-go)"
case .coding: "Coding plan"
}
}
}
/// One surface's model block — what Settings edits and S3 persists via the
/// write path (the profile's `model:` block).
nonisolated struct SurfaceModelConfig: Equatable, Sendable {
var provider: ModelProvider
var model: String
/// nil = unset · provider default (the key is simply not written).
var effort: ReasoningEffort?
/// The #132 fresh-seed posture: sonnet on all three surfaces, effort
/// unset. Never copied from the live museion profile.
static let surfaceDefault = SurfaceModelConfig(
provider: .anthropic,
model: ProfileSurface.defaultModelID,
effort: nil,
)
}
/// One provider's key block — endpoint (base URL) + API key. One key per
/// provider fans out to every profile on that provider (#131: no Keychain).
nonisolated struct ProviderKeyConfig: Equatable, Sendable {
var endpoint: String
var apiKey: String = ""
}
/// The Settings page's state (#135): per-surface model configs, per-provider
/// keys, the registry the model combobox reads, and the write path every
/// committed change flows through. #136: hydrated from the profiles at pane
/// open; pane-local still — the AppGateState lift waits on the
/// restart-on-change slice.
@MainActor
@Observable
final class SettingsModel {
private(set) var surfaces: [ProfileSurface: SurfaceModelConfig]
private(set) var keys: [ModelProvider: ProviderKeyConfig]
private(set) var zaiKeyType: ZaiKeyType = .standard
private(set) var registry: ModelRegistry
/// Write failures land here — the honest strip (the CLI rail can fail).
private(set) var lastWriteError: String?
/// #136: Test Connection state per provider (the Provider Keys page).
private(set) var testStates: [ModelProvider: TestState] = [:]
private let writer: any SettingsWriting
/// #137 (S4): fired after a SUCCESSFUL chat-surface write ONLY — the
/// resident chat engine restarts to read the new model block
/// (WorkspaceView wires it to MentorSessionModel.requestRestart).
/// Never on failure (lastWriteError path), never for pass surfaces
/// (their engines are one-shot), never for key writes.
var onChatSurfaceWrite: (() -> Void)?
/// Rapid edits per target coalesce: a newer write cancels the older
/// task during its debounce window (the key field fires per keystroke —
/// a partial prefix of a secret must never reach `.env`). Tests pass 0.
private let writeDebounce: TimeInterval
private var surfaceTasks: [ProfileSurface: Task<Void, Never>] = [:]
private var keyTasks: [ModelProvider: Task<Void, Never>] = [:]
init(
registry: ModelRegistry = .loadedDefault,
writer: any SettingsWriting = NoopSettingsWriter(),
surfaces: [ProfileSurface: SurfaceModelConfig]? = nil,
writeDebounce: TimeInterval = 0.35,
) {
self.registry = registry
self.writer = writer
self.writeDebounce = writeDebounce
self.surfaces = surfaces
?? Dictionary(uniqueKeysWithValues: ProfileSurface.allCases.map { ($0, .surfaceDefault) })
keys = Dictionary(
uniqueKeysWithValues: ModelProvider.allCases.map {
($0, ProviderKeyConfig(endpoint: $0.defaultEndpoint))
},
)
}
func config(for surface: ProfileSurface) -> SurfaceModelConfig {
var config = surfaces[surface] ?? .surfaceDefault
// Read-boundary clamp: a config hydrated with an effort outside the
// provider's ladder (S3 reads hand-edited config.yaml files) must not
// render a blank menu selection. The stored value is untouched — the
// next mutation writes a clamped copy.
if let effort = config.effort, !config.provider.effortOptions.contains(effort) {
config.effort = nil
}
return config
}
func keyConfig(for provider: ModelProvider) -> ProviderKeyConfig {
keys[provider] ?? ProviderKeyConfig(endpoint: provider.defaultEndpoint)
}
/// True when the model id isn't in Hermes' registry for its provider —
/// claude-sonnet-5-5 (the #132 seed) is NOT in the cache, so custom is
/// the DEFAULT state, not an edge case.
func isCustom(_ surface: ProfileSurface) -> Bool {
let config = config(for: surface)
return !registry.list(for: config.provider).contains(config.model)
}
/// #136: hydration — each profile's live `model:` block, read in
/// parallel through the writer's CLI rail (format owned by Hermes).
/// Surfaces on providers Settings doesn't offer stay seeded (their
/// config is the user's, not ours to rewrite); a z.ai profile pinned to
/// the coding endpoint infers the key type. Keys persist in the
/// fanned-out `.env` files — they're read back too, so a restart
/// neither blanks the fields nor refuses Test Connection. Reads only —
/// hydrate never writes.
func hydrate() async {
let writer = writer
await withTaskGroup(of: (ProfileSurface, (config: SurfaceModelConfig, baseURL: String?)?).self) { group in
for surface in ProfileSurface.allCases {
group.addTask { await (surface, try? writer.readSurface(surface)) }
}
for await (surface, read) in group {
guard let read else { continue }
// An edit that fired while this read was in flight owns the
// truth — applying the stale read would revert the UI and
// the next edit would persist from the stale base.
guard surfaceTasks[surface] == nil else { continue }
surfaces[surface] = read.config
if read.config.provider == .zai {
if read.baseURL == ZaiKeyType.coding.endpoint {
zaiKeyType = .coding
keys[.zai]?.endpoint = ZaiKeyType.coding.endpoint
} else if let baseURL = read.baseURL, !baseURL.isEmpty, baseURL != ZaiKeyType.standard.endpoint {
// A custom zai base_url (hand-edited, or a family
// Settings doesn't model) survives hydration — the
// next zai write-through threads it, never a default.
keys[.zai]?.endpoint = baseURL
}
}
}
}
for provider in ModelProvider.allCases {
guard keyTasks[provider] == nil else { continue }
if let key = try? await writer.readProviderKey(provider: provider), !key.isEmpty {
keys[provider]?.apiKey = key
}
}
}
/// A provider switch lands on that provider's pinned default model with
/// effort reset (each provider's ladder differs; the writer should see
/// intent, not residue).
func setProvider(_ provider: ModelProvider, for surface: ProfileSurface) {
var config = config(for: surface)
guard config.provider != provider else { return }
config.provider = provider
config.model = provider.switchDefaultModel
config.effort = nil
surfaces[surface] = config
persist(surface, config)
// No key re-fire: key writes land in ALL THREE .env files, so the
// key pre-landed before any switch (the zai endpoint family rides
// the surface write's zaiEndpoint).
}
func setModel(_ model: String, for surface: ProfileSurface) {
let trimmed = model.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
var config = config(for: surface)
guard config.model != trimmed else { return }
config.model = trimmed
surfaces[surface] = config
persist(surface, config)
}
func setEffort(_ effort: ReasoningEffort?, for surface: ProfileSurface) {
var config = config(for: surface)
guard config.effort != effort else { return }
config.effort = effort
surfaces[surface] = config
persist(surface, config)
}
/// Back to the #132 seed (sonnet, effort unset) — the page's Restore
/// Defaults button. No-op when already there; a real reset persists.
func resetToDefault(for surface: ProfileSurface) {
guard config(for: surface) != .surfaceDefault else { return }
surfaces[surface] = .surfaceDefault
persist(surface, .surfaceDefault)
}
/// z.ai's key type picks the endpoint family (factsheet §1). A custom
/// endpoint survives the toggle; a family default (or empty) swaps.
func setZaiKeyType(_ type: ZaiKeyType) {
guard zaiKeyType != type else { return }
zaiKeyType = type
let endpoint = keyConfig(for: .zai).endpoint
if endpoint.isEmpty || ZaiKeyType.allCases.contains(where: { $0.endpoint == endpoint }) {
keys[.zai]?.endpoint = type.endpoint
}
persistKey(.zai)
}
func setEndpoint(_ endpoint: String, for provider: ModelProvider) {
guard keys[provider]?.endpoint != endpoint else { return }
keys[provider]?.endpoint = endpoint
persistKey(provider)
}
func setAPIKey(_ key: String, for provider: ModelProvider) {
guard keys[provider]?.apiKey != key else { return }
keys[provider]?.apiKey = key
persistKey(provider)
}
// MARK: Test Connection (#136 — factsheet §4)
enum TestState: Equatable {
case running
case done(ProviderProbe.Outcome)
}
/// One probe per provider over the CURRENT key/endpoint state. Guarded
/// against stacking; the empty-key precondition makes an unkeyed probe
/// fail fast without touching the network.
func testConnection(for provider: ModelProvider) async {
guard testStates[provider] != .running else { return }
testStates[provider] = .running
let keyConfig = keyConfig(for: provider)
let config = ProviderProbe.Config(
provider: provider,
endpoint: keyConfig.endpoint,
apiKey: keyConfig.apiKey,
model: probeModel(for: provider),
)
testStates[provider] = await .done(ProviderProbe.probe(config))
}
/// The model the probe proves generation on: the first surface on this
/// provider (what the writer actually configures), else the provider's
/// pinned flagship.
func probeModel(for provider: ModelProvider) -> String {
for surface in ProfileSurface.allCases where config(for: surface).provider == provider {
return config(for: surface).model
}
return provider.switchDefaultModel
}
// MARK: Write plumbing
/// Awaits in-flight writes — the tests' deterministic sync point.
func awaitPendingWrites() async {
let tasks = Array(surfaceTasks.values) + Array(keyTasks.values)
for task in tasks {
await task.value
}
surfaceTasks.removeAll()
keyTasks.removeAll()
}
private func persist(_ surface: ProfileSurface, _ config: SurfaceModelConfig) {
let zaiEndpoint = config.provider == .zai ? keyConfig(for: .zai).endpoint : nil
let previous = surfaceTasks[surface]
previous?.cancel()
surfaceTasks[surface] = Task { [writeDebounce] in
if writeDebounce > 0 {
try? await Task.sleep(for: .seconds(writeDebounce))
}
guard !Task.isCancelled else { return }
// Cancellation can't stop a past-the-guard CLI write, so the
// newer write WAITS — the last edit is always the last write to
// land (2026-10-28 audit fix).
await previous?.value
guard !Task.isCancelled else { return }
do {
try await writer.writeSurface(surface, config: config, zaiEndpoint: zaiEndpoint)
lastWriteError = nil
if surface == .chat {
onChatSurfaceWrite?()
}
} catch {
lastWriteError = error.localizedDescription
}
}
}
private func persistKey(_ provider: ModelProvider) {
let config = keyConfig(for: provider)
// The zai base_url write-through targets: surfaces currently on
// this provider (the KEY lands in all three .env files regardless).
let profiles = ProfileSurface.allCases.filter { surfaces[$0]?.provider == provider }
let previous = keyTasks[provider]
previous?.cancel()
keyTasks[provider] = Task { [writeDebounce] in
if writeDebounce > 0 {
try? await Task.sleep(for: .seconds(writeDebounce))
}
guard !Task.isCancelled else { return }
// Same contract as persist: wait out the in-flight predecessor.
await previous?.value
guard !Task.isCancelled else { return }
do {
try await writer.writeProviderKey(provider: provider, config: config, profiles: profiles)
lastWriteError = nil
} catch {
lastWriteError = error.localizedDescription
}
}
}
}