// // 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? /// #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)? /// #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?, 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 { 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. // #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: 8) { Image(systemName: "bubble.left.and.text.bubble.right") .foregroundStyle(.secondary) Text("Mentor Session") .font(.headline) .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(.caption2) .foregroundStyle(.tertiary) .textSelection(.enabled) } } .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) }