Files
museion/Museion/SessionsPaneView.swift
T
AlexKucera 9895614b7e
CI / ci (push) Canceled after 0s
feat(sessions): session lifecycle UI (S2.3) (#28)
Each Session is a conversation Museion UIs, never owns. The mentor
bridge hosts multiple engine-owned sessions: per-session transcripts
keyed by wire sessionId behind same-named proxies (every existing
caller compiles unchanged), a names-only roster at Application
Support/sessions.json (0600; id/name/pieceTitle/date — the words
stay engine-owned per ADR-0007), and the standard affordances over
the wire: session/new, session/load, session/fork, compact as the
/compress slash prompt, session/cancel as the Stop rail.

The Sessions pane replaces its placeholder: roster list (piece-
associated by name when Posts has an open piece), row-click resume
with the engine's full-history replay (user turns included), Fork ·
Compact, live streaming with Stop; every pass auto-creates its
rostered session and streams into it; the transcript renderer is
shared with the mentor pane. Notification hops ride the main queue
(FIFO with the continuation resume) so the adapter's replay-before-
response contract is guaranteed, not probabilistic.

Resume refusals are honest and entry-attributed (an engine-unknown
session never fabricates history); concurrent replays refuse instead
of interleaving; restart replays from the engine rather than trusting
a diverging local copy. Finish-audit (three reviewers) surfaced the
concurrent-resume race, the dead restart branch, the runPass guard
window, the 15 s session/load default, and the missing createSession
backstop — all fixed and pinned (12 lifecycle pins; 359 tests green).

Closes #28
2026-10-22 12:21:12 +02:00

297 lines
8.7 KiB
Swift

//
// 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?
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)
// Same lazy lifecycle as MentorPaneView: idempotent open — whichever
// surface the writer reaches first spawns the engine.
.task {
if let binaryPath {
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:
ProgressView("Starting the mentor engine…")
.frame(maxWidth: .infinity, maxHeight: .infinity)
case .crashed:
crashedNote
case .ready:
VStack(spacing: 0) {
actionsRow
Divider()
if model.isStreaming {
livenessRow
Divider()
}
SessionTranscriptView(model: model, showsDebugRows: false)
}
}
}
/// 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()
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)
}
/// Liveness (the Mentor pane's #23 posture, no input bar here): silent
/// tool work must not read as dead, Stop is the pane's Cancel affordance.
private var livenessRow: some View {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
Text("Mentor is working — Stop to interrupt.")
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
Spacer()
Button("Stop") {
model.stopStreaming()
}
.buttonStyle(.bordered)
.controlSize(.small)
.accessibilityLabel("Stop the mentor")
}
.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
@ViewBuilder
private var newSessionControl: some View {
if let piece = Self.openPiece(in: posts) {
Menu {
Button("New Session") { createSession(associatedWith: nil) }
Button("New Session on \(piece.title)") { createSession(associatedWith: piece.title) }
} label: {
Image(systemName: "plus")
}
.menuStyle(.button)
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.muted)
.disabled(!model.canStartSession)
.help("New Session")
.accessibilityLabel("New Session")
} else {
Button {
createSession(associatedWith: nil)
} label: {
Image(systemName: "plus")
}
.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) }
}
/// 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: " · ")
}
}