Files
museion/Museion/MentorPaneView.swift
T
AlexKucera 3a7d495b4b
CI / ci (push) Canceled after 0s
CI / ci (pull_request) Canceled after 0s
feat(ui): design-council polish overhaul
Eight arbitrated rounds over the workspace surface: piece-scoped Mentor
hosting, conversation-voice system messages, glyph-measured roster
truncation, bounded learnings/archive columns, symmetric trends grid,
top-aligned settings forms, serif editor titles, outline rail rhythm,
launch auto-focus root fix. New seams pinned by SessionScopeTests +
WordBoundaryTruncationTests; full suite green.
2026-11-07 20:41:34 +01:00

587 lines
22 KiB
Swift

//
// MentorPaneView.swift
// Museion
//
// The mentor pane (#14 map → #153/#156): the editorial chrome per the
// locked contract (ref/prototypes/wf154-mentor-pane-prototype.html) —
// serif pane head with the green ready dot and session chip, the compact
// Pass 1 / Pass 2 selector + status line in the pass bar (the segmented
// mode picker died, settled #4), a plain mono fix-cards row, and the
// crash / missing-engine / starting states in the same voice.
//
import SwiftUI
/// The mentor pane: the pass bar + shared transcript around it (the
/// conversation surface itself lives in SessionTranscriptView) and the
/// crash restart prompt.
struct MentorPaneView: View {
@State private var model: MentorSessionModel
/// #23 follow-up: opens the Fix Cards palette window (scene "fix-cards").
@Environment(\.openWindow) private var openWindow
/// Set post-gate by ContentView: the probe's winning binary (no re-probe).
var binaryPath: String?
/// #151: the app-scoped gate — the header's engine states read the
/// gate's phase machine (nil = previews; the pane then derives from
/// the mentor model alone).
var gate: AppGateState?
/// #24 (S3.1): app-scoped Posts state for the pass bar (nil = no pass
/// surface, previews).
var posts: PostsModel?
/// #24 (S3.1): the Home passes run against.
var home: URL?
/// #137 (S4): opens Settings — the missing-key line's way out (nil =
/// previews; PostsPaneView threads WorkspaceView's pane hop).
var onOpenSettings: (() -> Void)?
/// Writing-session filter (#23 dogfood): session/tool/debug rows render
/// only when on — off by default, persisted. The model keeps every row
/// either way (debug history intact; the toggle flips instantly).
@AppStorage("mentorDebugRows") private var debugRows = false
init(
model: MentorSessionModel,
binaryPath: String?,
gate: AppGateState? = nil,
posts: PostsModel? = nil,
home: URL? = nil,
onOpenSettings: (() -> Void)? = nil,
) {
_model = State(initialValue: model)
self.binaryPath = binaryPath
self.gate = gate
self.posts = posts
self.home = home
self.onOpenSettings = onOpenSettings
}
var body: some View {
VStack(spacing: 0) {
header
Divider()
switch model.phase {
case .idle, .starting:
if case .fail? = gate?.gateModel.phase {
// #151: the gateless check answered "no engine" — an
// eternal "Starting…" spinner would lie. The rail card
// carries the install steps.
VStack(spacing: 10) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 24))
.foregroundStyle(DesignTokens.accent)
Text("The Hermes engine is missing")
.font(.system(size: 14, weight: .semibold, design: DesignTokens.serif))
Text("Install steps are one click away at the rail's status icon — the editor keeps working.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
.padding(.horizontal, 24)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
// #156: the interim in the editorial voice — mono, quiet.
VStack(spacing: 8) {
ProgressView().controlSize(.small)
Text("Starting the mentor engine…")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
case .ready:
// #156 (settled #4): the pass bar always carries — its Pass 1 /
// Pass 2 selector replaced the mode picker; the transcript +
// composer below are the conversation surface, chat is not a
// mode.
PassBarView(posts: posts, home: home, model: model, onOpenSettings: onOpenSettings)
Divider()
if let posts, !posts.openPieceCards.isEmpty {
// #23 follow-up + #156 ruling: a plain mono row — a link,
// not content (no card, no hairline of its own; the
// Divider above already separates it from the bar).
Button {
openWindow(id: "fix-cards")
} label: {
HStack(spacing: 6) {
Image(systemName: "rectangle.and.pencil.and.ellipsis")
Text("Fix Cards · \(posts.openPieceCards.count)")
}
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
.buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 16)
.padding(.top, 10)
}
// #28: the transcript rendering is shared — the Sessions pane
// reads the same surface in the writing voice. #30: the
// freeform input + liveness ride the shared surface too.
// #155: the debug toggle's seat is the composer's edge.
// Owner ruling (2026-11-07): no roster session for the open
// piece → the honest empty presentation below (pass controls
// above stay); a foreign transcript never renders.
if model.activeEntry == nil {
scopedEmptyPresentation
} else {
SessionTranscriptView(model: model, showsDebugRows: debugRows, debugBinding: $debugRows, home: home)
}
case let .crashed(lastPrompt):
crashCard(lastPrompt: lastPrompt)
}
}
// #17: the pane lives in the workspace's fixed 356pt mentor column —
// no root min frame (it was the full-window M0 surface).
// #151: keyed on binaryPath — the gateless check lands AFTER the
// pane mounts, so re-seeding rides the nil→value arrival and the
// engine spawns the moment the check passes.
.task(id: binaryPath) {
// #28 review: an honest if-let — the ?? self-assignment was a no-op.
if let binaryPath {
model.binaryPath = binaryPath
}
// #137: the Run Pass posture over the pass profiles' keys —
// a no-op without a binaryPath; every re-fire of this task
// re-runs it, so a key added in Settings re-enables Run Pass.
await model.refreshPassReadiness()
// Hosted unit tests run this app as their runner — never spawn a
// real engine child there (it outlives the test session and kills
// the runner).
guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return }
// #151: openSession with a nil binary would land the crash
// card ("no engine binary path available") — the honest
// missing-engine states own the no-binary interim.
if binaryPath != nil {
await model.openSession()
// Owner ruling (2026-11-07): the pane hosts the open piece's
// session — launch, first open, and every remount scope
// exactly like a piece switch (the restoring open piece, if
// any).
await scopeToOpenPiece()
}
}
// Owner ruling (2026-11-07): a piece switch re-hosts — the model's
// scope rail resumes the matching roster session or clears to the
// empty presentation; an in-flight turn or pass defers the switch
// to stream end (never torn down mid-stream).
.onChange(of: openPieceTitle) {
Task { await scopeToOpenPiece() }
}
}
// MARK: Piece-scoped hosting (owner ruling 2026-11-07)
/// The open piece in Posts — the hosting scope target. Reuses the
/// Sessions pane's pinned open-piece rail (the same association
/// "New Session on <title>" stamps); nil = unsaved draft, external
/// guest, or nothing open.
private var openPieceTitle: String? {
SessionsPaneView.openPiece(in: posts)?.title
}
private func scopeToOpenPiece() async {
await model.scopeHostedSession(toOpenPieceTitle: openPieceTitle)
}
/// The honest empty presentation: the open piece has no roster session
/// (or nothing is open). The pass bar above stays.
/// Round-7 (sol#30): TWO elements — the caption line + the wired
/// action; the serif heading and the separate Sessions-navigation
/// footnote line died (the caption already names the piece).
/// Round-7 (mercury#5): the block TOP-anchors ~48pt below the pass
/// bar — the centered block split the pane with a ~290px dead zone.
/// Round-8 (sol#2 + mercury#10/13 — FINAL RULING: left-align): the
/// caption + button align to the column's 16pt leading edge, one
/// axis with the pass controls above (centered text read as a second
/// glued region; re-centering stays outvoted — it produced r6's
/// dead zone).
private var scopedEmptyPresentation: some View {
VStack(alignment: .leading, spacing: 8) {
Text(emptyPresentationBody)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.leading)
.fixedSize(horizontal: false, vertical: true)
.frame(maxWidth: .infinity, alignment: .leading)
if model.canStartSession, let openPieceTitle {
Button("New session for this piece") {
Task { _ = await model.newSession(name: "New Session", pieceTitle: openPieceTitle) }
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.padding(.top, 4)
.help("Start a session on “\(openPieceTitle)” — it hosts right here.")
}
}
.padding(.horizontal, 16)
.padding(.top, 48)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
}
private var emptyPresentationBody: String {
if let openPieceTitle {
return "The mentor pane follows “\(openPieceTitle)” — start one below, or from the Sessions pane."
}
return "The mentor pane follows the open piece — open one to see its session here."
}
// MARK: Header
private var header: some View {
HStack(spacing: 10) {
// #156 (contract `.pane-head`): serif 15/600 title + engine
// status + session chip — nothing else (settled #5).
Text("Mentor")
.font(.system(size: 15, weight: .semibold, design: DesignTokens.serif))
.fixedSize()
MentorEngineStatus(gate: gate, model: model)
Spacer()
// #137: the transient pass transcript carries no session id — the
// chip stays hidden while a pass run owns the active surface.
// #151: renders only once ready — no live session exists while
// the engine is missing or checking (#149); status text wins
// layout priority.
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId, sessionId != MentorSessionModel.passTranscriptKey {
Text("session \(sessionId.prefix(8))")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.opacity(0.75)
.textSelection(.enabled)
}
}
.padding(.horizontal, 16)
// #90: pane heads align at the export's 52px — same height as the
// Posts header and the editor toolbar, so the three hairlines read
// as one line. Round-2 polish: 16 — the ONE leading edge the
// transcript, pass bar, and composer all share.
.frame(minHeight: 52)
}
}
// MARK: Crash card (file-scope extension — type_body_length posture; the
// freeform composer moved to the shared SessionTranscriptView in #30)
private extension MentorPaneView {
// MARK: Crash → restart prompt (map decision: EOF/crash surfaces an
// in-pane Restart prompt; the transcript replays from the engine, ADR-0007)
private func crashCard(lastPrompt: String?) -> some View {
// #156 (contract `.state-card`): accent tri (danger = terracotta —
// no second hue), serif 14/600 head, sans-12 muted body, Restart
// in the solid-accent button voice.
VStack(spacing: 10) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 24))
.foregroundStyle(DesignTokens.accent)
Text("The mentor engine stopped")
.font(.system(size: 14, weight: .semibold, design: DesignTokens.serif))
Text("Nothing is lost — the transcript stays, and the engine can be restarted.")
.font(.system(size: 12))
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
if let lastPrompt, !lastPrompt.isEmpty {
Text("Last prompt: \(lastPrompt)")
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(2)
}
MonoButton(title: "Restart") {
Task { await model.restart() }
}
if !model.stderrTail.isEmpty {
DisclosureGroup("Technical details") {
Text(model.stderrTail.joined(separator: "\n"))
.font(.system(size: 10, design: .monospaced))
// Round-2 sweep: muted at full ink (0.75 floor) —
// .secondary read fainter than the palette allows.
.foregroundStyle(DesignTokens.muted)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.font(.system(size: 11))
.frame(maxWidth: .infinity, alignment: .leading)
}
}
.padding(24)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// #156 (contract `.btn`): the pane's action button — mono 11, 28pt,
/// radius 6 — in the contract's three looks: accent solid (primary),
/// surface + border (secondary), accent outline (the danger/Stop voice).
/// #155 sendButton precedent: a plain button with the fills drawn by hand
/// (borderedProminent carries the system tint, not the palette).
private struct MonoButton: View {
enum Style { case solid, secondary, outline }
let title: String
var style: Style = .solid
var disabled = false
let action: () -> Void
var body: some View {
Button(action: action) {
Text(title)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(ink)
.padding(.horizontal, 13)
.frame(minHeight: 28)
.background(RoundedRectangle(cornerRadius: 6).fill(fill))
.overlay(
RoundedRectangle(cornerRadius: 6)
.strokeBorder(stroke, lineWidth: 1),
)
}
.buttonStyle(.plain)
.disabled(disabled)
// Round-4 contrast (sol#4/39 + argon#11 + mercury#52): a disabled
// SECONDARY no longer dims the whole button — the ink carries the
// state (see `ink`); solid/outline keep the 0.75 dim.
.opacity(disabled && style != .secondary ? 0.75 : 1)
}
private var ink: Color {
switch style {
case .solid: DesignTokens.surface
// Round-7 (argon#37/45 + mercury#45) → Round-8 (sol#1/argon#5 —
// FOURTH round, final): BOTH secondary states render muted #6B6964
// over the same clearly-visible border — full ink when enabled,
// ~65% when disabled. The r7 50% dim read as a ghost, not a
// control; the disabled state explains itself via `help`.
case .secondary: DesignTokens.muted.opacity(disabled ? 0.65 : 1)
case .outline: DesignTokens.accent
}
}
private var fill: Color {
switch style {
case .solid: DesignTokens.accent
case .secondary: DesignTokens.surface
case .outline: .clear
}
}
private var stroke: Color {
switch style {
case .solid: .clear
// Round-7 (final ruling, with `ink`): the SAME clearly-visible
// border in BOTH secondary states — the r5 one-step-stronger
// darkening of border #E8E5DF via foreground opacity (no new
// hex). Ink opacity alone separates enabled from disabled;
// both states stay unmistakably controls.
case .secondary: DesignTokens.foreground.opacity(0.17)
case .outline: DesignTokens.accent
}
}
}
/// #24 (S3.1) → #156: the pass bar — the compact Pass 1 / Pass 2 selector
/// + `PASS N · STATE` status line (settled #4: the selector replaced the
/// segmented mode picker), what the pass critiques + the honest cost
/// estimate (PassContext), and the Run / Blind Read / Cancel actions.
/// Additive chrome above the mentor pane's shared transcript.
private struct PassBarView: View {
/// The selected pass — the bar's own state (nothing outside reads it).
@State private var kind: PassKind = .pass1
let posts: PostsModel?
let home: URL?
let model: MentorSessionModel
/// #137 (S4): the missing-key line's way out — WorkspaceView's pane hop.
let onOpenSettings: (() -> Void)?
var body: some View {
VStack(alignment: .leading, spacing: 0) {
selector
.padding(.horizontal, 16)
// Round-6 (argon#44): the tab row sits DIRECTLY on the divider
// — the r5 9pt gap left the active underline floating ~10px
// above the strip's bottom edge. The tab's internal 5pt bottom
// padding keeps text off the underline; the underline itself
// lands flush (zero gap).
Divider()
statusLine
.padding(.horizontal, 16)
.padding(.top, 8)
.padding(.bottom, 5)
Text(description)
.font(.system(size: 11))
.foregroundStyle(DesignTokens.muted)
.fixedSize(horizontal: false, vertical: true)
.padding(.horizontal, 16)
.padding(.bottom, 10)
actions
.padding(.horizontal, 16)
// #137: the pass profile's provider has no key — name it and
// offer the way out. A readable-but-keyed profile shows nothing.
if let label = missingKeyLabel {
missingKeyLine(label: label)
.padding(.horizontal, 16)
.padding(.top, 8)
}
}
.padding(.vertical, 12)
// Round-2 polish (all three council seats): ONE leading edge — 16,
// the same inset as the header, the transcript's measure pads, and
// the composer below (the tabs/description/actions sat visibly
// deeper in the round-2 shots).
// Round-4 (argon#1/sol#6/mercury#25 — THIRD round on this): the
// padding above was always 16 — but the pane's outer VStack
// centers by default and this bar hugs its content, so the whole
// block rode ~56px in (centered in the 356pt column) while the
// header sits at 16. Claim the full width at leading; the
// declared 16 is now the REAL left edge.
.frame(maxWidth: .infinity, alignment: .leading)
}
/// Contract `.selector`: text tabs — mono 10, uppercase, tracked; the
/// active tab carries fg ink + a 2pt accent underline.
private var selector: some View {
HStack(spacing: 14) {
passTab(.pass1)
passTab(.pass2)
}
}
private func passTab(_ pass: PassKind) -> some View {
Button {
kind = pass
} label: {
Text(pass.rawValue)
.font(.system(size: 10, design: DesignTokens.mono))
.tracking(0.8) // CSS .08em @ 10px
.textCase(.uppercase)
.foregroundStyle(kind == pass ? DesignTokens.foreground : DesignTokens.muted)
.padding(.top, 3)
.padding(.bottom, 5)
.overlay(alignment: .bottom) {
if kind == pass {
Rectangle()
.fill(DesignTokens.accent)
.frame(height: 2)
}
}
}
.buttonStyle(.plain)
.accessibilityLabel(pass.rawValue)
.accessibilityAddTraits(kind == pass ? [.isSelected] : [])
}
/// Contract `.status-line`: `PASS N · STATE` — the open piece's Pass
/// State in the library's post-meta voice. Round-4: 11 — informational
/// micro-labels ride the 11pt legibility floor (mercury#52).
private var statusLine: some View {
Text("\(kind.rawValue) · \(stateLabel)")
.font(.system(size: 11, design: DesignTokens.mono))
.tracking(0.8)
.textCase(.uppercase)
.foregroundStyle(DesignTokens.muted)
}
/// #137: the missing-key ask — mono 11, the Open Settings way out.
private func missingKeyLine(label: String) -> some View {
HStack(spacing: 4) {
Text("Missing \(label) key —")
Button("Open Settings") {
onOpenSettings?()
}
.buttonStyle(.borderless)
.foregroundStyle(DesignTokens.accent)
}
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
/// #137: nil unless the pass profile's provider is readable AND unkeyed
/// (.unknown never blocks — the spawn's honest failure owns that path).
private var missingKeyLabel: String? {
if case let .missingKey(label) = model.readiness(for: kind) {
return label
}
return nil
}
/// What the pass does + the predictable cost — or the honest ask when
/// no piece is open.
private var description: String {
guard let posts, let session = posts.session, session.postID != nil else {
return "Open a post to run a pass."
}
let tokens = PassContext.estimateTokens(
kind: kind, body: session.text, pieceURL: session.passPieceURL, hasResearch: session.hasResearch,
)
return "Critiques \(kind.level) · ~\(tokens.formatted()) tokens"
}
/// The open piece's current Pass State (the library's post-meta voice).
private var stateLabel: String {
guard let posts else { return "—" }
return posts.posts.first(where: { $0.id == posts.selectedPostID })?.passState.rawValue ?? "—"
}
/// Cancel while a pass or Blind Read runs (the accent-outline danger
/// voice); Run + Blind Read otherwise — Run disabled with no open
/// piece, while the engine can't take the turn, or (#137) while the
/// pass profile's provider has no key (the help names it).
/// #122: the Blind Read trigger sits beside Run — advisory-only.
private var actions: some View {
HStack(spacing: 7) {
if posts?.runningPass != nil || posts?.runningBlindRead == true {
MonoButton(title: "Cancel", style: .outline) {
posts?.cancelPass(mentor: model)
}
} else {
blindReadButton
if let label = missingKeyLabel {
MonoButton(title: "Run \(kind.rawValue)", disabled: true, action: runPass)
.help("\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys.")
} else {
MonoButton(
title: "Run \(kind.rawValue)",
disabled: posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming,
action: runPass,
)
}
}
}
}
private func runPass() {
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
}
/// #122: the Blind Read — one purposeful click judges the current
/// document against the Pass-start snapshot, blind. Disabled with the
/// blocking reason in help (no snapshot yet is the fresh-piece norm).
private var blindReadButton: some View {
MonoButton(
title: "Blind Read",
style: .secondary,
disabled: blindReadBlocked != nil,
) {
guard let posts, let home else { return }
Task { await posts.blindRead(home: home, mentor: model) }
}
.help(
blindReadBlocked
?? "Judge the current document against the Pass-start snapshot — advisory only, nothing is recorded.",
)
}
/// #122: why the Blind Read can't fire right now (nil = it can). The
/// text names the actual gating condition — the snapshot one mirrors
/// `openPieceHasSnapshot` (latestPassSnapshot: no pass ever ran over
/// the open piece).
private var blindReadBlocked: String? {
guard let posts, posts.session?.postID != nil else { return "Open a post to run a Blind Read." }
guard posts.openPieceHasSnapshot else { return "Needs a pass snapshot — run Pass 1 first." }
guard model.phase.isReady, !model.isStreaming else { return "The mentor engine can't take the turn right now." }
return nil
}
}
#Preview {
MentorPaneView(model: MentorSessionModel(), binaryPath: nil)
}