Files
museion/Museion/MentorPaneView.swift
T
AlexKucera d6c4712aaa
CI / ci (push) Canceled after 0s
feat(mentor): editorial pane chrome (#156)
Wayfinder map #153, build slice 2 of the #154 contract: the pane's
chrome joins the transcript's editorial voice (#155).

Header per .pane-head — serif-15/600 "Mentor", engine status, mono-10
session chip; ready is the semantic green dot (DesignTokens.readyGreen,
the palette's sole exception) + lowercase mono "ready", base version in
the tooltip, the drift note kept visible. The segmented Pass 1 | Pass 2
| Chat picker is dead (settled #4): PassBarView always carries and owns
the compact text-tab selector (2pt accent underline) over a PASS N ·
STATE status line, the cost line, and the actions as MonoButton —
accent solid / surface+border / accent outline, the danger voice.
Fix-cards row is the ruled plain mono link; crash, missing-engine, and
starting states render as the quiet state-cards.

Finish-audit fanout: security clean; orphaned MARK, stale doc comment,
and a phantom-border comment fixed; pass-selector remount reset and
solid-button contrast parked in the devlog (swift-wiki gotcha #28).

Suite 592/592 (xcresult count), swiftformat + swiftlint clean at the
error tier.

Closes #153
2026-11-04 10:37:13 +01:00

472 lines
16 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, 14)
.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.
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()
}
}
}
// 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: 10, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.opacity(0.75)
.textSelection(.enabled)
}
}
.padding(.horizontal, 14)
// #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.
.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))
.foregroundStyle(.secondary)
.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)
.opacity(disabled ? 0.45 : 1)
}
private var ink: Color {
switch style {
case .solid: DesignTokens.surface
case .secondary: DesignTokens.foreground
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
case .secondary: DesignTokens.border
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(.bottom, 9)
statusLine
.padding(.bottom, 5)
Text(description)
.font(.system(size: 11))
.foregroundStyle(DesignTokens.muted)
.fixedSize(horizontal: false, vertical: true)
.padding(.bottom, 10)
actions
// #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(.top, 8)
}
}
.padding(.horizontal, 14)
.padding(.vertical, 12)
}
/// 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.
private var statusLine: some View {
Text("\(kind.rawValue) · \(stateLabel)")
.font(.system(size: 10, 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).
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 "No Pass snapshot yet — run a Pass 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)
}