// // 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 // 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. Round-2 polish: interruption/error status rows // carry a restrained terracotta accent. Composer: surface input, accent // Send flipping to a terracotta-outlined Stop, floating liveness chip // (streaming only), the debug toggle hover-revealed at the trailing // edge — zero visible footprint at rest. // 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? /// #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 = "" /// Round-2 polish (argon#21/sol#43/mercury#58): the debug toggle is /// hover-revealed — true while the pointer is over the composer row. @State private var composerHover = false /// #155: the pane's live width — the user capsule caps at 85% of the /// MEASURE 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 /// Round-1 polish (argon#4/mercury#43): the reading measure — /// conversational content caps at a comfortable ~720pt, centered in the /// (possibly ~830pt+) Sessions column. The mentor column (356) caps /// naturally. Scroll anchoring untouched (#24 bottom-anchor contract). private static let measureCap: CGFloat = 720 private var measureWidth: CGFloat { min(paneWidth, Self.measureCap) } private struct PendingKeep: Identifiable { let rowID: UUID let candidate: ResearchCandidate var id: UUID { rowID } } /// The user capsule's cap — 85% of the visible MEASURE column /// (contract ruling, pads included). private var capsuleCap: CGFloat { max(0, (measureWidth - 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 { let visible = model.rows.filter { showsDebugRows || Self.isWritingRow($0) } return ScrollView { // Contract turn rhythm: 18px between turns; pads 18/16/12. // Round-7 (mercury#21/argon#39): rows render with their // PREDECESSOR in reach — the warning-styling and gap rules // below are pairwise, not per-row. LazyVStack(alignment: .leading, spacing: 18) { ForEach(Array(visible.enumerated()), id: \.element.id) { pair in rowView(pair.element, previous: pair.offset > 0 ? visible[pair.offset - 1] : nil) } 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: 16, trailing: 16)) // Round-1 polish: the reading measure — content centers in a // ≤720pt column (argon#4/mercury#43); anchor untouched (#24). .frame(maxWidth: measureWidth) .frame(maxWidth: .infinity, alignment: .center) } // #24 fix: programmatic scrollTo raced the growing lazy rows and // mislanded at the TOP; the native bottom anchor needs no scroll code. .defaultScrollAnchor(.bottom) // Round-1 polish (argon#27/mercury#61): viewport clearance — a row // sliced mid-scroll never rides the header divider (the content pad // above only shows at full scroll-up). .padding(.top, 14) } /// 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. /// Round-1 polish: engine-emitted operational notices (interruptions) /// and replayed pass kick-offs are STATUS, not conversation — they map /// to the system voice too (never serif prose, never a user capsule). nonisolated static func speaker(of text: String) -> Speaker { if text.hasPrefix("Mentor: ") { let body = String(text.dropFirst("Mentor: ".count)) return body.hasPrefix("Operation interrupted:") ? .system : .agent } if text.hasPrefix("You: ") { return isPassKickoff(String(text.dropFirst("You: ".count))) ? .system : .user } return .system } /// Round-1 polish: a replayed pass kick-off — the engine replays the /// pass prompt as a user turn whose body opens with PassContext's fixed /// "Pass Pass N — ." line. Static, nonisolated — pure. nonisolated static func isPassKickoff(_ body: String) -> Bool { body.hasPrefix("Pass Pass ") } /// Round-1 polish: the system row's display text — a replayed pass /// kick-off shows its FIRST LINE only (the full engine prompt stays out /// of the UI); every other status row renders verbatim. Static, /// nonisolated — pure, testable from any context. /// /// Round-2 polish (r1 regression): PassContext's first line already /// carries "Pass " + the pass name, so the raw line reads "Pass Pass /// 2 — …" — collapse the doubled leading "Pass Pass N" to "Pass N". nonisolated static func statusDisplayText(_ text: String) -> String { guard text.hasPrefix("You: ") else { return text } let body = text.dropFirst("You: ".count) guard isPassKickoff(String(body)) else { return text } let line = String(body.prefix(while: { $0 != "\n" })) guard line.hasPrefix("Pass Pass ") else { return line } return "Pass " + line.dropFirst("Pass Pass ".count) } /// Round-2 polish (argon#24/mercury#60/sol#9): operational warnings — /// engine-emitted interruptions, connection losses, and the model's /// failure rows — get the restrained terracotta accent in the status /// voice. Refusals and cancellations stay neutral (they are outcomes, /// not failures). Static, nonisolated — pure, test-pinnable. nonisolated static func isWarningStatus(_ text: String) -> Bool { let body = text.hasPrefix("Mentor: ") ? String(text.dropFirst("Mentor: ".count)) : text return body.hasPrefix("Operation interrupted") || body.hasPrefix("connection lost") || body.contains(" failed — ") } /// 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, previous: 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: // Round-7 (mercury#21): the full warning treatment (tinted // fill + border) renders ONLY while this row is the // transcript's last meaningful row — an older interruption // above a completed reply is history. // Round-8 (argon#8): a historical warning keeps the // terracotta ink + glyph (see `statusBox`) — distinct, // just not shouting. let current = Self.isWarningStatus(text) && isLastMeaningfulRow(row) statusBox(Self.statusDisplayText(text), current: current) // Round-7 (argon#39): 8pt of air when the warning // banner directly follows the pass kick-off pill — // at the stack's uniform 18pt the pair read as one // fused block. .padding(.top, current && Self.isKickoffPill(previous) ? 8 : 0) } 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 14/1.5 (Round-2, mercury#62 partial: one point up; /// lineSpacing re-derived from the same CSS 1.5 math — pads 16/12 /// untouched), 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(14)) .foregroundStyle(DesignTokens.foreground) .lineSpacing(4) // CSS 1.5 (21 − Concourse's scaled natural ≈ 17) .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. /// Round-6 (mercury#5/sol#10/argon#15): warning rows are their own /// component — warning glyph, structured headline + muted detail. /// Round-7 (mercury#21): the full treatment (fill + border) renders /// only when the caller passes `current` (last meaningful row). /// Round-8 (argon#8/mercury#16): a warning row ALWAYS carries the /// terracotta ink + glyph — historical ones on the plain wash pill — /// and ALL status rows share one width treatment: the transcript /// column's full width, leading edge aligned (fit-content pills and /// full-width banners read as two glued regions). @ViewBuilder private func statusBox(_ text: String, current: Bool = false) -> some View { if Self.isWarningStatus(text) { let parts = Self.warningParts(text) WarningStatusRow( headline: parts.headline, detail: parts.detail.map(Self.calmDetail), emphasized: current, ) } else { Text(text) .font(DesignTokens.ubuntuMono(11)) .foregroundStyle(DesignTokens.muted) .lineSpacing(5.5) // CSS 1.5 .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) .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 { // Round-2 sweep: 0.45 broke the 0.75 informational floor — // 0.75 still reads closed against the 1.0 pending card. candidate.disposition == .pending ? 1 : 0.75 } 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(DesignTokens.muted) } .frame(maxWidth: .infinity, alignment: .leading) } } } // MARK: Warning status row (round-6 — file-scope, type_body_length // posture; MonoButton/ResearchNoteContent precedent) /// Round-6 (mercury#5/sol#10/argon#15 — all seats): the operational /// warning row as a real component — the 11pt warning glyph, mono 12, /// structured headline over a muted detail line; wrapping allowed. No /// new hues — the accent over its own wash. /// Round-8 (argon#8/mercury#16): `emphasized` (the transcript's last /// meaningful row) carries the full treatment — accent wash fill (~9%) /// + 1pt accent border; a historical warning keeps the terracotta glyph /// + headline on the same plain wash pill the neutral status rows use — /// distinct, never shouting. private struct WarningStatusRow: View { let headline: String let detail: String? var emphasized = true var body: some View { HStack(alignment: .top, spacing: 8) { Image(systemName: "exclamationmark.triangle") .font(.system(size: 11)) .foregroundStyle(DesignTokens.accent) VStack(alignment: .leading, spacing: 3) { Text(headline) .font(DesignTokens.ubuntuMono(12).weight(.semibold)) .foregroundStyle(DesignTokens.accent) if let detail { Text(detail) .font(DesignTokens.ubuntuMono(12)) .foregroundStyle(DesignTokens.muted) .fixedSize(horizontal: false, vertical: true) } } .frame(maxWidth: .infinity, alignment: .leading) } .padding(.horizontal, 12) .padding(.vertical, 10) .background(washFill) .overlay(emphasized ? borderOverlay : nil) .textSelection(.enabled) .accessibilityElement(children: .combine) } private var washFill: some View { RoundedRectangle(cornerRadius: DesignTokens.radius) .fill(emphasized ? DesignTokens.accent.opacity(0.09) : DesignTokens.foreground.opacity(0.06)) } private var borderOverlay: some View { RoundedRectangle(cornerRadius: DesignTokens.radius) .strokeBorder(DesignTokens.accent, lineWidth: 1) } } // MARK: Warning display seams (round-6 split + round-8 calm copy — // file-scope extension, type_body_length posture; pure + test-pinned. // NOT private: ACPClientTests pins both seams via @testable.) extension SessionTranscriptView { /// Round-6 (all seats): the warning row's headline/detail split — drop /// the speaker prefix, then cut at the first ": " ("Operation /// interrupted: waiting for model response (61.6s elapsed)." → headline /// "Operation interrupted", detail the rest). No ": " → the whole line /// is the headline ("connection lost"). Static, nonisolated — pure. nonisolated static func warningParts(_ text: String) -> (headline: String, detail: String?) { var body = text if body.hasPrefix("Mentor: ") { body = String(body.dropFirst("Mentor: ".count)) } if body.hasPrefix("You: ") { body = String(body.dropFirst("You: ".count)) } guard let separator = body.range(of: ": ") else { return (body, nil) } return (String(body[.. String { let trimmed = detail.hasSuffix(".") ? String(detail.dropLast()) : detail let prefix = "waiting for model response (" let suffix = " elapsed)" guard trimmed.hasPrefix(prefix), trimmed.hasSuffix(suffix), trimmed.count > prefix.count + suffix.count else { return detail } let elapsed = trimmed.dropFirst(prefix.count).dropLast(suffix.count) return "waiting on the model — \(elapsed)" } } // MARK: Round-7 row rules (file-scope extension — type_body_length // posture, the composer extension's precedent) private extension SessionTranscriptView { /// Round-7 (mercury#21): this row is the transcript's last MEANINGFUL /// row — nothing rendered or streaming sits below it. A warning row /// keeps its warning styling only in this position; once a reply (or a /// live stream) follows, it is history. Pure display — the model keeps /// every row either way. func isLastMeaningfulRow(_ row: SessionRow) -> Bool { guard !model.isStreaming else { return false } return model.rows.last(where: { showsDebugRows || Self.isWritingRow($0) })?.id == row.id } /// Round-7 (argon#39): a replayed pass kick-off row — the status pill /// a warning banner must not hug (the 8pt-air rule). Static, /// nonisolated — pure. nonisolated static func isKickoffPill(_ row: SessionRow?) -> Bool { guard let row, case let .text(text) = row.content, text.hasPrefix("You: ") else { return false } return isPassKickoff(String(text.dropFirst("You: ".count))) } } // 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 hover-revealed debug toggle at the row's trailing edge. The /// liveness chip floats ABOVE the composer while streaming (contract /// ruling: the composer row stays flat). /// Round-1 polish: field and Send match heights (36 — both edges align, /// argon#33/mercury#38); the debug toggle rides IN the row after Send, /// not on a strip below it (mercury#64/sol#50). /// Round-2 polish: the row centers inside the SAME ≤720pt measure the /// transcript reads in (argon#22/sol#48) with the transcript's 16pt /// edge — input and conversation share one column; the toggle renders /// only while the pointer is over the composer (argon#21/sol#43/ /// mercury#58) — its slot stays reserved so nothing shifts on hover. private var inputBar: some View { HStack(alignment: .bottom, spacing: 8) { TextField( "Ask the mentor…", text: $draft, // Round-1 polish (mercury#70/sol#51): placeholder at muted // ink — legible at a glance, not tertiary-faint. prompt: Text("Ask the mentor…").foregroundStyle(DesignTokens.muted), 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 { // Hover reveal: the view is ABSENT at rest (no hit target, // no focus stop, no a11y node) — the fixed slot keeps Send // from shifting when the pointer enters the row. ZStack { if composerHover { debugToggle(debugBinding) } } .frame(width: 40) } } .padding(.horizontal, 16) // Round-5 (argon#47 tail): symmetric vertical padding — top == // bottom at 14 (r4's 12/10 read heavier above the divider's // edge than below the input). .padding(.vertical, 14) // One column with the transcript: cap at the measure, center. .frame(maxWidth: measureWidth) .frame(maxWidth: .infinity, alignment: .center) .onHover { composerHover = $0 } .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) } } // Owner ruling (2026-11-07): the scoped Mentor pane can be ready // with NO hosted session (empty presentation) — the Sessions pane // then shows this surface with nothing active, and the composer // must refuse honestly (disabled), never eat a typed prompt into // a silently-failed sendPrompt. .disabled(!model.phase.isReady || model.activeEntry == nil) } /// 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. /// Round-1 polish: 36pt to match the input (both edges align, /// argon#33). Round-4 contrast (sol#39/argon#11/mercury#52/56): the /// disabled Send is no longer a 0.75-dimmed accent pill (near-invisible) /// — #6B6964 ink on the #E8E5DF-hinted fill at full opacity, the /// council's disabled language. private var canSend: Bool { model.isStreaming || !draft.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } private var sendFill: Color { if model.isStreaming { return .clear } return canSend ? DesignTokens.accent : DesignTokens.border } private var sendInk: Color { if model.isStreaming { return DesignTokens.accent } return canSend ? DesignTokens.surface : DesignTokens.muted } private var sendButton: some View { Button { if model.isStreaming { model.stopStreaming() } else { send() } } label: { Text(model.isStreaming ? "Stop" : "Send") .font(DesignTokens.ubuntuMono(11)) .foregroundStyle(sendInk) .padding(.horizontal, 14) .frame(minHeight: 36) .background( RoundedRectangle(cornerRadius: 6) .fill(sendFill), ) .overlay( RoundedRectangle(cornerRadius: 6) .strokeBorder(sendStroke, lineWidth: 1), ) } .buttonStyle(.plain) .disabled(!canSend) .keyboardShortcut(model.isStreaming ? nil : .defaultAction) .help( model.isStreaming ? "Cancel the running turn — the engine ends it with a cancelled stop." : "Send to the mentor.", ) } /// Round-5 (sol#36/argon#45): the disabled Send keeps its r4 ink /// treatment and gains the one-step-stronger border — the #D8D4CC- /// equivalent darkening of border #E8E5DF via foreground opacity /// (no new hex), same as the disabled Blind Read. Enabled states /// untouched (Send's fill carries it; Stop keeps its accent outline). private var sendStroke: Color { if model.isStreaming { return DesignTokens.accent } return canSend ? .clear : DesignTokens.foreground.opacity(0.17) } /// 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.") // Round-4: 11 — informational micro-labels ride the 11pt // legibility floor (mercury#52). .font(DesignTokens.ubuntuMono(11)) // Round-2 sweep: muted at full ink — .secondary broke the // 0.75 contrast floor for informational micro-labels. .foregroundStyle(DesignTokens.muted) } .padding(.horizontal, 12) .padding(.vertical, 5) .background(.thinMaterial, in: Capsule()) .allowsHitTesting(false) } /// Settled #5: the Debug toggle's seat — the composer row's trailing /// edge (Round-1: mono-10 lowercase, muted, riding IN the row after /// Send). Round-2 polish: hover-revealed — the toggle mounts only /// while the pointer is over the composer (see inputBar); muted at /// FULL opacity when off (the 0.65 dim broke the 0.75 floor). private func debugToggle(_ binding: Binding) -> some View { Button { binding.wrappedValue.toggle() } label: { Text("debug") .font(DesignTokens.ubuntuMono(10)) .foregroundStyle(binding.wrappedValue ? DesignTokens.accent : DesignTokens.muted) // Optically centers against the 36pt input at rest. .padding(.bottom, 11) } .buttonStyle(.plain) .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) }