feat(settings): sidebar + detail Settings page (#135)
CI / ci (push) Canceled after 0s

Profiles S2 over the variant C verdict (#130): Settings becomes a
sidebar + detail shell — Content (the #17 Home control, unchanged) ·
Pass 1 · Pass 2 · Chat ('· Sessions' rides it) · Provider Keys. Each
surface page edits its model block in memory: provider menu, an
NSComboBox sourcing hermes' registry cache with first-class free text
(the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the
default state, pinned), per-provider effort menus led by
'unset · provider default' (zai low/high/max; OpenAI + Anthropic the
five-rung ladder), variant B's current-model headline, and a
user-requested Restore Defaults back to the seed. Provider Keys carries
endpoint, the z.ai key-type toggle swapping the endpoint family
(paas/v4 ↔ coding/paas/v4 — a custom endpoint survives), and masked
keys with reveal; no Keychain (#131).

Persistence is S3's job: every change routes through an injectable
SettingsWriting seam whose implementer contract is frozen now (MUST
debounce — the key field fires per keystroke; secrets via stdin/env,
never argv; error text redacted before it renders). Write failures
surface in an orange strip, cleared by the next success.

Dogfood fix, log-observed via os_log probes on the live app:
comboBoxSelectionDidChange fires BEFORE stringValue updates — the pick
is read from objectValueOfSelectedItem and the box re-synced by hand,
or the model never learns a dropdown pick. Two blind fixes failed
before the probe round settled it; pinned against the stale-string
fixture and filed to the swift wiki.

Finish-audit fanout (ponytail/security/general): Ship/SHIP/APPROVE —
applied the SettingsWriting contract, an inlined one-caller wrapper,
a corrected registry-leniency comment, and a seed-provider pin;
declined deleting the hydration clamp (trust-boundary validation for
S3's config.yaml reads); deferred endpoint scheme validation to S3's
write boundary. Suite: 432 passed / 432 (xcresult-verified). DOX:
Museion/AGENTS.md, MuseionTests/AGENTS.md, CHANGELOG, session log.

Closes #135
This commit is contained in:
AlexKucera committed 2026-10-27 11:52:39 +01:00
1 parent 610f8789bd
commit 42a27cc8a3
12 files changed
+1315 -32

No files matched your search

+2 -4
View File
@@ -8,8 +8,6 @@ Museion — the Agentic Writing Environment (AWE): a native SwiftUI macOS app wh
- **Forge**: Gitea @ git.babylondreams.de (`tea` CLI), CI via Gitea Actions (ADR-0003) — needs a self-hosted macOS runner.
- **License**: GPL-3.0-or-later (ADR-0002).
When working on Swift or SwiftUI code, consult SwiftFairy for relevant API, framework, or domain guidance and examples before making changes. Audit the affected code with SwiftFairy after meaningful edits. Read the cited guidance and assess findings against the project context before applying them.
Commands:
```bash
@@ -132,7 +130,7 @@ Single-context: `CONTEXT.md` + `docs/adr/` at the repo root. See `docs/agents/do
<!-- gitnexus:start -->
# GitNexus — Code Intelligence
This project is indexed by GitNexus as **museion** (4735 symbols, 16431 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
This project is indexed by GitNexus as **museion** (4911 symbols, 17496 relationships, 300 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.
> Index stale? Run `node .gitnexus/run.cjs analyze` from the project root — it auto-selects an available runner. No `.gitnexus/run.cjs` yet? `npx gitnexus analyze` (npm 11 crash → `npm i -g gitnexus`; #1939).
@@ -189,6 +187,7 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
<!-- write-log: window-start -->
| Date | Log |
|------|-----|
| 2026-10-27 | [20261027-issue135-profiles-s2-settings-page-ui_log.md](docs/devlog/20261027-issue135-profiles-s2-settings-page-ui_log.md) |
| 2026-10-27 | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](docs/devlog/20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) |
| 2026-10-22 | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](docs/devlog/20261022-issue31-first-draft-stats-capture-s5-1_log.md) |
| 2026-10-22 | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](docs/devlog/20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) |
@@ -198,5 +197,4 @@ Session logs live in `docs/devlog/` (one per completed task/issue/milestone). Fu
| 2026-10-21 | [20261021-issue26-promote-consult-learnings_log.md](docs/devlog/20261021-issue26-promote-consult-learnings_log.md) |
| 2026-10-20 | [20261020-issue124-cancel-ack-fake-deferred-teardown_log.md](docs/devlog/20261020-issue124-cancel-ack-fake-deferred-teardown_log.md) |
| 2026-10-20 | [20261020-issue25-apply-skip-fix-cards-trust-ui_log.md](docs/devlog/20261020-issue25-apply-skip-fix-cards-trust-ui_log.md) |
| 2026-10-20 | [20261020-issue24-pass-guard-matrix_log.md](docs/devlog/20261020-issue24-pass-guard-matrix_log.md) |
<!-- write-log: window-end -->
+2
View File
@@ -6,6 +6,8 @@ All notable changes to this project will be documented in this file. The format
### Added
- **settings:** Profiles S2 — Settings page as sidebar + detail (#130 prototype variant C verdict) — destinations Content (the unchanged Home control) · Pass 1 · Pass 2 · Chat (annotated "· Sessions") · Provider Keys. Each surface page edits its model block over an in-memory model: provider menu, model combobox sourcing Hermes' own registry cache with first-class free text (the seed `claude-sonnet-5-5` reads as *custom (not in registry)* — the default state), per-provider reasoning-effort menu led by "unset · provider default", variant B's current-model headline, and Restore Defaults back to the #132 seed; the Provider Keys page carries endpoint, the z.ai key-type toggle swapping the endpoint family (`/api/paas/v4` ↔ `/api/coding/paas/v4`, custom endpoints survive), and masked keys with reveal. Persistence is S3's — every change routes through an injectable `SettingsWriting` seam whose contract (debounce, secrets never via argv, redacted error text) is frozen now; write failures surface in an orange strip. Dropdown picks commit through `comboBoxSelectionDidChange` reading the selection index — the notification fires before `stringValue` updates (log-observed dogfood fix). Suite 432 (issue #135)
- **profiles:** Profiles S1 — surface registry + provisioning ×3 (PRD #134, ADR-0014) — one gate pass now provisions ALL THREE Hermes profiles: `museion` is adopted in place (never re-created or reconfigured — its model stays the user's), `museion-pass1`/`museion-pass2` are created fresh with the #132 defaults (`claude-sonnet-5-5` on anthropic, reasoning effort unset, 24k output budget as a guardrail) written via the engine's own `hermes -p <profile> config set` rail — wire-verified, marker-gated so a re-pass is a no-op and Settings changes survive, and a failed provision names the profile on the #48 card. Writing skills move to ONE master copy at `~/Library/Application Support/Museion/skills/` symlinked into each profile per the #133 allocation (Pass 1: 9 · Pass 2: 8 · Chat: 10 — the persona pair never co-occurs); today's copy-era dirs migrate to symlinks only on byte-match, diverged dirs stay copies, user skills untouched. Daily backup widens to one stamp carrying all three profiles — any live engine skips the whole stamp; restore docs name the three folders (issue #134)
- **stats:** First-draft stats capture (PRD S5.1) — running Pass 1 or Pass 2 on an unaided draft (writer-origin, First Draft Pass State, post type) computes four style metrics natively in Swift at the invocation — before the mentor sees anything — and stamps `stats_captured` plus four `stats_*` values into the piece's frontmatter, so the coming trend view is a scan of `posts/`; a cancelled pass keeps its capture, re-runs while still First Draft overwrite (latest draft wins), and the frontmatter write paths (pass completion, editor save) now update their keys in place instead of rebuilding the block — captured stats and foreign YAML survive (issue #31)
+1 -1
View File
@@ -34,7 +34,7 @@ Owned by the root AGENTS.md contract. The `.xcodeproj` uses **filesystem-synchro
- `OutlineRowTextView.swift` — #109 the promoted row editor (extracted from OutlineEditorView.swift in #112, code unchanged): borderless NSTextView subclass (`RowTextView`), native undo/IME, rust caret, wraps at the column width; `keyDown` intercepts the structural key set (every intercepted branch returns WITHOUT super); echo-guard update (adopt model text only when it differs from the last local emission); `sizeThatFits` floors at 21 so the row never grows on focus.
- Editor core (#19 / S1.2, ADR-0010 mode B): `ProsePresenter.swift` (nonisolated) — **#77 reading-parity rework**: line-kind → attributes map mirroring the calm-ruled reading surface (#78) — leading calibrated to CSS `--lh 1.8` via font metrics (`lineHeightMultiple(font:cssLineHeight:)` — copying the CSS number would overshoot ~20%, TextKit multiplies the natural box), heading ladder h1 30 / h2 22 / h3 19 body-face-bold / h4+ bold body (blank source lines = 9pt half-height separators), quote = secondary ink + 20pt firstLineHeadIndent, fence interiors mono-14 on substrate (fence-state scan of the prefix for reattribute), inline traits: `**bold**` / `_italic_` / `` `code` `` / link labels (ink + underline; brackets+URL dim; CommonMark intraword-`_` never emphasizes), list markers + heading hashes + quote markers dim; full-doc `attribute` on load, per-paragraph `reattribute` on edit; plain store stays the source of truth (ADR-0010: presentation-only attributes). `EditorSession.swift` — @MainActor @Observable session per open document: **#22 `SessionTarget`** (`.post(id, home)` | `.externalFile(url)` — postID/fileURL computed per target; #107: `folderURL` is a stored property, resolved once at init for posts via `PostStore.folder(of:)` (fallback `projects/posts/<id>` for a vanished piece); the convenience `init(postID:home:)` keeps #19 call sites unchanged); `edit` re-arms a ~1 s debounce (#64) → `flush` (⌘S / selection change / window close / app quit also flush); `flush` routes through target-aware `writeDocument` — posts write `PostStore.overwrite` + the cursor sidecar, externals write the whole text in place with NO sidecar (#93); `loadFailed` (audit fix: a foreign file whose read failed — wrong encoding, permissions, vanished — never opens as a writable empty session; `openExternal` refuses it into `lastError` and `flush` is a no-op, so the empty editor's first keystroke can't destroy the file); external reads strip BOM + normalize CRLF→LF (the corpus machinery splits on `\n`; a CRLF pair is one Swift grapheme); tracks `saveState` Changed→Saved (+ Save failed in accent, #65/#83, routed to `lastError` too — dirty = local text ≠ last flushed, shown honestly while the debounce holds); `diskDidChange(diskText:)` raises the #67 conflict when disk ≠ last-flushed AND ≠ local (posts via the projects/+archive watcher rescan, externals via the per-file watcher); `reloadFromDisk` (alert Yes) bumps `loadGeneration` + re-reads (posts restore the sidecar cursor, externals reset it — #93); `keepLocal` (No/Esc) marks disk as seen — next autosave overwrites (explicit choice); the debounce never fires while the conflict alert is unanswered (#67 — only ⌘S is explicit enough to overwrite then); `teardown(flushFirst:)` is the owner's lifecycle exit (flush before rename's disk read, cancel-only on trash/vanish so the debounce can't fire at a dead path); **#25:** `adoptText(_:)` — Fix Card apply's programmatic adoption, Yes-reload's body with a provided text (`loadGeneration` bump re-seeds both the prose and outline surfaces, immediate flush); writer-consented like ⌘S, so the #67 guard is the CALLER's job (applyCard aborts on an unanswered conflict); `folderURL` exposes the document's folder for reading image resolution (#71). `PostEditorView.swift` — toolbar (mono crumb + `SaveStateDot`: 6px dot + label, accessibilityLabel role=status; drafts show "⌘S saves" instead — no Save button, the stub's died; **#92: the external guest's crumb is the file name**) + `ProseTextView` (NSViewRepresentable: plain `isRichText = false` NSTextView, presentation-only attributes, native undo/IME/find, 640pt measure, loads keyed by session `loadGeneration` — never per keystroke; cursor state pushed on selection change, restored clamped on load); window-close observer flushes (#64); the #67 alert (Reload / Keep Local) lives here, above the surface swap (shows while reading too; **#22: message names the file, post.md or the external's**). #77 spellcheck posture: `AppGateState.spellChecking` (default false — Neo triage, markdown on disk carries the spelling; per-launch, no persistence) toggled by Edit ▸ Check Spelling While Typing (`EditSpellingToggle` in MuseionApp.swift — commands views take `gate` as a plain property, they don't inherit the window environment) and applied to the live NSTextView in `makeNSView`/`updateNSView`. `PostStore` cursor sidecar (#66): `CursorState{selectionLocation,selectionLength,scrollOffset}` Codable in the resolved piece folder's `.museion-state.json` (#107 — wherever the piece lives, projects/ or archive/) — Finder-invisible, dies with the folder on Trash, drafts skip it; content write and sidecar write are separate (a failed sidecar never reads as a failed save).
- Prose list machinery (#115 / S5, map #110): `ProseList.swift` (nonisolated, pure) — list-item scan/mutation model over the plain mode-B buffer: `Item` (marker line, marker end, block, fold scope, hidden-line count, indent), CommonMark-ish marker regex shared with `ProsePresenter.listMarkerPattern` (marker math must agree with classify), indent derives the unit from the previous sibling's content column ("- "→2, "1. "→3), outdent ≤2 columns with caret riding the shift, move = sibling-adjacent swap preserving between-text with the subtree; every structural edit is ONE range replacement (single undo step), fences end blocks, lazy continuations belong to the item. `ProseListTextView.swift` — NSTextView subclass the editor installs in place of the stock view: keyDown/insertBacktab intercept Tab/⇧Tab/⌥↑/⌥↓ (every intercepted branch returns without super, RowTextView precedent), edits apply through shouldChangeText/didChangeText so undo + coordinator reattribute stay native; fold state is VIEW state (`Fold` keyed by marker-line location, re-keyed to the nearest parent with the same marker text on edit — no match → fold dies), hidden scopes styled to near-zero height via `ProseTypography.foldedAttributes` (buffer never changes, ADR-0013 posture in prose), caret landing inside a hidden scope parks at the marker end. **Chrome rendering (#115 field findings):** SwiftUI-hosted TextKit2 never calls `NSTextView.draw(_:)` and every `NSTextLayoutManager` fragment query (location bridge, `textLayoutFragment(for:)`, enumeration) yields nothing — chevrons/⋯N render offscreen into an NSImage set as a click-through overlay's `layer.contents` (`ProseChromeView`, deferred one main-queue tick past textDidChange), and line geometry comes from `firstRect(forCharacterRange:)` (SCREEN coords → `window.convertFromScreen` → view) because the selection/caret pipeline is the only geometry source that answers under this hosting.
- `SettingsPaneView.swift` — Home control (NSOpenPanel folder pick; files/canCreate on). Repoint-only semantics stated in-UI. #72 rework: the Typography/Text Flow sections are deleted — single-user app, prose type is hardcoded (ProseTypography constants + reading.css).
- Settings (#135, Profiles S2 — #130 prototype variant C verdict, ADR-0014): `SettingsPaneView.swift` — sidebar + detail shell (`SettingsPage`: Content · Pass 1 · Pass 2 · Chat · Provider Keys; sidebar rows = quiet label + trailing mono annotation, Chat carries "· Sessions"; surface card + inset 2px accent bar when current). Content page = the #17 Home control unchanged (NSOpenPanel folder pick; files/canCreate on; repoint-only semantics stated in-UI; #72: no Typography/Text Flow sections — prose type is hardcoded). `SettingsPagesView.swift` — the per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline, 24k budget stated as a non-control, and a Restore Defaults button in the page header — `resetToDefault(for:)`, a no-op at the seed, persists like any change) and the Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the endpoint family, masked key + reveal; coding-plan keys are distribution-restricted — standard keys ship). `ModelComboBox.swift` — NSComboBox representable: registry list + first-class free text (the #132 seed claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern); commits ride THREE rails — Enter (action), blur (controlTextDidEndEditing), and `comboBoxSelectionDidChange` for dropdown picks (dogfood #135, log-observed: the notification fires BEFORE stringValue updates, so the pick is read from `objectValueOfSelectedItem` and the box re-synced by hand — reading stringValue commits the stale value and the model never learns the pick; pinned in SettingsModelTests against the stale-string fixture). `SettingsModel.swift` — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`) with per-provider effort ladders + pinned switch-default models, `ZaiKeyType` endpoint families, `ModelRegistry` (lenient load of `~/.hermes/provider_models_cache.json`, memoized via `loadedDefault` — the pane's @State init re-runs the default args per SwiftUI construction), `SettingsModel` (@MainActor @Observable, pane-local until S3): `config(for:)` clamps a hydrated effort outside the provider's ladder to nil (S3 reads hand-edited config.yaml — a blank menu selection never renders), fire-and-forget writes tracked in `pendingWrites` (capped; `awaitPendingWrites()` is the tests' sync point), and the `SettingsWriting` write-path seam — S3 implements it (`config set` + `.env` fan-out); the docstring carries the implementer contract (MUST debounce — the key field fires per keystroke; secrets via stdin/env never argv; error text redacted before `lastWriteError` renders it); S2 ships `NoopSettingsWriter`; write failures land in `lastWriteError` (orange strip under the header, cleared by the next SUCCESSFUL write — interleaving ceiling ponytail-noted). DesignTokens gains `settingsSidebarWidth` 190 / `settingsFormWidth` 480.
- Focus mode (#21 / S1.2, map #21 — landed, calibration gate #88 ruled CALM 2026-10-09): `AppGateState.isFocused` (transient like reading #68 — per-launch, no persistence; View ▸ Toggle Focus Mode beside Toggle Reading Mode + ⌥⌘F via `FocusModeToggle` in MuseionApp.swift — ⇧⌘F collides with a system-wide shortcut on this machine, ⌃F shadows the editor's caret-forward binding; disabled when no post is open and no draft exists, but exit stays armed so trashing the open post can't trap). `FocusChrome.swift` — `HoverZone` (tracking-area edge strip, click-through via `hitTest → nil`; `zoneWidth` is the calibration knob), `FocusOverlayPanel` (slide-in overlay panel — floats over the measure, never pushes it; 140 ms hide grace covers the zone→panel transit; hidden = `opacity(0)` + `accessibilityHidden`), `CaretCentering` (soft caret centering: ±60pt comfort band, pure `targetOffset` math + animated clip-view scroll from `textDidChange` only — scrollback/drag-selection never fought, document clamp parks at the bottom, no jump; **#88 calibration: EDITOR-WIDE, not focus-gated** — centering plus `syncTypewriterInset` breathing room (half-viewport text-container padding, so the clamp can center the last lines while typing at the document end) apply in plain editing too; revert = restore the `focused` guard at the two call sites). `WorkspaceView` hides the rail in focus (pane takes full width); left-edge hover slides rail+library back in (library only when window ≥1100px — #17's width collapse is not overridden). `PostsPaneView` hides library+mentor columns; right-edge hover slides the mentor back in (same width verdict — `showsMentor`). `PostsLibraryColumn` (extracted from PostsPaneView) is the shared library implementation, unfocused layout and focus overlay alike — rename sheet + context menu travel with it. `PostEditorView` — toolbar row recedes in focus; the failure surface is a floating chip at the top edge: save failure shows the full `SaveStateDot` (loud), a dirty draft shows the muted "⌘S saves" cue (drafts have no autosave); ⌘S lives at body level so it stays armed with the toolbar hidden; `ProseTextView.focused` carries the ground posture through the representable. Focus × reading orthogonal (⌘R works in focus, ⌥⌘F works while reading — independent state axes). **#89 two-color world (calibrated live, deliberate departure from the export):** `DesignTokens.background` #FAF9F3 (chrome + focus ground), `DesignTokens.surface` #FFFEFB (ONE page color — editing card, editor ground, and reading page all share it; the hardcoded `NSColor.white` sites are gone), rust #C96442 caret (`insertionPointColor`), reading highlights cream washes (#C4AF8A, .075 hover / .19 selection) with rust focus ring. **#90:** Posts header, editor toolbar, mentor header all at the export's 52px — hairlines read as one line.
- Reading mode (#76 / S1.2, map #20; ADR-0011 apex HTML pipeline; decisions #68/#69/#70/#73): `ReadingPresenter.swift` (nonisolated, pure) — `stampSource` prepends `<!--S:N-->` sentinels before every blank-line chunk (apex passes HTML comments through); `apexRender` runs the **bundled apex binary** (`Museion/Resources/apex`, fs-sync group ships it in Resources automatically; fallback chain bundle → `APEX_PATH` → Homebrew, dev-only) with `-t html --no-mixed-lists --embed-images [--base-dir <postFolder>]` (no-mixed-lists REQUIRED: apex default merges ordered-after-bullets into one <ul>, killing `1. 1. 1.` renumbering; embed-images inlines base64 so `loadHTMLString` needs no file access and nothing is written to the vault); `stampHTML` regex-rewrites sentinels to `data-source-line="N"` on the following element (0 mis-stamps corpus-wide, #74); `blocks(for:)` builds the line↔UTF-16-range map (the #68 click→edit/scroll-sync contract); `page(for:postFolder:)` assembles the shell with `styleSheet()` — #72 rework: the whole stylesheet is `Museion/Resources/reading.css`, read FRESH per page build (dev builds prefer the repo copy via DerivedData-path detection, so CSS edits apply on the next reading toggle with no rebuild; the bundle copy ships in release). Values hardcoded for Alexander's fonts: Valkyrie OT B body 17/1.5, Concourse OT headings (w600), UbuntuMono code 14, 66ch measure — no UserDefaults, no Settings. **#72 polish (critique-directed, 2026-10-07):** flow defaults leading 1.5 / para 0.65 lines / code 14px; heading ladder h1 1.15× / h2 0.85× / h3 body×1.12 body-face w600 with cling margins (hN→content margin-top 0, hN+hN 0.35em, `body > :first-child` no offset); blockquote confident (near-ink #48484d, 3px rail #a1a1a6, nesting degrades to hairline); tables booktabs (top/bottom rules, heavier header rule, no vertical grid, full width); code = substrate-tint panel, inline code 0.88em relative; link underline #a1a1a6 → ink on hover; `::selection`/`:focus-visible` themed; secondary tokens `--secondary/--rule/--substrate`. Fallback on apex failure = escaped source in a `<pre>` (#69 rule: fallback is the source, not a second renderer); footnotes render natively (apex upgrade over #69's fallback-decision). `ReadingSurface.swift` — `ReadingStateBox`/`CaretHintBox` (flow state, #68) + one **WKWebView reloaded in place** (remount was the dominant switch cost, #74; keyed render on generation+text+flowKey, never per keystroke): injected `probeJS` maps click→source line (tap = edit intent at that block), ⌘-click→`NSWorkspace.open`, scroll→top-visible-line into `stateBox.topSourceLocation`; `decidePolicyFor` allows only our own about:blank main-frame load, cancels the rest; entry-caret mapping scrolls the caret's block to top after `didFinish`; reload keyed on generation+text only (#72 rework: no flow knobs — the CSS file is read per build). DELETED with the pivot: `ReadingCanvasView`, `Decoration`, `framesForRange`, `ImagePopoverView` (ADR-0011: fallbacks rot; the #71 stale-flow defect dies unfixed). Editing side untouched: `ProsePresenter`, `EditorSession`, `ProseTextView`, toggle wiring (#68) all stand; editing-side spacing obligation lives in #77.
- `AppGateState.museionHome` — app-scoped Home (UserDefaults `museionHome`, default `~/Documents/Museion` = `defaultMuseionHome`; non-file URLs read back as nil — the Home is always a folder). Explicit init: `Self` in a stored-property initializer breaks `@ObservationTracked` (covariant-Self error).
+5
View File
@@ -22,6 +22,11 @@ enum DesignTokens {
static let radius: CGFloat = 10
/// #135 (prototype `.vC`): the Settings sidebar column and the detail
/// form's max width.
static let settingsSidebarWidth: CGFloat = 190
static let settingsFormWidth: CGFloat = 480
/// The workspace grid: rail | posts library | editor | mentor (grid-template-columns
/// `56px 232px minmax(420px, 1fr) 356px`). Editor min (420) has no enforcement
/// yet — the editor column arrives with #19.
+105
View File
@@ -0,0 +1,105 @@
//
// 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 SwiftUI
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)
}
}
}
+345
View File
@@ -0,0 +1,345 @@
//
// SettingsModel.swift
// Museion
//
// #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.
//
import Foundation
import Observation
/// The three providers Settings offers (#135). Raw values are Hermes' own
/// provider slugs (`CANONICAL_PROVIDERS`) — the same ids key the registry
/// cache; OpenAI's slug is `openai-api`.
nonisolated enum ModelProvider: String, CaseIterable, Sendable {
case zai
case anthropic
case openaiAPI = "openai-api"
var label: String {
switch self {
case .zai: "z.ai"
case .anthropic: "Anthropic"
case .openaiAPI: "OpenAI"
}
}
/// #128: the per-provider ladders Hermes clamps per route — one
/// `model.reasoning_effort` key, surfaced per provider.
var effortOptions: [ReasoningEffort] {
switch self {
case .zai: [.low, .high, .max]
case .anthropic, .openaiAPI: [.low, .medium, .high, .xhigh, .max]
}
}
/// The model a provider switch lands on (prototype #130's pinned
/// flagships — registry order is capability-sorted, not default-sorted).
var switchDefaultModel: String {
switch self {
case .zai: "glm-5.3"
case .anthropic: "claude-sonnet-5"
case .openaiAPI: "gpt-5.6-sol"
}
}
/// Default endpoint families (factsheet §1; z.ai's is key-type keyed).
var defaultEndpoint: String {
switch self {
case .zai: ZaiKeyType.standard.endpoint
case .anthropic: "https://api.anthropic.com"
case .openaiAPI: "https://api.openai.com/v1"
}
}
}
nonisolated enum ReasoningEffort: String, CaseIterable, Sendable, Equatable {
case low
case medium
case high
case xhigh
case max
}
/// z.ai's two key types pick the endpoint family (factsheet §1.1) — coding
/// plan keys are distribution-restricted; shipped Museion uses standard.
nonisolated enum ZaiKeyType: String, CaseIterable, Sendable {
case standard
case coding
var endpoint: String {
switch self {
case .standard: "https://api.z.ai/api/paas/v4"
case .coding: "https://api.z.ai/api/coding/paas/v4"
}
}
var label: String {
switch self {
case .standard: "Standard (pay-as-you-go)"
case .coding: "Coding plan"
}
}
}
/// One surface's model block — what Settings edits and S3 persists via the
/// write path (the profile's `model:` block).
nonisolated struct SurfaceModelConfig: Equatable, Sendable {
var provider: ModelProvider
var model: String
/// nil = unset · provider default (the key is simply not written).
var effort: ReasoningEffort?
/// The #132 fresh-seed posture: sonnet on all three surfaces, effort
/// unset. Never copied from the live museion profile.
static let surfaceDefault = SurfaceModelConfig(
provider: .anthropic,
model: ProfileSurface.defaultModelID,
effort: nil,
)
}
/// One provider's key block — endpoint (base URL) + API key. One key per
/// provider fans out to every profile on that provider (#131: no Keychain).
nonisolated struct ProviderKeyConfig: Equatable, Sendable {
var endpoint: String
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.
@MainActor
@Observable
final class SettingsModel {
private(set) var surfaces: [ProfileSurface: SurfaceModelConfig]
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).
private(set) var lastWriteError: String?
private let writer: any SettingsWriting
init(
registry: ModelRegistry = .loadedDefault,
writer: any SettingsWriting = NoopSettingsWriter(),
surfaces: [ProfileSurface: SurfaceModelConfig]? = nil,
) {
self.registry = registry
self.writer = writer
self.surfaces = surfaces
?? Dictionary(uniqueKeysWithValues: ProfileSurface.allCases.map { ($0, .surfaceDefault) })
keys = Dictionary(
uniqueKeysWithValues: ModelProvider.allCases.map {
($0, ProviderKeyConfig(endpoint: $0.defaultEndpoint))
},
)
}
func config(for surface: ProfileSurface) -> SurfaceModelConfig {
var config = surfaces[surface] ?? .surfaceDefault
// Read-boundary clamp: a config hydrated with an effort outside the
// provider's ladder (S3 reads hand-edited config.yaml files) must not
// render a blank menu selection. The stored value is untouched — the
// next mutation writes a clamped copy.
if let effort = config.effort, !config.provider.effortOptions.contains(effort) {
config.effort = nil
}
return config
}
func keyConfig(for provider: ModelProvider) -> ProviderKeyConfig {
keys[provider] ?? ProviderKeyConfig(endpoint: provider.defaultEndpoint)
}
/// True when the model id isn't in Hermes' registry for its provider —
/// claude-sonnet-5-5 (the #132 seed) is NOT in the cache, so custom is
/// the DEFAULT state, not an edge case.
func isCustom(_ surface: ProfileSurface) -> Bool {
let config = config(for: surface)
return !registry.list(for: config.provider).contains(config.model)
}
/// 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).
func setProvider(_ provider: ModelProvider, for surface: ProfileSurface) {
var config = config(for: surface)
guard config.provider != provider else { return }
config.provider = provider
config.model = provider.switchDefaultModel
config.effort = nil
surfaces[surface] = config
persist(surface, config)
}
func setModel(_ model: String, for surface: ProfileSurface) {
let trimmed = model.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty else { return }
var config = config(for: surface)
guard config.model != trimmed else { return }
config.model = trimmed
surfaces[surface] = config
persist(surface, config)
}
func setEffort(_ effort: ReasoningEffort?, for surface: ProfileSurface) {
var config = config(for: surface)
guard config.effort != effort else { return }
config.effort = effort
surfaces[surface] = config
persist(surface, config)
}
/// Back to the #132 seed (sonnet, effort unset) — the page's Restore
/// Defaults button. No-op when already there; a real reset persists.
func resetToDefault(for surface: ProfileSurface) {
guard config(for: surface) != .surfaceDefault else { return }
surfaces[surface] = .surfaceDefault
persist(surface, .surfaceDefault)
}
/// z.ai's key type picks the endpoint family (factsheet §1). A custom
/// endpoint survives the toggle; a family default (or empty) swaps.
func setZaiKeyType(_ type: ZaiKeyType) {
guard zaiKeyType != type else { return }
zaiKeyType = type
let endpoint = keyConfig(for: .zai).endpoint
if endpoint.isEmpty || ZaiKeyType.allCases.contains(where: { $0.endpoint == endpoint }) {
keys[.zai]?.endpoint = type.endpoint
}
persistKey(.zai)
}
func setEndpoint(_ endpoint: String, for provider: ModelProvider) {
guard keys[provider]?.endpoint != endpoint else { return }
keys[provider]?.endpoint = endpoint
persistKey(provider)
}
func setAPIKey(_ key: String, for provider: ModelProvider) {
guard keys[provider]?.apiKey != key else { return }
keys[provider]?.apiKey = key
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>] = []
/// Awaits in-flight writes — the tests' deterministic sync point.
func awaitPendingWrites() async {
for task in pendingWrites {
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)
}
}
private func persist(_ surface: ProfileSurface, _ config: SurfaceModelConfig) {
track(Task {
do {
try await writer.writeSurface(surface, config: config)
lastWriteError = nil
} catch {
lastWriteError = error.localizedDescription
}
})
}
private func persistKey(_ provider: ModelProvider) {
let config = keyConfig(for: provider)
let keyType = provider == .zai ? zaiKeyType : nil
track(Task {
do {
try await writer.writeProviderKey(provider: provider, config: config, keyType: keyType)
lastWriteError = nil
} catch {
lastWriteError = error.localizedDescription
}
})
}
}
+273
View File
@@ -0,0 +1,273 @@
//
// 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
/// 10.5 uppercase, 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: 10.5, 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 {
let config = model.config(for: surface)
VStack(alignment: .leading, spacing: 4) {
HStack {
Text(label)
.font(.system(size: 16, 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)
.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)
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)
}
.padding(.top, 12)
}
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.padding(.horizontal, 26)
.padding(.top, 18)
.padding(.bottom, 48)
}
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: 16, 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)
VStack(alignment: .leading, spacing: 10) {
ForEach(ModelProvider.allCases, id: \.self) { provider in
ProviderKeyBlock(model: model, provider: provider)
}
}
.padding(.top, 12)
}
.frame(maxWidth: DesignTokens.settingsFormWidth + 60, alignment: .leading)
.padding(.horizontal, 26)
.padding(.top, 18)
.padding(.bottom, 48)
}
}
/// 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)
}
}
.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 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")
}
}
+181 -27
View File
@@ -3,50 +3,204 @@
// Museion
//
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
// #72 rework: the Typography + Text Flow sections are gone — single-user
// app, prose typography is hardcoded (editing: ProseTypography constants;
// reading: Museion/Resources/reading.css, editable while the app runs).
// #135 (Profiles S2): reworked to the #130 prototype's variant C verdict —
// a Settings sidebar + detail column (System Settings shape): destinations
// Content · Pass 1 · Pass 2 · Chat · Provider Keys. Content keeps the #17
// Home control unchanged; the surface and keys pages live in
// SettingsPagesView.swift over the in-memory SettingsModel (persistence is
// S3's job — the write-path protocol is the seam).
//
import AppKit
import SwiftUI
/// Settings pane. Home control per #17.
/// Settings pane — sidebar + detail per prototype variant C.
struct SettingsPaneView: View {
@Binding var home: URL
@State private var page: SettingsPage = .content
/// #135: in-memory model, pane-local until S3 lifts persistence in.
@State private var model = SettingsModel()
var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 24) {
contentSection
VStack(spacing: 0) {
PaneHeader(title: "Settings")
if let error = model.lastWriteError {
Text(error)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(.orange)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14)
.padding(.vertical, 4)
}
HStack(spacing: 0) {
sidebar
Rectangle()
.fill(DesignTokens.border)
.frame(width: 1)
detail
}
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
.background(DesignTokens.background)
}
// MARK: Home (#17)
// MARK: Sidebar (prototype `.vC .side`)
private var contentSection: some View {
VStack(alignment: .leading, spacing: 12) {
Text("Content")
.font(.system(size: 13, weight: .semibold))
HStack(spacing: 8) {
Text(home.path(percentEncoded: false))
.font(.system(size: 12, design: DesignTokens.mono))
.lineLimit(1)
.truncationMode(.middle)
.textSelection(.enabled)
Spacer(minLength: 12)
Button("Choose…") { chooseHome() }
private var sidebar: some View {
VStack(alignment: .leading, spacing: 2) {
ForEach(SettingsPage.allCases) { candidate in
SettingsSidebarButton(
page: candidate,
selection: $page,
)
}
Text(
"Repoint-only: Museion never moves content. The Posts list reads this folder's projects/ and archive/ directories.",
)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
Spacer(minLength: 0)
}
.padding(.horizontal, 8)
.padding(.vertical, 14)
.frame(width: DesignTokens.settingsSidebarWidth)
}
// MARK: Detail (prototype `.vC .detail`)
private var detail: some View {
ScrollView {
switch page {
case .content:
ContentSettingsPage(home: $home)
case .pass1:
SurfaceSettingsPage(model: model, surface: .pass1)
case .pass2:
SurfaceSettingsPage(model: model, surface: .pass2)
case .chat:
SurfaceSettingsPage(model: model, surface: .chat)
case .keys:
ProviderKeysPage(model: model)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// The sidebar's destinations (#135): the #17 Content control, one page per
/// LLM surface (Sessions rides Chat — #126), and the provider keys.
enum SettingsPage: String, CaseIterable, Identifiable, Hashable {
case content
case pass1
case pass2
case chat
case keys
var id: String {
rawValue
}
var label: String {
switch self {
case .content: "Content"
case .pass1: "Pass 1"
case .pass2: "Pass 2"
case .chat: "Chat"
case .keys: "Provider Keys"
}
}
/// The prototype's trailing mono annotation: pass chips + the Sessions
/// note on Chat (the chat row notes "Sessions rides this engine").
var annotation: String? {
switch self {
case .pass1: "P1"
case .pass2: "P2"
case .chat: "· Sessions"
default: nil
}
}
}
/// One sidebar row (prototype `.vC .side-button`): quiet label, trailing
/// mono annotation, surface card + inset accent bar when current.
private struct SettingsSidebarButton: View {
let page: SettingsPage
@Binding var selection: SettingsPage
@State private var hover = false
var body: some View {
let selected = selection == page
Button {
selection = page
} label: {
HStack(spacing: 8) {
Text(page.label)
.foregroundStyle(DesignTokens.foreground)
Spacer(minLength: 0)
if let annotation = page.annotation {
Text(annotation)
.font(.system(size: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
.padding(.horizontal, 10)
.padding(.vertical, 7)
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.background {
if selected || hover {
RoundedRectangle(cornerRadius: 8)
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
}
}
.overlay(alignment: .leading) {
// `.side-button.current` inset accent bar.
if selected {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 4)
}
}
.onHover { hover = $0 }
.accessibilityLabel(page.label)
.accessibilityAddTraits(selected ? [.isSelected] : [])
}
}
/// The Content page: the existing #17 Home control, repoint-only, in the
/// variant C form (quiet label, mono path, Choose…).
private struct ContentSettingsPage: View {
@Binding var home: URL
var body: some View {
VStack(alignment: .leading, spacing: 4) {
Text("Content")
.font(.system(size: 16, weight: .semibold, design: DesignTokens.serif))
Text("Where the corpus lives.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
VStack(alignment: .leading, spacing: 14) {
VStack(alignment: .leading, spacing: 4) {
SettingsFieldLabel("Museion Home")
HStack(spacing: 8) {
Text(home.path(percentEncoded: false))
.font(.system(size: 12, design: DesignTokens.mono))
.lineLimit(1)
.truncationMode(.middle)
.textSelection(.enabled)
Spacer(minLength: 12)
Button("Choose…") { chooseHome() }
.buttonStyle(.bordered)
}
}
Text("Repoint-only: Museion never moves content.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
}
.padding(.top, 12)
}
.frame(maxWidth: DesignTokens.settingsFormWidth, alignment: .leading)
.padding(.horizontal, 26)
.padding(.top, 18)
.padding(.bottom, 48)
}
private func chooseHome() {
+1
View File
@@ -39,6 +39,7 @@ Owned by the root AGENTS.md contract.
- `OutlineDragTests.swift` (#112) — the drag plumbing pins: the tracker holds its OWN arm-time copies of the callbacks (a post-arm swap of the view's closures never fires — the gesture is self-contained, so a mid-drag scroll that drops the origin row's catcher can't strand the surface's drag state; a true dealloc can't be reproduced in the host — AppKit keeps internal retains on once-installed views, so the swap is the observable), arming a second drag cancels a stuck predecessor as a cancel, and `rowFrames` prefers the grip catcher's full-row frame over the body catcher's text-only frame in both subview orders.
- ReadingPresenterTests gains the #109 pin: a canonical outline body (nested bullets) renders NESTED `<ul>` through the real apex pipeline — reading mode needs no outline-specific surface (ADR-0013).
- `ProseListTests.swift` (#115 / S5) — the prose list model + fold rendering: scan pins (item basics, nested children + fold scope, lazy continuation, blank-separated child folds the blank too, fences end blocks, parents scan), indent/outdent (dash content column, caret ride + park, ordered-marker unit, boundary nils), move (subtree swap with between-text, boundary no-ops); `ProseFoldRenderingTests` (@MainActor, plain `ProseListTextView()` — no window, chrome never installs) — folding never edits the buffer, hidden scopes carry `foldedAttributes`, parent stays body-size, unfold restores, folds re-key to the nearest same-marker parent after an edit above, and a fold dies when its marker text vanishes.
- `SettingsModelTests.swift` (#135, Profiles S2 — scenario headers at file top) — the Settings view-model mapping over a live-shaped registry fixture (claude-sonnet-5-5 deliberately ABSENT — custom is the default state): provider → effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max) + effort-unset default + provider-switch reset; custom-model state (seed custom, registry id known, per-provider pinned switch defaults, empty registry = all custom free text, blank edits never commit); z.ai key-type → endpoint family (both defaults, toggle swaps, custom endpoint survives, cleared endpoint adopts the family); the `SettingsWriting` seam via a `RecordingWriter` double (surface writes carry config, key writes carry keyType only for zai — struct record, not a tuple, #134 ConfigWrite precedent; `failSurfaceWrites` knob pins the failure path — `lastWriteError` surfaces, next success clears it); write-sync via `awaitPendingWrites()` (deterministic, never sleeps); the hydration clamp (an effort outside the provider's ladder reads nil); `ModelRegistry.load` lenient decode (unknown providers skipped, missing file → empty, never fatal); the ModelComboBox commit rails (list pick via `comboBoxSelectionDidChange`, Enter via the action, blur via end-editing — idempotent through the echo guard, blanks never commit; the dogfood #135 pin: a bare dropdown pick fires neither action nor end-editing).
## Verification
+322
View File
@@ -0,0 +1,322 @@
//
// SettingsModelTests.swift
// MuseionTests
//
// #135 (Profiles S2) — the Settings page's view-model mapping: provider →
// effort options, custom-model state, key-type → endpoint family, and the
// write-path seam S3 implements.
//
// Scenario: Provider pins its effort ladder — Given a surface page whose
// provider is known, when the reasoning-effort menu builds (or the provider
// switches), then the menu offers exactly that provider's ladder — z.ai
// low/high/max, OpenAI + Anthropic low/medium/high/xhigh/max — always led
// by "unset · provider default" (one model.reasoning_effort key, nil).
//
// Scenario: Custom is the default state — Given the #132 seed
// claude-sonnet-5-5 (NOT in hermes' registry cache), when a surface page
// opens, then the model reads as custom (not in registry); a provider
// switch lands on that provider's pinned default model with effort reset;
// an empty registry leaves every model custom (free text is first-class).
//
// Scenario: z.ai key type picks the endpoint family — Given the Provider
// Keys page, when the key-type toggle flips, then the endpoint swaps
// /api/paas/v4 ↔ /api/coding/paas/v4 — unless the writer typed a custom
// endpoint, which survives the toggle.
//
// Scenario: Changes route through the write path — Given any Settings
// change, when it commits, then the injectable writer receives it (S3's
// seam: `hermes config set` for surface model blocks, `.env` fan-out for
// provider keys); a FAILED write surfaces its reason in the strip and the
// next successful write clears it.
//
// Scenario: Hydrated config can be stale — Given a surface whose stored
// effort sits outside its provider's ladder (a hand-edited config.yaml S3
// will read), when the page renders, then the read boundary clamps the
// effort to unset rather than show a blank menu selection.
//
import AppKit
import Foundation
@testable import Museion
import Testing
/// Records write-path calls; the injected seam's test double.
@MainActor
private final class RecordingWriter: SettingsWriting {
/// A labeled record, not a tuple — SwiftLint's `large_tuple` (the #134
/// ConfigWrite precedent).
struct KeyWriteRecord: Equatable {
let provider: ModelProvider
let config: ProviderKeyConfig
let keyType: ZaiKeyType?
}
var surfaces: [(ProfileSurface, SurfaceModelConfig)] = []
var keys: [KeyWriteRecord] = []
/// Knob: surface writes throw while set (the failure-path tests).
var failSurfaceWrites = false
func writeSurface(_ surface: ProfileSurface, config: SurfaceModelConfig) async throws {
if failSurfaceWrites {
throw NSError(domain: "test", code: 1, userInfo: [NSLocalizedDescriptionKey: "config set failed"])
}
surfaces.append((surface, config))
}
func writeProviderKey(provider: ModelProvider, config: ProviderKeyConfig, keyType: ZaiKeyType?) async throws {
keys.append(KeyWriteRecord(provider: provider, config: config, keyType: keyType))
}
}
@Suite("SettingsModelTests")
struct SettingsModelTests {
/// The real cache's shape, subset — zai + anthropic + openai-api lists,
/// with claude-sonnet-5-5 deliberately absent (live truth: the seed is
/// NOT in the registry, so custom is the default state).
private func liveShapedRegistry() -> ModelRegistry {
ModelRegistry(models: [
.zai: ["glm-4.5", "glm-5", "glm-5.3", "glm-5.3-flashx"],
.anthropic: ["claude-fable-5.1", "claude-opus-5-5", "claude-sonnet-5", "claude-sonnet-4-6"],
.openaiAPI: ["gpt-5.6-sol", "gpt-5.5", "gpt-5.4-mini"],
])
}
// MARK: Provider → effort options
@Test func `provider pins its effort ladder`() {
#expect(ModelProvider.zai.effortOptions == [.low, .high, .max])
#expect(ModelProvider.openaiAPI.effortOptions == [.low, .medium, .high, .xhigh, .max])
#expect(ModelProvider.anthropic.effortOptions == [.low, .medium, .high, .xhigh, .max])
}
@Test @MainActor func `effort unset is the leading default state`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
for surface in ProfileSurface.allCases {
#expect(model.config(for: surface).effort == nil)
}
}
@Test @MainActor func `provider switch rebuilds the effort menu and resets effort`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
model.setEffort(.max, for: .pass1)
model.setProvider(.zai, for: .pass1)
// zai's ladder drops xhigh/medium — the menu rebuilds from the new
// provider and the old choice must not survive as residue.
#expect(model.config(for: .pass1).effort == nil)
#expect(model.config(for: .pass1).provider == .zai)
}
// MARK: Custom-model state
@Test @MainActor func `the seeded sonnet model reads as custom not in registry`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
#expect(model.config(for: .pass1).model == ProfileSurface.defaultModelID)
#expect(model.isCustom(.pass1))
#expect(model.isCustom(.pass2))
#expect(model.isCustom(.chat))
// One seed truth: the Settings seed provider must stay the provisioner's
// #132 seed provider (defaultModelProvider) — Restore Defaults and
// fresh provisioning diverge silently if these drift apart.
#expect(SurfaceModelConfig.surfaceDefault.provider.rawValue == ProfileSurface.defaultModelProvider)
}
@Test @MainActor func `a registry model reads as known`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
// Chat's provider is anthropic by default — an in-registry id reads known.
model.setModel("claude-sonnet-5", for: .chat)
#expect(!model.isCustom(.chat))
}
@Test @MainActor func `provider switch lands on the provider's pinned default model`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
model.setProvider(.zai, for: .chat)
#expect(model.config(for: .chat).model == "glm-5.3")
#expect(!model.isCustom(.chat))
model.setProvider(.openaiAPI, for: .chat)
#expect(model.config(for: .chat).model == "gpt-5.6-sol")
model.setProvider(.anthropic, for: .chat)
#expect(model.config(for: .chat).model == "claude-sonnet-5")
}
@Test @MainActor func `an empty registry leaves every model custom free text stays first class`() {
let model = SettingsModel(registry: ModelRegistry(), writer: RecordingWriter())
#expect(model.isCustom(.pass1))
model.setModel("any-model-id-anyone-types", for: .pass1)
#expect(model.config(for: .pass1).model == "any-model-id-anyone-types")
#expect(model.isCustom(.pass1))
}
@Test @MainActor func `blank model edits never commit`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
model.setModel(" ", for: .pass2)
#expect(model.config(for: .pass2).model == ProfileSurface.defaultModelID)
}
// MARK: Restore Defaults
@Test @MainActor func `reset returns a changed surface to the seed and persists it`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
model.setProvider(.zai, for: .pass2)
model.setEffort(.max, for: .pass2)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 2)
model.resetToDefault(for: .pass2)
await model.awaitPendingWrites()
#expect(model.config(for: .pass2) == SurfaceModelConfig(provider: .anthropic, model: ProfileSurface.defaultModelID, effort: nil))
#expect(writer.surfaces.count == 3)
// Already at the seed — a second reset is a no-op, no write.
model.resetToDefault(for: .pass2)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 3)
}
// MARK: Key-type → endpoint family
@Test func `zai key type maps to its endpoint family`() {
#expect(ZaiKeyType.standard.endpoint == "https://api.z.ai/api/paas/v4")
#expect(ZaiKeyType.coding.endpoint == "https://api.z.ai/api/coding/paas/v4")
}
@Test @MainActor func `zai toggle swaps the endpoint family`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.standard.endpoint)
model.setZaiKeyType(.coding)
#expect(model.zaiKeyType == .coding)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
model.setZaiKeyType(.standard)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.standard.endpoint)
}
@Test @MainActor func `a custom zai endpoint survives the toggle`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
model.setEndpoint("https://proxy.internal:8443/v4", for: .zai)
model.setZaiKeyType(.coding)
#expect(model.keyConfig(for: .zai).endpoint == "https://proxy.internal:8443/v4")
}
@Test @MainActor func `a cleared zai endpoint still adopts the new family`() {
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter())
model.setEndpoint("", for: .zai)
model.setZaiKeyType(.coding)
#expect(model.keyConfig(for: .zai).endpoint == ZaiKeyType.coding.endpoint)
}
// MARK: Write-path seam
@Test @MainActor func `surface changes route through the writer`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
model.setProvider(.zai, for: .pass1)
await model.awaitPendingWrites()
#expect(writer.surfaces.count == 1)
let (surface, config) = writer.surfaces[0]
#expect(surface == .pass1)
#expect(config == SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: nil))
}
@Test @MainActor func `key changes route through the writer with key type only for zai`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
model.setZaiKeyType(.coding)
model.setAPIKey("sk-test", for: .anthropic)
await model.awaitPendingWrites()
#expect(writer.keys.count == 2)
let first = writer.keys[0]
#expect(first.provider == .zai)
#expect(first.keyType == .coding)
#expect(first.config.endpoint == ZaiKeyType.coding.endpoint)
let second = writer.keys[1]
#expect(second.provider == .anthropic)
#expect(second.keyType == nil)
}
@Test @MainActor func `a failed write surfaces lastWriteError and a later success clears it`() async {
let writer = RecordingWriter()
let model = SettingsModel(registry: liveShapedRegistry(), writer: writer)
writer.failSurfaceWrites = true
model.setModel("glm-5.3", for: .chat)
await model.awaitPendingWrites()
#expect(model.lastWriteError == "config set failed")
writer.failSurfaceWrites = false
model.setModel("claude-sonnet-5", for: .chat)
await model.awaitPendingWrites()
#expect(model.lastWriteError == nil)
// The failed write never landed; the successful one did.
#expect(writer.surfaces.count == 1)
}
// MARK: Hydration clamp
@Test @MainActor func `an effort outside the provider's ladder reads clamped to unset`() {
// S3 will hydrate from config.yaml a user may have hand-edited —
// zai carries no `medium` rung, so the read boundary drops it rather
// than render a blank menu selection.
let stale = SurfaceModelConfig(provider: .zai, model: "glm-5.3", effort: .medium)
let model = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), surfaces: [.pass1: stale])
#expect(model.config(for: .pass1).effort == nil)
// An in-ladder effort passes through untouched.
let valid = SurfaceModelConfig(provider: .anthropic, model: "claude-sonnet-5", effort: .medium)
let model2 = SettingsModel(registry: liveShapedRegistry(), writer: RecordingWriter(), surfaces: [.pass2: valid])
#expect(model2.config(for: .pass2).effort == .medium)
}
// MARK: Model combobox wiring (dogfood fix #135)
@Test @MainActor func `combobox list pick action and end editing all commit`() {
// The bug (probe-observed): comboBoxSelectionDidChange fires BEFORE
// stringValue updates — the handler must take the pick from the
// selection index; Enter (action) and blur (end-editing) read the
// settled stringValue.
let box = NSComboBox()
box.addItems(withObjectValues: ["glm-4.5", "glm-5.2"])
box.selectItem(at: 1)
box.stringValue = "glm-4.5" // the stale value AppKit still holds at notification time
var committed: [String] = []
let coordinator = ModelComboBox.Coordinator { committed.append($0) }
coordinator.lastLocalValue = "glm-4.5"
coordinator.comboBoxSelectionDidChange(
Notification(name: Notification.Name("ComboBoxSelectionDidChangeNotification"), object: box),
)
#expect(committed == ["glm-5.2"]) // the PICKED item, not the stale string
#expect(box.stringValue == "glm-5.2") // the handler re-syncs the box
// Idempotent: the re-sync and the follow-up events never double-commit.
coordinator.picked(box)
coordinator.controlTextDidEndEditing(
Notification(name: Notification.Name("NSTextDidEndEditingNotification"), object: box),
)
#expect(committed == ["glm-5.2"])
// Enter/action on a NEW value commits through the same rail.
box.stringValue = "glm-5.1"
coordinator.picked(box)
#expect(committed == ["glm-5.2", "glm-5.1"])
// Blank edits never commit.
box.stringValue = " "
coordinator.picked(box)
#expect(committed == ["glm-5.2", "glm-5.1"])
}
// MARK: Registry loading
@Test func `registry loads from hermes' picker cache leniently`() {
let path = (NSTemporaryDirectory() as NSString)
.appendingPathComponent("settings-registry-\(UUID().uuidString).json")
let json = """
{"zai": {"fp": "abc", "at": 123, "models": ["glm-5.3"]},
"openai-api": {"fp": "def", "at": 123, "models": ["gpt-5.6-sol"]},
"unknown-provider": {"fp": "x", "at": 1, "models": ["whatever"]}}
"""
try? json.write(toFile: path, atomically: true, encoding: .utf8)
let registry = ModelRegistry.load(path: path)
#expect(registry.list(for: .zai) == ["glm-5.3"])
#expect(registry.list(for: .openaiAPI) == ["gpt-5.6-sol"])
#expect(registry.list(for: .anthropic) == [])
// Unknown providers and an unreadable file degrade to free-text-only.
#expect(registry.list(for: .anthropic)
== ModelRegistry.load(path: "/nonexistent/cache.json").list(for: .anthropic))
}
}
@@ -0,0 +1,77 @@
# #135 Profiles S2 — Settings page UI (sidebar + detail)
> **Date:** 2026-10-27
> **Type:** issue
> **Reference:** https://git.babylondreams.de/AlexKucera/museion/issues/135
## Goal
Implement ticket #135 (Profiles S2, part of the #125 wayfinder map): rework SettingsPaneView to the #130 prototype's variant C verdict — a sidebar + detail shape with destinations Content · Pass 1 · Pass 2 · Chat · Provider Keys — over an in-memory model with an injectable write-path protocol (persistence is S3's job). Acceptance: variant C reproduced natively with working interactions (provider switch swaps the effort menu, z.ai key-type toggle swaps the endpoint family, reveal toggles) + unit tests for provider → effort options, custom-model state, key-type → endpoint family.
## Verification
- **Full suite: 432 passed / 432 total** (xcresult executed-count verified, never the banner), `xcodebuild build` SUCCEEDED, swiftformat + swiftlint clean on every touched file.
- The one first-run failure (`second pass while one runs refuses and cancel ends it`) was the documented fake-ACP load flake (#30/#134 class) — it ran while the app was launching; 432/432 on the isolation rerun.
- The combobox dogfood fix was verified from the LIVE app via temporary os_log probes (`log show --info`): a real click logged `selectionDidChange stringValue=claude-sonnet-5-5 idx=7` → `commit: raw=claude-opus-4-6 -> COMMIT`, then the user confirmed working. Probes stripped afterwards.
- Visual capture from the agent shell was impossible all session (no Screen Recording/AX permission, cua-driver down, testmanagerd flake per #134) — the pixel-level pass was the user's one-glance checklist instead.
## What Was Done
- `Museion/SettingsModel.swift` (new) — `ModelProvider` (rawValues are hermes slugs; OpenAI = `openai-api`, label "OpenAI"), per-provider effort ladders (zai low/high/max; OpenAI + Anthropic low/medium/high/xhigh/max), pinned provider-switch default models (prototype #130's flagships), `ZaiKeyType` endpoint families (/api/paas/v4 ↔ /api/coding/paas/v4, factsheet §1), `ModelRegistry` (lenient decode of `~/.hermes/provider_models_cache.json`, memoized via `static let loadedDefault`), `SurfaceModelConfig` (seed = the #132 sonnet posture), `SettingsModel` (@MainActor @Observable, pane-local until S3): `config(for:)` clamps a hydrated out-of-ladder effort to nil, `resetToDefault` (the user-requested Restore Defaults), fire-and-forget writes tracked in `pendingWrites` (capped; `awaitPendingWrites()` is the tests' deterministic sync), `lastWriteError` failure strip cleared by the next SUCCESSFUL write, and the `SettingsWriting` write-path seam — the docstring carries the implementer contract (MUST debounce — the key field fires per keystroke; secrets via stdin/env never argv; error text redacted). S2 ships `NoopSettingsWriter`.
- `Museion/SettingsPaneView.swift` (reworked) — variant C shell: `SettingsPage` sidebar (quiet labels + trailing mono annotations — Chat carries "· Sessions"; surface card + inset 2px accent bar when current) + detail column; Content page = the #17 Home control unchanged (repoint-only); orange `lastWriteError` strip under the header.
- `Museion/SettingsPagesView.swift` (new) — per-surface page (provider menu, model combobox + "custom (not in registry)" note, per-provider effort menu led by "unset · provider default", variant B's current-model accent headline stolen into C, 24k budget stated as a non-control, Restore Defaults in the page header) + Provider Keys page (per-provider block: endpoint, z.ai key-type segment swapping the family, masked key + reveal, coding-plan distribution note).
- `Museion/ModelComboBox.swift` (new) — NSComboBox representable: registry list + first-class free text (claude-sonnet-5-5 is NOT in the cache — custom is the default state), echo-guard update (OutlineRowTextView pattern), commits on three rails (action/Enter, controlTextDidEndEditing/blur, comboBoxSelectionDidChange/list-pick).
- `Museion/DesignTokens.swift` — `settingsSidebarWidth` 190 / `settingsFormWidth` 480.
- `MuseionTests/SettingsModelTests.swift` (new, 18 tests + the combobox pin) — effort ladders + unset default + provider-switch reset; custom-model state (seed custom, registry known, switch defaults, empty registry = all free text, blanks never commit); z.ai family mapping, toggle swap, custom-endpoint survival, cleared-endpoint adoption; the write-path seam via a `RecordingWriter` double (struct record, #134 ConfigWrite precedent; `failSurfaceWrites` knob pins the failure path); reset-to-seed; hydration clamp; registry lenient decode; the combobox commit rails incl. the stale-stringValue fixture.
- DOX — `Museion/AGENTS.md` (Settings section rewritten for the #135 world) + `MuseionTests/AGENTS.md` (test-file entry).
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Model combobox = NSComboBox representable | The issue's fold-in demands "a proper combobox" — the native control gives dropdown + free text + completion in one; the prototype's Custom… ↩ two-state dance collapsed into it |
| Provider switch resets model to a pinned flagship + effort to unset | Prototype #130's pinned behavior (the visual contract); registry order is capability-sorted, not default-sorted |
| Single z.ai endpoint value; toggle swaps family only when at a family default | The real write path persists ONE base_url; a custom endpoint is user data and survives the toggle (2-line guard, prevents loss) |
| `@MainActor protocol SettingsWriting` | The `NonisolatedNonsendingByDefault` upcoming feature rejects nonisolated-async conformances touching MainActor state (measured on this toolchain); S3 writers hop off-main internally |
| Write failures land in `lastWriteError`, cleared on SUCCESS not commit | LearningsPane strip posture; clearing at commit was optimistic and documented wrong (mid-session review catch) |
| Registry memoized (`loadedDefault`), per-launch | SwiftUI runs @State default args on every construction of the pane — the disk read must happen once (mid-session review catch; ponytail: no live refresh) |
| Read-boundary effort clamp in `config(for:)` | S3 hydrates from hand-edited config.yaml; an out-of-ladder effort would render a blank menu selection — the exact silent-UI-break class the combobox bug demonstrated. Ponytail reviewer asked to delete it as S3-for-later; declined — trust-boundary validation for data a planned slice certainly delivers, pinned + documented |
| `awaitPendingWrites()` instead of test sleeps | Repo learning #30/#134: timing-based waits are the fake-ACP flake class; deterministic main-actor sync instead |
| Endpoint scheme validation deferred | No network call exists in S2; the key only attaches to the URL at S3's write boundary — validate there (finish-audit deferral, recorded) |
| SettingsWriting docstring contract (debounce-MUST, secrets never argv, redact errors) | Finish-audit security finding (medium): per-keystroke commits would make S3's .env fan-out persist every partial prefix of a typed key; the cheapest right-seam fix is freezing the contract at the seam, not UI plumbing now |
| One-caller `ModelRegistry.contains` inlined | Finish-audit ponytail finding; 4 lines out, no loss |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Model dropdown picks didn't change the model (user-reported twice) | Guess #1 (missing delegate method) was half right; the REAL cause, proven by os_log probes on the live app: `comboBoxSelectionDidChange` fires BEFORE `stringValue` updates — the handler read the STALE old value, the echo guard SKIPped, and the pick never reached the model (the box followed visually, the state was stuck) | Read the pick from `objectValueOfSelectedItem`, re-sync `box.stringValue` by hand (the no-field-editor path produces no follow-up event); pinned against the stale-string fixture |
| Two blind fixes shipped before the probe round | AppKit event-ordering questions aren't answerable by reading docs — macOS 27's actual delivery differs | Temporary os_log probes + one human click settled it in a single round; probes stripped after. Recorded in the swift wiki (`gotchas/swiftui-appkit-layout.md` #17) + agent memory |
| Probe log came back empty | `log stream`/`log show` filter out `Logger.info` lines unless `--info`/`--level info` is passed | Re-query with `--info`; captured the decisive trace |
| First delegate fix round failed to compile (`os` import, probe access level, `self.` capture in the log closure) | Iterated in the small; swiftformat also re-joins guard lines the linter then flags (148/154-char lines) | Fixed per error; split guards so the formatter can't re-join them into line-length violations |
| `Task.isFinished` doesn't exist on this toolchain | `pendingWrites.removeAll { $0.isFinished }` failed to build | Cap-64 array trim instead (ponytail-commented) |
| First finish-audit fanout died (3/3 interrupted, no findings drafted) | Provider-side interruption mid-model-response | User cancelled that round; re-ran cleanly after the dogfood fix — all three completed |
| Root AGENTS.md lost its SwiftFairy paragraph mid-session | User's own edit, not ours | Left untouched; the MCP was unavailable all session anyway — consulted the swift agent-wiki + live probes instead |
## Files Changed
| File | Change Summary |
|------|---------------|
| `Museion/SettingsModel.swift` | NEW — providers/efforts/key-types/registry + SettingsModel + SettingsWriting seam |
| `Museion/SettingsPaneView.swift` | Reworked to variant C sidebar + detail shell; Content page unchanged behavior |
| `Museion/SettingsPagesView.swift` | NEW — surface pages + Provider Keys page + field-label/segment controls |
| `Museion/ModelComboBox.swift` | NEW — NSComboBox representable, three commit rails |
| `Museion/DesignTokens.swift` | +settingsSidebarWidth/settingsFormWidth |
| `MuseionTests/SettingsModelTests.swift` | NEW — 19 tests over the model + combobox wiring |
| `Museion/AGENTS.md`, `MuseionTests/AGENTS.md` | DOX pass for the Settings slice |
## Open Items & Next Steps
- [ ] Profiles S3 — persistence over the `SettingsWriting` seam (`hermes -p <profile> config set` + `.env` fan-out per the docstring contract); lift SettingsModel to AppGateState; endpoint scheme validation at the write boundary (finish-audit deferral).
- [ ] Profiles S4 (#137) — per-surface engine lifecycle; consumes `ProfileSurface(passKind:)`.
- [ ] Visual pixel-diff of variant C against the prototype remains human-verified only (capture permissions blocked all session) — if it recurs, granting the terminal Screen Recording + AX would unlock automated visual checks.
- [ ] testmanagerd UI-runner flake persists machine-wide (pre-dates this slice, #134).
---
*Log written by write-log skill*
+1
View File
@@ -5,6 +5,7 @@ Complete history of session logs in this directory, newest first. One-line summa
<!-- write-log: full-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-10-27 | issue | [20261027-issue135-profiles-s2-settings-page-ui_log.md](20261027-issue135-profiles-s2-settings-page-ui_log.md) | #135 Profiles S2: variant C Settings sidebar+detail over the SettingsWriting seam; NSComboBox stale-stringValue dogfood fix; 432 tests |
| 2026-10-27 | issue | [20261027-issue134-profiles-s1-registry-provisioning-x3_log.md](20261027-issue134-profiles-s1-registry-provisioning-x3_log.md) | #134 Profiles S1: ×3 surface registry + provisioner, master-symlink skills with byte-match migration, three-profile backup; 412 tests |
| 2026-10-22 | issue | [20261022-issue31-first-draft-stats-capture-s5-1_log.md](20261022-issue31-first-draft-stats-capture-s5-1_log.md) | #31 S5.1: Swift-native first-draft stats stamped in place at pass invocation; two frontmatter-erasure bugs fixed; finish-audit fanout — 396 tests |
| 2026-10-22 | issue | [20261022-issue30-sessions-new-post-from-session-drill-offers_log.md](20261022-issue30-sessions-new-post-from-session-drill-offers_log.md) | #30 lands: session-born Posts stamp origin: ai, brainstorm flavor, shared composer, and the real-engine resume wire fix. |