Files
museion/Museion/SettingsPaneView.swift
T
AlexKucera efad422e03
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
fix(ui): finish-audit fixes — blank search glyph, quadratic truncation, scope-rail refusal leak
Three-reviewer audit of the polish overhaul:
- magnifyinglass -> magnifyingglass (blank SF Symbol, all 3 seats)
- WordBoundaryTruncation.fit measures each word once (O(n^2) -> O(n)
  on pathological imported titles; live-title pins unchanged)
- scopeHostedSession defers behind an in-flight replay instead of
  refusing (automatic actions never leak a 'Resume refused' row);
  replay completion re-fires the pending scope — pinned over the real
  client path with loadReplayHold, flip-verified
- transcript ForEach on stable row ids, not indices
- delete dead softBorder param; fold caretPastLeadingBlanks onto
  firstContentLocation; native TextField prompt for the search field
- ElidedPathText.candidates/elide nonisolated (off-actor first(where:)
  trapped the host); new pins: degenerate truncation shapes,
  firstContentLocation, elide ladder
2026-11-07 21:13:31 +01:00

354 lines
12 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// SettingsPaneView.swift
// Museion
//
// #17 (S1.1): Settings — the Museion Home path, repoint-only (ADR-0004).
// #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.
// #136 (Profiles S3): the model runs over HermesSettingsWriter (the real
// CLI/.env rail) and hydrates from the profiles at pane open.
//
import AppKit
import SwiftUI
/// Settings pane — sidebar + detail per prototype variant C.
struct SettingsPaneView: View {
@Binding var home: URL
/// #136: the gate's binary winner — HermesSettingsWriter's CLI rail and
/// the hydration reads both need it (nil before a gate pass: writes
/// surface their failure, reads leave the seed).
let binaryPath: String?
@State private var page: SettingsPage = .content
/// #135/#136: the model over the REAL write path; hydrated from the
/// profiles at pane open.
@State private var model: SettingsModel
init(home: Binding<URL>, binaryPath: String?, onChatSurfaceWrite: (() -> Void)? = nil) {
_home = home
self.binaryPath = binaryPath
let model = SettingsModel(writer: HermesSettingsWriter(hermesBinary: binaryPath))
// #137: a committed Chat model write reaches the resident engine
// (WorkspaceView wires requestRestart).
model.onChatSurfaceWrite = onChatSurfaceWrite
_model = State(initialValue: model)
}
var body: some View {
// r5 (argon#51, mercury#32 — the Sessions r2 pattern): the
// 'Settings' header band + its hairline live in the SIDEBAR
// column alone; the sidebar/detail divider runs the full height
// (up to the titlebar) and the detail's content starts under
// the titlebar, not under a pane-wide band.
HStack(spacing: 0) {
VStack(spacing: 0) {
// r4: title inset 24 — one leading-text token for the whole
// pane (mercury#38 tail): the sidebar column pads 8, its
// rows 16, so item labels start at x24; the header and the
// detail column's forms share that edge.
PaneHeader(title: "Settings", titleInset: 24)
sidebar
}
.frame(width: DesignTokens.settingsSidebarWidth)
Rectangle()
.fill(DesignTokens.border)
.frame(width: 1)
detail
}
.background(DesignTokens.background)
.task { await model.hydrate() }
}
// MARK: Sidebar (prototype `.vC .side`)
private var sidebar: some View {
VStack(alignment: .leading, spacing: 2) {
ForEach(SettingsPage.allCases) { candidate in
SettingsSidebarButton(
page: candidate,
selection: $page,
)
}
Spacer(minLength: 0)
}
.padding(.horizontal, 8)
.padding(.vertical, 14)
.frame(width: DesignTokens.settingsSidebarWidth)
}
// MARK: Detail (prototype `.vC .detail`)
private var detail: some View {
VStack(spacing: 0) {
// Writes happen in the detail pages, so the write-error strip
// rides the detail column's top (r5: no pane-wide band above
// the detail anymore).
if let error = model.lastWriteError {
Text(error)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(.orange)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 24)
.padding(.vertical, 4)
}
// r8 (mercury#20, sol — owner regression): each page pins its
// header (baseline-aligned with the sidebar's 'Settings' title)
// and TOP-ALIGNS its form stack ~24pt under the intro — no
// ScrollView, no vertical centering (the r6 pattern died).
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").
/// r2: "SESSIONS" — an uppercase mono badge in the same voice as
/// P1/P2, not a lowercase "· Sessions" aside.
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: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
}
// r4: leading 16 — labels land at x24 (the pane's one inset
// token) and the inset accent bar keeps an 8-10pt gap to the
// label text (bar at x12-14), up from the old 4pt sliver.
.padding(.horizontal, 16)
.padding(.vertical, 7)
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.background {
if selected || hover {
RoundedRectangle(cornerRadius: 8)
// r2: one contrast step above the 0.06 hover wash —
// the selected row reads as raised, not identical to
// its background (surface #FFFEFB was invisible on
// the #FAF9F3 chrome).
.fill(selected ? DesignTokens.foreground.opacity(0.10) : DesignTokens.foreground.opacity(0.06))
}
}
.overlay(alignment: .leading) {
// `.side-button.current` inset accent bar — inset from the
// highlight's edges (leading 4; r6 mercury#49/52: vertical
// inset 6, the shared SelectedRowStrip capsule — radius-1
// ends, one step deeper-set than r4's 3) so it sits ON the
// fill, never half-off its rounded boundary.
if selected {
SelectedRowStrip()
.padding(.leading, 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) {
// r6 (sol#12, argon#19, mercury#31): serif-15 — the PaneHeader
// face — with top padding 17: the title box (~18pt) centers in
// the sidebar's 52pt band ((52−18)/2 = 17), so 'Content' and
// 'Settings' baselines align exactly across the divider.
Text("Content")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
Text("Where the corpus lives.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
// r7 (ALL SEATS regression): the form stack is TOP-aligned and the
// page carries NO ScrollView — a single setting must fit the
// viewport whole. The r6 ScrollView + minHeight proposal is what
// let ElidedPathText's greedy frame stretch the field card to
// ~750pt; both are gone.
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 form: some View {
VStack(alignment: .leading, spacing: 14) {
// r5 (argon#21): label→field 6pt. r7: field→caption 8pt
// (the r6 6 squeezed the caption into the group).
VStack(alignment: .leading, spacing: 6) {
SettingsFieldLabel("Museion Home")
// r2: ONE bounded field-group row — surface fill + 1pt
// #E8E5DF hairline. r6: the path FILLS the row —
// glyph-measured slash-boundary elision (ElidedPathText)
// replaces character-middle truncation; Choose… stays
// intrinsic at the row's end with a FULL-strength
// hairline. r7 (ALL SEATS regression + mercury#55,
// argon#41): the row HUGS its intrinsic single-row
// height (~48pt) — symmetric inner padding 14 both
// sides, vertical 10 — and no child expands vertically.
HStack(spacing: 8) {
ElidedPathText(path: home.path(percentEncoded: false))
Button("Choose…") { chooseHome() }
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.help("Pick the folder holding your posts")
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
.background(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.surface)
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border),
),
)
// r7: caption directly below the group — spacing 6 + 2 = 8pt.
Text("Repoint-only: Museion never moves content.")
.font(.system(size: 11.5))
.foregroundStyle(DesignTokens.muted)
.padding(.top, 2)
}
}
.padding(.top, 12)
}
private func chooseHome() {
let panel = NSOpenPanel()
panel.canChooseDirectories = true
panel.canChooseFiles = false
panel.canCreateDirectories = true
panel.message = "Choose the folder holding your posts. Museion never moves content."
if panel.runModal() == .OK, let url = panel.url {
home = url
}
}
}
/// r6 (sol#12, argon#19, mercury#31): the Home path, glyph-measured
/// slash-boundary elision that FILLS the width. Candidates from the full
/// path down to `/first/…/last` (a growing leading run of components kept
/// whole, one `/…/` before the final component) are measured in the row's
/// REAL mono face (NSFont.monospacedSystemFont 12 — the same face
/// `.system(size: 12, design: .monospaced)` resolves to) against the
/// ACTUAL available width; the longest candidate that fits renders.
/// Character-middle truncation is the last resort only — the Text carries
/// `.truncationMode(.middle)` and it engages only when even
/// `/first/…/last` overflows. Internal + pure statics so a test can pin
/// the ladder.
struct ElidedPathText: View {
let path: String
var body: some View {
// r7 (ALL SEATS regression): fixed 16pt height, no maxHeight —
// the r6 greedy `.frame(maxHeight: .infinity)` let the
// GeometryReader swallow whatever the (now-deleted) ScrollView
// proposed and stretched the field card to ~750pt. Width stays
// flexible: the elision ladder needs the real available width.
GeometryReader { geo in
Text(Self.elide(path, into: geo.size.width))
.font(.system(size: 12, design: DesignTokens.mono))
.lineLimit(1)
.truncationMode(.middle)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(height: 16)
.help(path)
.accessibilityLabel(path)
}
/// The candidate ladder, longest first: the full path, then each
/// shorter variant with one more leading component kept whole.
nonisolated static func candidates(_ path: String) -> [String] {
let comps = path.split(separator: "/").map(String.init)
guard comps.count > 2 else { return [path] }
var ladder = [path]
for keep in stride(from: comps.count - 3, through: 0, by: -1) {
ladder.append("/" + comps[0 ... keep].joined(separator: "/") + "/…/" + comps[comps.count - 1])
}
return ladder
}
/// The longest candidate whose glyph-measured width fits `width`.
nonisolated static func elide(_ path: String, into width: CGFloat) -> String {
let font = NSFont.monospacedSystemFont(ofSize: 12, weight: .regular)
func fits(_ candidate: String) -> Bool {
(candidate as NSString).size(withAttributes: [.font: font]).width <= width
}
let ladder = candidates(path)
// Nothing fitting (even `/first/…/last` overflows) falls through
// to the shortest candidate — the Text's character-middle
// truncation handles it (the documented last resort).
return ladder.first(where: fits) ?? ladder.last ?? path
}
}