// // 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() } transcript 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 { model.binaryPath = binaryPath ?? model.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() } } /// The writing-session transcript: prose (verdicts, labels, notes) and /// card events stay; raw session/tool rows and collapsed thinking are /// debug-only. Static — pure, testable. static func isWritingRow(_ row: SessionRow) -> Bool { switch row.content { case .text, .fixCard: true case .thought, .raw: false } } // 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 let .ready(sessionId) = model.phase { 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: Transcript private var transcript: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 10) { ForEach(model.rows.filter { debugRows || Self.isWritingRow($0) }) { row in rowView(row) } if debugRows, !model.streamingThought.isEmpty { // Live thinking: quiet, capped — it's transient (the full // text lands in a collapsed row when the turn ends). Text(model.streamingThought) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .lineLimit(3) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } if !model.streamingText.isEmpty { textRow("Mentor: \(model.streamingText)") } } .padding(12) .frame(maxWidth: .infinity, alignment: .leading) } // #24 fix: programmatic scrollTo raced the growing lazy rows and // mislanded at the TOP; the native bottom anchor needs no scroll code. .defaultScrollAnchor(.bottom) } @ViewBuilder private func rowView(_ row: SessionRow) -> some View { switch row.content { case let .text(text): textRow(text) case let .thought(text): ThoughtRow(text: text) case let .fixCard(card): // #23 follow-up: detail lives in the palette window — the // transcript keeps a one-line event, not the card. FixCardEventRow(pattern: card.pattern) case let .raw(kind, json): RawUpdateRow(kind: kind, json: json) } } private func textRow(_ text: String) -> some View { Text(text) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) } // MARK: Rows /// The tool-call EVENT, not the card: the pattern title alone. The /// card's full statement lives in the Fix Cards palette window. private struct FixCardEventRow: View { let pattern: String var body: some View { Label(pattern, systemImage: "rectangle.and.pencil.and.ellipsis") .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .frame(maxWidth: .infinity, alignment: .leading) } } /// #24 fix: the engine's thinking, collapsed — a pass's thought stream runs /// to hundreds of lines and is not the critique (only `agent_message_chunk` /// is). Same shape as RawUpdateRow: quiet mono, expandable, never in the way. private struct ThoughtRow: View { let text: String var body: some View { DisclosureGroup { Text(text) .font(.system(size: 10, design: .monospaced)) .foregroundStyle(.secondary) .textSelection(.enabled) } label: { Text("thinking") .font(.system(size: 11, design: .monospaced)) .foregroundStyle(DesignTokens.muted) } .frame(maxWidth: .infinity, alignment: .leading) } } private struct RawUpdateRow: View { let kind: String let json: String var body: some View { DisclosureGroup { Text(json) .font(.system(size: 10, design: .monospaced)) .textSelection(.enabled) } label: { Text(kind) .font(.system(size: 11, design: .monospaced)) .foregroundStyle(.secondary) } .frame(maxWidth: .infinity, alignment: .leading) } } } // 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, never data loss) 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) }