Files
museion/Museion/ModelComboBox.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

149 lines
5.3 KiB
Swift

//
// ModelComboBox.swift
// Museion
//
// #135 (Profiles S2): the model picker as a proper macOS combobox — free
// text is first-class (the #132 seed claude-sonnet-5-5 isn't in the
// registry), the registry list rides the dropdown + autocompletion. The
// prototype #130's Custom… ↩ two-state dance collapsed into this one
// control.
//
import AppKit
import Foundation
import SwiftUI
/// 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.
static let loadedDefault = ModelRegistry.load()
}
struct ModelComboBox: NSViewRepresentable {
/// The committed model id (the model's truth; the box echoes it).
var value: String
/// The provider's registry list — dropdown + completion source.
var items: [String]
/// Commit: Enter, blur (end editing), or a list pick.
var onCommit: (String) -> Void
func makeCoordinator() -> Coordinator {
Coordinator(onCommit: onCommit)
}
func makeNSView(context: Context) -> NSComboBox {
let box = NSComboBox()
box.usesDataSource = false
box.completes = true
box.numberOfVisibleItems = 12
box.font = .monospacedSystemFont(ofSize: 11.5, weight: .regular)
box.stringValue = value
box.delegate = context.coordinator
box.target = context.coordinator
box.action = #selector(Coordinator.picked(_:))
box.setAccessibilityLabel("Model")
context.coordinator.syncItems(box, items: items)
context.coordinator.lastLocalValue = value
return box
}
func updateNSView(_ box: NSComboBox, context: Context) {
context.coordinator.onCommit = onCommit
context.coordinator.syncItems(box, items: items)
// Echo guard, OutlineRowTextView pattern: our own commits round-trip
// byte-equal through the model, so only adopt when the model's value
// differs from what this box last emitted — a provider switch. Never
// clobber in-flight editing; commits arrive via the delegate.
if value != context.coordinator.lastLocalValue, box.currentEditor() == nil {
box.stringValue = value
context.coordinator.lastLocalValue = value
}
}
@MainActor
final class Coordinator: NSObject, NSComboBoxDelegate {
var onCommit: (String) -> Void
var lastLocalValue = ""
init(onCommit: @escaping (String) -> Void) {
self.onCommit = onCommit
}
/// Only rebuild the item list when it actually changed — an unrelated
/// state tick (effort menu, reveal toggle) must not close an open
/// dropdown.
func syncItems(_ box: NSComboBox, items: [String]) {
guard (box.objectValues as? [String]) != items else { return }
box.removeAllItems()
box.addItems(withObjectValues: items)
}
private func commit(_ box: NSComboBox, value: String? = nil) {
let trimmed = (value ?? box.stringValue).trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, trimmed != lastLocalValue else { return }
lastLocalValue = trimmed
onCommit(trimmed)
}
/// Return (NSComboBox's action).
@objc func picked(_ sender: NSComboBox) {
commit(sender)
}
/// A list pick (#135 dogfood, log-observed): the notification fires
/// BEFORE stringValue updates — the picked item must come from the
/// selection index; reading stringValue here commits the STALE value
/// and the model never learns the pick. The box is re-synced by hand
/// because this no-field-editor path never produces a follow-up event.
func comboBoxSelectionDidChange(_ notification: Notification) {
guard let box = notification.object as? NSComboBox else { return }
// nil when nothing is selected (indexOfSelectedItem < 0).
guard let picked = box.objectValueOfSelectedItem as? String else { return }
commit(box, value: picked)
box.stringValue = picked
}
/// Blur / Enter through the field editor.
func controlTextDidEndEditing(_ obj: Notification) {
guard let box = obj.object as? NSComboBox else { return }
commit(box)
}
}
}