Files
museion/Museion/SessionsPaneView.swift
T
AlexKucera 5bf09552f6
CI / ci (push) Canceled after 0s
refactor(posts): route every library write through one rail
#179: every library-reflecting store write (draft save, session-born
post, rename, move to project, archive/restore, trash, convert,
project creation, import batch, pass advance) now rides one internal
seam — performWrite pairs the write with exactly one rescan and owns
the error strip (cleared BEFORE the write so importFiles' per-file
failure messages survive the success tail; a nil-Home refusal writes
nothing). The model owns the Home: watchedHome is private(set), set
only by bind (construction + the Settings repoint); no public method
takes a Home parameter — 14 view call sites and ~115 test call sites
swept, dead home plumbing cut. The editor's debounced flush, the card
closes, the pass substrate and the micropub publish stay off the rail
by design (own error semantics, no library regroup).

A converged review finding is closed with a guard: the pass advance
re-resolves watchedHome after the engine's minutes-long turn, so a
mid-pass Settings repoint now refuses the advance with an honest strip
message instead of silently stamping pass state into the repointed
library (wrong-piece write on a slug collision). createProject
failures now surface in the sheet AND the strip — the rail-owns-the-
strip posture supersedes the #108 sheet-only rule.

Five rail pins (PostsModelWriteRailTests, suite members): write → one
library refresh + strip cleared, failed write owns the strip, nil-Home
refusal, import batch keeps per-file messages, mid-pass repoint
refuses the advance — the last two flip-verified against their guards.
ScriptedEngine gains endHeldPrompt (release a held turn as ended).

Verification: suite 657/657 the evening this landed; the next-morning
re-run could not start — both test runners hung before establishing
connection (#134 testmanagerd wedge; an untouched control suite hangs
identically — machine state, not this diff; reboot pending). Rail pins
5/5 isolated after the last test-only edit; swiftlint at baseline
parity; swiftformat clean.

Closes #179

[Generated by AI]
2026-11-10 08:45:04 +01:00

579 lines
23 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//
// 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 AppKit
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 {
// Round-1 polish (argon#3/sol#19/mercury#41): the pane header —
// title + New Session + its hairline — confines to the roster
// column (the Posts pane's language), and the roster|transcript
// divider runs full height.
HStack(spacing: 0) {
VStack(spacing: 0) {
PaneHeader(title: "Sessions") {
newSessionControl
}
rosterList
}
.frame(width: DesignTokens.libraryWidth)
paneBorder
if model.roster.isEmpty {
emptyState
} else {
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()
// Round-4 (all seats — Sessions scored 6 everywhere): entering
// the archive with nothing active (the Mentor pane's piece
// scoping clears activeEntry) auto-selects the newest roster
// session — the blank-canvas + bare em-dash entry dies.
// openSession is idempotent once ready, so this is the
// pane-entry selection rail; Sessions stays the unscoped
// archive (the Mentor pane re-scopes at ITS mount).
// (#142 posture: the wrapped condition list's brace lands on
// its own line and trips opening_brace — nested ifs, never
// fight the formatter.)
if model.activeEntry == nil, !model.isStreaming {
if let newest = model.roster.first {
await model.resumeSession(newest)
}
}
}
}
// 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(.top, 14) // Round-1 polish: the topmost row clears the header hairline
.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 + Fork/Compact beside them
/// — disabled while a turn streams (canStartSession).
/// Round-4: the row rides the #90 52pt header height so its hairline
/// runs continuous with the roster header's (argon#14/mercury#29); the
/// pills take the app's bordered secondary language at 28pt with a 16pt
/// window margin (sol#43/argon#48); a no-selection state never renders
/// a bare em-dash, and the session-scoped actions disable until a
/// session is active (all seats, round 3).
/// Round-5 (argon#47): a 'Pass N ·' prefix reads muted beside the ink
/// title (same line).
/// Round-8 (mercury#17 — FINAL RULING): the version badge sits BESIDE
/// the trailing button group — title | spacer | badge | buttons. Its
/// r5-r7 seat beside the title left a dead middle gap; it rides
/// vertically centered with the 28pt pills, 12pt off the group
/// (8 row spacing + the group's 4pt lead).
private var actionsRow: some View {
HStack(spacing: 8) {
if let name = model.activeEntry?.name {
passTitle(name)
.lineLimit(1)
.truncationMode(.tail)
} else {
Text("No session selected")
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.muted)
.help("Select a session in the roster — or start a new conversation from the + above.")
}
Spacer()
if let version = model.engineVersion {
// Round-1 polish (sol#53/mercury#68): the engine version is its
// own muted mono chunk on the fg-wash card. Round-6 (sol#35):
// fixedSize — the badge never truncates or compresses; the
// TITLE's budget accounts for it and truncates first.
Text(version)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(1)
.fixedSize()
.padding(.horizontal, 7)
.padding(.vertical, 2)
.background(
RoundedRectangle(cornerRadius: 5)
.fill(DesignTokens.foreground.opacity(0.06)),
)
.help(model.versionNote ?? version)
}
// #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).
HStack(spacing: 8) {
Button("New Post") {
sessionDraft = model.draftCandidateText() ?? ""
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(model.activeEntry == nil)
.help("Start a Post from this session's draft candidate")
.accessibilityLabel("New Post from Session")
Button("Fork") {
Task { _ = await model.forkActiveSession() }
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(!model.canStartSession || model.activeEntry == nil)
.help("Copy this session's history into a new one")
.accessibilityLabel("Fork session")
Button("Compact") {
Task { await model.compactActiveSession() }
}
.buttonStyle(BorderedSecondaryButtonStyle(minHeight: 28))
.disabled(!model.canStartSession || model.activeEntry == nil)
.help("Compress the session's history")
.accessibilityLabel("Compact session")
}
.padding(.leading, 4)
}
.padding(.horizontal, 16)
.frame(minHeight: 52)
}
/// Round-5 (argon#47): the conversation title — a 'Pass N ·' prefix
/// renders in muted beside the ink remainder (one line, two tones); any
/// other name renders whole in ink. The serif face applies per piece:
/// a concatenated Text keeps each segment's own styling.
private func passTitle(_ name: String) -> Text {
if let separator = name.range(of: " · "), Self.isPassLabel(String(name[..<separator.lowerBound])) {
return Text(String(name[..<separator.upperBound]))
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.muted)
+ Text(String(name[separator.upperBound...]))
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.foreground)
}
return Text(name)
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.foreground)
}
/// The pass transcripts' label heads — "Pass 1"/"Pass 12" (the model's
/// `runOneShot` names; "Blind Read" keeps its plain-ink title).
private static func isPassLabel(_ head: String) -> Bool {
let digits = head.dropFirst("Pass ".count)
return head.hasPrefix("Pass ") && !digits.isEmpty && digits.allSatisfy(\.isNumber)
}
/// 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))
// Round-2 polish: the #156 danger voice — terracotta, never
// the system orange (two-color world, no stray hues).
.foregroundStyle(DesignTokens.accent)
Text("The mentor engine stopped")
.font(.title3)
Text("Restart it in the Mentor pane — nothing is lost.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
}
.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: {
// Round-4 (mercury#57): accent tint + a heavier weight — the
// plus reads as a control, not decoration. Round-7 (argon#39):
// a real 24×24 hit-target container in the header pill family
// (surface fill + hairline, BorderedSecondaryButtonStyle's
// shape) — the bare glyph had no target.
Image(systemName: "plus")
.font(.system(size: 13, weight: .medium))
.frame(width: 24, height: 24)
.background(
RoundedRectangle(cornerRadius: 8)
.fill(DesignTokens.surface),
)
.overlay(
RoundedRectangle(cornerRadius: 8)
.strokeBorder(DesignTokens.border, lineWidth: 1),
)
}
.menuStyle(.button)
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.accent)
.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 else { return "No library to write into." }
if posts.newPostFromSession(body: sessionDraft ?? "") == 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))
// Round-4 (all seats): 'select a session or start a new
// conversation' — the empty canvas names its way out.
Text("Start a new conversation with the + above — sessions also arrive when a pass runs.")
.font(.callout)
.foregroundStyle(DesignTokens.muted)
.multilineTextAlignment(.center)
}
.padding(38)
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
/// One roster row: the library's post-row language — selected strip as a
/// vertically-inset rounded capsule (round-6: part of the card, not
/// pasted on), 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
/// Round-6 (mercury#4/sol#9 — verified against the r5 live shot):
/// the title budget is GLYPH-MEASURED. The r5 ~58-char estimate
/// overshot the real two-line capacity of this width (the r5 shot
/// still cut mid-word — "Markd…"); the seam now measures the row's
/// exact serif-13 semibold face, so its output is what renders and
/// lineLimit(2) below is a no-op safety net.
/// libraryWidth 232 − 16 row pads − 14 leading (2 strip + 12 gap) −
/// 10 trailing.
private static let titleWidth = DesignTokens.libraryWidth - 16 - 14 - 10
var body: some View {
// Same card shape as LibraryPostRow; the selected strip rides as
// an inset capsule overlay (below) — only the strip's LANGUAGE
// diverges from LibraryPostRow, by the round-6 ruling.
let shape = UnevenRoundedRectangle(cornerRadii: .init(bottomTrailing: 8, topTrailing: 8))
return Button(action: select) {
HStack(spacing: 0) {
VStack(alignment: .leading, spacing: 5) {
// Round-4 (sol#7/argon#15 tail/mercury#30): two lines
// — titles stop dying mid-word; meta stays below.
// Round-5 (mercury#4/sol#8/argon#16): word-boundary
// truncation replaces the native mid-word tail cut.
// Round-6: glyph-measured (see titleWidth) — the seam
// decides, lineLimit(2) is the safety net.
Text(WordBoundaryTruncation.fit(entry.name, maxWidth: Self.titleWidth))
.font(.system(size: 13, weight: .semibold, design: DesignTokens.serif))
.lineLimit(2)
.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)
}
// Round-5 (sol#38/mercury#54) kept 10-12pt between the
// strip and the text; the overlay strip (2pt) + 12pt
// internal leading = 14 off the card edge — same seat.
.padding(.leading, 14)
.padding(.trailing, 10)
.padding(.vertical, 10)
}
.clipShape(shape)
}
.buttonStyle(.plain)
.foregroundStyle(DesignTokens.foreground)
.background {
if selected || hover {
shape
.fill(selected ? DesignTokens.surface : DesignTokens.foreground.opacity(0.06))
.overlay(
// Round-5 (sol#38/mercury#54): the selected border one
// step stronger than the hairline — the #D8D4CC-equivalent
// darkening of border #E8E5DF via foreground opacity
// (no new hex) — so selection reads at a glance.
shape.strokeBorder(
selected ? DesignTokens.foreground.opacity(0.17) : .clear,
),
)
}
}
// Round-6 (mercury#25/49, argon#13): the selected strip is a
// vertically-inset rounded capsule — 7pt off the card's top and
// bottom, 2pt wide, radius 1 — reading as part of the card, not
// a full-height strip pasted beside it.
.overlay(alignment: .leading) {
if selected {
RoundedRectangle(cornerRadius: 1)
.fill(DesignTokens.accent)
.frame(width: 2)
.padding(.vertical, 7)
}
}
.padding(.horizontal, 8)
.onHover { hover = $0 }
.help(entry.name)
.accessibilityLabel("\(entry.name), \(entry.pieceTitle ?? "free-floating session")")
}
private var metaLine: String {
// Round-2 polish (argon#23/sol#13/mercury#61): display-level dedupe
// — when the session name already carries the piece title, the meta
// line shows the timestamp only. Contract otherwise unchanged
// (pieceTitle · yyyy-MM-dd HH:mm).
var parts: [String] = []
if let piece = entry.pieceTitle, !entry.name.contains(piece) {
parts.append(piece)
}
parts.append(FixCardStore.formatted(entry.createdAt, "yyyy-MM-dd HH:mm"))
return parts.joined(separator: " · ")
}
}
/// Round-5 (mercury#4/sol#8/argon#16) → Round-6 glyph-measured
/// (mercury#4/sol#9) → Round-7 middle-eliding (argon#14/sol#32/47) →
/// Round-8 head-biased split (sol#3): pure title truncation —
/// SwiftUI's tail truncation cuts mid-word ("Markd…") and, worse,
/// killed the roster's shared titles at their common boilerplate. The
/// seam measures the row's exact face (system serif 13 semibold,
/// through NSFont) against `maxWidth`; an overflowing title splits
/// HEAD-BIASED (~60/40): the head keeps a leading label ("Pass N ·")
/// plus as many following words as fit in ~60% of the glyph budget —
/// the unique topic survives — then the LONGEST word suffix that still
/// fits (r7 kept only the label and maximized the tail; the topic died
/// either way). Pinned in WordBoundaryTruncationTests.
nonisolated enum WordBoundaryTruncation {
/// The roster title's exact face — SessionEntryRow's serif-13
/// semibold system design, the same metrics SwiftUI's Text renders.
/// nonisolated(unsafe) — NSFont isn't Sendable (ProseTypography
/// precedent); the descriptor-built font is effectively immutable.
private nonisolated(unsafe) static let titleFont: NSFont = {
let base = NSFont.systemFont(ofSize: 13, weight: .semibold)
return base.fontDescriptor.withDesign(.serif).flatMap { NSFont(descriptor: $0, size: 13) } ?? base
}()
private static let spaceWidth = NSAttributedString(
string: " ", attributes: [.font: titleFont],
).size().width
/// Round-8 (sol#3): the head's share of the lines × maxWidth glyph
/// budget — bias the split toward the unique head, away from the
/// shared tail.
private static let headShare: CGFloat = 0.6
private static func width(_ text: String) -> CGFloat {
NSAttributedString(string: text, attributes: [.font: titleFont]).size().width
}
/// Passthrough when `text` wraps within `lines` × `maxWidth`;
/// otherwise (round-8, sol#3) MIDDLE-elide with a head-biased
/// (~60/40) split — the head keeps a leading "Label ·" trio when the
/// name carries one (the roster's "Pass N ·" shape) plus following
/// words up to `headShare` of the budget; the tail keeps the LONGEST
/// word suffix that still fits: more of the unique topic, less of
/// the shared boilerplate. When no suffix fits beside the head, the
/// head truncates alone (the r5/r6 shape — the ellipsis binds to its
/// last word); a word wider than the line keeps its own line
/// (lineLimit catches it).
static func fit(_ text: String, maxWidth: CGFloat, lines: Int = 2) -> String {
let words = text.split(separator: " ", omittingEmptySubsequences: true).map(String.init)
guard !words.isEmpty else { return text }
// Finish-audit: measure each word ONCE — a pathological title (an
// imported post's first line is unbounded) must not turn the
// candidate loop into quadratic glyph measurement on the main actor.
// ponytail: one pass per word is fine to ~10k words; bail to native
// lineLimit if a roster row ever renders slower than a frame.
let widths = words.map { width($0) }
guard lineCount(widths, maxWidth) > lines else { return text }
var head = [words[0]]
if words.count > 2, words[2] == "·" {
head = [words[0], words[1], words[2]]
}
let budget = CGFloat(lines) * maxWidth * headShare
// Grow the head into its budget — always leaving the tail at
// least one word to keep (a head that consumed everything is
// just the r5 prefix cut again).
var index = head.count
while index < words.count - 1, width((head + [words[index]]).joined(separator: " ")) <= budget {
head.append(words[index])
index += 1
}
let tail = Array(words.dropFirst(head.count))
let ellipsis = width("…")
let headWidths = Array(widths[0 ..< head.count])
for count in stride(from: tail.count, through: 1, by: -1) {
let candidateWidths = headWidths + [ellipsis] + Array(widths[(words.count - count)...])
if lineCount(candidateWidths, maxWidth) <= lines {
return head.joined(separator: " ") + " … " + tail.suffix(count).joined(separator: " ")
}
}
return head.joined(separator: " ") + "…"
}
/// Greedy word wrap (the text system's own algorithm): how many
/// lines `widths` (per-word glyph widths, measured once) need at
/// `maxWidth`.
private static func lineCount(_ widths: [CGFloat], _ maxWidth: CGFloat) -> Int {
var lines = 1
var used: CGFloat = 0
for tokenWidth in widths {
if used == 0 {
// A word wider than the line keeps its own line — the
// mid-word break is SwiftUI's, never the seam's.
used = tokenWidth
} else if used + spaceWidth + tokenWidth <= maxWidth {
used += spaceWidth + tokenWidth
} else {
lines += 1
used = tokenWidth
}
}
return lines
}
}