Files
museion/Museion/MentorPaneView.swift
T
AlexKucera 97e86cf62d
CI / ci (push) Canceled after 0s
feat(mentor): blind read A/B judgment (#122)
A purposeful writer action on the open post — the "Blind Read" button
beside Run Pass — triggers a whole-document advisory judgment: the
current document against the Pass-start snapshot (the newest
passes/pass-N.md on disk), decided by a FRESH session of the same
museion profile over the existing one-shot ACP rail. Both versions
travel inline in one prompt under neutral A/B position labels with
randomized order — the judge never learns which is the rewrite — and
the A/B-to-origin reveal appends only after the verdict, so the mapping
cannot leak; cancelled, refused, and spawn-failed turns reveal nothing.

Advisory-only per decision #120: no Pass State advance, no cards, no
Learnings, the roster never grows — the verdict is display-only and
dies with the transient transcript. The writer stays judge of record;
demonstrator picks and Fix Card status are untouched. Honest refusals
for the degenerate states: no snapshot yet, an unchanged document, or
a busy rail (passes and reads refuse each other; the pass bar's one
Cancel ends either).

The pass engine's spawn/session/teardown block became one shared
runOneShot rail (failure rows speak the run's own name), the pass-bar
button gates on a derived openPieceHasSnapshot flag, the fake ACP
gained a prompt-log observable, and the GLOSSARY "Blind Read" term
landed with the issue.

Finish-audit (three reviewers): a refusal still ends .ended, so the
reveal now gates on the stopReason (flip-verified pin), plus the
Cancel-rail and pass/blind-read exclusivity pins. Suite 500; swiftformat
clean; swiftlint adds no violations over the HEAD baseline.

Closes #122
2026-10-30 17:31:00 +01:00

352 lines
12 KiB
Swift

//
// MentorPaneView.swift
// Museion
//
// M0 ACP bridge (#14): the debug pane — the M0 demo surface. Post-gate main
// surface replacing the content placeholder (map decision: pane placement).
//
import SwiftUI
/// The mentor debug pane: transcript, freeform input, Stop while streaming,
/// restart prompt on crash. Post-gate main surface (map decision).
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?
/// #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)?
/// #24 (S3.1): the segmented surface — Pass 1 | Pass 2 | Chat. Pass
/// modes carry the pass bar; Chat is the freeform surface alone.
private enum Mode: Hashable { case pass1, pass2, chat }
@State private var mode: Mode = .pass1
/// 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?,
posts: PostsModel? = nil,
home: URL? = nil,
onOpenSettings: (() -> Void)? = nil,
) {
_model = State(initialValue: model)
self.binaryPath = binaryPath
self.posts = posts
self.home = home
self.onOpenSettings = onOpenSettings
}
var body: some View {
VStack(spacing: 0) {
header
Divider()
switch model.phase {
case .idle, .starting:
ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
case .ready:
modePicker
if let kind = passKind {
PassBarView(kind: kind, posts: posts, home: home, model: model, onOpenSettings: onOpenSettings)
Divider()
}
if let posts, !posts.openPieceCards.isEmpty {
// #23 follow-up: the detail moved to the palette window —
// this row just names it and opens it.
Button {
openWindow(id: "fix-cards")
} label: {
Label(
"Fix Cards · \(posts.openPieceCards.count)",
systemImage: "rectangle.and.pencil.and.ellipsis",
)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
}
.buttonStyle(.borderless)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 12)
.padding(.vertical, 6)
Divider()
}
// #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.
SessionTranscriptView(model: model, showsDebugRows: 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).
.task {
// #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; pane re-entry re-fires this
// task, 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 }
await model.openSession()
}
}
// MARK: Header
private var header: some View {
HStack(spacing: 8) {
Image(systemName: "bubble.left.and.text.bubble.right")
.foregroundStyle(.secondary)
Text("Mentor Session")
.font(.headline)
if let version = model.engineVersion {
Text(version)
.font(.caption)
.foregroundStyle(.tertiary)
}
if let note = model.versionNote {
Text(note)
.font(.caption)
.foregroundStyle(.orange)
.help(note)
}
Spacer()
// #137: the transient pass transcript carries no session id — the
// chip stays hidden while a pass run owns the active surface.
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId, sessionId != MentorSessionModel.passTranscriptKey {
Text("session \(sessionId.prefix(8))")
.font(.caption2)
.foregroundStyle(.tertiary)
.textSelection(.enabled)
}
Toggle("Debug", isOn: $debugRows)
.toggleStyle(.checkbox)
.controlSize(.mini)
.foregroundStyle(.tertiary)
.help("Show session updates, tool calls, and engine thinking.")
}
.padding(.horizontal, 12)
// #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: Pass surface (#24, S3.1)
private var passKind: PassKind? {
switch mode {
case .pass1: .pass1
case .pass2: .pass2
case .chat: nil
}
}
private var modePicker: some View {
Picker("Mentor surface", selection: $mode) {
Text("Pass 1").tag(Mode.pass1)
Text("Pass 2").tag(Mode.pass2)
Text("Chat").tag(Mode.chat)
}
.pickerStyle(.segmented)
.padding(.horizontal, 12)
.padding(.top, 10)
.padding(.bottom, 8)
}
}
// 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 {
VStack(spacing: 14) {
Image(systemName: "exclamationmark.triangle.fill")
.font(.system(size: 30))
.foregroundStyle(.orange)
Text("The mentor engine stopped")
.font(.title3)
Text("Nothing is lost — the transcript stays, and the engine can be restarted.")
.font(.callout)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
if let lastPrompt, !lastPrompt.isEmpty {
Text("Last prompt: \(lastPrompt)")
.font(.caption)
.foregroundStyle(.tertiary)
.lineLimit(2)
}
Button("Restart") {
Task { await model.restart() }
}
.buttonStyle(.borderedProminent)
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)
}
}
/// #24 (S3.1): the pass bar — what the pass critiques + the honest cost
/// estimate (PassContext), the open piece's Pass State, and the Run/Cancel
/// action. Additive chrome above the mentor pane's shared transcript.
private struct PassBarView: View {
let kind: PassKind
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: 8) {
Text(description)
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
HStack {
Text(stateLabel)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
Spacer()
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 {
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)
}
}
.padding(.horizontal, 12)
.padding(.bottom, 10)
}
/// #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; Run otherwise — 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.
@ViewBuilder
private var actions: some View {
if posts?.runningPass != nil || posts?.runningBlindRead == true {
Button("Cancel") {
posts?.cancelPass(mentor: model)
}
.buttonStyle(.bordered)
} else {
blindReadButton
if let label = missingKeyLabel {
runPassButton
.disabled(true)
.help("\(kind.rawValue) needs a \(label) API key — add it in Settings → Provider Keys.")
} else {
runPassButton
.disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming)
}
}
}
/// #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 {
Button("Blind Read") {
guard let posts, let home else { return }
Task { await posts.blindRead(home: home, mentor: model) }
}
.buttonStyle(.bordered)
.disabled(blindReadBlocked != nil)
.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
}
/// The Run button core — shared by the ready and missing-key branches.
private var runPassButton: some View {
Button("Run \(kind.rawValue)") {
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
}
.buttonStyle(.borderedProminent)
}
}
#Preview {
MentorPaneView(model: MentorSessionModel(), binaryPath: nil)
}