feat(mentor): editorial chat voice for the transcript (#155)
CI / ci (push) Canceled after 0s

Wayfinder map #153, build slice 1 of the #154 contract: the shared
SessionTranscriptView speaks the two-color editorial voice — speaker
prefixes map onto serif agent prose (markdown at flush, verbatim
streaming), right-aligned terracotta user capsules, and the mono status
box on the fg-wash card; ThinkingBlock port; composer restyle with one
Send/Stop button, floating liveness chip, and the Debug toggle moved to
its trailing edge (Sessions pane inherits the same surface).

Finish-audit fanout hardened it: interpreted markdown opens http(s) only
(openURL gate at the sink — engine prose echoes imported content; pinned
via the pure linkVerdict seam), Caps Lock no longer turns Shift+Return
into a send (pinned), the plain-Button toggles speak state to VoiceOver,
and the dead GeometryReader wrapper is gone.

Suite 584/584 (xcresult count), flip-verified pins, swiftformat +
swiftlint clean at the error tier.
This commit is contained in:
AlexKucera committed 2026-11-04 09:46:21 +01:00
1 parent ef246e3f27
commit 2aa8bdabd8
8 files changed
+542 -101

No files matched your search

+405 -82
View File
@@ -7,20 +7,34 @@
// 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 input rail (#28, extracted from MentorPaneView so
/// 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).
/// 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?
@@ -30,6 +44,11 @@ struct SessionTranscriptView: View {
@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
@@ -39,12 +58,30 @@ struct SessionTranscriptView: View {
}
}
/// 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)
@@ -52,27 +89,42 @@ struct SessionTranscriptView: View {
}
}
/// 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 {
LazyVStack(alignment: .leading, spacing: 10) {
// 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: quiet, capped — it's transient (the full
// text lands in a collapsed row when the turn ends).
Text(model.streamingThought)
.font(.system(size: 11, design: DesignTokens.mono))
.foregroundStyle(DesignTokens.muted)
.lineLimit(3)
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
// 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 {
textRow("Mentor: \(model.streamingText)")
// Verbatim while streaming (#97) — markdown parses at
// flush, when the row lands.
agentProse(Text(verbatim: model.streamingText))
}
}
.padding(12)
.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
@@ -80,55 +132,6 @@ struct SessionTranscriptView: View {
.defaultScrollAnchor(.bottom)
}
/// The freeform composer + liveness — the Mentor pane's #23 rail,
/// shared with the Sessions pane (#30).
private var inputBar: some View {
VStack(alignment: .leading, spacing: 8) {
// Liveness: a pass legitimately runs minutes of silent tool work
// (skill loads, learnings) — without this the pane reads as dead
// (dogfood #23: "hard to tell if it is still thinking").
if model.isStreaming {
HStack(spacing: 8) {
ProgressView()
.controlSize(.small)
Text("Mentor is working — Stop to interrupt.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
HStack(spacing: 8) {
TextField("Ask the mentor…", text: $draft, axis: .vertical)
.textFieldStyle(.plain)
.lineLimit(1 ... 4)
.onSubmit { send() }
Button {
send()
} label: {
Image(systemName: "arrow.up.circle.fill")
.font(.title2)
}
.buttonStyle(.plain)
.disabled(draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || model.isStreaming)
if model.isStreaming {
Button {
model.stopStreaming()
} label: {
Text("Stop")
}
.controlSize(.regular)
}
}
}
.padding(12)
.disabled(model.phase.isReady == false)
}
private func send() {
let text = draft
draft = ""
Task { await model.sendPrompt(text) }
}
/// The writing-session filter: prose + card events stay; raw rows and
/// thinking are debug-only. Static, nonisolated — pure, testable from
/// any context.
@@ -139,13 +142,65 @@ struct SessionTranscriptView: View {
}
}
/// #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):
textRow(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):
ThoughtRow(text: 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.
@@ -162,12 +217,82 @@ struct SessionTranscriptView: View {
}
}
private func textRow(_ text: String) -> some View {
Text(text)
/// 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(.system(size: 15, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.foreground)
.lineSpacing(9) // CSS 1.6
.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(.system(size: 13))
.foregroundStyle(DesignTokens.foreground)
.lineSpacing(6.5) // CSS 1.5
.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(.system(size: 11, design: DesignTokens.mono))
.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 {
@@ -182,9 +307,11 @@ struct SessionTranscriptView: View {
}
/// #29 (S8.3): one candidate research-note card — serif title, mono
/// muted url, selectable note, muted-italic quote. Pending offers Keep
/// (ask-before) + Reject (no confirm — vanishes, nothing recorded);
/// kept/rejected dim 0.45 (closed-card voice) with their meta line.
/// 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
@@ -197,6 +324,9 @@ struct SessionTranscriptView: View {
dispositionView
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14)
.padding(.vertical, 12)
.background(washCard)
.opacity(dimmed)
}
@@ -229,6 +359,11 @@ struct SessionTranscriptView: View {
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(.system(size: 11, design: DesignTokens.mono))
@@ -236,23 +371,63 @@ struct SessionTranscriptView: View {
}
}
/// #24 fix: the engine's thinking, collapsed — a pass's thought stream
/// runs to hundreds of lines and is not the critique.
private struct ThoughtRow: View {
let text: String
/// #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 {
DisclosureGroup {
Text(text)
.font(.system(size: 10, design: .monospaced))
.foregroundStyle(.secondary)
.textSelection(.enabled)
} label: {
Text("thinking")
.font(.system(size: 11, design: .monospaced))
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(.system(size: 11, design: DesignTokens.mono))
.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(.system(size: 13, design: DesignTokens.serif))
.foregroundStyle(DesignTokens.muted)
.lineSpacing(7.8) // CSS 1.6
.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)
}
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
@@ -275,6 +450,154 @@ struct SessionTranscriptView: View {
}
}
// 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(.system(size: 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(.system(size: 11, design: DesignTokens.mono))
.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(.caption)
.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(.system(size: 10, design: DesignTokens.mono))
.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.