// // SessionsPaneView.swift // Museion // // #28 (S2.3): the Sessions pane — the roster (newest-first) + the active // session's transcript, with New/Resume/Fork/Compact/Cancel over // MentorSessionModel. Also hosts the shared session transcript extracted // from MentorPaneView (one renderer, two panes; writing voice here, debug // toggle there). // import SwiftUI /// The Sessions rail destination: two-column body like Posts — roster list /// (library width) + transcript. Selecting a row resumes that session; the /// engine owns the words, so a fresh activation replays its history. struct SessionsPaneView: View { var model: MentorSessionModel /// The open piece is the New Session control's association target. var posts: PostsModel? /// The gate's winning binary (no re-probe) — this pane can be the first /// to open the engine. var binaryPath: String? /// #29 (S8.3): the Home a kept research note lands in. var home: URL? /// #151: the app-scoped gate — the detail column's idle branch reads /// the gate's fail verdict (nil = previews). var gate: AppGateState? /// #30 (S2.7): the staged New Post from Session ask — the editable /// draft candidate; nil = no sheet. The sheet is pane-local: this pane /// holds posts + home, so no WorkspaceView staging is needed. @State private var sessionDraft: String? var body: some View { VStack(spacing: 0) { PaneHeader(title: "Sessions") { newSessionControl } if model.roster.isEmpty { emptyState } else { HStack(spacing: 0) { rosterList .frame(width: DesignTokens.libraryWidth) paneBorder sessionDetail } } } .frame(maxWidth: .infinity, maxHeight: .infinity) .background(DesignTokens.background) // #30 (S2.7): the ask prefills the candidate; dismissal is the // cancel (nothing materializes). .sheet(isPresented: Binding( get: { sessionDraft != nil }, set: { if !$0 { sessionDraft = nil } }, )) { NewPostFromSessionSheet( draft: Binding( get: { sessionDraft ?? "" }, set: { sessionDraft = $0 }, ), create: { newPostFromSession() }, ) } // Same lazy lifecycle as MentorPaneView: idempotent open — whichever // surface the writer reaches first spawns the engine. #151: keyed // on binaryPath (nil→value arrival) so the pane spawns the moment // the gateless check lands; a nil binary never spawns (openSession // would land the crash card). .task(id: binaryPath) { guard let binaryPath else { return } model.binaryPath = binaryPath // Hosted unit tests run this app as their runner — never spawn a // real engine child there. guard ProcessInfo.processInfo.environment["XCTestConfigurationFilePath"] == nil else { return } await model.openSession() } } // MARK: Roster list private var rosterList: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 4) { ForEach(model.roster) { entry in SessionEntryRow(entry: entry, selected: entry.id == model.activeEntry?.id) { // Resume = activate: the engine replays the history // into the fresh transcript; unknown sessions land // the model's honest refusal row and stay rostered. Task { await model.resumeSession(entry) } } } } .padding(.bottom, 12) } } private var paneBorder: some View { Rectangle() .fill(DesignTokens.border) .frame(width: 1) } // MARK: Detail column @ViewBuilder private var sessionDetail: some View { switch model.phase { case .idle, .starting: if case .fail? = gate?.gateModel.phase { // #151: the same honest notice as the Mentor pane — the // roster stays readable, the detail column never lies with // an eternal "Starting…" spinner. 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 roster below stays readable.") .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 .crashed: crashedNote case .ready: VStack(spacing: 0) { actionsRow Divider() // #30: transcript + freeform input + liveness ride the shared // surface (the composer lives in SessionTranscriptView). SessionTranscriptView(model: model, showsDebugRows: false, home: home) } } } /// The active session's name + engine version, Fork/Compact beside them /// — disabled while a turn streams (canStartSession). private var actionsRow: some View { HStack(spacing: 8) { Text(model.activeEntry?.name ?? "—") .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) .lineLimit(1) .truncationMode(.tail) if let version = model.engineVersion { Text(version) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .lineLimit(1) .help(model.versionNote ?? version) } Spacer() // #30 (S2.7): the draft candidate prefills the ask sheet (empty // transcript → empty prefill — the sheet still works). Reads // in-memory transcript rows — engine-free, never gated on // canStartSession (a crashed engine must not strand the draft). Button("New Post") { sessionDraft = model.draftCandidateText() ?? "" } .buttonStyle(.bordered) .controlSize(.small) .font(.system(size: 11, design: DesignTokens.mono)) .help("Start a Post from this session's draft candidate") .accessibilityLabel("New Post from Session") Button("Fork") { Task { _ = await model.forkActiveSession() } } .buttonStyle(.bordered) .controlSize(.small) .font(.system(size: 11, design: DesignTokens.mono)) .disabled(!model.canStartSession) .help("Copy this session's history into a new one") .accessibilityLabel("Fork session") Button("Compact") { Task { await model.compactActiveSession() } } .buttonStyle(.bordered) .controlSize(.small) .font(.system(size: 11, design: DesignTokens.mono)) .disabled(!model.canStartSession) .help("Compress the session's history") .accessibilityLabel("Compact session") } .padding(.horizontal, 12) .padding(.vertical, 8) } /// No second restart flow — the Mentor pane owns Restart (map decision). private var crashedNote: some View { VStack(spacing: 8) { Image(systemName: "exclamationmark.triangle.fill") .font(.system(size: 30)) .foregroundStyle(.orange) Text("The mentor engine stopped") .font(.title3) Text("Restart it in the Mentor pane — nothing is lost.") .font(.callout) .foregroundStyle(.secondary) } .padding(24) .frame(maxWidth: .infinity, maxHeight: .infinity) } // MARK: New Session control /// #30 (S2.7): one Menu in both states — New Brainstorm joined the /// roster of actions, so the plain-button branch (single action) is /// gone. Brainstorm rides the same piece association when Posts has /// an open piece. private var newSessionControl: some View { let piece = Self.openPiece(in: posts) return Menu { Button("New Session") { createSession(associatedWith: nil) } if let piece { Button("New Session on \(piece.title)") { createSession(associatedWith: piece.title) } } Button("New Brainstorm") { Task { _ = await model.beginBrainstormSession(pieceTitle: piece?.title) } } } label: { Image(systemName: "plus") } .menuStyle(.button) .buttonStyle(.plain) .foregroundStyle(DesignTokens.muted) .disabled(!model.canStartSession) .help("New Session") .accessibilityLabel("New Session") } private func createSession(associatedWith title: String?) { Task { _ = await model.newSession(name: "New Session", pieceTitle: title) } } /// #30 (S2.7): the ask's confirm — materialize + open in Posts. Returns /// the failure reason for the sheet's inline refusal (nil = written + /// opened); a failed write keeps the sheet up with the draft intact /// (ApplyAskSheet posture — the edited draft is never destroyed). private func newPostFromSession() -> String? { guard let posts, let home else { return "No library to write into." } if posts.newPostFromSession(body: sessionDraft ?? "", home: home) == nil { return posts.lastError ?? "The piece couldn't be written." } sessionDraft = nil return nil } /// The open piece in Posts — the association target for the New Session /// choice (nil = free-floating only). Static + posts-coupled: test-pinned. static func openPiece(in posts: PostsModel?) -> Post? { guard let posts, let id = posts.session?.postID else { return nil } return posts.posts.first(where: { $0.id == id }) } private var emptyState: some View { VStack(spacing: 8) { Text("No sessions yet.") .font(.system(size: 16, weight: .semibold, design: DesignTokens.serif)) Text("Sessions arrive when a pass runs — or create one with New Session.") .font(.callout) .foregroundStyle(DesignTokens.muted) .multilineTextAlignment(.center) } .padding(38) .frame(maxWidth: .infinity, maxHeight: .infinity) } } /// One roster row: the library's post-row language — always-2px leading /// strip (accent when selected, no layout shift), surface card + border on /// selection, serif name over mono-11 meta (piece · created). private struct SessionEntryRow: View { let entry: SessionEntry let selected: Bool let select: () -> Void @State private var hover = false var body: some View { // Same shape as LibraryPostRow: leading corners square (the 2px // strip), trailing rounded 8 — only the strip's COLOR changes. let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8)) return Button(action: select) { HStack(spacing: 0) { Rectangle() .fill(selected ? DesignTokens.accent : .clear) .frame(width: 2) VStack(alignment: .leading, spacing: 5) { Text(entry.name) .font(.system(size: 13, weight: .semibold, design: DesignTokens.serif)) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) Text(metaLine) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(DesignTokens.muted) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) } .padding(10) } .clipShape(shape) } .buttonStyle(.plain) .foregroundStyle(DesignTokens.foreground) .background { if selected || hover { shape .fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06)) .overlay( shape.strokeBorder(selected ? DesignTokens.border : .clear), ) } } .padding(.horizontal, 8) .onHover { hover = $0 } .help(entry.name) .accessibilityLabel("\(entry.name), \(entry.pieceTitle ?? "free-floating session")") } private var metaLine: String { var parts: [String] = [] if let piece = entry.pieceTitle { parts.append(piece) } parts.append(FixCardStore.formatted(entry.createdAt, "yyyy-MM-dd HH:mm")) return parts.joined(separator: " · ") } } /// #30 (S2.7): the New Post from Session ask — the draft candidate /// (the session's last mentor reply) prefills and stays editable. /// Confirm materializes the piece stamped `origin: ai` — never /// stats-eligible — and opens it in Posts; Cancel writes nothing. /// The error line is SHEET-LOCAL state: it dies with the presentation, /// so a re-opened ask never shows a stale refusal. private struct NewPostFromSessionSheet: View { @Binding var draft: String /// The confirm's failure reason — a failed write keeps the sheet up, /// draft intact; dismissal itself is the cancel. @State private var createError: String? let create: () -> String? var body: some View { VStack(alignment: .leading, spacing: 12) { Text("New Post from Session") .font(.system(size: 15, weight: .semibold, design: DesignTokens.serif)) Text( "The draft starts from the session's last mentor reply. It lands in your library stamped origin: ai — never counted as your writing.", ) .font(.callout) .foregroundStyle(DesignTokens.muted) TextEditor(text: $draft) .font(.system(size: 13, design: DesignTokens.serif)) .frame(width: 380, height: 160) .overlay( RoundedRectangle(cornerRadius: DesignTokens.radius) .strokeBorder(DesignTokens.border), ) if let createError { Text(createError) .font(.system(size: 11, design: DesignTokens.mono)) .foregroundStyle(.orange) } HStack { Spacer() // Dismissal itself is the cancel (binding set(false) → // sessionDraft = nil) — Esc and ⌘. land here too. Button("Cancel", role: .cancel) {} .keyboardShortcut(.cancelAction) Button("Create Post", action: confirm) .keyboardShortcut(.defaultAction) .disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } .padding(20) .frame(width: 420) } /// No dismiss() here — success closes the sheet via the pane's /// `sessionDraft = nil` (the binding); failure keeps it up with the /// inline reason and the edited draft intact. private func confirm() { createError = create() } }