Files
museion/Museion/SessionTranscriptView.swift
T
AlexKucera 7ed9b41256 feat(chat): apply the editor's typefaces to the conversation surface
Per the 2026-11-05 owner ruling, the chat wears ProseTypography's
faces: Valkyrie OT B for agent prose/thinking, Concourse OT Book for
the user capsule and composer, UbuntuMono NFM for the mono voice.
DesignTokens gains valkyrie/concourse/ubuntuMono constructors
(Font.custom falls back to system faces when absent), and
SessionTranscriptView's lineSpacings are recalibrated to each face's
natural line box to hold the CSS leading ratios. AGENTS.md updated to
match.
2026-11-05 14:29:45 +01:00

633 lines
21 KiB
Swift
Raw 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.
//
// SessionTranscriptView.swift
// Museion
//
// #28 (S2.3): the shared session transcript, extracted from MentorPaneView —
// one renderer for the ACTIVE session's rows + streaming buffers. The
// Mentor pane passes its debug toggle; the Sessions pane reads the writing
// voice.
//
// #155 (map #153): the editorial chat voice — the Vivarium treatment
// remapped onto the two-color palette per the locked contract
// (ref/prototypes/wf154-mentor-pane-prototype.html). Speaker-act rows
// render as speech (right-aligned terracotta capsule / full-width serif
// prose, markdown parsed at flush, verbatim while streaming — the Vivarium
// #97 pattern); every other text row is the system's quiet mono voice on
// the fg-wash 6% card. Composer: surface input, accent Send flipping to a
// terracotta-outlined Stop, floating liveness chip (streaming only), the
// debug toggle at the trailing edge.
//
import SwiftUI
/// The shared session surface — the ACTIVE session's rows + streaming
/// buffers + the freeform composer (#28, extracted from MentorPaneView so
/// the Sessions pane reads the same surface; **#30: the composer moved here
/// too — a session is a conversation, and every session surface offers
/// one**). Writing voice: pass `showsDebugRows: false` (the debug toggle
/// stays the Mentor pane's — hand its binding in to seat it at the
/// composer's trailing edge, settled map #153 #5).
struct SessionTranscriptView: View {
let model: MentorSessionModel
/// Raw session/tool rows, collapsed thinking, and live thinking render
/// only when on — the model keeps every row either way.
var showsDebugRows = false
/// #155 (settled #5): the Debug toggle's seat is the composer's trailing
/// edge. Nil (the Sessions pane, previews) renders no toggle.
var debugBinding: Binding<Bool>?
/// #29 (S8.3): the Home a kept research note lands in — nil (previews)
/// hides the candidate card's Keep/Reject buttons.
var home: URL?
/// The ask-before keep (#29 G9): ONE blocking confirm per candidate,
/// presented over the transcript — never inside a lazy row.
@State private var pendingKeep: PendingKeep?
/// The freeform draft (#30: shared input rail).
@State private var draft = ""
/// #155: the pane's live width — the user capsule caps at 85% of the
/// CONTENT column (width − 2×16 transcript pads). Seeded to the mentor
/// column so the first frame is right there; the Sessions pane's wider
/// column corrects it on the first geometry pass.
@State private var paneWidth: CGFloat = 356
private struct PendingKeep: Identifiable {
let rowID: UUID
let candidate: ResearchCandidate
var id: UUID {
rowID
}
}
/// The user capsule's cap — 85% of the visible column (contract ruling).
private var capsuleCap: CGFloat {
max(0, (paneWidth - 32) * 0.85)
}
var body: some View {
VStack(spacing: 0) {
transcript
Divider()
inputBar
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.onGeometryChange(for: CGFloat.self) { $0.size.width } action: { paneWidth = $0 }
// Security audit (#155): the prose/thinking markdown is this
// surface's first INTERPRETED render of engine-sourced text, and
// engine replies echo imported content — Text renders parsed links
// tappable by default. Gate at the sink (#34 doctrine): http(s)
// opens system-side, every other scheme dies.
.environment(\.openURL, OpenURLAction { url in
switch Self.linkVerdict(for: url) {
case .open: .systemAction(url)
case .discard: .discarded
}
})
.sheet(item: $pendingKeep) { pending in
if let home {
ResearchKeepSheet(model: model, rowID: pending.rowID, candidate: pending.candidate, home: home)
}
}
}
/// The link-open gate for interpreted markdown: http(s) opens; every
/// other scheme (file:, mailto:, custom app schemes) discards —
/// engine-sourced prose must never open arbitrary handlers. Returns a
/// pure verdict (`OpenURLAction.Result` is a struct, not an enum —
/// unpinnable by pattern). Static, nonisolated — test-pinned.
nonisolated static func linkVerdict(for url: URL) -> LinkVerdict {
if let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" {
return .open
}
return .discard
}
nonisolated enum LinkVerdict {
case open
case discard
}
private var transcript: some View {
ScrollView {
// Contract turn rhythm: 18px between turns; pads 18/16/12.
LazyVStack(alignment: .leading, spacing: 18) {
ForEach(model.rows.filter { showsDebugRows || Self.isWritingRow($0) }) { row in
rowView(row)
}
if showsDebugRows, !model.streamingThought.isEmpty {
// Live thinking: open while it runs (spinner toggle),
// collapsed into a `thought` row at flush.
ThinkingBlock(content: Text(verbatim: model.streamingThought), initiallyExpanded: true, live: true)
}
if !model.streamingText.isEmpty {
// Verbatim while streaming (#97) — markdown parses at
// flush, when the row lands.
agentProse(Text(verbatim: model.streamingText))
}
}
.padding(EdgeInsets(top: 18, leading: 16, bottom: 12, trailing: 16))
.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)
}
/// The writing-session filter: prose + card events stay; raw rows and
/// thinking are debug-only. Static, nonisolated — pure, testable from
/// any context.
nonisolated static func isWritingRow(_ row: SessionRow) -> Bool {
switch row.content {
case .text, .fixCard, .researchNote: true
case .thought, .raw: false
}
}
/// #155: the editorial-voice classifier — the model's text rows carry
/// speaker prefixes ("Mentor: ", "You: "); the render seam maps them
/// onto the contract's three voices. Everything else (refusals, pass
/// kick-off labels, reveals) is the system's mono voice. Static,
/// nonisolated — pure, testable from any context.
nonisolated static func speaker(of text: String) -> Speaker {
if text.hasPrefix("Mentor: ") {
return .agent
}
if text.hasPrefix("You: ") {
return .user
}
return .system
}
/// The three contract voices for a text row.
nonisolated enum Speaker {
case agent
case user
case system
}
/// The composer's Return split: plain Return sends, Shift+Return breaks
/// the line, every other chord passes through to native handling. Caps
/// Lock is masked — an exact `==` turned Shift+Return under Caps Lock
/// into a send. Static, nonisolated — pure, test-pinned.
nonisolated static func returnIntent(for modifiers: EventModifiers) -> ReturnIntent {
let mods = modifiers.subtracting(.capsLock)
if mods.isEmpty {
return .send
}
if mods == .shift {
return .lineBreak
}
return .passthrough
}
nonisolated enum ReturnIntent {
case send
case lineBreak
case passthrough
}
@ViewBuilder
private func rowView(_ row: SessionRow) -> some View {
switch row.content {
case let .text(text):
switch Self.speaker(of: text) {
case .agent:
agentProse(markdownText(String(text.dropFirst("Mentor: ".count))))
case .user:
userCapsule(String(text.dropFirst("You: ".count)))
case .system:
statusBox(text)
}
case let .thought(text):
// #24 dogfood fix: collapsed — a pass's thought stream runs to
// hundreds of lines and is not the critique.
ThinkingBlock(content: markdownText(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 .researchNote(candidate):
ResearchNoteRow(
candidate: candidate,
actions: home != nil,
keep: { pendingKeep = PendingKeep(rowID: row.id, candidate: candidate) },
reject: { model.setResearchDisposition(rowID: row.id, .rejected) },
)
case let .raw(kind, json):
RawUpdateRow(kind: kind, json: json)
}
}
/// Agent turns: full-width serif 15/1.6, no bubble (#81 treatment,
/// two-color voice). Flushed rows arrive markdown-parsed (rowView), the
/// live stream verbatim (#97).
private func agentProse(_ content: Text) -> some View {
content
.font(DesignTokens.valkyrie(15))
.foregroundStyle(DesignTokens.foreground)
.lineSpacing(5.3) // CSS 1.6 — Valkyrie's natural 18.7 carries most of it
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
/// User turns: the right-aligned capsule — terracotta wash 14% fill,
/// fg ink, sans 13/1.5, pads 16/12, radius 12/12/2/12 (the 2pt tail
/// bottom-trailing), capped at 85% of the visible column.
private func userCapsule(_ text: String) -> some View {
Text(text)
.font(DesignTokens.concourse(13))
.foregroundStyle(DesignTokens.foreground)
.lineSpacing(3.7) // CSS 1.5 (19.5 − Concourse's natural 15.8)
.textSelection(.enabled)
.padding(.horizontal, 16)
.padding(.vertical, 12)
.background(
UnevenRoundedRectangle(
topLeadingRadius: 12,
bottomLeadingRadius: 12,
bottomTrailingRadius: 2,
topTrailingRadius: 12,
).fill(DesignTokens.accent.opacity(0.14)),
)
.fixedSize(horizontal: false, vertical: true)
// Trailing INSIDE the cap too: the cap frame is greedy, so a
// leading alignment parked short bubbles mid-column (Vivarium
// owner report 2026-11-02).
.frame(maxWidth: capsuleCap, alignment: .trailing)
.frame(maxWidth: .infinity, alignment: .trailing)
}
/// The quiet system voice: mono 11/1.5 muted on the fg-wash card —
/// refusals, pass kick-off labels, reveals. Fit-content width.
private func statusBox(_ text: String) -> some View {
Text(text)
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(DesignTokens.muted)
.lineSpacing(5.5) // CSS 1.5
.textSelection(.enabled)
.padding(.horizontal, 12)
.padding(.vertical, 10)
.background(washCard)
}
/// The card-fill ruling (owner, 2026-11-03): thinking cards, status
/// boxes, and research-note cards sit on fg-wash 6% — borderless,
/// radius 10.
private var washCard: some View {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.foreground.opacity(0.06))
}
/// Inline markdown keeping line breaks; verbatim if parsing throws —
/// the Vivarium pattern applied to the mentor's replies.
/// ponytail: flushed rows re-parse per publish on later turns (ForEach
/// row closures re-run with the body) — bounded by prior transcript
/// size; a per-row Text cache is the upgrade if long sessions ever
/// measure slow.
private func markdownText(_ markdown: String) -> Text {
if let attributed = try? AttributedString(
markdown: markdown,
options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace),
) {
return Text(attributed)
}
return Text(verbatim: markdown)
}
/// 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(DesignTokens.ubuntuMono(11))
.foregroundStyle(DesignTokens.muted)
.frame(maxWidth: .infinity, alignment: .leading)
}
}
/// #29 (S8.3): one candidate research-note card — serif title, mono
/// muted url, selectable note, muted-italic quote, on the wash card
/// (#155 — the folded derivation: research cards inherit the card
/// family). Pending offers Keep (ask-before) + Reject (no confirm —
/// vanishes, nothing recorded); kept/rejected dim 0.45 (closed-card
/// voice) with their meta line.
private struct ResearchNoteRow: View {
let candidate: ResearchCandidate
let actions: Bool
let keep: () -> Void
let reject: () -> Void
var body: some View {
VStack(alignment: .leading, spacing: 6) {
ResearchNoteContent(candidate: candidate)
dispositionView
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14)
.padding(.vertical, 12)
.background(washCard)
.opacity(dimmed)
}
@ViewBuilder
private var dispositionView: some View {
switch candidate.disposition {
case .pending:
if actions {
HStack(spacing: 8) {
Button("Keep", action: keep)
.buttonStyle(.bordered)
.controlSize(.small)
.font(DesignTokens.ubuntuMono(11))
.help("Land this note in the piece's research/ folder")
Button("Reject", action: reject)
.buttonStyle(.bordered)
.controlSize(.small)
.font(DesignTokens.ubuntuMono(11))
.help("Vanish the candidate — nothing is recorded")
}
}
case let .kept(fileName):
meta("kept · research/\(fileName)")
case .rejected:
meta("rejected")
}
}
private var dimmed: Double {
candidate.disposition == .pending ? 1 : 0.45
}
private var washCard: some View {
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.foreground.opacity(0.06))
}
private func meta(_ text: String) -> some View {
Text(text)
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(DesignTokens.muted)
}
}
/// #155: the ThinkingBlock port — mono-11 toggle over serif-13 muted
/// content on the recessed wash card (contract: thinking = mono 11
/// toggle + serif 13 muted on the card). Owns its expansion state: the
/// LIVE stream mounts open (`initiallyExpanded: true`), flushed rows
/// mount collapsed (Vivarium audit: a pane-level binding carried a
/// collapse from turn 1 into turn 2's live block).
private struct ThinkingBlock: View {
/// Pre-rendered content (markdown at flush, verbatim live — #97);
/// the block itself never re-parses.
let content: Text
/// The live stream renders the spinner toggle and no chevron.
var live = false
@State private var expanded: Bool
init(content: Text, initiallyExpanded: Bool = false, live: Bool = false) {
self.content = content
self.live = live
_expanded = State(initialValue: initiallyExpanded)
}
var body: some View {
VStack(alignment: .leading, spacing: 0) {
Button {
withAnimation { expanded.toggle() }
} label: {
HStack(spacing: 6) {
if live {
ProgressView().controlSize(.mini)
} else {
Image(systemName: expanded ? "chevron.down" : "chevron.right")
}
Text("Thinking…")
}
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(DesignTokens.muted)
}
.buttonStyle(.plain)
// Audit #155: a plain Button carries no switch semantics —
// speak the state the color/opacity encodes.
.accessibilityLabel("Thinking")
.accessibilityValue(expanded ? "expanded" : "collapsed")
if expanded {
content
.font(DesignTokens.valkyrie(13))
.foregroundStyle(DesignTokens.muted)
.lineSpacing(4.6) // CSS 1.6 (20.8 − Valkyrie's natural 16.2)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14)
.padding(.vertical, 12)
.background(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.fill(DesignTokens.foreground.opacity(0.06)),
)
.padding(.top, 8)
}
}
}
}
private struct RawUpdateRow: View {
let kind: String
let json: String
var body: some View {
DisclosureGroup {
Text(json)
.font(DesignTokens.ubuntuMono(10))
.textSelection(.enabled)
} label: {
Text(kind)
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
// MARK: Composer (#155 contract restyle; file-scope extension —
// type_body_length posture, MentorPaneView precedent)
private extension SessionTranscriptView {
/// The composer: surface-fill input (radius 10, border), the ONE action
/// button — accent Send idle, terracotta-outlined Stop mid-stream — and
/// the debug toggle at the trailing edge. The liveness chip floats
/// ABOVE the composer while streaming (contract ruling: the composer
/// row stays flat).
private var inputBar: some View {
VStack(alignment: .leading, spacing: 8) {
HStack(alignment: .bottom, spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain)
.font(DesignTokens.concourse(13))
.lineLimit(1 ... 4)
.padding(.horizontal, 10)
.padding(.vertical, 8)
.frame(minHeight: 36)
.background(RoundedRectangle(cornerRadius: DesignTokens.radius).fill(DesignTokens.surface))
.overlay(
RoundedRectangle(cornerRadius: DesignTokens.radius)
.strokeBorder(DesignTokens.border, lineWidth: 1),
)
.onSubmit { send() } // ⌅/fallback submit — send() no-ops on the double fire
.onKeyPress(phases: .down) { press in
guard press.key == .return else { return .ignored }
// Plain Return sends, Shift+Return breaks the line,
// every other chord keeps its native newline (⌥↩ above
// all). macOS routes Return — ANY modifiers — to the
// field's submit action otherwise (Vivarium owner
// report 2026-10-26). Caps Lock is masked inside
// returnIntent — an exact `==` sent the draft under it.
// ponytail: the newline appends at the END, not the
// caret — caret-aware insertion needs NSTextView
// access; revisit if mid-draft edits ever matter.
switch Self.returnIntent(for: press.modifiers) {
case .send:
send()
return .handled
case .lineBreak:
draft += "\n"
return .handled
case .passthrough:
return .ignored
}
}
sendButton
}
if let debugBinding {
debugToggle(debugBinding)
}
}
.padding(.horizontal, 14)
.padding(.top, 12)
.padding(.bottom, 10)
.overlay(alignment: .top) {
// #23 dogfood: a pass legitimately runs minutes of silent tool
// work — without the chip the pane reads as dead. Contract
// ruling: floating, streaming-only, hit-through.
if model.isStreaming {
livenessChip
.offset(y: -40)
}
}
.disabled(model.phase.isReady == false)
}
/// ONE action button (Vivarium): Send idle / Stop mid-stream. The
/// default-action shortcut rides the Send state ONLY — Stop must never
/// catch a plain Return.
private var sendButton: some View {
Button {
if model.isStreaming {
model.stopStreaming()
} else {
send()
}
} label: {
Text(model.isStreaming ? "Stop" : "Send")
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(model.isStreaming ? DesignTokens.accent : DesignTokens.surface)
.padding(.horizontal, 14)
.frame(minHeight: 30)
.background(
RoundedRectangle(cornerRadius: 6)
.fill(model.isStreaming ? Color.clear : DesignTokens.accent),
)
.overlay(
RoundedRectangle(cornerRadius: 6)
.strokeBorder(model.isStreaming ? DesignTokens.accent : Color.clear, lineWidth: 1),
)
}
.buttonStyle(.plain)
.disabled(!model.isStreaming && draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
.keyboardShortcut(model.isStreaming ? nil : .defaultAction)
.help(
model.isStreaming
? "Cancel the running turn — the engine ends it with a cancelled stop."
: "Send to the mentor.",
)
}
/// The liveness chip — a hint, not a control (Stop lives in the Send
/// slot). thinMaterial is the contract's translucent-surface+blur
/// approximation (#154 deviation note).
private var livenessChip: some View {
HStack(spacing: 8) {
ProgressView().controlSize(.small)
Text("Mentor is working — Stop to interrupt.")
.font(DesignTokens.ubuntuMono(10))
.foregroundStyle(.secondary)
}
.padding(.horizontal, 12)
.padding(.vertical, 5)
.background(.thinMaterial, in: Capsule())
.allowsHitTesting(false)
}
/// Settled #5: the Debug toggle's new seat — mono-10 lowercase text
/// toggle at the composer's trailing edge (muted off, accent on).
private func debugToggle(_ binding: Binding<Bool>) -> some View {
Button {
binding.wrappedValue.toggle()
} label: {
Text("debug")
.font(DesignTokens.ubuntuMono(10))
.foregroundStyle(binding.wrappedValue ? DesignTokens.accent : DesignTokens.muted)
.opacity(binding.wrappedValue ? 1 : 0.65)
}
.buttonStyle(.plain)
.frame(maxWidth: .infinity, alignment: .trailing)
.help("Show session updates, tool calls, and engine thinking.")
// Audit #155: the checkbox this replaced announced switch state —
// a plain Button must say it itself.
.accessibilityLabel("Debug rows")
.accessibilityValue(binding.wrappedValue ? "on" : "off")
}
private func send() {
let text = draft.trimmingCharacters(in: .whitespacesAndNewlines)
guard !text.isEmpty, !model.isStreaming else { return }
draft = ""
Task { await model.sendPrompt(text) }
}
}
/// #29 audit: the candidate's content block — title/url/note/quote — shared
/// by the transcript row and the keep sheet's preview, so a restyle edits
/// one place. File scope: ResearchKeepSheet reuses it.
struct ResearchNoteContent: View {
let candidate: ResearchCandidate
var body: some View {
VStack(alignment: .leading, spacing: 6) {
Text(candidate.title)
.font(DesignTokens.valkyrie(13))
Text(candidate.url)
.font(DesignTokens.ubuntuMono(11))
.foregroundStyle(DesignTokens.muted)
.lineLimit(1)
.truncationMode(.middle)
if !candidate.note.isEmpty {
Text(candidate.note)
.textSelection(.enabled)
}
if !candidate.quote.isEmpty {
Text("“\(candidate.quote)”")
.italic()
.foregroundStyle(DesignTokens.muted)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
#Preview {
SessionsPaneView(model: MentorSessionModel(), posts: nil, binaryPath: nil)
}