Files
museion/Museion/SettingsPagesView.swift
AlexKucera f49e4b6ca0
CI / ci (push) Canceled after 0s
refactor(settings): provider facts as data
#181: ModelProvider is the provider-descriptor table — label, effort
ladder, flagship, endpoint, env var joined by wire dialect (chat/models
paths + the SSE decoder selector), auth mode (Bearer vs Anthropic's
header pair), keyless (nous rides the Portal login), and the ONE
trailing-slash endpoint trim. The probe's URL builders, auth headers,
and stream-decoder picks select by data; the per-dialect bodies and
decoders stay separate functions, not switch clothing.

ProviderCredential.resolve is the ONE credential rail (provider key,
else the shared Portal session key for keyless providers — official
endpoint ONLY, never a user-set URL). Settings' Test Connection and the
new PassReadiness module both call it; the twice-implemented #175
fallback can no longer drift. One deliberate tightening, reviewer-
blessed: a nous pass profile on a custom base_url with no pasted key now
reads missingKey where the old session-model fallback said ready — the
old copy had no endpoint gate at all.

Pass readiness leaves the session model (PassReadiness.swift maps each
pass surface to ready/missingKey/unknown over the descriptor;
MentorSessionModel stores the verdicts and reads no keys or auth
files). runPass and blindRead run their guards through one shared rail
(guardOpenPieceRun) — identical refusal strings, blockers named
honestly. No app-side model-settings store (ADR-0014 red line).

Rider: the #179 mid-pass repoint pin polls the rig's hasHeldPrompt
before releasing the held turn — runningPass flips before the one-shot
engine parks its prompt, so firing into that window false-failed under
parallel-suite load.

Full suite 668/668 (xcresult executed count). Finish-audit: three
reviewers (ponytail/security/general), zero findings above LOW; two
ponytail trims and one pin tightening applied.

Closes #181
2026-11-10 10:58:29 +01:00

381 lines
13 KiB
Swift

//
// SettingsPagesView.swift
// Museion
//
// #135 (Profiles S2): the Settings sidebar's detail pages over the
// in-memory SettingsModel — one page per LLM surface (provider select,
// registry combobox with first-class free text, per-provider effort menu)
// and the Provider Keys page (endpoint, z.ai key-type toggle swapping the
// endpoint family, masked key + reveal). Visual contract: #130 prototype
// variant C, with variant B's current-model headline folded in.
//
import SwiftUI
/// The quiet field label (prototype `.field-label`, #130 fold-in): mono
/// 11 uppercase (r4: 10.5 → 11, the phase-2 micro-label sweep), one line,
/// never a wrapping caption.
struct SettingsFieldLabel: View {
let text: String
init(_ text: String) {
self.text = text
}
var body: some View {
Text(text)
.font(.system(size: 11, design: DesignTokens.mono))
.lineLimit(1)
.tracking(0.5)
.textCase(.uppercase)
.foregroundStyle(DesignTokens.muted)
}
}
/// One surface's model page (prototype `.vC .detail` surface branch +
/// variant B's `.current` headline): provider, model combobox, reasoning
/// effort. Output budget is not a control (#128).
struct SurfaceSettingsPage: View {
let model: SettingsModel
let surface: ProfileSurface
var body: some View {
// r8 (mercury#20, sol — owner regression): the r6 ScrollView +
// minHeight frame CENTERED the form in the viewport (~320px of
// dead space under the intro) and its +24 bottom padding kept a
// phantom scrollbar alive. Both gone — a plain top-aligned stack
// (the Content page's r7 shape): one control column, every
// control label-above-control at the page title's x, ~24pt under
// the intro, no scrolling (the page fits).
VStack(alignment: .leading, spacing: 24) {
header
form
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 24)
.padding(.top, 17)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
private var header: some View {
let config = model.config(for: surface)
return VStack(alignment: .leading, spacing: 4) {
HStack {
Text(label)
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Spacer(minLength: 12)
// macOS convention: Restore Defaults in the page header.
Button("Restore Defaults") {
model.resetToDefault(for: surface)
}
.buttonStyle(.bordered)
.controlSize(.small)
// r6 (sol#6/21 — contrast final): disabled reads muted
// ink + the system border, never washed out.
.foregroundStyle(config == .surfaceDefault ? DesignTokens.muted : DesignTokens.foreground)
.disabled(config == .surfaceDefault)
}
// Variant B's stolen headline: the current model reads first.
Text(config.model + (model.isCustom(surface) ? " · custom (not in registry)" : ""))
.font(.system(size: 12.5, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
Text("profile · \(surface.profileName) — \(note)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
private var form: some View {
let config = model.config(for: surface)
return VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Provider")
Picker("Provider", selection: Binding(
get: { config.provider },
set: { model.setProvider($0, for: surface) },
)) {
ForEach(ModelProvider.allCases, id: \.self) { provider in
Text(provider.label).tag(provider)
}
}
.pickerStyle(.menu)
.frame(width: 200)
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Model")
HStack(spacing: 8) {
ModelComboBox(
value: config.model,
items: model.registry.list(for: config.provider),
) { model.setModel($0, for: surface) }
.frame(width: 240)
if model.isCustom(surface) {
Text("custom (not in registry)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Reasoning Effort")
Picker("Reasoning Effort", selection: Binding(
get: { config.effort },
set: { model.setEffort($0, for: surface) },
)) {
Text("unset · provider default").tag(ReasoningEffort?.none)
// The provider's ladder only — a provider switch
// rebuilds this menu (and resets the choice).
ForEach(config.provider.effortOptions, id: \.self) { effort in
Text(effort.rawValue).tag(ReasoningEffort?.some(effort))
}
}
.pickerStyle(.menu)
.frame(width: 200)
}
Text("Output budget fixed at \(ProfileSurface.outputBudgetTokens / 1000)k tokens — not a setting.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
}
// wf130 `.vC .detail`: left-anchored after the sidebar, never centered
// (r4: horizontal 24 — one leading-text token with the sidebar labels;
// r6: the width/scroll wrappers live in body).
private var label: String {
switch surface {
case .pass1: "Pass 1"
case .pass2: "Pass 2"
case .chat: "Chat"
}
}
/// The page's posture note (prototype `SURFACES[].note`): passes apply
/// on the next run (on-demand engines, ADR-0014); Chat is the resident
/// engine Sessions rides, restarted in place on a model change (#129).
private var note: String {
switch surface {
case .pass1, .pass2: "applies on the next pass"
case .chat: "Sessions rides this engine · a model change restarts it (after any streaming turn)"
}
}
}
/// The Provider Keys page (#135): one block per provider — endpoint, z.ai
/// key-type toggle, masked API key + reveal. One key per provider fans out
/// to every profile on that provider; no Keychain (#131 verdict).
struct ProviderKeysPage: View {
let model: SettingsModel
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text("Provider Keys")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("One key per provider, fanned out to every profile on it. No Keychain.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
// r8 (mercury#20, sol — owner regression): top-aligned under
// the intro (stack 4 + padding 20 = 24pt), NO ScrollView —
// the blocks fit the viewport whole; the r6 minHeight-center
// + scroll wrapper died with the surface pages' copy.
VStack(alignment: .leading, spacing: 10) {
ForEach(ModelProvider.allCases, id: \.self) { provider in
ProviderKeyBlock(model: model, provider: provider)
}
}
.padding(.top, 20)
.frame(maxWidth: DesignTokens.settingsFormWidth + 60, alignment: .leading)
.frame(maxWidth: .infinity, alignment: .leading)
}
.padding(.horizontal, 24)
.padding(.top, 17)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
}
/// One provider's key block (prototype `.block`).
private struct ProviderKeyBlock: View {
let model: SettingsModel
let provider: ModelProvider
@State private var revealed = false
var body: some View {
let config = model.keyConfig(for: provider)
VStack(alignment: .leading, spacing: 10) {
HStack {
Text(provider.label)
.font(.system(size: 14, weight: .semibold, design: DesignTokens.serif))
Spacer(minLength: 12)
if provider == .zai {
KeyTypeSegment(model: model)
}
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Endpoint (Base URL)")
TextField(
"Endpoint",
text: Binding(
get: { config.endpoint },
set: { model.setEndpoint($0, for: provider) },
),
)
.font(.system(size: 11.5, design: DesignTokens.mono))
}
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("API Key")
HStack(spacing: 6) {
if revealed {
TextField("API key", text: Binding(
get: { config.apiKey },
set: { model.setAPIKey($0, for: provider) },
))
.font(.system(size: 11.5, design: DesignTokens.mono))
} else {
SecureField("API key", text: Binding(
get: { config.apiKey },
set: { model.setAPIKey($0, for: provider) },
))
.font(.system(size: 11.5, design: DesignTokens.mono))
}
Button(revealed ? "hide" : "show") {
revealed.toggle()
}
.buttonStyle(.bordered)
.controlSize(.small)
.font(.system(size: 11, design: DesignTokens.mono))
}
}
if provider == .zai {
Text("Key type picks the endpoint family — coding-plan keys are distribution-restricted; shipped Museion uses standard keys.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
if provider.keyless {
// #175: the engine auths nous through hermes' own Portal
// login (device-code, shared across profiles) — the key
// field is optional and bills the same account credits.
// #181: keyed off the descriptor, like every provider fact.
Text(
"Chats ride your Hermes Portal login — no key needed once hermes is signed in (hermes auth add nous). "
+ "A pasted key bills the same account credits (API or subscription).",
)
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
// #136: Test Connection (factsheet §4) — /models count + a
// minimal streaming chat; latency + model count on success,
// the honest decoded verdict otherwise.
HStack(spacing: 8) {
Button("Test Connection") {
Task { await model.testConnection(for: provider) }
}
.buttonStyle(.bordered)
.controlSize(.small)
.font(.system(size: 11, design: DesignTokens.mono))
// r6 (sol#6/21 — contrast final): disabled reads muted ink +
// the system border, never washed out.
.foregroundStyle(model.testStates[provider] == .running ? DesignTokens.muted : DesignTokens.foreground)
.disabled(model.testStates[provider] == .running)
switch model.testStates[provider] {
case .running:
HStack(spacing: 4) {
ProgressView()
.controlSize(.small)
Text("testing…")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
case let .done(outcome):
TestConnectionResult(outcome: outcome)
case nil:
EmptyView()
}
}
}
.padding(EdgeInsets(top: 14, leading: 16, bottom: 14, trailing: 16))
.background(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border),
),
)
}
}
/// The probe's one-line verdict (#136): works carries latency + model
/// count; every failure states its decoded reason (the AC's
/// wrong-key-type vs unreachable vs works distinction).
private struct TestConnectionResult: View {
let outcome: ProviderProbe.Outcome
var body: some View {
switch outcome {
case let .works(latencyMS, modelCount):
Text("✓ works · \(latencyMS) ms · \(modelCount) models")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.accent)
case let .authFailed(detail):
text("key rejected — \(detail)")
case let .wrongKeyType(detail):
text("wrong key type — \(detail)")
case let .unreachable(detail):
text("unreachable — \(detail)")
case let .starved(detail):
text("token cap starved — \(detail)")
case let .requestFailed(status, detail):
text("HTTP \(status) — \(detail)")
}
}
private func text(_ content: String) -> some View {
Text(content)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(.orange)
.lineLimit(2)
.truncationMode(.middle)
.help(content)
}
}
/// The z.ai key-type toggle (prototype `.seg`): a two-segment capsule, the
/// selected segment filled with the foreground ink. Toggling swaps the
/// endpoint family (the model guards a custom endpoint).
private struct KeyTypeSegment: View {
let model: SettingsModel
var body: some View {
HStack(spacing: 0) {
ForEach(ZaiKeyType.allCases, id: \.self) { type in
let selected = model.zaiKeyType == type
Button {
model.setZaiKeyType(type)
} label: {
Text(type.label)
.font(.system(size: 11.5))
.padding(.horizontal, 10)
.padding(.vertical, 4)
.foregroundStyle(selected ? DesignTokens.background : DesignTokens.muted)
.background {
if selected {
RoundedRectangle(cornerRadius: 6)
.fill(DesignTokens.foreground)
.padding(1)
}
}
}
.buttonStyle(.plain)
.accessibilityAddTraits(selected ? [.isSelected] : [])
}
}
.background(
RoundedRectangle(cornerRadius: 7)
.fill(DesignTokens.surface)
.overlay(RoundedRectangle(cornerRadius: 7).strokeBorder(DesignTokens.border)),
)
.accessibilityLabel("z.ai key type")
}
}