Files
museion/Museion/SettingsPagesView.swift
T
AlexKucera 6938826101 feat(microblog): add app token settings page and honest 5xx wording
The app token could only be entered in the publish sheet, and that
field came back only after a 401/403, so a saved token had no standing
way to be replaced or removed. The new Settings → Micro.blog page
writes the same `MicropubTokenStore` slot the sheet reads, with a
status row read back from the Keychain after every write so a locked
keychain fails visibly instead of claiming "stored". The sheet now
names the stored token a send carries when its field is hidden.

Micro.blog's errors arrive as HTML pages, never Micropub JSON, so
`decodeFailure` fell through to a bare `HTTP 503` that said nothing
about whose side it was on. Any 5xx without a JSON description now
reads "unavailable on their side — retry in a few minutes"; a
described 5xx keeps its description and a 4xx keeps the bare status.
One decode covers create, publish, q=config, and media uploads.

Docs: AGENTS.md bullets, CHANGELOG [Unreleased] Added/Fixed, and the
devlog for this task plus the 0.1.2 release log.
2026-12-04 15:06:00 +01:00

460 lines
16 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). The Micro.blog page is the app
// token's home (saved status, replace, remove over the publish sheet's own
// Keychain slot). 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 Micro.blog page: the app token's home — saved status, replace,
/// remove. Writes the SAME Keychain slot the publish sheet reads
/// (`MicropubTokenStore`), so a token saved here is the one a send
/// carries; the sheet's own field stays the first-run path and its
/// 401/403 re-entry. `saved` is read back from the Keychain after every
/// write, never assumed — a locked keychain fails the save and the
/// status line says so.
struct MicroblogSettingsPage: View {
@State private var tokenField = ""
@State private var saved = MicropubTokenStore.read() != nil
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text("Micro.blog")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Where the Micro.blog app token lives.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
form
.padding(.top, 12)
.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 trimmedToken: String {
tokenField.trimmingCharacters(in: .whitespaces)
}
private var form: some View {
VStack(alignment: .leading, spacing: 6) {
SettingsFieldLabel("App Token")
HStack(spacing: 8) {
SecureField("App token", text: $tokenField)
.textFieldStyle(.roundedBorder)
.font(.system(size: 12, design: DesignTokens.mono))
Button("Save") {
let token = trimmedToken
MicropubTokenStore.save(token)
tokenField = ""
saved = MicropubTokenStore.read() == token
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(trimmedToken.isEmpty)
if saved {
Button("Remove") {
MicropubTokenStore.delete()
saved = MicropubTokenStore.read() != nil
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
}
}
// The standing state, in the Settings verdict idiom (Provider
// Keys' "✓ works"). The intro line is a description — a state
// swap there never read as a status.
status
Text("From micro.blog → Account → App Tokens. Stored in your Keychain — the publish sheet sends with this token.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
.padding(.top, 2)
}
}
/// Live: Save and Remove read the Keychain back, so this line is
/// both the confirmation that a write landed and the standing
/// answer to "is a token stored?".
private var status: some View {
Text(saved ? "✓ Token saved in your Keychain" : "No token saved — publishing will ask for one")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(saved ? DesignTokens.accent : DesignTokens.muted)
.padding(.top, 2)
}
}
/// 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")
}
}