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:
AlexKucera committed 2026-10-27 18:32:30 +01:00
1 parent 42a27cc8a3
commit 5ad605eb3c
20 files changed
+1983 -161

No files matched your search

+150 -97
View File
@@ -5,8 +5,14 @@
// #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 — persistence lands with S3 over this seam;
// S2 ships a no-op writer.
// 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.
//
import Foundation
@@ -38,12 +44,14 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
}
/// The model a provider switch lands on (prototype #130's pinned
/// flagships — registry order is capability-sorted, not default-sorted).
/// 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-5.6-sol"
case .openaiAPI: "gpt-6.1-sol"
}
}
@@ -55,6 +63,17 @@ nonisolated enum ModelProvider: String, CaseIterable, Sendable {
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 {
@@ -110,76 +129,11 @@ nonisolated struct ProviderKeyConfig: Equatable, Sendable {
var apiKey: String = ""
}
/// Hermes' own picker cache (`~/.hermes/provider_models_cache.json`) — zero
/// HTTP, exactly what Hermes accepts (ADR-0014). Lenient by design: a
/// missing, unreadable, or foreign-shaped file leaves every model free-text
/// (all custom), which is the picker's first-class mode anyway.
nonisolated struct ModelRegistry: Sendable {
var models: [ModelProvider: [String]] = [:]
func list(for provider: ModelProvider) -> [String] {
models[provider] ?? []
}
/// Cache shape: `{provider: {fp, at, models: [ids]}}`. Lenient per the
/// DECODE, not per entry: unknown provider slugs are skipped, but any
/// foreign shape inside a known provider's entry (a non-string models
/// element) fails the whole decode and the registry degrades to
/// free-text-only — the picker's first-class mode anyway.
static func load(path: String = ("~/.hermes/provider_models_cache.json" as NSString).expandingTildeInPath) -> ModelRegistry {
guard let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else {
return ModelRegistry()
}
struct Entry: Decodable {
let models: [String]?
}
guard let parsed = try? JSONDecoder().decode([String: Entry].self, from: data) else {
return ModelRegistry()
}
var registry = ModelRegistry()
for (slug, entry) in parsed {
if let provider = ModelProvider(rawValue: slug) {
registry.models[provider] = entry.models ?? []
}
}
return registry
}
/// The default load, memoized — `SettingsModel()` runs its default
/// arguments on every SwiftUI construction of the pane, so the disk read
/// + decode must happen once. ponytail: refreshed on next launch, not
/// live; S3 lifts persistence anyway.
static let loadedDefault = ModelRegistry.load()
}
/// The write-path seam (#135). S3 implements this against the Hermes CLI
/// (`hermes -p <profile> config set` for the model block, `.env` fan-out
/// for provider keys — ADR-0014); implementations own batching/debounce and
/// hop off-main internally when the rail needs it. Contract for implementers
/// (finish-audit #135): in-flight edits are TENTATIVE — implementations MUST
/// debounce writes (the key field fires per keystroke; persisting every
/// partial prefix of a secret to `.env` leaks key material through later
/// overwrites). Secrets travel via stdin or the child's environment, never
/// argv (`ps` reads live command lines), and surfaced error text must be
/// redacted of key-bearing content (lastWriteError renders verbatim).
@MainActor
protocol SettingsWriting {
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig) async throws
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, keyType: ZaiKeyType?) async throws
}
/// S2's inert writer: persistence is S3's job; the UI runs over the
/// in-memory model meanwhile.
struct NoopSettingsWriter: SettingsWriting {
func writeSurface(_: ProfileSurface, config _: SurfaceModelConfig) async throws {}
func writeProviderKey(provider _: ModelProvider, config _: ProviderKeyConfig, keyType _: ZaiKeyType?) async throws {}
}
/// 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. Pane-local for S2 — S3 lifts it to
/// AppGateState when persistence lands.
/// 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 {
@@ -187,18 +141,28 @@ final class SettingsModel {
private(set) var keys: [ModelProvider: ProviderKeyConfig]
private(set) var zaiKeyType: ZaiKeyType = .standard
private(set) var registry: ModelRegistry
/// Write failures land here — the honest strip (S3's rail can fail).
/// 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
/// 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(
@@ -232,6 +196,48 @@ final class SettingsModel {
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).
@@ -243,6 +249,9 @@ final class SettingsModel {
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) {
@@ -295,51 +304,95 @@ final class SettingsModel {
persistKey(provider)
}
/// Fire-and-forget: the UI never blocks on writes; failures surface in
/// `lastWriteError` (LearningsPane's strip posture), cleared by the next
/// SUCCESSFUL write — not optimistically at commit.
/// ponytail: interleaved writes are unordered — an older write failing
/// after a newer one succeeded leaves its error up; a write-generation
/// token fixes it if S3's real writers ever interleave.
private var pendingWrites: [Task<Void, Never>] = []
// 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 {
for task in pendingWrites {
let tasks = Array(surfaceTasks.values) + Array(keyTasks.values)
for task in tasks {
await task.value
}
pendingWrites.removeAll()
}
// ponytail: finished tasks are only reference-hygiene; cap, don't track.
private func track(_ task: Task<Void, Never>) {
pendingWrites.append(task)
if pendingWrites.count > 64 {
pendingWrites.removeFirst(pendingWrites.count - 64)
}
surfaceTasks.removeAll()
keyTasks.removeAll()
}
private func persist(_ surface: ProfileSurface, _ config: SurfaceModelConfig) {
track(Task {
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)
try await writer.writeSurface(surface, config: config, zaiEndpoint: zaiEndpoint)
lastWriteError = nil
} catch {
lastWriteError = error.localizedDescription
}
})
}
}
private func persistKey(_ provider: ModelProvider) {
let config = keyConfig(for: provider)
let keyType = provider == .zai ? zaiKeyType : nil
track(Task {
// 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, keyType: keyType)
try await writer.writeProviderKey(provider: provider, config: config, profiles: profiles)
lastWriteError = nil
} catch {
lastWriteError = error.localizedDescription
}
})
}
}
}