// // 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) } } }