Files
museion/Museion/MentorPaneView.swift
T
AlexKucera b02d36bb5d
CI / ci (push) Canceled after 0s
feat(mentor): research & library-light (S8) (#29)
The mentor researches mid-pass and its findings arrive as candidate
source-notes with provenance inside their Session. A third museion-
tools tool, submit_research_notes, is the typed rail (ADR-0006
posture): decode-validate only, reply {"received": N}, write NOTHING
— the session is the holding area, and keeping is the writer's act.

Candidates ride the transcript as first-class rows (researchNote):
parsed from the tool call's rawInput by payload shape — the notes
array routes before the fix-card parse, titles are display text —
one row per note, all-or-nothing per batch, the wire's whitespace
rule mirrored so both boundaries agree. Resume re-materializes them
for free: replays re-run the same parse; dispositions reset honestly
(they were never persisted — engine-owned cargo, ADR-0007).

The writer curates in place (full cards in the shared transcript, no
palette — a handful curates where it lands): Keep opens the
ask-before sheet (G9; PromoteAskSheet posture — inline refusal,
buttons kept) and ONE confirm lands one plain markdown note with
provenance into the piece's research/ via writeResearchNote — the
one folder(of:) id lookup anchors it inside this Home, a symlinked
research/ refuses, collision -2; Reject vanishes, recording nothing.
The pass stub names the rail and forbids the engine writing
candidates itself; kept notes flip hasResearch, so every later pass
sees the research/ path (S8.3 at v1 depth).

Finish-audit (three reviewers) drove the whitespace-parity and
shape-routing fixes, the ResearchNoteContent dedup, and a poll-loop
fix for the debounce rig's sidecar half that the larger suite's load
had pushed past its fixed sleep — full suite green (373 tests).

Closes #29
2026-10-22 14:06:16 +02:00

322 lines
9.6 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 draft = ""
@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?
/// #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) {
_model = State(initialValue: model)
self.binaryPath = binaryPath
self.posts = posts
self.home = home
}
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)
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.
SessionTranscriptView(model: model, showsDebugRows: debugRows, home: home)
Divider()
inputBar
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
}
// 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()
if case .ready = model.phase, let sessionId = model.activeEntry?.sessionId {
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: Input + crash card (file-scope extension — type_body_length posture)
private extension MentorPaneView {
// MARK: Input
private var inputBar: some View {
VStack(alignment: .leading, spacing: 8) {
// Liveness: a pass legitimately runs minutes of silent tool work
// (skill loads, learnings) — without this the pane reads as dead
// (dogfood #23: "hard to tell if it is still thinking").
if model.isStreaming {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
Text("Mentor is working — Stop to interrupt.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
HStack(spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain)
.lineLimit(1 ... 4)
.onSubmit { send() }
Button {
send()
} label: {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
if model.isStreaming {
Button {
model.stopStreaming()
} label: {
Text("Stop")
}
.controlSize(.regular)
}
}
}
.padding(12)
.disabled(model.phase.isReady == false)
}
private func send() {
let text = draft
draft = ""
Task { await model.sendPrompt(text) }
}
// 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
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
}
}
.padding(.horizontal, 12)
.padding(.bottom, 10)
}
/// 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 runs; Run otherwise — disabled with no open
/// piece or while the engine can't take the turn.
@ViewBuilder
private var actions: some View {
if posts?.runningPass != nil {
Button("Cancel") {
posts?.cancelPass(mentor: model)
}
.buttonStyle(.bordered)
} else {
Button("Run \(kind.rawValue)") {
guard let posts, let home else { return }
Task { await posts.runPass(kind, home: home, mentor: model) }
}
.buttonStyle(.borderedProminent)
.disabled(posts?.session?.postID == nil || !model.phase.isReady || model.isStreaming)
}
}
}
#Preview {
MentorPaneView(model: MentorSessionModel(), binaryPath: nil)
}